blob: cd9d76d23b4aeeaf31cda9fa78d2bf410ff79ce5 [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 Farsi5dbad402024-11-07 12:43:13 -080023import re
Luca Farsi5717d6f2023-12-28 15:09:28 -080024import subprocess
25import sys
Luca Farsi8ea67422024-09-17 15:48:11 -070026from typing import Callable
Luca Farsib130e792024-08-22 12:04:41 -070027from build_context import BuildContext
Luca Farsi040fabe2024-05-22 17:21:47 -070028import optimized_targets
Luca Farsi7d859712024-11-06 16:09:16 -080029import metrics_agent
Luca Farsi5dbad402024-11-07 12:43:13 -080030import test_discovery_agent
Luca Farsi040fabe2024-05-22 17:21:47 -070031
32
33REQUIRED_ENV_VARS = frozenset(['TARGET_PRODUCT', 'TARGET_RELEASE', 'TOP'])
34SOONG_UI_EXE_REL_PATH = 'build/soong/soong_ui.bash'
Luca Farsi2eaa5d02024-07-23 16:34:27 -070035LOG_PATH = 'logs/build_test_suites.log'
Luca Farsi5717d6f2023-12-28 15:09:28 -080036
37
Luca Farsidb136442024-03-26 10:55:21 -070038class Error(Exception):
39
40 def __init__(self, message):
41 super().__init__(message)
Luca Farsi5717d6f2023-12-28 15:09:28 -080042
43
Luca Farsidb136442024-03-26 10:55:21 -070044class BuildFailureError(Error):
45
46 def __init__(self, return_code):
47 super().__init__(f'Build command failed with return code: f{return_code}')
48 self.return_code = return_code
49
50
Luca Farsi040fabe2024-05-22 17:21:47 -070051class BuildPlanner:
52 """Class in charge of determining how to optimize build targets.
53
54 Given the build context and targets to build it will determine a final list of
55 targets to build along with getting a set of packaging functions to package up
56 any output zip files needed by the build.
57 """
58
59 def __init__(
60 self,
Luca Farsib130e792024-08-22 12:04:41 -070061 build_context: BuildContext,
Luca Farsi040fabe2024-05-22 17:21:47 -070062 args: argparse.Namespace,
63 target_optimizations: dict[str, optimized_targets.OptimizedBuildTarget],
64 ):
65 self.build_context = build_context
66 self.args = args
67 self.target_optimizations = target_optimizations
68
69 def create_build_plan(self):
70
Luca Farsib130e792024-08-22 12:04:41 -070071 if 'optimized_build' not in self.build_context.enabled_build_features:
Luca Farsi040fabe2024-05-22 17:21:47 -070072 return BuildPlan(set(self.args.extra_targets), set())
73
74 build_targets = set()
Luca Farsi8ea67422024-09-17 15:48:11 -070075 packaging_commands_getters = []
Luca Farsi5dbad402024-11-07 12:43:13 -080076 test_discovery_zip_regexes = set()
77 optimization_rationale = ''
78 try:
79 # Do not use these regexes for now, only run this to collect data on what
80 # would be optimized.
81 test_discovery_zip_regexes = self._get_test_discovery_zip_regexes()
82 logging.info(f'Discovered test discovery regexes: {test_discovery_zip_regexes}')
83 except test_discovery_agent.TestDiscoveryError as e:
84 optimization_rationale = e.message
85 logging.warning(f'Unable to perform test discovery: {optimization_rationale}')
Luca Farsi040fabe2024-05-22 17:21:47 -070086 for target in self.args.extra_targets:
Luca Farsi5dbad402024-11-07 12:43:13 -080087 if optimization_rationale:
88 get_metrics_agent().report_unoptimized_target(target, optimization_rationale)
89 else:
90 regex = r'\b(%s)\b' % re.escape(target)
91 if any(re.search(regex, opt) for opt in test_discovery_zip_regexes):
92 get_metrics_agent().report_optimized_target(target)
93
Luca Farsib24c1c32024-08-01 14:47:10 -070094 if self._unused_target_exclusion_enabled(
95 target
Luca Farsib130e792024-08-22 12:04:41 -070096 ) and not self.build_context.build_target_used(target):
Luca Farsib24c1c32024-08-01 14:47:10 -070097 continue
98
Luca Farsi040fabe2024-05-22 17:21:47 -070099 target_optimizer_getter = self.target_optimizations.get(target, None)
100 if not target_optimizer_getter:
101 build_targets.add(target)
102 continue
103
104 target_optimizer = target_optimizer_getter(
105 target, self.build_context, self.args
106 )
107 build_targets.update(target_optimizer.get_build_targets())
Luca Farsi8ea67422024-09-17 15:48:11 -0700108 packaging_commands_getters.append(
109 target_optimizer.get_package_outputs_commands
110 )
Luca Farsi040fabe2024-05-22 17:21:47 -0700111
Luca Farsi8ea67422024-09-17 15:48:11 -0700112 return BuildPlan(build_targets, packaging_commands_getters)
Luca Farsidb136442024-03-26 10:55:21 -0700113
Luca Farsib24c1c32024-08-01 14:47:10 -0700114 def _unused_target_exclusion_enabled(self, target: str) -> bool:
Luca Farsib130e792024-08-22 12:04:41 -0700115 return (
116 f'{target}_unused_exclusion'
117 in self.build_context.enabled_build_features
Luca Farsib24c1c32024-08-01 14:47:10 -0700118 )
119
Luca Farsi5dbad402024-11-07 12:43:13 -0800120 def _get_test_discovery_zip_regexes(self) -> set[str]:
121 build_target_regexes = set()
122 for test_info in self.build_context.test_infos:
123 tf_command = self._build_tf_command(test_info)
124 discovery_agent = test_discovery_agent.TestDiscoveryAgent(tradefed_args=tf_command)
125 for regex in discovery_agent.discover_test_zip_regexes():
126 build_target_regexes.add(regex)
127 return build_target_regexes
128
129
130 def _build_tf_command(self, test_info) -> list[str]:
131 command = [test_info.command]
132 for extra_option in test_info.extra_options:
133 if not extra_option.get('key'):
134 continue
135 arg_key = '--' + extra_option.get('key')
136 if arg_key == '--build-id':
137 command.append(arg_key)
138 command.append(os.environ.get('BUILD_NUMBER'))
139 continue
140 if extra_option.get('values'):
141 for value in extra_option.get('values'):
142 command.append(arg_key)
143 command.append(value)
144 else:
145 command.append(arg_key)
146
147 return command
Luca Farsidb136442024-03-26 10:55:21 -0700148
Luca Farsi040fabe2024-05-22 17:21:47 -0700149@dataclass(frozen=True)
150class BuildPlan:
151 build_targets: set[str]
Luca Farsi8ea67422024-09-17 15:48:11 -0700152 packaging_commands_getters: list[Callable[[], list[list[str]]]]
Luca Farsidb136442024-03-26 10:55:21 -0700153
154
155def build_test_suites(argv: list[str]) -> int:
Luca Farsi040fabe2024-05-22 17:21:47 -0700156 """Builds all test suites passed in, optimizing based on the build_context content.
Luca Farsidb136442024-03-26 10:55:21 -0700157
158 Args:
159 argv: The command line arguments passed in.
160
161 Returns:
162 The exit code of the build.
163 """
Luca Farsi7d859712024-11-06 16:09:16 -0800164 get_metrics_agent().analysis_start()
165 try:
166 args = parse_args(argv)
167 check_required_env()
168 build_context = BuildContext(load_build_context())
169 build_planner = BuildPlanner(
170 build_context, args, optimized_targets.OPTIMIZED_BUILD_TARGETS
171 )
172 build_plan = build_planner.create_build_plan()
173 except:
174 raise
175 finally:
176 get_metrics_agent().analysis_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800177
Luca Farsidb136442024-03-26 10:55:21 -0700178 try:
Luca Farsi040fabe2024-05-22 17:21:47 -0700179 execute_build_plan(build_plan)
Luca Farsidb136442024-03-26 10:55:21 -0700180 except BuildFailureError as e:
181 logging.error('Build command failed! Check build_log for details.')
182 return e.return_code
Luca Farsi7d859712024-11-06 16:09:16 -0800183 finally:
184 get_metrics_agent().end_reporting()
Luca Farsidb136442024-03-26 10:55:21 -0700185
186 return 0
187
188
Luca Farsi040fabe2024-05-22 17:21:47 -0700189def parse_args(argv: list[str]) -> argparse.Namespace:
190 argparser = argparse.ArgumentParser()
191
192 argparser.add_argument(
193 'extra_targets', nargs='*', help='Extra test suites to build.'
194 )
195
196 return argparser.parse_args(argv)
197
198
Luca Farsidb136442024-03-26 10:55:21 -0700199def check_required_env():
200 """Check for required env vars.
201
202 Raises:
203 RuntimeError: If any required env vars are not found.
204 """
205 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
206
207 if not missing_env_vars:
208 return
209
210 t = ','.join(missing_env_vars)
211 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800212
213
Luca Farsi040fabe2024-05-22 17:21:47 -0700214def load_build_context():
215 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
216 if build_context_path.is_file():
217 try:
218 with open(build_context_path, 'r') as f:
219 return json.load(f)
220 except json.decoder.JSONDecodeError as e:
221 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700222
Luca Farsi040fabe2024-05-22 17:21:47 -0700223 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
224 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800225
226
Luca Farsi040fabe2024-05-22 17:21:47 -0700227def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700228 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700229
Luca Farsidb136442024-03-26 10:55:21 -0700230
Luca Farsi040fabe2024-05-22 17:21:47 -0700231def execute_build_plan(build_plan: BuildPlan):
232 build_command = []
233 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
234 build_command.append('--make-mode')
235 build_command.extend(build_plan.build_targets)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800236
Luca Farsidb136442024-03-26 10:55:21 -0700237 try:
238 run_command(build_command)
239 except subprocess.CalledProcessError as e:
240 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800241
Luca Farsi7d859712024-11-06 16:09:16 -0800242 get_metrics_agent().packaging_start()
243 try:
244 for packaging_commands_getter in build_plan.packaging_commands_getters:
Luca Farsi8ea67422024-09-17 15:48:11 -0700245 for packaging_command in packaging_commands_getter():
246 run_command(packaging_command)
Luca Farsi7d859712024-11-06 16:09:16 -0800247 except subprocess.CalledProcessError as e:
248 raise BuildFailureError(e.returncode) from e
249 finally:
250 get_metrics_agent().packaging_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800251
Luca Farsidb136442024-03-26 10:55:21 -0700252
Luca Farsi040fabe2024-05-22 17:21:47 -0700253def get_top() -> pathlib.Path:
254 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800255
256
Luca Farsidb136442024-03-26 10:55:21 -0700257def run_command(args: list[str], stdout=None):
258 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800259
260
Luca Farsi7d859712024-11-06 16:09:16 -0800261def get_metrics_agent():
262 return metrics_agent.MetricsAgent.instance()
263
264
Luca Farsi2dc17012024-03-19 16:47:54 -0700265def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700266 dist_dir = os.environ.get('DIST_DIR')
267 if dist_dir:
268 log_file = pathlib.Path(dist_dir) / LOG_PATH
269 logging.basicConfig(
270 level=logging.DEBUG,
271 format='%(asctime)s %(levelname)s %(message)s',
272 filename=log_file,
273 )
Luca Farsidb136442024-03-26 10:55:21 -0700274 sys.exit(build_test_suites(argv))
Luca Farsi10adf352024-11-06 14:23:36 -0800275
276
277if __name__ == '__main__':
278 main(sys.argv[1:])