blob: 91cb6215c08622d293bc43aeb614a86a57636c60 [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
132
133 regex = r'\b(%s.*)\b' % re.escape(target)
134 for opt in test_discovery_zip_regexes:
135 try:
136 if re.search(regex, opt):
137 get_metrics_agent().report_unoptimized_target(target, 'Test artifact used.')
138 build_targets.add(target)
Julien Despreze3879332024-12-17 17:03:57 -0800139 # proceed to next target evaluation
140 break
Luca Farsi26c0d8a2024-11-22 00:09:47 +0000141 get_metrics_agent().report_optimized_target(target)
142 except Exception as e:
143 # In case of exception report as unoptimized
144 build_targets.add(target)
145 get_metrics_agent().report_unoptimized_target(target, f'Error in parsing test discovery output for {target}: {repr(e)}')
146 logging.error(f'unable to parse test discovery output: {repr(e)}')
Julien Despreze3879332024-12-17 17:03:57 -0800147 break
Julien Desprez254daef2024-12-19 10:04:43 -0800148 # If discovery is not enabled, return the original list
149 if not enable_discovery:
150 return self._legacy_collect_preliminary_build_targets()
Luca Farsi26c0d8a2024-11-22 00:09:47 +0000151
152 return build_targets
153
154 def _legacy_collect_preliminary_build_targets(self):
155 build_targets = set()
156 for target in self.args.extra_targets:
157 if self._unused_target_exclusion_enabled(
158 target
159 ) and not self.build_context.build_target_used(target):
160 continue
161
162 build_targets.add(target)
163 return build_targets
164
Luca Farsib24c1c32024-08-01 14:47:10 -0700165 def _unused_target_exclusion_enabled(self, target: str) -> bool:
Luca Farsib130e792024-08-22 12:04:41 -0700166 return (
167 f'{target}_unused_exclusion'
168 in self.build_context.enabled_build_features
Luca Farsib24c1c32024-08-01 14:47:10 -0700169 )
170
Luca Farsi5dbad402024-11-07 12:43:13 -0800171 def _get_test_discovery_zip_regexes(self) -> set[str]:
172 build_target_regexes = set()
173 for test_info in self.build_context.test_infos:
174 tf_command = self._build_tf_command(test_info)
175 discovery_agent = test_discovery_agent.TestDiscoveryAgent(tradefed_args=tf_command)
176 for regex in discovery_agent.discover_test_zip_regexes():
177 build_target_regexes.add(regex)
178 return build_target_regexes
179
180
181 def _build_tf_command(self, test_info) -> list[str]:
182 command = [test_info.command]
183 for extra_option in test_info.extra_options:
184 if not extra_option.get('key'):
185 continue
186 arg_key = '--' + extra_option.get('key')
187 if arg_key == '--build-id':
188 command.append(arg_key)
189 command.append(os.environ.get('BUILD_NUMBER'))
190 continue
191 if extra_option.get('values'):
192 for value in extra_option.get('values'):
193 command.append(arg_key)
194 command.append(value)
195 else:
196 command.append(arg_key)
197
198 return command
Luca Farsidb136442024-03-26 10:55:21 -0700199
Luca Farsi040fabe2024-05-22 17:21:47 -0700200@dataclass(frozen=True)
201class BuildPlan:
202 build_targets: set[str]
Luca Farsi8ea67422024-09-17 15:48:11 -0700203 packaging_commands_getters: list[Callable[[], list[list[str]]]]
Luca Farsidb136442024-03-26 10:55:21 -0700204
205
206def build_test_suites(argv: list[str]) -> int:
Luca Farsi040fabe2024-05-22 17:21:47 -0700207 """Builds all test suites passed in, optimizing based on the build_context content.
Luca Farsidb136442024-03-26 10:55:21 -0700208
209 Args:
210 argv: The command line arguments passed in.
211
212 Returns:
213 The exit code of the build.
214 """
Luca Farsi7d859712024-11-06 16:09:16 -0800215 get_metrics_agent().analysis_start()
216 try:
217 args = parse_args(argv)
218 check_required_env()
219 build_context = BuildContext(load_build_context())
220 build_planner = BuildPlanner(
221 build_context, args, optimized_targets.OPTIMIZED_BUILD_TARGETS
222 )
223 build_plan = build_planner.create_build_plan()
224 except:
225 raise
226 finally:
227 get_metrics_agent().analysis_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800228
Luca Farsidb136442024-03-26 10:55:21 -0700229 try:
Luca Farsi040fabe2024-05-22 17:21:47 -0700230 execute_build_plan(build_plan)
Luca Farsidb136442024-03-26 10:55:21 -0700231 except BuildFailureError as e:
232 logging.error('Build command failed! Check build_log for details.')
233 return e.return_code
Luca Farsi7d859712024-11-06 16:09:16 -0800234 finally:
235 get_metrics_agent().end_reporting()
Luca Farsidb136442024-03-26 10:55:21 -0700236
237 return 0
238
239
Luca Farsi040fabe2024-05-22 17:21:47 -0700240def parse_args(argv: list[str]) -> argparse.Namespace:
241 argparser = argparse.ArgumentParser()
242
243 argparser.add_argument(
244 'extra_targets', nargs='*', help='Extra test suites to build.'
245 )
Luca Farsi62035d92024-11-25 18:21:45 +0000246 argparser.add_argument(
247 '--device-build',
248 action='store_true',
249 help='Flag to indicate running a device build.',
250 )
Luca Farsi040fabe2024-05-22 17:21:47 -0700251
252 return argparser.parse_args(argv)
253
254
Luca Farsidb136442024-03-26 10:55:21 -0700255def check_required_env():
256 """Check for required env vars.
257
258 Raises:
259 RuntimeError: If any required env vars are not found.
260 """
261 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
262
263 if not missing_env_vars:
264 return
265
266 t = ','.join(missing_env_vars)
267 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800268
269
Luca Farsi040fabe2024-05-22 17:21:47 -0700270def load_build_context():
271 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
272 if build_context_path.is_file():
273 try:
274 with open(build_context_path, 'r') as f:
275 return json.load(f)
276 except json.decoder.JSONDecodeError as e:
277 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700278
Luca Farsi040fabe2024-05-22 17:21:47 -0700279 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
280 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800281
282
Luca Farsi040fabe2024-05-22 17:21:47 -0700283def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700284 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700285
Luca Farsidb136442024-03-26 10:55:21 -0700286
Luca Farsi040fabe2024-05-22 17:21:47 -0700287def execute_build_plan(build_plan: BuildPlan):
288 build_command = []
289 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
290 build_command.append('--make-mode')
291 build_command.extend(build_plan.build_targets)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800292
Luca Farsidb136442024-03-26 10:55:21 -0700293 try:
294 run_command(build_command)
295 except subprocess.CalledProcessError as e:
296 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800297
Luca Farsi7d859712024-11-06 16:09:16 -0800298 get_metrics_agent().packaging_start()
299 try:
300 for packaging_commands_getter in build_plan.packaging_commands_getters:
Luca Farsi8ea67422024-09-17 15:48:11 -0700301 for packaging_command in packaging_commands_getter():
302 run_command(packaging_command)
Luca Farsi7d859712024-11-06 16:09:16 -0800303 except subprocess.CalledProcessError as e:
304 raise BuildFailureError(e.returncode) from e
305 finally:
306 get_metrics_agent().packaging_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800307
Luca Farsidb136442024-03-26 10:55:21 -0700308
Luca Farsi040fabe2024-05-22 17:21:47 -0700309def get_top() -> pathlib.Path:
310 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800311
312
Luca Farsidb136442024-03-26 10:55:21 -0700313def run_command(args: list[str], stdout=None):
314 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800315
316
Luca Farsi7d859712024-11-06 16:09:16 -0800317def get_metrics_agent():
318 return metrics_agent.MetricsAgent.instance()
319
320
Luca Farsi2dc17012024-03-19 16:47:54 -0700321def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700322 dist_dir = os.environ.get('DIST_DIR')
323 if dist_dir:
324 log_file = pathlib.Path(dist_dir) / LOG_PATH
325 logging.basicConfig(
326 level=logging.DEBUG,
327 format='%(asctime)s %(levelname)s %(message)s',
328 filename=log_file,
329 )
Luca Farsidb136442024-03-26 10:55:21 -0700330 sys.exit(build_test_suites(argv))
Luca Farsi10adf352024-11-06 14:23:36 -0800331
332
333if __name__ == '__main__':
334 main(sys.argv[1:])