blob: 75dd9f2f70b361d1f0a95a9d4c450e8bb7fd0c41 [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()
84 for target in self.args.extra_targets:
Luca Farsib24c1c32024-08-01 14:47:10 -070085 if self._unused_target_exclusion_enabled(
86 target
87 ) and not self._build_target_used(target):
88 continue
89
Luca Farsi040fabe2024-05-22 17:21:47 -070090 target_optimizer_getter = self.target_optimizations.get(target, None)
91 if not target_optimizer_getter:
92 build_targets.add(target)
93 continue
94
95 target_optimizer = target_optimizer_getter(
96 target, self.build_context, self.args
97 )
98 build_targets.update(target_optimizer.get_build_targets())
99 packaging_functions.add(target_optimizer.package_outputs)
100
101 return BuildPlan(build_targets, packaging_functions)
Luca Farsidb136442024-03-26 10:55:21 -0700102
Luca Farsib24c1c32024-08-01 14:47:10 -0700103 def _unused_target_exclusion_enabled(self, target: str) -> bool:
104 return f'{target}_unused_exclusion' in self.build_context.get(
105 'enabledBuildFeatures', []
106 )
107
108 def _build_target_used(self, target: str) -> bool:
109 """Determines whether this target's outputs are used by the test configurations listed in the build context."""
110 file_download_regexes = self._aggregate_file_download_regexes()
111 # 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.
114 for artifact in self._get_target_potential_outputs(target):
115 for regex in file_download_regexes:
116 if re.match(regex, artifact):
117 return True
118 return False
119
120 def _get_target_potential_outputs(self, target: str) -> set[str]:
121 tests_suffix = '-tests'
122 if target.endswith('tests'):
123 tests_suffix = ''
124 # This is a list of all the potential zips output by the test suite targets.
125 # If the test downloads artifacts from any of these zips, we will be
126 # conservative and avoid skipping the tests.
127 return {
128 f'{target}.zip',
129 f'android-{target}.zip',
130 f'android-{target}-verifier.zip',
131 f'{target}{tests_suffix}_list.zip',
132 f'android-{target}{tests_suffix}_list.zip',
133 f'{target}{tests_suffix}_host-shared-libs.zip',
134 f'android-{target}{tests_suffix}_host-shared-libs.zip',
135 f'{target}{tests_suffix}_configs.zip',
136 f'android-{target}{tests_suffix}_configs.zip',
137 }
138
139 def _aggregate_file_download_regexes(self) -> set[re.Pattern]:
140 """Lists out all test config options to specify targets to download.
141
142 These come in the form of regexes.
143 """
144 all_regexes = set()
145 for test_info in self._get_test_infos():
146 for opt in test_info.get('extraOptions', []):
147 # check the known list of options for downloading files.
148 if opt.get('key') in self._DOWNLOAD_OPTS:
149 all_regexes.update(
150 re.compile(value) for value in opt.get('values', [])
151 )
152 return all_regexes
153
154 def _get_test_infos(self):
155 return self.build_context.get('testContext', dict()).get('testInfos', [])
156
Luca Farsidb136442024-03-26 10:55:21 -0700157
Luca Farsi040fabe2024-05-22 17:21:47 -0700158@dataclass(frozen=True)
159class BuildPlan:
160 build_targets: set[str]
161 packaging_functions: set[Callable[..., None]]
Luca Farsidb136442024-03-26 10:55:21 -0700162
163
164def build_test_suites(argv: list[str]) -> int:
Luca Farsi040fabe2024-05-22 17:21:47 -0700165 """Builds all test suites passed in, optimizing based on the build_context content.
Luca Farsidb136442024-03-26 10:55:21 -0700166
167 Args:
168 argv: The command line arguments passed in.
169
170 Returns:
171 The exit code of the build.
172 """
Luca Farsi5717d6f2023-12-28 15:09:28 -0800173 args = parse_args(argv)
Luca Farsidb136442024-03-26 10:55:21 -0700174 check_required_env()
Luca Farsi040fabe2024-05-22 17:21:47 -0700175 build_context = load_build_context()
176 build_planner = BuildPlanner(
177 build_context, args, optimized_targets.OPTIMIZED_BUILD_TARGETS
178 )
179 build_plan = build_planner.create_build_plan()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800180
Luca Farsidb136442024-03-26 10:55:21 -0700181 try:
Luca Farsi040fabe2024-05-22 17:21:47 -0700182 execute_build_plan(build_plan)
Luca Farsidb136442024-03-26 10:55:21 -0700183 except BuildFailureError as e:
184 logging.error('Build command failed! Check build_log for details.')
185 return e.return_code
186
187 return 0
188
189
Luca Farsi040fabe2024-05-22 17:21:47 -0700190def parse_args(argv: list[str]) -> argparse.Namespace:
191 argparser = argparse.ArgumentParser()
192
193 argparser.add_argument(
194 'extra_targets', nargs='*', help='Extra test suites to build.'
195 )
196
197 return argparser.parse_args(argv)
198
199
Luca Farsidb136442024-03-26 10:55:21 -0700200def check_required_env():
201 """Check for required env vars.
202
203 Raises:
204 RuntimeError: If any required env vars are not found.
205 """
206 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
207
208 if not missing_env_vars:
209 return
210
211 t = ','.join(missing_env_vars)
212 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800213
214
Luca Farsi040fabe2024-05-22 17:21:47 -0700215def load_build_context():
216 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
217 if build_context_path.is_file():
218 try:
219 with open(build_context_path, 'r') as f:
220 return json.load(f)
221 except json.decoder.JSONDecodeError as e:
222 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700223
Luca Farsi040fabe2024-05-22 17:21:47 -0700224 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
225 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800226
227
Luca Farsi040fabe2024-05-22 17:21:47 -0700228def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700229 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700230
Luca Farsidb136442024-03-26 10:55:21 -0700231
Luca Farsi040fabe2024-05-22 17:21:47 -0700232def execute_build_plan(build_plan: BuildPlan):
233 build_command = []
234 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
235 build_command.append('--make-mode')
236 build_command.extend(build_plan.build_targets)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800237
Luca Farsidb136442024-03-26 10:55:21 -0700238 try:
239 run_command(build_command)
240 except subprocess.CalledProcessError as e:
241 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800242
Luca Farsi040fabe2024-05-22 17:21:47 -0700243 for packaging_function in build_plan.packaging_functions:
244 packaging_function()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800245
Luca Farsidb136442024-03-26 10:55:21 -0700246
Luca Farsi040fabe2024-05-22 17:21:47 -0700247def get_top() -> pathlib.Path:
248 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800249
250
Luca Farsidb136442024-03-26 10:55:21 -0700251def run_command(args: list[str], stdout=None):
252 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800253
254
Luca Farsi2dc17012024-03-19 16:47:54 -0700255def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700256 dist_dir = os.environ.get('DIST_DIR')
257 if dist_dir:
258 log_file = pathlib.Path(dist_dir) / LOG_PATH
259 logging.basicConfig(
260 level=logging.DEBUG,
261 format='%(asctime)s %(levelname)s %(message)s',
262 filename=log_file,
263 )
Luca Farsidb136442024-03-26 10:55:21 -0700264 sys.exit(build_test_suites(argv))