blob: 07acbb083d196f928fa76124cd7cb673db327dce [file] [log] [blame]
Alex Kleina9d500b2019-04-22 15:37:51 -06001# Copyright 2019 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Utility functions that are useful for controllers."""
Lizzy Presland29e62452022-01-05 21:58:21 +00006
7import glob
Alex Klein28e59a62021-09-09 15:45:14 -06008import logging
Lizzy Presland29e62452022-01-05 21:58:21 +00009import os
Kevin Sheltona8056362022-04-04 16:19:23 -070010from typing import Optional, TYPE_CHECKING, Union
Alex Kleina9d500b2019-04-22 15:37:51 -060011
Lizzy Presland4feb2372022-01-20 05:16:30 +000012from chromite.api.gen.chromite.api import sysroot_pb2, test_pb2
Alex Klein1f67cf32019-10-09 11:13:42 -060013from chromite.api.gen.chromiumos import common_pb2
Alex Klein26e472b2020-03-10 14:35:01 -060014from chromite.lib import build_target_lib
Alex Klein18a60af2020-06-11 12:08:47 -060015from chromite.lib import constants
16from chromite.lib.parser import package_info
George Engelbrecht35b6e8d2021-06-18 09:43:28 -060017from chromite.lib import chroot_lib
Ram Chandrasekare08e3ba2022-04-04 21:42:27 +000018from chromite.lib import goma_lib
Joanna Wang92cad812021-11-03 14:52:08 -070019from chromite.lib import remoteexec_util
George Engelbrecht35b6e8d2021-06-18 09:43:28 -060020from chromite.lib import sysroot_lib
Alex Klein171da612019-08-06 14:00:42 -060021
Alex Klein46c30f32021-11-10 13:12:50 -070022if TYPE_CHECKING:
23 from chromite.api.gen.chromiumos.build.api import portage_pb2
24
Alex Klein171da612019-08-06 14:00:42 -060025class Error(Exception):
26 """Base error class for the module."""
27
28
29class InvalidMessageError(Error):
30 """Invalid message."""
Alex Kleina9d500b2019-04-22 15:37:51 -060031
32
Kevin Sheltona8056362022-04-04 16:19:23 -070033def ParseChroot(chroot_message: common_pb2.Chroot) -> chroot_lib.Chroot:
Alex Klein171da612019-08-06 14:00:42 -060034 """Create a chroot object from the chroot message.
35
36 Args:
Kevin Sheltona8056362022-04-04 16:19:23 -070037 chroot_message: The chroot message.
Alex Klein171da612019-08-06 14:00:42 -060038
39 Returns:
40 Chroot: The parsed chroot object.
41
42 Raises:
43 AssertionError: When the message is not a Chroot message.
44 """
45 assert isinstance(chroot_message, common_pb2.Chroot)
46
Alex Klein915cce92019-12-17 14:19:50 -070047 path = chroot_message.path or constants.DEFAULT_CHROOT_PATH
Alex Klein4f0eb432019-05-02 13:56:04 -060048 cache_dir = chroot_message.cache_dir
Alex Klein5e4b1bc2019-07-02 12:27:06 -060049 chrome_root = chroot_message.chrome_dir
Alex Klein4f0eb432019-05-02 13:56:04 -060050
Alex Klein38c7d9e2019-05-08 09:31:19 -060051 use_flags = [u.flag for u in chroot_message.env.use_flags]
52 features = [f.feature for f in chroot_message.env.features]
53
54 env = {}
55 if use_flags:
56 env['USE'] = ' '.join(use_flags)
57
Alex Kleinb7485bb2019-09-19 13:23:37 -060058 # Make sure it'll use the local source to build chrome when we have it.
59 if chrome_root:
60 env['CHROME_ORIGIN'] = 'LOCAL_SOURCE'
61
Alex Klein38c7d9e2019-05-08 09:31:19 -060062 if features:
63 env['FEATURES'] = ' '.join(features)
64
George Engelbrecht35b6e8d2021-06-18 09:43:28 -060065 chroot = chroot_lib.Chroot(
Alex Klein9b7331e2019-12-30 14:37:21 -070066 path=path, cache_dir=cache_dir, chrome_root=chrome_root, env=env)
Alex Klein171da612019-08-06 14:00:42 -060067
Alex Klein9b7331e2019-12-30 14:37:21 -070068 return chroot
Alex Klein171da612019-08-06 14:00:42 -060069
George Engelbrechtc9a8e812021-06-16 18:14:17 -060070
Kevin Sheltona8056362022-04-04 16:19:23 -070071def ParseSysroot(sysroot_message: sysroot_pb2.Sysroot) -> sysroot_lib.Sysroot:
George Engelbrechtc9a8e812021-06-16 18:14:17 -060072 """Create a sysroot object from the sysroot message.
73
74 Args:
Kevin Sheltona8056362022-04-04 16:19:23 -070075 sysroot_message: The sysroot message.
George Engelbrechtc9a8e812021-06-16 18:14:17 -060076
77 Returns:
78 Sysroot: The parsed sysroot object.
79
80 Raises:
81 AssertionError: When the message is not a Sysroot message.
82 """
83 assert isinstance(sysroot_message, sysroot_pb2.Sysroot)
84
George Engelbrecht35b6e8d2021-06-18 09:43:28 -060085 return sysroot_lib.Sysroot(sysroot_message.path)
George Engelbrechtc9a8e812021-06-16 18:14:17 -060086
87
Joanna Wang92cad812021-11-03 14:52:08 -070088def ParseRemoteexecConfig(remoteexec_message: common_pb2.RemoteexecConfig):
89 """Parse a remoteexec config message."""
90 assert isinstance(remoteexec_message, common_pb2.RemoteexecConfig)
91
92 if not (remoteexec_message.reclient_dir or
93 remoteexec_message.reproxy_cfg_file):
94 return None
95
96 return remoteexec_util.Remoteexec(remoteexec_message.reclient_dir,
97 remoteexec_message.reproxy_cfg_file)
98
99
Alex Klein915cce92019-12-17 14:19:50 -0700100def ParseGomaConfig(goma_message, chroot_path):
101 """Parse a goma config message."""
102 assert isinstance(goma_message, common_pb2.GomaConfig)
103
104 if not goma_message.goma_dir:
105 return None
106
107 # Parse the goma config.
108 chromeos_goma_dir = goma_message.chromeos_goma_dir or None
David Burgerec676f62020-07-03 09:09:31 -0600109 if goma_message.goma_approach == common_pb2.GomaConfig.RBE_STAGING:
Ram Chandrasekare08e3ba2022-04-04 21:42:27 +0000110 goma_approach = goma_lib.GomaApproach('?staging',
111 'staging-goma.chromium.org', True)
Yoshisato Yanagisawa57f7f672021-01-08 02:42:42 +0000112 elif goma_message.goma_approach == common_pb2.GomaConfig.RBE_PROD:
Ram Chandrasekare08e3ba2022-04-04 21:42:27 +0000113 goma_approach = goma_lib.GomaApproach('?prod', 'goma.chromium.org', True)
Yoshisato Yanagisawa57f7f672021-01-08 02:42:42 +0000114 else:
Ram Chandrasekare08e3ba2022-04-04 21:42:27 +0000115 goma_approach = goma_lib.GomaApproach('?cros', 'goma.chromium.org', True)
Alex Klein915cce92019-12-17 14:19:50 -0700116
Michael Mortensen4ccfb082020-01-22 16:24:03 -0700117 # Note that we are not specifying the goma log_dir so that goma will create
118 # and use a tmp dir for the logs.
Alex Klein915cce92019-12-17 14:19:50 -0700119 stats_filename = goma_message.stats_file or None
120 counterz_filename = goma_message.counterz_file or None
121
Ram Chandrasekare08e3ba2022-04-04 21:42:27 +0000122 return goma_lib.Goma(
123 goma_message.goma_dir,
124 goma_message.goma_client_json,
125 stage_name='BuildAPI',
126 chromeos_goma_dir=chromeos_goma_dir,
127 chroot_dir=chroot_path,
128 goma_approach=goma_approach,
129 stats_filename=stats_filename,
130 counterz_filename=counterz_filename)
Alex Klein915cce92019-12-17 14:19:50 -0700131
132
Kevin Sheltona8056362022-04-04 16:19:23 -0700133def ParseBuildTarget(
134 build_target_message: common_pb2.BuildTarget,
135 profile_message: Optional[sysroot_pb2.Profile] = None
136) -> build_target_lib.BuildTarget:
Alex Klein171da612019-08-06 14:00:42 -0600137 """Create a BuildTarget object from a build_target message.
138
139 Args:
Kevin Sheltona8056362022-04-04 16:19:23 -0700140 build_target_message: The BuildTarget message.
141 profile_message: The profile message.
Alex Klein171da612019-08-06 14:00:42 -0600142
143 Returns:
144 BuildTarget: The parsed instance.
145
146 Raises:
147 AssertionError: When the field is not a BuildTarget message.
148 """
149 assert isinstance(build_target_message, common_pb2.BuildTarget)
Alex Klein26e472b2020-03-10 14:35:01 -0600150 assert (profile_message is None or
151 isinstance(profile_message, sysroot_pb2.Profile))
Alex Klein171da612019-08-06 14:00:42 -0600152
Alex Klein26e472b2020-03-10 14:35:01 -0600153 profile_name = profile_message.name if profile_message else None
154 return build_target_lib.BuildTarget(
155 build_target_message.name, profile=profile_name)
Alex Klein171da612019-08-06 14:00:42 -0600156
157
158def ParseBuildTargets(repeated_build_target_field):
159 """Create a BuildTarget for each entry in the repeated field.
160
161 Args:
162 repeated_build_target_field: The repeated BuildTarget field.
163
164 Returns:
165 list[BuildTarget]: The parsed BuildTargets.
166
167 Raises:
168 AssertionError: When the field contains non-BuildTarget messages.
169 """
170 return [ParseBuildTarget(target) for target in repeated_build_target_field]
Alex Klein4f0eb432019-05-02 13:56:04 -0600171
172
Alex Klein28e59a62021-09-09 15:45:14 -0600173def serialize_package_info(pkg_info: package_info.PackageInfo,
Alex Klein46c30f32021-11-10 13:12:50 -0700174 pkg_info_msg: Union[common_pb2.PackageInfo,
175 'portage_pb2.Portage.Package']):
Alex Klein1e68a8e2020-10-06 17:25:11 -0600176 """Serialize a PackageInfo object to a PackageInfo proto."""
Alex Klein28e59a62021-09-09 15:45:14 -0600177 if not isinstance(pkg_info, package_info.PackageInfo):
178 # Allows us to swap everything to serialize_package_info, and search the
179 # logs for usages that aren't passing though a PackageInfo yet.
180 logging.warning(
181 'serialize_package_info: Got a %s instead of a PackageInfo.',
182 type(pkg_info))
183 pkg_info = package_info.parse(pkg_info)
Alex Klein1e68a8e2020-10-06 17:25:11 -0600184 pkg_info_msg.package_name = pkg_info.package
185 if pkg_info.category:
186 pkg_info_msg.category = pkg_info.category
187 if pkg_info.vr:
188 pkg_info_msg.version = pkg_info.vr
189
190
191def deserialize_package_info(pkg_info_msg):
192 """Deserialize a PackageInfo message to a PackageInfo object."""
193 return package_info.parse(PackageInfoToString(pkg_info_msg))
194
195
Lizzy Presland29e62452022-01-05 21:58:21 +0000196def retrieve_package_log_paths(error: sysroot_lib.PackageInstallError,
197 output_proto: Union[
198 sysroot_pb2.InstallPackagesResponse,
Lizzy Presland4feb2372022-01-20 05:16:30 +0000199 sysroot_pb2.InstallToolchainResponse,
200 test_pb2.BuildTargetUnitTestResponse
201 ],
Lizzy Presland29e62452022-01-05 21:58:21 +0000202 target_sysroot: sysroot_lib.Sysroot) -> None:
203 """Get the path to the log file for each package that failed to build.
204
205 Args:
206 error: The error message produced by the build step.
207 output_proto: The Response message for a given API call. This response proto
208 must contain a failed_package_data field.
209 target_sysroot: The sysroot used by the build step.
210 """
211 for pkg_info in error.failed_packages:
212 # TODO(b/206514844): remove when field is deleted
213 package_info_msg = output_proto.failed_packages.add()
214 serialize_package_info(pkg_info, package_info_msg)
215 # Grab the paths to the log files for each failed package from the
216 # sysroot.
217 # Logs currently exist within the sysroot in the form of:
218 # /build/${BOARD}/tmp/portage/logs/$CATEGORY:$PF:$TIMESTAMP.log
219 failed_pkg_data_msg = output_proto.failed_package_data.add()
220 serialize_package_info(pkg_info, failed_pkg_data_msg.name)
221 glob_path = os.path.join(target_sysroot.portage_logdir,
222 f'{pkg_info.category}:{pkg_info.pvr}:*.log')
223 log_files = glob.glob(glob_path)
224 log_files.sort(reverse=True)
225 # Omit path if files don't exist for some reason.
226 if not log_files:
227 logging.warning('Log file for %s was not found. Search path: %s',
228 pkg_info.cpvr, glob_path)
229 continue
230 failed_pkg_data_msg.log_path.path = log_files[0]
231 failed_pkg_data_msg.log_path.location = common_pb2.Path.INSIDE
232
233
Alex Klein18a60af2020-06-11 12:08:47 -0600234def PackageInfoToCPV(package_info_msg):
Alex Kleina9d500b2019-04-22 15:37:51 -0600235 """Helper to translate a PackageInfo message into a CPV."""
Alex Klein18a60af2020-06-11 12:08:47 -0600236 if not package_info_msg or not package_info_msg.package_name:
Alex Kleina9d500b2019-04-22 15:37:51 -0600237 return None
238
Alex Klein18a60af2020-06-11 12:08:47 -0600239 return package_info.SplitCPV(PackageInfoToString(package_info_msg),
240 strict=False)
Alex Kleina9d500b2019-04-22 15:37:51 -0600241
242
Alex Klein18a60af2020-06-11 12:08:47 -0600243def PackageInfoToString(package_info_msg):
Alex Kleina9d500b2019-04-22 15:37:51 -0600244 # Combine the components into the full CPV string that SplitCPV parses.
Alex Klein18a60af2020-06-11 12:08:47 -0600245 # TODO: Use the lib.parser.package_info.PackageInfo class instead.
246 if not package_info_msg.package_name:
247 raise ValueError('Invalid PackageInfo message.')
Alex Kleina9d500b2019-04-22 15:37:51 -0600248
Alex Klein18a60af2020-06-11 12:08:47 -0600249 c = ('%s/' % package_info_msg.category) if package_info_msg.category else ''
250 p = package_info_msg.package_name
251 v = ('-%s' % package_info_msg.version) if package_info_msg.version else ''
Alex Kleina9d500b2019-04-22 15:37:51 -0600252 return '%s%s%s' % (c, p, v)
253
254
Kevin Sheltona8056362022-04-04 16:19:23 -0700255def CPVToString(cpv: package_info.CPV) -> str:
Alex Kleina9d500b2019-04-22 15:37:51 -0600256 """Get the most useful string representation from a CPV.
257
258 Args:
Kevin Sheltona8056362022-04-04 16:19:23 -0700259 cpv: The CPV object.
Alex Kleina9d500b2019-04-22 15:37:51 -0600260
261 Raises:
262 ValueError - when the CPV has no useful fields set.
263 """
264 if cpv.cpf:
265 return cpv.cpf
266 elif cpv.cpv:
267 return cpv.cpv
268 elif cpv.cp:
269 return cpv.cp
270 elif cpv.package:
271 return cpv.package
272 else:
273 raise ValueError('Invalid CPV provided.')