blob: b8c4a385e080d33f4339dcbc3192664da4212692 [file] [log] [blame]
Luca Farsi5717d6f2023-12-28 15:09:28 -08001# Copyright 2024, The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Luca Farsidb136442024-03-26 10:55:21 -070015"""Build script for the CI `test_suites` target."""
Luca Farsi5717d6f2023-12-28 15:09:28 -080016
17import argparse
Luca Farsi040fabe2024-05-22 17:21:47 -070018from dataclasses import dataclass
19import json
Luca Farsidb136442024-03-26 10:55:21 -070020import logging
Luca Farsi5717d6f2023-12-28 15:09:28 -080021import os
22import pathlib
Luca Farsi5717d6f2023-12-28 15:09:28 -080023import subprocess
24import sys
Luca Farsi8ea67422024-09-17 15:48:11 -070025from typing import Callable
Luca Farsib130e792024-08-22 12:04:41 -070026from build_context import BuildContext
Luca Farsi040fabe2024-05-22 17:21:47 -070027import optimized_targets
28
29
30REQUIRED_ENV_VARS = frozenset(['TARGET_PRODUCT', 'TARGET_RELEASE', 'TOP'])
31SOONG_UI_EXE_REL_PATH = 'build/soong/soong_ui.bash'
Luca Farsi2eaa5d02024-07-23 16:34:27 -070032LOG_PATH = 'logs/build_test_suites.log'
Luca Farsi5717d6f2023-12-28 15:09:28 -080033
34
Luca Farsidb136442024-03-26 10:55:21 -070035class Error(Exception):
36
37 def __init__(self, message):
38 super().__init__(message)
Luca Farsi5717d6f2023-12-28 15:09:28 -080039
40
Luca Farsidb136442024-03-26 10:55:21 -070041class BuildFailureError(Error):
42
43 def __init__(self, return_code):
44 super().__init__(f'Build command failed with return code: f{return_code}')
45 self.return_code = return_code
46
47
Luca Farsi040fabe2024-05-22 17:21:47 -070048class BuildPlanner:
49 """Class in charge of determining how to optimize build targets.
50
51 Given the build context and targets to build it will determine a final list of
52 targets to build along with getting a set of packaging functions to package up
53 any output zip files needed by the build.
54 """
55
56 def __init__(
57 self,
Luca Farsib130e792024-08-22 12:04:41 -070058 build_context: BuildContext,
Luca Farsi040fabe2024-05-22 17:21:47 -070059 args: argparse.Namespace,
60 target_optimizations: dict[str, optimized_targets.OptimizedBuildTarget],
61 ):
62 self.build_context = build_context
63 self.args = args
64 self.target_optimizations = target_optimizations
65
66 def create_build_plan(self):
67
Luca Farsib130e792024-08-22 12:04:41 -070068 if 'optimized_build' not in self.build_context.enabled_build_features:
Luca Farsi040fabe2024-05-22 17:21:47 -070069 return BuildPlan(set(self.args.extra_targets), set())
70
71 build_targets = set()
Luca Farsi8ea67422024-09-17 15:48:11 -070072 packaging_commands_getters = []
Luca Farsi040fabe2024-05-22 17:21:47 -070073 for target in self.args.extra_targets:
Luca Farsib24c1c32024-08-01 14:47:10 -070074 if self._unused_target_exclusion_enabled(
75 target
Luca Farsib130e792024-08-22 12:04:41 -070076 ) and not self.build_context.build_target_used(target):
Luca Farsib24c1c32024-08-01 14:47:10 -070077 continue
78
Luca Farsi040fabe2024-05-22 17:21:47 -070079 target_optimizer_getter = self.target_optimizations.get(target, None)
80 if not target_optimizer_getter:
81 build_targets.add(target)
82 continue
83
84 target_optimizer = target_optimizer_getter(
85 target, self.build_context, self.args
86 )
87 build_targets.update(target_optimizer.get_build_targets())
Luca Farsi8ea67422024-09-17 15:48:11 -070088 packaging_commands_getters.append(
89 target_optimizer.get_package_outputs_commands
90 )
Luca Farsi040fabe2024-05-22 17:21:47 -070091
Luca Farsi8ea67422024-09-17 15:48:11 -070092 return BuildPlan(build_targets, packaging_commands_getters)
Luca Farsidb136442024-03-26 10:55:21 -070093
Luca Farsib24c1c32024-08-01 14:47:10 -070094 def _unused_target_exclusion_enabled(self, target: str) -> bool:
Luca Farsib130e792024-08-22 12:04:41 -070095 return (
96 f'{target}_unused_exclusion'
97 in self.build_context.enabled_build_features
Luca Farsib24c1c32024-08-01 14:47:10 -070098 )
99
Luca Farsidb136442024-03-26 10:55:21 -0700100
Luca Farsi040fabe2024-05-22 17:21:47 -0700101@dataclass(frozen=True)
102class BuildPlan:
103 build_targets: set[str]
Luca Farsi8ea67422024-09-17 15:48:11 -0700104 packaging_commands_getters: list[Callable[[], list[list[str]]]]
Luca Farsidb136442024-03-26 10:55:21 -0700105
106
107def build_test_suites(argv: list[str]) -> int:
Luca Farsi040fabe2024-05-22 17:21:47 -0700108 """Builds all test suites passed in, optimizing based on the build_context content.
Luca Farsidb136442024-03-26 10:55:21 -0700109
110 Args:
111 argv: The command line arguments passed in.
112
113 Returns:
114 The exit code of the build.
115 """
Luca Farsi5717d6f2023-12-28 15:09:28 -0800116 args = parse_args(argv)
Luca Farsidb136442024-03-26 10:55:21 -0700117 check_required_env()
Luca Farsib130e792024-08-22 12:04:41 -0700118 build_context = BuildContext(load_build_context())
Luca Farsi040fabe2024-05-22 17:21:47 -0700119 build_planner = BuildPlanner(
120 build_context, args, optimized_targets.OPTIMIZED_BUILD_TARGETS
121 )
122 build_plan = build_planner.create_build_plan()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800123
Luca Farsidb136442024-03-26 10:55:21 -0700124 try:
Luca Farsi040fabe2024-05-22 17:21:47 -0700125 execute_build_plan(build_plan)
Luca Farsidb136442024-03-26 10:55:21 -0700126 except BuildFailureError as e:
127 logging.error('Build command failed! Check build_log for details.')
128 return e.return_code
129
130 return 0
131
132
Luca Farsi040fabe2024-05-22 17:21:47 -0700133def parse_args(argv: list[str]) -> argparse.Namespace:
134 argparser = argparse.ArgumentParser()
135
136 argparser.add_argument(
137 'extra_targets', nargs='*', help='Extra test suites to build.'
138 )
139
140 return argparser.parse_args(argv)
141
142
Luca Farsidb136442024-03-26 10:55:21 -0700143def check_required_env():
144 """Check for required env vars.
145
146 Raises:
147 RuntimeError: If any required env vars are not found.
148 """
149 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
150
151 if not missing_env_vars:
152 return
153
154 t = ','.join(missing_env_vars)
155 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800156
157
Luca Farsi040fabe2024-05-22 17:21:47 -0700158def load_build_context():
159 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
160 if build_context_path.is_file():
161 try:
162 with open(build_context_path, 'r') as f:
163 return json.load(f)
164 except json.decoder.JSONDecodeError as e:
165 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700166
Luca Farsi040fabe2024-05-22 17:21:47 -0700167 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
168 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800169
170
Luca Farsi040fabe2024-05-22 17:21:47 -0700171def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700172 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700173
Luca Farsidb136442024-03-26 10:55:21 -0700174
Luca Farsi040fabe2024-05-22 17:21:47 -0700175def execute_build_plan(build_plan: BuildPlan):
176 build_command = []
177 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
178 build_command.append('--make-mode')
179 build_command.extend(build_plan.build_targets)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800180
Luca Farsidb136442024-03-26 10:55:21 -0700181 try:
182 run_command(build_command)
183 except subprocess.CalledProcessError as e:
184 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800185
Luca Farsi8ea67422024-09-17 15:48:11 -0700186 for packaging_commands_getter in build_plan.packaging_commands_getters:
Luca Farsid4e4b642024-09-10 16:37:51 -0700187 try:
Luca Farsi8ea67422024-09-17 15:48:11 -0700188 for packaging_command in packaging_commands_getter():
189 run_command(packaging_command)
Luca Farsid4e4b642024-09-10 16:37:51 -0700190 except subprocess.CalledProcessError as e:
191 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800192
Luca Farsidb136442024-03-26 10:55:21 -0700193
Luca Farsi040fabe2024-05-22 17:21:47 -0700194def get_top() -> pathlib.Path:
195 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800196
197
Luca Farsidb136442024-03-26 10:55:21 -0700198def run_command(args: list[str], stdout=None):
199 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800200
201
Luca Farsi2dc17012024-03-19 16:47:54 -0700202def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700203 dist_dir = os.environ.get('DIST_DIR')
204 if dist_dir:
205 log_file = pathlib.Path(dist_dir) / LOG_PATH
206 logging.basicConfig(
207 level=logging.DEBUG,
208 format='%(asctime)s %(levelname)s %(message)s',
209 filename=log_file,
210 )
Luca Farsidb136442024-03-26 10:55:21 -0700211 sys.exit(build_test_suites(argv))