blob: 7d76b9afdca7151df604a140f3889e7d5ac5129d [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 Farsi5717d6f2023-12-28 15:09:28 -080023import subprocess
24import sys
Luca Farsi8ea67422024-09-17 15:48:11 -070025from typing import Callable
Luca Farsib130e792024-08-22 12:04:41 -070026from build_context import BuildContext
Luca Farsi040fabe2024-05-22 17:21:47 -070027import optimized_targets
Luca Farsi7d859712024-11-06 16:09:16 -080028import metrics_agent
Luca Farsi040fabe2024-05-22 17:21:47 -070029
30
31REQUIRED_ENV_VARS = frozenset(['TARGET_PRODUCT', 'TARGET_RELEASE', 'TOP'])
32SOONG_UI_EXE_REL_PATH = 'build/soong/soong_ui.bash'
Luca Farsi2eaa5d02024-07-23 16:34:27 -070033LOG_PATH = 'logs/build_test_suites.log'
Luca Farsi5717d6f2023-12-28 15:09:28 -080034
35
Luca Farsidb136442024-03-26 10:55:21 -070036class Error(Exception):
37
38 def __init__(self, message):
39 super().__init__(message)
Luca Farsi5717d6f2023-12-28 15:09:28 -080040
41
Luca Farsidb136442024-03-26 10:55:21 -070042class BuildFailureError(Error):
43
44 def __init__(self, return_code):
45 super().__init__(f'Build command failed with return code: f{return_code}')
46 self.return_code = return_code
47
48
Luca Farsi040fabe2024-05-22 17:21:47 -070049class BuildPlanner:
50 """Class in charge of determining how to optimize build targets.
51
52 Given the build context and targets to build it will determine a final list of
53 targets to build along with getting a set of packaging functions to package up
54 any output zip files needed by the build.
55 """
56
57 def __init__(
58 self,
Luca Farsib130e792024-08-22 12:04:41 -070059 build_context: BuildContext,
Luca Farsi040fabe2024-05-22 17:21:47 -070060 args: argparse.Namespace,
61 target_optimizations: dict[str, optimized_targets.OptimizedBuildTarget],
62 ):
63 self.build_context = build_context
64 self.args = args
65 self.target_optimizations = target_optimizations
66
67 def create_build_plan(self):
68
Luca Farsib130e792024-08-22 12:04:41 -070069 if 'optimized_build' not in self.build_context.enabled_build_features:
Luca Farsi040fabe2024-05-22 17:21:47 -070070 return BuildPlan(set(self.args.extra_targets), set())
71
72 build_targets = set()
Luca Farsi8ea67422024-09-17 15:48:11 -070073 packaging_commands_getters = []
Luca Farsi040fabe2024-05-22 17:21:47 -070074 for target in self.args.extra_targets:
Luca Farsib24c1c32024-08-01 14:47:10 -070075 if self._unused_target_exclusion_enabled(
76 target
Luca Farsib130e792024-08-22 12:04:41 -070077 ) and not self.build_context.build_target_used(target):
Luca Farsib24c1c32024-08-01 14:47:10 -070078 continue
79
Luca Farsi040fabe2024-05-22 17:21:47 -070080 target_optimizer_getter = self.target_optimizations.get(target, None)
81 if not target_optimizer_getter:
82 build_targets.add(target)
83 continue
84
85 target_optimizer = target_optimizer_getter(
86 target, self.build_context, self.args
87 )
88 build_targets.update(target_optimizer.get_build_targets())
Luca Farsi8ea67422024-09-17 15:48:11 -070089 packaging_commands_getters.append(
90 target_optimizer.get_package_outputs_commands
91 )
Luca Farsi040fabe2024-05-22 17:21:47 -070092
Luca Farsi8ea67422024-09-17 15:48:11 -070093 return BuildPlan(build_targets, packaging_commands_getters)
Luca Farsidb136442024-03-26 10:55:21 -070094
Luca Farsib24c1c32024-08-01 14:47:10 -070095 def _unused_target_exclusion_enabled(self, target: str) -> bool:
Luca Farsib130e792024-08-22 12:04:41 -070096 return (
97 f'{target}_unused_exclusion'
98 in self.build_context.enabled_build_features
Luca Farsib24c1c32024-08-01 14:47:10 -070099 )
100
Luca Farsidb136442024-03-26 10:55:21 -0700101
Luca Farsi040fabe2024-05-22 17:21:47 -0700102@dataclass(frozen=True)
103class BuildPlan:
104 build_targets: set[str]
Luca Farsi8ea67422024-09-17 15:48:11 -0700105 packaging_commands_getters: list[Callable[[], list[list[str]]]]
Luca Farsidb136442024-03-26 10:55:21 -0700106
107
108def build_test_suites(argv: list[str]) -> int:
Luca Farsi040fabe2024-05-22 17:21:47 -0700109 """Builds all test suites passed in, optimizing based on the build_context content.
Luca Farsidb136442024-03-26 10:55:21 -0700110
111 Args:
112 argv: The command line arguments passed in.
113
114 Returns:
115 The exit code of the build.
116 """
Luca Farsi7d859712024-11-06 16:09:16 -0800117 get_metrics_agent().analysis_start()
118 try:
119 args = parse_args(argv)
120 check_required_env()
121 build_context = BuildContext(load_build_context())
122 build_planner = BuildPlanner(
123 build_context, args, optimized_targets.OPTIMIZED_BUILD_TARGETS
124 )
125 build_plan = build_planner.create_build_plan()
126 except:
127 raise
128 finally:
129 get_metrics_agent().analysis_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800130
Luca Farsidb136442024-03-26 10:55:21 -0700131 try:
Luca Farsi040fabe2024-05-22 17:21:47 -0700132 execute_build_plan(build_plan)
Luca Farsidb136442024-03-26 10:55:21 -0700133 except BuildFailureError as e:
134 logging.error('Build command failed! Check build_log for details.')
135 return e.return_code
Luca Farsi7d859712024-11-06 16:09:16 -0800136 finally:
137 get_metrics_agent().end_reporting()
Luca Farsidb136442024-03-26 10:55:21 -0700138
139 return 0
140
141
Luca Farsi040fabe2024-05-22 17:21:47 -0700142def parse_args(argv: list[str]) -> argparse.Namespace:
143 argparser = argparse.ArgumentParser()
144
145 argparser.add_argument(
146 'extra_targets', nargs='*', help='Extra test suites to build.'
147 )
148
149 return argparser.parse_args(argv)
150
151
Luca Farsidb136442024-03-26 10:55:21 -0700152def check_required_env():
153 """Check for required env vars.
154
155 Raises:
156 RuntimeError: If any required env vars are not found.
157 """
158 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
159
160 if not missing_env_vars:
161 return
162
163 t = ','.join(missing_env_vars)
164 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800165
166
Luca Farsi040fabe2024-05-22 17:21:47 -0700167def load_build_context():
168 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
169 if build_context_path.is_file():
170 try:
171 with open(build_context_path, 'r') as f:
172 return json.load(f)
173 except json.decoder.JSONDecodeError as e:
174 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700175
Luca Farsi040fabe2024-05-22 17:21:47 -0700176 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
177 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800178
179
Luca Farsi040fabe2024-05-22 17:21:47 -0700180def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700181 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700182
Luca Farsidb136442024-03-26 10:55:21 -0700183
Luca Farsi040fabe2024-05-22 17:21:47 -0700184def execute_build_plan(build_plan: BuildPlan):
185 build_command = []
186 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
187 build_command.append('--make-mode')
188 build_command.extend(build_plan.build_targets)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800189
Luca Farsidb136442024-03-26 10:55:21 -0700190 try:
191 run_command(build_command)
192 except subprocess.CalledProcessError as e:
193 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800194
Luca Farsi7d859712024-11-06 16:09:16 -0800195 get_metrics_agent().packaging_start()
196 try:
197 for packaging_commands_getter in build_plan.packaging_commands_getters:
Luca Farsi8ea67422024-09-17 15:48:11 -0700198 for packaging_command in packaging_commands_getter():
199 run_command(packaging_command)
Luca Farsi7d859712024-11-06 16:09:16 -0800200 except subprocess.CalledProcessError as e:
201 raise BuildFailureError(e.returncode) from e
202 finally:
203 get_metrics_agent().packaging_end()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800204
Luca Farsidb136442024-03-26 10:55:21 -0700205
Luca Farsi040fabe2024-05-22 17:21:47 -0700206def get_top() -> pathlib.Path:
207 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800208
209
Luca Farsidb136442024-03-26 10:55:21 -0700210def run_command(args: list[str], stdout=None):
211 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800212
213
Luca Farsi7d859712024-11-06 16:09:16 -0800214def get_metrics_agent():
215 return metrics_agent.MetricsAgent.instance()
216
217
Luca Farsi2dc17012024-03-19 16:47:54 -0700218def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700219 dist_dir = os.environ.get('DIST_DIR')
220 if dist_dir:
221 log_file = pathlib.Path(dist_dir) / LOG_PATH
222 logging.basicConfig(
223 level=logging.DEBUG,
224 format='%(asctime)s %(levelname)s %(message)s',
225 filename=log_file,
226 )
Luca Farsidb136442024-03-26 10:55:21 -0700227 sys.exit(build_test_suites(argv))
Luca Farsi10adf352024-11-06 14:23:36 -0800228
229
230if __name__ == '__main__':
231 main(sys.argv[1:])