blob: deb1f1d0fbec7c31f2d86bd33e21abbf27431c8e [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 Farsib24c1c32024-08-01 14:47:10 -070023import re
Luca Farsi5717d6f2023-12-28 15:09:28 -080024import subprocess
25import sys
Luca Farsi040fabe2024-05-22 17:21:47 -070026from typing import Callable
27import optimized_targets
28
29
30REQUIRED_ENV_VARS = frozenset(['TARGET_PRODUCT', 'TARGET_RELEASE', 'TOP'])
31SOONG_UI_EXE_REL_PATH = 'build/soong/soong_ui.bash'
Luca Farsi2eaa5d02024-07-23 16:34:27 -070032LOG_PATH = 'logs/build_test_suites.log'
Luca Farsi5717d6f2023-12-28 15:09:28 -080033
34
Luca Farsidb136442024-03-26 10:55:21 -070035class Error(Exception):
36
37 def __init__(self, message):
38 super().__init__(message)
Luca Farsi5717d6f2023-12-28 15:09:28 -080039
40
Luca Farsidb136442024-03-26 10:55:21 -070041class BuildFailureError(Error):
42
43 def __init__(self, return_code):
44 super().__init__(f'Build command failed with return code: f{return_code}')
45 self.return_code = return_code
46
47
Luca Farsi040fabe2024-05-22 17:21:47 -070048class BuildPlanner:
49 """Class in charge of determining how to optimize build targets.
50
51 Given the build context and targets to build it will determine a final list of
52 targets to build along with getting a set of packaging functions to package up
53 any output zip files needed by the build.
54 """
55
Luca Farsib24c1c32024-08-01 14:47:10 -070056 _DOWNLOAD_OPTS = {
57 'test-config-only-zip',
58 'test-zip-file-filter',
59 'extra-host-shared-lib-zip',
60 'sandbox-tests-zips',
61 'additional-files-filter',
62 'cts-package-name',
63 }
64
Luca Farsi040fabe2024-05-22 17:21:47 -070065 def __init__(
66 self,
67 build_context: dict[str, any],
68 args: argparse.Namespace,
69 target_optimizations: dict[str, optimized_targets.OptimizedBuildTarget],
70 ):
71 self.build_context = build_context
72 self.args = args
73 self.target_optimizations = target_optimizations
74
75 def create_build_plan(self):
76
Luca Farsib24c1c32024-08-01 14:47:10 -070077 if 'optimized_build' not in self.build_context.get(
78 'enabledBuildFeatures', []
79 ):
Luca Farsi040fabe2024-05-22 17:21:47 -070080 return BuildPlan(set(self.args.extra_targets), set())
81
82 build_targets = set()
83 packaging_functions = set()
Luca Farsi99d40d72024-08-06 13:35:28 -070084 self.file_download_options = self._aggregate_file_download_options()
Luca Farsi040fabe2024-05-22 17:21:47 -070085 for target in self.args.extra_targets:
Luca Farsib24c1c32024-08-01 14:47:10 -070086 if self._unused_target_exclusion_enabled(
87 target
88 ) and not self._build_target_used(target):
89 continue
90
Luca Farsi040fabe2024-05-22 17:21:47 -070091 target_optimizer_getter = self.target_optimizations.get(target, None)
92 if not target_optimizer_getter:
93 build_targets.add(target)
94 continue
95
96 target_optimizer = target_optimizer_getter(
97 target, self.build_context, self.args
98 )
99 build_targets.update(target_optimizer.get_build_targets())
100 packaging_functions.add(target_optimizer.package_outputs)
101
102 return BuildPlan(build_targets, packaging_functions)
Luca Farsidb136442024-03-26 10:55:21 -0700103
Luca Farsib24c1c32024-08-01 14:47:10 -0700104 def _unused_target_exclusion_enabled(self, target: str) -> bool:
105 return f'{target}_unused_exclusion' in self.build_context.get(
106 'enabledBuildFeatures', []
107 )
108
109 def _build_target_used(self, target: str) -> bool:
110 """Determines whether this target's outputs are used by the test configurations listed in the build context."""
Luca Farsib24c1c32024-08-01 14:47:10 -0700111 # For all of a targets' outputs, check if any of the regexes used by tests
112 # to download artifacts would match it. If any of them do then this target
113 # is necessary.
Luca Farsi99d40d72024-08-06 13:35:28 -0700114 regex = r'\b(%s)\b' % re.escape(target)
115 return any(re.search(regex, opt) for opt in self.file_download_options)
Luca Farsib24c1c32024-08-01 14:47:10 -0700116
Luca Farsi99d40d72024-08-06 13:35:28 -0700117 def _aggregate_file_download_options(self) -> set[str]:
Luca Farsib24c1c32024-08-01 14:47:10 -0700118 """Lists out all test config options to specify targets to download.
119
120 These come in the form of regexes.
121 """
Luca Farsi99d40d72024-08-06 13:35:28 -0700122 all_options = set()
Luca Farsib24c1c32024-08-01 14:47:10 -0700123 for test_info in self._get_test_infos():
124 for opt in test_info.get('extraOptions', []):
125 # check the known list of options for downloading files.
126 if opt.get('key') in self._DOWNLOAD_OPTS:
Luca Farsi99d40d72024-08-06 13:35:28 -0700127 all_options.update(opt.get('values', []))
128 return all_options
Luca Farsib24c1c32024-08-01 14:47:10 -0700129
130 def _get_test_infos(self):
131 return self.build_context.get('testContext', dict()).get('testInfos', [])
132
Luca Farsidb136442024-03-26 10:55:21 -0700133
Luca Farsi040fabe2024-05-22 17:21:47 -0700134@dataclass(frozen=True)
135class BuildPlan:
136 build_targets: set[str]
137 packaging_functions: set[Callable[..., None]]
Luca Farsidb136442024-03-26 10:55:21 -0700138
139
140def build_test_suites(argv: list[str]) -> int:
Luca Farsi040fabe2024-05-22 17:21:47 -0700141 """Builds all test suites passed in, optimizing based on the build_context content.
Luca Farsidb136442024-03-26 10:55:21 -0700142
143 Args:
144 argv: The command line arguments passed in.
145
146 Returns:
147 The exit code of the build.
148 """
Luca Farsi5717d6f2023-12-28 15:09:28 -0800149 args = parse_args(argv)
Luca Farsidb136442024-03-26 10:55:21 -0700150 check_required_env()
Luca Farsi040fabe2024-05-22 17:21:47 -0700151 build_context = load_build_context()
152 build_planner = BuildPlanner(
153 build_context, args, optimized_targets.OPTIMIZED_BUILD_TARGETS
154 )
155 build_plan = build_planner.create_build_plan()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800156
Luca Farsidb136442024-03-26 10:55:21 -0700157 try:
Luca Farsi040fabe2024-05-22 17:21:47 -0700158 execute_build_plan(build_plan)
Luca Farsidb136442024-03-26 10:55:21 -0700159 except BuildFailureError as e:
160 logging.error('Build command failed! Check build_log for details.')
161 return e.return_code
162
163 return 0
164
165
Luca Farsi040fabe2024-05-22 17:21:47 -0700166def parse_args(argv: list[str]) -> argparse.Namespace:
167 argparser = argparse.ArgumentParser()
168
169 argparser.add_argument(
170 'extra_targets', nargs='*', help='Extra test suites to build.'
171 )
172
173 return argparser.parse_args(argv)
174
175
Luca Farsidb136442024-03-26 10:55:21 -0700176def check_required_env():
177 """Check for required env vars.
178
179 Raises:
180 RuntimeError: If any required env vars are not found.
181 """
182 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
183
184 if not missing_env_vars:
185 return
186
187 t = ','.join(missing_env_vars)
188 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800189
190
Luca Farsi040fabe2024-05-22 17:21:47 -0700191def load_build_context():
192 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
193 if build_context_path.is_file():
194 try:
195 with open(build_context_path, 'r') as f:
196 return json.load(f)
197 except json.decoder.JSONDecodeError as e:
198 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700199
Luca Farsi040fabe2024-05-22 17:21:47 -0700200 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
201 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800202
203
Luca Farsi040fabe2024-05-22 17:21:47 -0700204def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700205 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700206
Luca Farsidb136442024-03-26 10:55:21 -0700207
Luca Farsi040fabe2024-05-22 17:21:47 -0700208def execute_build_plan(build_plan: BuildPlan):
209 build_command = []
210 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
211 build_command.append('--make-mode')
212 build_command.extend(build_plan.build_targets)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800213
Luca Farsidb136442024-03-26 10:55:21 -0700214 try:
215 run_command(build_command)
216 except subprocess.CalledProcessError as e:
217 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800218
Luca Farsi040fabe2024-05-22 17:21:47 -0700219 for packaging_function in build_plan.packaging_functions:
220 packaging_function()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800221
Luca Farsidb136442024-03-26 10:55:21 -0700222
Luca Farsi040fabe2024-05-22 17:21:47 -0700223def get_top() -> pathlib.Path:
224 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800225
226
Luca Farsidb136442024-03-26 10:55:21 -0700227def run_command(args: list[str], stdout=None):
228 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800229
230
Luca Farsi2dc17012024-03-19 16:47:54 -0700231def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700232 dist_dir = os.environ.get('DIST_DIR')
233 if dist_dir:
234 log_file = pathlib.Path(dist_dir) / LOG_PATH
235 logging.basicConfig(
236 level=logging.DEBUG,
237 format='%(asctime)s %(levelname)s %(message)s',
238 filename=log_file,
239 )
Luca Farsidb136442024-03-26 10:55:21 -0700240 sys.exit(build_test_suites(argv))