blob: cdcba5a87ea267f7a9a7e754823d4e0cab67f2c3 [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.
Julien Desprez254daef2024-12-19 10:04:43 -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
Julien Desprez254daef2024-12-19 10:04:43 -080094 )
95 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 Farsi040fabe2024-05-22 17:21:47 -0700255
256 return argparser.parse_args(argv)
257
258
Luca Farsidb136442024-03-26 10:55:21 -0700259def check_required_env():
260 """Check for required env vars.
261
262 Raises:
263 RuntimeError: If any required env vars are not found.
264 """
265 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
266
267 if not missing_env_vars:
268 return
269
270 t = ','.join(missing_env_vars)
271 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800272
273
Luca Farsi040fabe2024-05-22 17:21:47 -0700274def load_build_context():
275 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
276 if build_context_path.is_file():
277 try:
278 with open(build_context_path, 'r') as f:
279 return json.load(f)
280 except json.decoder.JSONDecodeError as e:
281 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700282
Luca Farsi040fabe2024-05-22 17:21:47 -0700283 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
284 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800285
286
Luca Farsi040fabe2024-05-22 17:21:47 -0700287def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700288 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700289
Luca Farsidb136442024-03-26 10:55:21 -0700290
Luca Farsi040fabe2024-05-22 17:21:47 -0700291def execute_build_plan(build_plan: BuildPlan):
292 build_command = []
293 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
294 build_command.append('--make-mode')
295 build_command.extend(build_plan.build_targets)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800296
Luca Farsidb136442024-03-26 10:55:21 -0700297 try:
298 run_command(build_command)
299 except subprocess.CalledProcessError as e:
300 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800301
Luca Farsi7d859712024-11-06 16:09:16 -0800302 get_metrics_agent().packaging_start()
303 try:
304 for packaging_commands_getter in build_plan.packaging_commands_getters:
Luca Farsi8ea67422024-09-17 15:48:11 -0700305 for packaging_command in packaging_commands_getter():
306 run_command(packaging_command)
Luca Farsi7d859712024-11-06 16:09:16 -0800307 except subprocess.CalledProcessError as e:
308 raise BuildFailureError(e.returncode) from e
309 finally:
310 get_metrics_agent().packaging_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800311
Luca Farsidb136442024-03-26 10:55:21 -0700312
Luca Farsi040fabe2024-05-22 17:21:47 -0700313def get_top() -> pathlib.Path:
314 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800315
316
Luca Farsidb136442024-03-26 10:55:21 -0700317def run_command(args: list[str], stdout=None):
318 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800319
320
Luca Farsi7d859712024-11-06 16:09:16 -0800321def get_metrics_agent():
322 return metrics_agent.MetricsAgent.instance()
323
324
Luca Farsi2dc17012024-03-19 16:47:54 -0700325def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700326 dist_dir = os.environ.get('DIST_DIR')
327 if dist_dir:
328 log_file = pathlib.Path(dist_dir) / LOG_PATH
329 logging.basicConfig(
330 level=logging.DEBUG,
331 format='%(asctime)s %(levelname)s %(message)s',
332 filename=log_file,
333 )
Luca Farsidb136442024-03-26 10:55:21 -0700334 sys.exit(build_test_suites(argv))
Luca Farsi10adf352024-11-06 14:23:36 -0800335
336
337if __name__ == '__main__':
338 main(sys.argv[1:])