blob: 402880c6ac134ade0d07ebaffb95bd5f47482cfa [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
Luca Farsib130e792024-08-22 12:04:41 -070027from build_context import BuildContext
Luca Farsi040fabe2024-05-22 17:21:47 -070028import optimized_targets
29
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()
73 packaging_functions = set()
74 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())
89 packaging_functions.add(target_optimizer.package_outputs)
90
91 return BuildPlan(build_targets, packaging_functions)
Luca Farsidb136442024-03-26 10:55:21 -070092
Luca Farsib24c1c32024-08-01 14:47:10 -070093 def _unused_target_exclusion_enabled(self, target: str) -> bool:
Luca Farsib130e792024-08-22 12:04:41 -070094 return (
95 f'{target}_unused_exclusion'
96 in self.build_context.enabled_build_features
Luca Farsib24c1c32024-08-01 14:47:10 -070097 )
98
Luca Farsidb136442024-03-26 10:55:21 -070099
Luca Farsi040fabe2024-05-22 17:21:47 -0700100@dataclass(frozen=True)
101class BuildPlan:
102 build_targets: set[str]
103 packaging_functions: set[Callable[..., None]]
Luca Farsidb136442024-03-26 10:55:21 -0700104
105
106def build_test_suites(argv: list[str]) -> int:
Luca Farsi040fabe2024-05-22 17:21:47 -0700107 """Builds all test suites passed in, optimizing based on the build_context content.
Luca Farsidb136442024-03-26 10:55:21 -0700108
109 Args:
110 argv: The command line arguments passed in.
111
112 Returns:
113 The exit code of the build.
114 """
Luca Farsi5717d6f2023-12-28 15:09:28 -0800115 args = parse_args(argv)
Luca Farsidb136442024-03-26 10:55:21 -0700116 check_required_env()
Luca Farsib130e792024-08-22 12:04:41 -0700117 build_context = BuildContext(load_build_context())
Luca Farsi040fabe2024-05-22 17:21:47 -0700118 build_planner = BuildPlanner(
119 build_context, args, optimized_targets.OPTIMIZED_BUILD_TARGETS
120 )
121 build_plan = build_planner.create_build_plan()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800122
Luca Farsidb136442024-03-26 10:55:21 -0700123 try:
Luca Farsi040fabe2024-05-22 17:21:47 -0700124 execute_build_plan(build_plan)
Luca Farsidb136442024-03-26 10:55:21 -0700125 except BuildFailureError as e:
126 logging.error('Build command failed! Check build_log for details.')
127 return e.return_code
128
129 return 0
130
131
Luca Farsi040fabe2024-05-22 17:21:47 -0700132def parse_args(argv: list[str]) -> argparse.Namespace:
133 argparser = argparse.ArgumentParser()
134
135 argparser.add_argument(
136 'extra_targets', nargs='*', help='Extra test suites to build.'
137 )
138
139 return argparser.parse_args(argv)
140
141
Luca Farsidb136442024-03-26 10:55:21 -0700142def check_required_env():
143 """Check for required env vars.
144
145 Raises:
146 RuntimeError: If any required env vars are not found.
147 """
148 missing_env_vars = sorted(v for v in REQUIRED_ENV_VARS if v not in os.environ)
149
150 if not missing_env_vars:
151 return
152
153 t = ','.join(missing_env_vars)
154 raise Error(f'Missing required environment variables: {t}')
Luca Farsi5717d6f2023-12-28 15:09:28 -0800155
156
Luca Farsi040fabe2024-05-22 17:21:47 -0700157def load_build_context():
158 build_context_path = pathlib.Path(os.environ.get('BUILD_CONTEXT', ''))
159 if build_context_path.is_file():
160 try:
161 with open(build_context_path, 'r') as f:
162 return json.load(f)
163 except json.decoder.JSONDecodeError as e:
164 raise Error(f'Failed to load JSON file: {build_context_path}')
Luca Farsidb136442024-03-26 10:55:21 -0700165
Luca Farsi040fabe2024-05-22 17:21:47 -0700166 logging.info('No BUILD_CONTEXT found, skipping optimizations.')
167 return empty_build_context()
Luca Farsi11767d52024-03-07 13:33:57 -0800168
169
Luca Farsi040fabe2024-05-22 17:21:47 -0700170def empty_build_context():
Luca Farsib24c1c32024-08-01 14:47:10 -0700171 return {'enabledBuildFeatures': []}
Luca Farsidb136442024-03-26 10:55:21 -0700172
Luca Farsidb136442024-03-26 10:55:21 -0700173
Luca Farsi040fabe2024-05-22 17:21:47 -0700174def execute_build_plan(build_plan: BuildPlan):
175 build_command = []
176 build_command.append(get_top().joinpath(SOONG_UI_EXE_REL_PATH))
177 build_command.append('--make-mode')
178 build_command.extend(build_plan.build_targets)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800179
Luca Farsidb136442024-03-26 10:55:21 -0700180 try:
181 run_command(build_command)
182 except subprocess.CalledProcessError as e:
183 raise BuildFailureError(e.returncode) from e
Luca Farsi5717d6f2023-12-28 15:09:28 -0800184
Luca Farsi040fabe2024-05-22 17:21:47 -0700185 for packaging_function in build_plan.packaging_functions:
186 packaging_function()
Luca Farsi5717d6f2023-12-28 15:09:28 -0800187
Luca Farsidb136442024-03-26 10:55:21 -0700188
Luca Farsi040fabe2024-05-22 17:21:47 -0700189def get_top() -> pathlib.Path:
190 return pathlib.Path(os.environ['TOP'])
Luca Farsi5717d6f2023-12-28 15:09:28 -0800191
192
Luca Farsidb136442024-03-26 10:55:21 -0700193def run_command(args: list[str], stdout=None):
194 subprocess.run(args=args, check=True, stdout=stdout)
Luca Farsi5717d6f2023-12-28 15:09:28 -0800195
196
Luca Farsi2dc17012024-03-19 16:47:54 -0700197def main(argv):
Luca Farsi2eaa5d02024-07-23 16:34:27 -0700198 dist_dir = os.environ.get('DIST_DIR')
199 if dist_dir:
200 log_file = pathlib.Path(dist_dir) / LOG_PATH
201 logging.basicConfig(
202 level=logging.DEBUG,
203 format='%(asctime)s %(levelname)s %(message)s',
204 filename=log_file,
205 )
Luca Farsidb136442024-03-26 10:55:21 -0700206 sys.exit(build_test_suites(argv))