blob: d81248b4962d7d46bc97633c01d261870f7c7010 [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
Luca Farsi62035d92024-11-25 18:21:45 +000033REQUIRED_ENV_VARS = frozenset(['TARGET_PRODUCT', 'TARGET_RELEASE', 'TOP', 'DIST_DIR'])
Luca Farsi040fabe2024-05-22 17:21:47 -070034SOONG_UI_EXE_REL_PATH = 'build/soong/soong_ui.bash'
Luca Farsi2eaa5d02024-07-23 16:34:27 -070035LOG_PATH = 'logs/build_test_suites.log'
Julien Desprezcd6d27c2024-12-10 12:21:30 -080036# Currently, this prevents the removal of those tags when they exist. In the future we likely
37# want the script to supply 'dist directly
Julien Desprezdc2d3bd2024-12-16 10:11:56 -080038REQUIRED_BUILD_TARGETS = frozenset(['dist', 'droid', 'checkbuild'])
Luca Farsi5717d6f2023-12-28 15:09:28 -080039
40
Luca Farsidb136442024-03-26 10:55:21 -070041class Error(Exception):
42
43 def __init__(self, message):
44 super().__init__(message)
Luca Farsi5717d6f2023-12-28 15:09:28 -080045
46
Luca Farsidb136442024-03-26 10:55:21 -070047class BuildFailureError(Error):
48
49 def __init__(self, return_code):
50 super().__init__(f'Build command failed with return code: f{return_code}')
51 self.return_code = return_code
52
53
Luca Farsi040fabe2024-05-22 17:21:47 -070054class BuildPlanner:
55 """Class in charge of determining how to optimize build targets.
56
57 Given the build context and targets to build it will determine a final list of
58 targets to build along with getting a set of packaging functions to package up
59 any output zip files needed by the build.
60 """
61
62 def __init__(
63 self,
Luca Farsib130e792024-08-22 12:04:41 -070064 build_context: BuildContext,
Luca Farsi040fabe2024-05-22 17:21:47 -070065 args: argparse.Namespace,
66 target_optimizations: dict[str, optimized_targets.OptimizedBuildTarget],
67 ):
68 self.build_context = build_context
69 self.args = args
70 self.target_optimizations = target_optimizations
71
72 def create_build_plan(self):
73
Luca Farsib130e792024-08-22 12:04:41 -070074 if 'optimized_build' not in self.build_context.enabled_build_features:
Luca Farsi040fabe2024-05-22 17:21:47 -070075 return BuildPlan(set(self.args.extra_targets), set())
76
Julien Desprez692dd322024-12-11 00:31:02 +000077 if not self.build_context.test_infos:
78 logging.warning('Build context has no test infos, skipping optimizations.')
79 for target in self.args.extra_targets:
80 get_metrics_agent().report_unoptimized_target(target, 'BUILD_CONTEXT has no test infos.')
81 return BuildPlan(set(self.args.extra_targets), set())
82
Luca Farsi040fabe2024-05-22 17:21:47 -070083 build_targets = set()
Luca Farsi8ea67422024-09-17 15:48:11 -070084 packaging_commands_getters = []
Luca Farsi26c0d8a2024-11-22 00:09:47 +000085 # In order to roll optimizations out differently between test suites and
86 # device builds, we have separate flags.
Luca Farsi18f6e102025-01-09 10:18:28 -080087 enable_discovery = (('test_suites_zip_test_discovery'
Luca Farsi26c0d8a2024-11-22 00:09:47 +000088 in self.build_context.enabled_build_features
89 and not self.args.device_build
90 ) or (
91 'device_zip_test_discovery'
92 in self.build_context.enabled_build_features
93 and self.args.device_build
Luca Farsi18f6e102025-01-09 10:18:28 -080094 )) and not self.args.test_discovery_info_mode
Julien Desprez254daef2024-12-19 10:04:43 -080095 logging.info(f'Discovery mode is enabled= {enable_discovery}')
96 preliminary_build_targets = self._collect_preliminary_build_targets(enable_discovery)
Luca Farsi5dbad402024-11-07 12:43:13 -080097
Luca Farsi26c0d8a2024-11-22 00:09:47 +000098 for target in preliminary_build_targets:
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
Julien Desprez254daef2024-12-19 10:04:43 -0800114 def _collect_preliminary_build_targets(self, enable_discovery: bool):
Luca Farsi26c0d8a2024-11-22 00:09:47 +0000115 build_targets = set()
116 try:
117 test_discovery_zip_regexes = self._get_test_discovery_zip_regexes()
118 logging.info(f'Discovered test discovery regexes: {test_discovery_zip_regexes}')
119 except test_discovery_agent.TestDiscoveryError as e:
120 optimization_rationale = e.message
121 logging.warning(f'Unable to perform test discovery: {optimization_rationale}')
122
123 for target in self.args.extra_targets:
124 get_metrics_agent().report_unoptimized_target(target, optimization_rationale)
125 return self._legacy_collect_preliminary_build_targets()
126
127 for target in self.args.extra_targets:
128 if target in REQUIRED_BUILD_TARGETS:
129 build_targets.add(target)
Julien Desprez1075a6b2024-12-14 17:44:18 -0800130 get_metrics_agent().report_unoptimized_target(target, 'Required build target.')
Luca Farsi26c0d8a2024-11-22 00:09:47 +0000131 continue
Julien Desprez13875332024-12-20 10:47:05 -0800132 # If nothing is discovered without error, that means nothing is needed.
133 if not test_discovery_zip_regexes:
134 get_metrics_agent().report_optimized_target(target)
135 continue
Luca Farsi26c0d8a2024-11-22 00:09:47 +0000136
137 regex = r'\b(%s.*)\b' % re.escape(target)
138 for opt in test_discovery_zip_regexes:
139 try:
140 if re.search(regex, opt):
141 get_metrics_agent().report_unoptimized_target(target, 'Test artifact used.')
142 build_targets.add(target)
Julien Despreze3879332024-12-17 17:03:57 -0800143 # proceed to next target evaluation
144 break
Luca Farsi26c0d8a2024-11-22 00:09:47 +0000145 get_metrics_agent().report_optimized_target(target)
146 except Exception as e:
147 # In case of exception report as unoptimized
148 build_targets.add(target)
149 get_metrics_agent().report_unoptimized_target(target, f'Error in parsing test discovery output for {target}: {repr(e)}')
150 logging.error(f'unable to parse test discovery output: {repr(e)}')
Julien Despreze3879332024-12-17 17:03:57 -0800151 break
Julien Desprez254daef2024-12-19 10:04:43 -0800152 # If discovery is not enabled, return the original list
153 if not enable_discovery:
154 return self._legacy_collect_preliminary_build_targets()
Luca Farsi26c0d8a2024-11-22 00:09:47 +0000155
156 return build_targets
157
158 def _legacy_collect_preliminary_build_targets(self):
159 build_targets = set()
160 for target in self.args.extra_targets:
161 if self._unused_target_exclusion_enabled(
162 target
163 ) and not self.build_context.build_target_used(target):
164 continue
165
166 build_targets.add(target)
167 return build_targets
168
Luca Farsib24c1c32024-08-01 14:47:10 -0700169 def _unused_target_exclusion_enabled(self, target: str) -> bool:
Luca Farsib130e792024-08-22 12:04:41 -0700170 return (
171 f'{target}_unused_exclusion'
172 in self.build_context.enabled_build_features
Luca Farsib24c1c32024-08-01 14:47:10 -0700173 )
174
Luca Farsi5dbad402024-11-07 12:43:13 -0800175 def _get_test_discovery_zip_regexes(self) -> set[str]:
176 build_target_regexes = set()
177 for test_info in self.build_context.test_infos:
178 tf_command = self._build_tf_command(test_info)
179 discovery_agent = test_discovery_agent.TestDiscoveryAgent(tradefed_args=tf_command)
180 for regex in discovery_agent.discover_test_zip_regexes():
181 build_target_regexes.add(regex)
182 return build_target_regexes
183
184
185 def _build_tf_command(self, test_info) -> list[str]:
186 command = [test_info.command]
187 for extra_option in test_info.extra_options:
188 if not extra_option.get('key'):
189 continue
190 arg_key = '--' + extra_option.get('key')
191 if arg_key == '--build-id':
192 command.append(arg_key)
193 command.append(os.environ.get('BUILD_NUMBER'))
194 continue
195 if extra_option.get('values'):
196 for value in extra_option.get('values'):
197 command.append(arg_key)
198 command.append(value)
199 else:
200 command.append(arg_key)
201
202 return command
Luca Farsidb136442024-03-26 10:55:21 -0700203
Luca Farsi040fabe2024-05-22 17:21:47 -0700204@dataclass(frozen=True)
205class BuildPlan:
206 build_targets: set[str]
Luca Farsi8ea67422024-09-17 15:48:11 -0700207 packaging_commands_getters: list[Callable[[], list[list[str]]]]
Luca Farsidb136442024-03-26 10:55:21 -0700208
209
210def build_test_suites(argv: list[str]) -> int:
Luca Farsi040fabe2024-05-22 17:21:47 -0700211 """Builds all test suites passed in, optimizing based on the build_context content.
Luca Farsidb136442024-03-26 10:55:21 -0700212
213 Args:
214 argv: The command line arguments passed in.
215
216 Returns:
217 The exit code of the build.
218 """
Luca Farsi7d859712024-11-06 16:09:16 -0800219 get_metrics_agent().analysis_start()
220 try:
221 args = parse_args(argv)
222 check_required_env()
223 build_context = BuildContext(load_build_context())
224 build_planner = BuildPlanner(
225 build_context, args, optimized_targets.OPTIMIZED_BUILD_TARGETS
226 )
227 build_plan = build_planner.create_build_plan()
228 except:
229 raise
230 finally:
231 get_metrics_agent().analysis_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800232
Luca Farsidb136442024-03-26 10:55:21 -0700233 try:
Luca Farsi040fabe2024-05-22 17:21:47 -0700234 execute_build_plan(build_plan)
Luca Farsidb136442024-03-26 10:55:21 -0700235 except BuildFailureError as e:
236 logging.error('Build command failed! Check build_log for details.')
237 return e.return_code
Luca Farsi7d859712024-11-06 16:09:16 -0800238 finally:
239 get_metrics_agent().end_reporting()
Luca Farsidb136442024-03-26 10:55:21 -0700240
241 return 0
242
243
Luca Farsi040fabe2024-05-22 17:21:47 -0700244def parse_args(argv: list[str]) -> argparse.Namespace:
245 argparser = argparse.ArgumentParser()
246
247 argparser.add_argument(
248 'extra_targets', nargs='*', help='Extra test suites to build.'
249 )
Luca Farsi62035d92024-11-25 18:21:45 +0000250 argparser.add_argument(
251 '--device-build',
252 action='store_true',
253 help='Flag to indicate running a device build.',
254 )
Luca Farsi18f6e102025-01-09 10:18:28 -0800255 argparser.add_argument(
256 '--test_discovery_info_mode',
257 action='store_true',
258 help='Flag to enable running test discovery in info only mode.',
259 )
Luca Farsi040fabe2024-05-22 17:21:47 -0700260
261 return argparser.parse_args(argv)
262
263
Luca Farsidb136442024-03-26 10:55:21 -0700264def check_required_env():
265 """Check for required env vars.
266
267 Raises:
268 RuntimeError: If any required env vars are not found.
269 """
270 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
271
272 if not missing_env_vars:
273 return
274
275 t = ','.join(missing_env_vars)
276 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800277
278
Luca Farsi040fabe2024-05-22 17:21:47 -0700279def load_build_context():
280 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
281 if build_context_path.is_file():
282 try:
283 with open(build_context_path, 'r') as f:
284 return json.load(f)
285 except json.decoder.JSONDecodeError as e:
286 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700287
Luca Farsi040fabe2024-05-22 17:21:47 -0700288 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
289 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800290
291
Luca Farsi040fabe2024-05-22 17:21:47 -0700292def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700293 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700294
Luca Farsidb136442024-03-26 10:55:21 -0700295
Luca Farsi040fabe2024-05-22 17:21:47 -0700296def execute_build_plan(build_plan: BuildPlan):
297 build_command = []
298 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
299 build_command.append('--make-mode')
300 build_command.extend(build_plan.build_targets)
Julien Desprezaa4ee4b2025-01-10 20:35:11 -0800301 logging.info(f'Running build command: {build_command}')
Luca Farsidb136442024-03-26 10:55:21 -0700302 try:
303 run_command(build_command)
304 except subprocess.CalledProcessError as e:
305 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800306
Luca Farsi7d859712024-11-06 16:09:16 -0800307 get_metrics_agent().packaging_start()
308 try:
309 for packaging_commands_getter in build_plan.packaging_commands_getters:
Luca Farsi8ea67422024-09-17 15:48:11 -0700310 for packaging_command in packaging_commands_getter():
311 run_command(packaging_command)
Luca Farsi7d859712024-11-06 16:09:16 -0800312 except subprocess.CalledProcessError as e:
313 raise BuildFailureError(e.returncode) from e
314 finally:
315 get_metrics_agent().packaging_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800316
Luca Farsidb136442024-03-26 10:55:21 -0700317
Luca Farsi040fabe2024-05-22 17:21:47 -0700318def get_top() -> pathlib.Path:
319 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800320
321
Luca Farsidb136442024-03-26 10:55:21 -0700322def run_command(args: list[str], stdout=None):
323 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800324
325
Luca Farsi7d859712024-11-06 16:09:16 -0800326def get_metrics_agent():
327 return metrics_agent.MetricsAgent.instance()
328
329
Luca Farsi2dc17012024-03-19 16:47:54 -0700330def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700331 dist_dir = os.environ.get('DIST_DIR')
332 if dist_dir:
333 log_file = pathlib.Path(dist_dir) / LOG_PATH
334 logging.basicConfig(
335 level=logging.DEBUG,
336 format='%(asctime)s %(levelname)s %(message)s',
337 filename=log_file,
338 )
Luca Farsidb136442024-03-26 10:55:21 -0700339 sys.exit(build_test_suites(argv))
Luca Farsi10adf352024-11-06 14:23:36 -0800340
341
342if __name__ == '__main__':
343 main(sys.argv[1:])