blob: 19f0a2c7aad18c768cec678e7ace2502f64fa773 [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'
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:
Luca Farsi1b9b6ed2024-12-04 03:47:03 -080090 try:
91 regex = r'\b(%s)\b' % re.escape(target)
92 if any(re.search(regex, opt) for opt in test_discovery_zip_regexes):
93 get_metrics_agent().report_unoptimized_target(target, 'Test artifact used.')
94 else:
95 get_metrics_agent().report_optimized_target(target)
96 except Exception as e:
97 logging.error(f'unable to parse test discovery output: {repr(e)}')
Luca Farsi5dbad402024-11-07 12:43:13 -080098
Luca Farsib24c1c32024-08-01 14:47:10 -070099 if self._unused_target_exclusion_enabled(
100 target
Luca Farsib130e792024-08-22 12:04:41 -0700101 ) and not self.build_context.build_target_used(target):
Luca Farsib24c1c32024-08-01 14:47:10 -0700102 continue
103
Luca Farsi040fabe2024-05-22 17:21:47 -0700104 target_optimizer_getter = self.target_optimizations.get(target, None)
105 if not target_optimizer_getter:
106 build_targets.add(target)
107 continue
108
109 target_optimizer = target_optimizer_getter(
110 target, self.build_context, self.args
111 )
112 build_targets.update(target_optimizer.get_build_targets())
Luca Farsi8ea67422024-09-17 15:48:11 -0700113 packaging_commands_getters.append(
114 target_optimizer.get_package_outputs_commands
115 )
Luca Farsi040fabe2024-05-22 17:21:47 -0700116
Luca Farsi8ea67422024-09-17 15:48:11 -0700117 return BuildPlan(build_targets, packaging_commands_getters)
Luca Farsidb136442024-03-26 10:55:21 -0700118
Luca Farsib24c1c32024-08-01 14:47:10 -0700119 def _unused_target_exclusion_enabled(self, target: str) -> bool:
Luca Farsib130e792024-08-22 12:04:41 -0700120 return (
121 f'{target}_unused_exclusion'
122 in self.build_context.enabled_build_features
Luca Farsib24c1c32024-08-01 14:47:10 -0700123 )
124
Luca Farsi5dbad402024-11-07 12:43:13 -0800125 def _get_test_discovery_zip_regexes(self) -> set[str]:
126 build_target_regexes = set()
127 for test_info in self.build_context.test_infos:
128 tf_command = self._build_tf_command(test_info)
129 discovery_agent = test_discovery_agent.TestDiscoveryAgent(tradefed_args=tf_command)
130 for regex in discovery_agent.discover_test_zip_regexes():
131 build_target_regexes.add(regex)
132 return build_target_regexes
133
134
135 def _build_tf_command(self, test_info) -> list[str]:
136 command = [test_info.command]
137 for extra_option in test_info.extra_options:
138 if not extra_option.get('key'):
139 continue
140 arg_key = '--' + extra_option.get('key')
141 if arg_key == '--build-id':
142 command.append(arg_key)
143 command.append(os.environ.get('BUILD_NUMBER'))
144 continue
145 if extra_option.get('values'):
146 for value in extra_option.get('values'):
147 command.append(arg_key)
148 command.append(value)
149 else:
150 command.append(arg_key)
151
152 return command
Luca Farsidb136442024-03-26 10:55:21 -0700153
Luca Farsi040fabe2024-05-22 17:21:47 -0700154@dataclass(frozen=True)
155class BuildPlan:
156 build_targets: set[str]
Luca Farsi8ea67422024-09-17 15:48:11 -0700157 packaging_commands_getters: list[Callable[[], list[list[str]]]]
Luca Farsidb136442024-03-26 10:55:21 -0700158
159
160def build_test_suites(argv: list[str]) -> int:
Luca Farsi040fabe2024-05-22 17:21:47 -0700161 """Builds all test suites passed in, optimizing based on the build_context content.
Luca Farsidb136442024-03-26 10:55:21 -0700162
163 Args:
164 argv: The command line arguments passed in.
165
166 Returns:
167 The exit code of the build.
168 """
Luca Farsi7d859712024-11-06 16:09:16 -0800169 get_metrics_agent().analysis_start()
170 try:
171 args = parse_args(argv)
172 check_required_env()
173 build_context = BuildContext(load_build_context())
174 build_planner = BuildPlanner(
175 build_context, args, optimized_targets.OPTIMIZED_BUILD_TARGETS
176 )
177 build_plan = build_planner.create_build_plan()
178 except:
179 raise
180 finally:
181 get_metrics_agent().analysis_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800182
Luca Farsidb136442024-03-26 10:55:21 -0700183 try:
Luca Farsi040fabe2024-05-22 17:21:47 -0700184 execute_build_plan(build_plan)
Luca Farsidb136442024-03-26 10:55:21 -0700185 except BuildFailureError as e:
186 logging.error('Build command failed! Check build_log for details.')
187 return e.return_code
Luca Farsi7d859712024-11-06 16:09:16 -0800188 finally:
189 get_metrics_agent().end_reporting()
Luca Farsidb136442024-03-26 10:55:21 -0700190
191 return 0
192
193
Luca Farsi040fabe2024-05-22 17:21:47 -0700194def parse_args(argv: list[str]) -> argparse.Namespace:
195 argparser = argparse.ArgumentParser()
196
197 argparser.add_argument(
198 'extra_targets', nargs='*', help='Extra test suites to build.'
199 )
Luca Farsi62035d92024-11-25 18:21:45 +0000200 argparser.add_argument(
201 '--device-build',
202 action='store_true',
203 help='Flag to indicate running a device build.',
204 )
Luca Farsi040fabe2024-05-22 17:21:47 -0700205
206 return argparser.parse_args(argv)
207
208
Luca Farsidb136442024-03-26 10:55:21 -0700209def check_required_env():
210 """Check for required env vars.
211
212 Raises:
213 RuntimeError: If any required env vars are not found.
214 """
215 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
216
217 if not missing_env_vars:
218 return
219
220 t = ','.join(missing_env_vars)
221 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800222
223
Luca Farsi040fabe2024-05-22 17:21:47 -0700224def load_build_context():
225 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
226 if build_context_path.is_file():
227 try:
228 with open(build_context_path, 'r') as f:
229 return json.load(f)
230 except json.decoder.JSONDecodeError as e:
231 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700232
Luca Farsi040fabe2024-05-22 17:21:47 -0700233 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
234 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800235
236
Luca Farsi040fabe2024-05-22 17:21:47 -0700237def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700238 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700239
Luca Farsidb136442024-03-26 10:55:21 -0700240
Luca Farsi040fabe2024-05-22 17:21:47 -0700241def execute_build_plan(build_plan: BuildPlan):
242 build_command = []
243 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
244 build_command.append('--make-mode')
245 build_command.extend(build_plan.build_targets)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800246
Luca Farsidb136442024-03-26 10:55:21 -0700247 try:
248 run_command(build_command)
249 except subprocess.CalledProcessError as e:
250 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800251
Luca Farsi7d859712024-11-06 16:09:16 -0800252 get_metrics_agent().packaging_start()
253 try:
254 for packaging_commands_getter in build_plan.packaging_commands_getters:
Luca Farsi8ea67422024-09-17 15:48:11 -0700255 for packaging_command in packaging_commands_getter():
256 run_command(packaging_command)
Luca Farsi7d859712024-11-06 16:09:16 -0800257 except subprocess.CalledProcessError as e:
258 raise BuildFailureError(e.returncode) from e
259 finally:
260 get_metrics_agent().packaging_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800261
Luca Farsidb136442024-03-26 10:55:21 -0700262
Luca Farsi040fabe2024-05-22 17:21:47 -0700263def get_top() -> pathlib.Path:
264 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800265
266
Luca Farsidb136442024-03-26 10:55:21 -0700267def run_command(args: list[str], stdout=None):
268 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800269
270
Luca Farsi7d859712024-11-06 16:09:16 -0800271def get_metrics_agent():
272 return metrics_agent.MetricsAgent.instance()
273
274
Luca Farsi2dc17012024-03-19 16:47:54 -0700275def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700276 dist_dir = os.environ.get('DIST_DIR')
277 if dist_dir:
278 log_file = pathlib.Path(dist_dir) / LOG_PATH
279 logging.basicConfig(
280 level=logging.DEBUG,
281 format='%(asctime)s %(levelname)s %(message)s',
282 filename=log_file,
283 )
Luca Farsidb136442024-03-26 10:55:21 -0700284 sys.exit(build_test_suites(argv))
Luca Farsi10adf352024-11-06 14:23:36 -0800285
286
287if __name__ == '__main__':
288 main(sys.argv[1:])