Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 1 | # 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 Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 15 | """Build script for the CI `test_suites` target.""" |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 16 | |
| 17 | import argparse |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 18 | from dataclasses import dataclass |
| 19 | import json |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 20 | import logging |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 21 | import os |
| 22 | import pathlib |
Luca Farsi | 5dbad40 | 2024-11-07 12:43:13 -0800 | [diff] [blame] | 23 | import re |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 24 | import subprocess |
| 25 | import sys |
Luca Farsi | 8ea6742 | 2024-09-17 15:48:11 -0700 | [diff] [blame] | 26 | from typing import Callable |
Luca Farsi | b130e79 | 2024-08-22 12:04:41 -0700 | [diff] [blame] | 27 | from build_context import BuildContext |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 28 | import optimized_targets |
Luca Farsi | 7d85971 | 2024-11-06 16:09:16 -0800 | [diff] [blame] | 29 | import metrics_agent |
Luca Farsi | 5dbad40 | 2024-11-07 12:43:13 -0800 | [diff] [blame] | 30 | import test_discovery_agent |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 31 | |
| 32 | |
| 33 | REQUIRED_ENV_VARS = frozenset(['TARGET_PRODUCT', 'TARGET_RELEASE', 'TOP']) |
| 34 | SOONG_UI_EXE_REL_PATH = 'build/soong/soong_ui.bash' |
Luca Farsi | 2eaa5d0 | 2024-07-23 16:34:27 -0700 | [diff] [blame] | 35 | LOG_PATH = 'logs/build_test_suites.log' |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 36 | |
| 37 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 38 | class Error(Exception): |
| 39 | |
| 40 | def __init__(self, message): |
| 41 | super().__init__(message) |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 42 | |
| 43 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 44 | class 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 Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 51 | class 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 Farsi | b130e79 | 2024-08-22 12:04:41 -0700 | [diff] [blame] | 61 | build_context: BuildContext, |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 62 | 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 Farsi | b130e79 | 2024-08-22 12:04:41 -0700 | [diff] [blame] | 71 | if 'optimized_build' not in self.build_context.enabled_build_features: |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 72 | return BuildPlan(set(self.args.extra_targets), set()) |
| 73 | |
| 74 | build_targets = set() |
Luca Farsi | 8ea6742 | 2024-09-17 15:48:11 -0700 | [diff] [blame] | 75 | packaging_commands_getters = [] |
Luca Farsi | 5dbad40 | 2024-11-07 12:43:13 -0800 | [diff] [blame] | 76 | 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 Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 86 | for target in self.args.extra_targets: |
Luca Farsi | 5dbad40 | 2024-11-07 12:43:13 -0800 | [diff] [blame] | 87 | if optimization_rationale: |
| 88 | get_metrics_agent().report_unoptimized_target(target, optimization_rationale) |
| 89 | else: |
Luca Farsi | 1b9b6ed | 2024-12-04 03:47:03 -0800 | [diff] [blame] | 90 | 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 Farsi | 5dbad40 | 2024-11-07 12:43:13 -0800 | [diff] [blame] | 98 | |
Luca Farsi | b24c1c3 | 2024-08-01 14:47:10 -0700 | [diff] [blame] | 99 | if self._unused_target_exclusion_enabled( |
| 100 | target |
Luca Farsi | b130e79 | 2024-08-22 12:04:41 -0700 | [diff] [blame] | 101 | ) and not self.build_context.build_target_used(target): |
Luca Farsi | b24c1c3 | 2024-08-01 14:47:10 -0700 | [diff] [blame] | 102 | continue |
| 103 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 104 | 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 Farsi | 8ea6742 | 2024-09-17 15:48:11 -0700 | [diff] [blame] | 113 | packaging_commands_getters.append( |
| 114 | target_optimizer.get_package_outputs_commands |
| 115 | ) |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 116 | |
Luca Farsi | 8ea6742 | 2024-09-17 15:48:11 -0700 | [diff] [blame] | 117 | return BuildPlan(build_targets, packaging_commands_getters) |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 118 | |
Luca Farsi | b24c1c3 | 2024-08-01 14:47:10 -0700 | [diff] [blame] | 119 | def _unused_target_exclusion_enabled(self, target: str) -> bool: |
Luca Farsi | b130e79 | 2024-08-22 12:04:41 -0700 | [diff] [blame] | 120 | return ( |
| 121 | f'{target}_unused_exclusion' |
| 122 | in self.build_context.enabled_build_features |
Luca Farsi | b24c1c3 | 2024-08-01 14:47:10 -0700 | [diff] [blame] | 123 | ) |
| 124 | |
Luca Farsi | 5dbad40 | 2024-11-07 12:43:13 -0800 | [diff] [blame] | 125 | 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 Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 153 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 154 | @dataclass(frozen=True) |
| 155 | class BuildPlan: |
| 156 | build_targets: set[str] |
Luca Farsi | 8ea6742 | 2024-09-17 15:48:11 -0700 | [diff] [blame] | 157 | packaging_commands_getters: list[Callable[[], list[list[str]]]] |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 158 | |
| 159 | |
| 160 | def build_test_suites(argv: list[str]) -> int: |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 161 | """Builds all test suites passed in, optimizing based on the build_context content. |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 162 | |
| 163 | Args: |
| 164 | argv: The command line arguments passed in. |
| 165 | |
| 166 | Returns: |
| 167 | The exit code of the build. |
| 168 | """ |
Luca Farsi | 7d85971 | 2024-11-06 16:09:16 -0800 | [diff] [blame] | 169 | 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 Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 182 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 183 | try: |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 184 | execute_build_plan(build_plan) |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 185 | except BuildFailureError as e: |
| 186 | logging.error('Build command failed! Check build_log for details.') |
| 187 | return e.return_code |
Luca Farsi | 7d85971 | 2024-11-06 16:09:16 -0800 | [diff] [blame] | 188 | finally: |
| 189 | get_metrics_agent().end_reporting() |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 190 | |
| 191 | return 0 |
| 192 | |
| 193 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 194 | def 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 | ) |
| 200 | |
| 201 | return argparser.parse_args(argv) |
| 202 | |
| 203 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 204 | def check_required_env(): |
| 205 | """Check for required env vars. |
| 206 | |
| 207 | Raises: |
| 208 | RuntimeError: If any required env vars are not found. |
| 209 | """ |
| 210 | missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ) |
| 211 | |
| 212 | if not missing_env_vars: |
| 213 | return |
| 214 | |
| 215 | t = ','.join(missing_env_vars) |
| 216 | raise Error(f'Missing required environment variables: {t}') |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 217 | |
| 218 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 219 | def load_build_context(): |
| 220 | build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', '')) |
| 221 | if build_context_path.is_file(): |
| 222 | try: |
| 223 | with open(build_context_path, 'r') as f: |
| 224 | return json.load(f) |
| 225 | except json.decoder.JSONDecodeError as e: |
| 226 | raise Error(f'Failed to load JSON file: {build_context_path}') |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 227 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 228 | logging.info('No BUILD_CONTEXT found, skipping optimizations.') |
| 229 | return empty_build_context() |
Luca Farsi | 11767d5 | 2024-03-07 13:33:57 -0800 | [diff] [blame] | 230 | |
| 231 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 232 | def empty_build_context(): |
Luca Farsi | b24c1c3 | 2024-08-01 14:47:10 -0700 | [diff] [blame] | 233 | return {'enabledBuildFeatures': []} |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 234 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 235 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 236 | def execute_build_plan(build_plan: BuildPlan): |
| 237 | build_command = [] |
| 238 | build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH)) |
| 239 | build_command.append('--make-mode') |
| 240 | build_command.extend(build_plan.build_targets) |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 241 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 242 | try: |
| 243 | run_command(build_command) |
| 244 | except subprocess.CalledProcessError as e: |
| 245 | raise BuildFailureError(e.returncode) from e |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 246 | |
Luca Farsi | 7d85971 | 2024-11-06 16:09:16 -0800 | [diff] [blame] | 247 | get_metrics_agent().packaging_start() |
| 248 | try: |
| 249 | for packaging_commands_getter in build_plan.packaging_commands_getters: |
Luca Farsi | 8ea6742 | 2024-09-17 15:48:11 -0700 | [diff] [blame] | 250 | for packaging_command in packaging_commands_getter(): |
| 251 | run_command(packaging_command) |
Luca Farsi | 7d85971 | 2024-11-06 16:09:16 -0800 | [diff] [blame] | 252 | except subprocess.CalledProcessError as e: |
| 253 | raise BuildFailureError(e.returncode) from e |
| 254 | finally: |
| 255 | get_metrics_agent().packaging_end() |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 256 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 257 | |
Luca Farsi | 040fabe | 2024-05-22 17:21:47 -0700 | [diff] [blame] | 258 | def get_top() -> pathlib.Path: |
| 259 | return pathlib.Path(os.environ['TOP']) |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 260 | |
| 261 | |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 262 | def run_command(args: list[str], stdout=None): |
| 263 | subprocess.run(args=args, check=True, stdout=stdout) |
Luca Farsi | 5717d6f | 2023-12-28 15:09:28 -0800 | [diff] [blame] | 264 | |
| 265 | |
Luca Farsi | 7d85971 | 2024-11-06 16:09:16 -0800 | [diff] [blame] | 266 | def get_metrics_agent(): |
| 267 | return metrics_agent.MetricsAgent.instance() |
| 268 | |
| 269 | |
Luca Farsi | 2dc1701 | 2024-03-19 16:47:54 -0700 | [diff] [blame] | 270 | def main(argv): |
Luca Farsi | 2eaa5d0 | 2024-07-23 16:34:27 -0700 | [diff] [blame] | 271 | dist_dir = os.environ.get('DIST_DIR') |
| 272 | if dist_dir: |
| 273 | log_file = pathlib.Path(dist_dir) / LOG_PATH |
| 274 | logging.basicConfig( |
| 275 | level=logging.DEBUG, |
| 276 | format='%(asctime)s %(levelname)s %(message)s', |
| 277 | filename=log_file, |
| 278 | ) |
Luca Farsi | db13644 | 2024-03-26 10:55:21 -0700 | [diff] [blame] | 279 | sys.exit(build_test_suites(argv)) |
Luca Farsi | 10adf35 | 2024-11-06 14:23:36 -0800 | [diff] [blame] | 280 | |
| 281 | |
| 282 | if __name__ == '__main__': |
| 283 | main(sys.argv[1:]) |