blob: 4a152b9f435abcbebd114202af0d12e937359b0d [file] [log] [blame]
Alex Kleineb77ffa2019-05-28 14:47:44 -06001# -*- coding: utf-8 -*-
2# Copyright 2019 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Package utility functionality."""
7
8from __future__ import print_function
9
Yaakov Shaul730814a2019-09-10 13:58:25 -060010import collections
Ben Reiche779cf42020-12-15 03:21:31 +000011from distutils.version import LooseVersion
Yaakov Shaulcb1cfc32019-09-16 13:51:19 -060012import fileinput
Alex Klein87531182019-08-12 15:23:37 -060013import functools
Yaakov Shaul395ae832019-09-09 14:45:32 -060014import json
Evan Hernandezb51f1522019-08-15 11:29:40 -060015import os
Michael Mortensenb70e8a82019-10-10 18:43:41 -060016import re
Yaakov Shaulcb1cfc32019-09-16 13:51:19 -060017import sys
Ben Reiche779cf42020-12-15 03:21:31 +000018from typing import List
Alex Klein87531182019-08-12 15:23:37 -060019
Andrew Lamb2bde9e42019-11-04 13:24:09 -070020from google.protobuf import json_format
Yaakov Shaul730814a2019-09-10 13:58:25 -060021
Andrew Lamb2bde9e42019-11-04 13:24:09 -070022from chromite.api.gen.config import replication_config_pb2
Michael Mortensen9fdb14b2019-10-17 11:17:30 -060023from chromite.cbuildbot import manifest_version
Alex Kleineb77ffa2019-05-28 14:47:44 -060024from chromite.lib import constants
Evan Hernandezb51f1522019-08-15 11:29:40 -060025from chromite.lib import cros_build_lib
Alex Klein4de25e82019-08-05 15:58:39 -060026from chromite.lib import cros_logging as logging
Alex Kleineb77ffa2019-05-28 14:47:44 -060027from chromite.lib import git
Michael Mortensende716a12020-05-15 11:27:00 -060028from chromite.lib import image_lib
Michael Mortensenb70e8a82019-10-10 18:43:41 -060029from chromite.lib import osutils
Alex Kleineb77ffa2019-05-28 14:47:44 -060030from chromite.lib import portage_util
Andrew Lamb2bde9e42019-11-04 13:24:09 -070031from chromite.lib import replication_lib
Alex Kleind6195b62019-08-06 16:01:16 -060032from chromite.lib import uprev_lib
Alex Klein18a60af2020-06-11 12:08:47 -060033from chromite.lib.parser import package_info
Alex Kleineb77ffa2019-05-28 14:47:44 -060034
Alex Klein36b117f2019-09-30 15:13:46 -060035if cros_build_lib.IsInsideChroot():
36 from chromite.service import dependency
37
Mike Frysingerbafb3182020-02-21 03:15:43 -050038
Alex Klein87531182019-08-12 15:23:37 -060039# Registered handlers for uprevving versioned packages.
40_UPREV_FUNCS = {}
41
Alex Kleineb77ffa2019-05-28 14:47:44 -060042
43class Error(Exception):
44 """Module's base error class."""
45
46
Alex Klein4de25e82019-08-05 15:58:39 -060047class UnknownPackageError(Error):
48 """Uprev attempted for a package without a registered handler."""
49
50
Alex Kleineb77ffa2019-05-28 14:47:44 -060051class UprevError(Error):
52 """An error occurred while uprevving packages."""
53
54
Michael Mortensenb70e8a82019-10-10 18:43:41 -060055class NoAndroidVersionError(Error):
56 """An error occurred while trying to determine the android version."""
57
58
59class NoAndroidBranchError(Error):
60 """An error occurred while trying to determine the android branch."""
61
62
63class NoAndroidTargetError(Error):
64 """An error occurred while trying to determine the android target."""
65
66
Alex Klein4de25e82019-08-05 15:58:39 -060067class AndroidIsPinnedUprevError(UprevError):
68 """Raised when we try to uprev while Android is pinned."""
69
70 def __init__(self, new_android_atom):
71 """Initialize a AndroidIsPinnedUprevError.
72
73 Args:
74 new_android_atom: The Android atom that we failed to
75 uprev to, due to Android being pinned.
76 """
77 assert new_android_atom
78 msg = ('Failed up uprev to Android version %s as Android was pinned.' %
79 new_android_atom)
80 super(AndroidIsPinnedUprevError, self).__init__(msg)
81 self.new_android_atom = new_android_atom
Alex Klein87531182019-08-12 15:23:37 -060082
83
Andrew Lamb9563a152019-12-04 11:42:18 -070084class GeneratedCrosConfigFilesError(Error):
85 """Error when cros_config_schema does not produce expected files"""
86
87 def __init__(self, expected_files, found_files):
88 msg = ('Expected to find generated C files: %s. Actually found: %s' %
89 (expected_files, found_files))
90 super(GeneratedCrosConfigFilesError, self).__init__(msg)
91
Alex Klein7a3a7dd2020-01-08 16:44:38 -070092
Yaakov Shaulcb1cfc32019-09-16 13:51:19 -060093def patch_ebuild_vars(ebuild_path, variables):
94 """Updates variables in ebuild.
95
96 Use this function rather than portage_util.EBuild.UpdateEBuild when you
97 want to preserve the variable position and quotes within the ebuild.
98
99 Args:
100 ebuild_path: The path of the ebuild.
101 variables: Dictionary of variables to update in ebuild.
102 """
103 try:
104 for line in fileinput.input(ebuild_path, inplace=1):
105 varname, eq, _ = line.partition('=')
106 if eq == '=' and varname.strip() in variables:
107 value = variables[varname]
108 sys.stdout.write('%s="%s"\n' % (varname, value))
109 else:
110 sys.stdout.write(line)
111 finally:
112 fileinput.close()
113
114
Alex Klein87531182019-08-12 15:23:37 -0600115def uprevs_versioned_package(package):
116 """Decorator to register package uprev handlers."""
117 assert package
118
119 def register(func):
120 """Registers |func| as a handler for |package|."""
121 _UPREV_FUNCS[package] = func
122
123 @functools.wraps(func)
124 def pass_through(*args, **kwargs):
125 return func(*args, **kwargs)
126
127 return pass_through
128
129 return register
130
131
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700132def uprev_android(tracking_branch,
133 android_package,
134 android_build_branch,
135 chroot,
136 build_targets=None,
Shao-Chuan Lee9c39e0c2020-04-24 11:40:34 +0900137 android_version=None):
Alex Klein4de25e82019-08-05 15:58:39 -0600138 """Returns the portage atom for the revved Android ebuild - see man emerge."""
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700139 command = [
140 'cros_mark_android_as_stable',
141 '--tracking_branch=%s' % tracking_branch,
142 '--android_package=%s' % android_package,
143 '--android_build_branch=%s' % android_build_branch,
144 ]
Alex Klein4de25e82019-08-05 15:58:39 -0600145 if build_targets:
146 command.append('--boards=%s' % ':'.join(bt.name for bt in build_targets))
147 if android_version:
148 command.append('--force_version=%s' % android_version)
Alex Klein4de25e82019-08-05 15:58:39 -0600149
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700150 result = cros_build_lib.run(
151 command,
152 stdout=True,
153 enter_chroot=True,
Mike Frysinger88d96362020-02-14 19:05:45 -0500154 encoding='utf-8',
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700155 chroot_args=chroot.get_enter_args())
Alex Klein4de25e82019-08-05 15:58:39 -0600156
Mike Frysinger88d96362020-02-14 19:05:45 -0500157 portage_atom_string = result.stdout.strip()
158 android_atom = None
159 if portage_atom_string:
160 android_atom = portage_atom_string.splitlines()[-1].partition('=')[-1]
Alex Klein4de25e82019-08-05 15:58:39 -0600161 if not android_atom:
162 logging.info('Found nothing to rev.')
163 return None
164
165 for target in build_targets or []:
166 # Sanity check: We should always be able to merge the version of
167 # Android we just unmasked.
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700168 command = ['emerge-%s' % target.name, '-p', '--quiet', '=%s' % android_atom]
Alex Klein4de25e82019-08-05 15:58:39 -0600169 try:
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700170 cros_build_lib.run(
171 command, enter_chroot=True, chroot_args=chroot.get_enter_args())
Alex Klein4de25e82019-08-05 15:58:39 -0600172 except cros_build_lib.RunCommandError:
173 logging.error(
174 'Cannot emerge-%s =%s\nIs Android pinned to an older '
175 'version?', target, android_atom)
176 raise AndroidIsPinnedUprevError(android_atom)
177
178 return android_atom
179
180
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700181def uprev_build_targets(build_targets,
182 overlay_type,
183 chroot=None,
Alex Kleineb77ffa2019-05-28 14:47:44 -0600184 output_dir=None):
185 """Uprev the set provided build targets, or all if not specified.
186
187 Args:
Alex Klein2960c752020-03-09 13:43:38 -0600188 build_targets (list[build_target_lib.BuildTarget]|None): The build targets
Alex Kleineb77ffa2019-05-28 14:47:44 -0600189 whose overlays should be uprevved, empty or None for all.
190 overlay_type (str): One of the valid overlay types except None (see
191 constants.VALID_OVERLAYS).
192 chroot (chroot_lib.Chroot|None): The chroot to clean, if desired.
193 output_dir (str|None): The path to optionally dump result files.
194 """
195 # Need a valid overlay, but exclude None.
196 assert overlay_type and overlay_type in constants.VALID_OVERLAYS
197
198 if build_targets:
199 overlays = portage_util.FindOverlaysForBoards(
200 overlay_type, boards=[t.name for t in build_targets])
201 else:
202 overlays = portage_util.FindOverlays(overlay_type)
203
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700204 return uprev_overlays(
205 overlays,
206 build_targets=build_targets,
207 chroot=chroot,
208 output_dir=output_dir)
Alex Kleineb77ffa2019-05-28 14:47:44 -0600209
210
211def uprev_overlays(overlays, build_targets=None, chroot=None, output_dir=None):
212 """Uprev the given overlays.
213
214 Args:
215 overlays (list[str]): The list of overlay paths.
Alex Klein2960c752020-03-09 13:43:38 -0600216 build_targets (list[build_target_lib.BuildTarget]|None): The build targets
Alex Kleineb77ffa2019-05-28 14:47:44 -0600217 to clean in |chroot|, if desired. No effect unless |chroot| is provided.
218 chroot (chroot_lib.Chroot|None): The chroot to clean, if desired.
219 output_dir (str|None): The path to optionally dump result files.
220
221 Returns:
222 list[str] - The paths to all of the modified ebuild files. This includes the
223 new files that were added (i.e. the new versions) and all of the removed
224 files (i.e. the old versions).
225 """
226 assert overlays
227
228 manifest = git.ManifestCheckout.Cached(constants.SOURCE_ROOT)
229
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700230 uprev_manager = uprev_lib.UprevOverlayManager(
231 overlays,
232 manifest,
233 build_targets=build_targets,
234 chroot=chroot,
235 output_dir=output_dir)
Alex Kleineb77ffa2019-05-28 14:47:44 -0600236 uprev_manager.uprev()
237
238 return uprev_manager.modified_ebuilds
239
240
Alex Klein87531182019-08-12 15:23:37 -0600241def uprev_versioned_package(package, build_targets, refs, chroot):
242 """Call registered uprev handler function for the package.
243
244 Args:
Alex Klein75df1792020-06-11 14:42:49 -0600245 package (package_info.CPV): The package being uprevved.
Alex Klein2960c752020-03-09 13:43:38 -0600246 build_targets (list[build_target_lib.BuildTarget]): The build targets to
Alex Klein87531182019-08-12 15:23:37 -0600247 clean on a successful uprev.
248 refs (list[uprev_lib.GitRef]):
249 chroot (chroot_lib.Chroot): The chroot to enter for cleaning.
250
251 Returns:
Alex Klein34afcbc2019-08-22 16:14:31 -0600252 UprevVersionedPackageResult: The result.
Alex Klein87531182019-08-12 15:23:37 -0600253 """
254 assert package
255
256 if package.cp not in _UPREV_FUNCS:
257 raise UnknownPackageError(
258 'Package "%s" does not have a registered handler.' % package.cp)
259
Andrew Lambea9a8a22019-12-12 14:03:43 -0700260 return _UPREV_FUNCS[package.cp](build_targets, refs, chroot)
Alex Klein87531182019-08-12 15:23:37 -0600261
262
Navil Perezf57ba872020-06-04 22:38:37 +0000263@uprevs_versioned_package('media-libs/virglrenderer')
264def uprev_virglrenderer(_build_targets, refs, _chroot):
265 """Updates virglrenderer ebuilds.
266
267 See: uprev_versioned_package.
268
269 Returns:
270 UprevVersionedPackageResult: The result of updating virglrenderer ebuilds.
271 """
Navil Perezf57ba872020-06-04 22:38:37 +0000272 overlay = os.path.join(constants.SOURCE_ROOT,
273 constants.CHROMIUMOS_OVERLAY_DIR)
George Engelbrechte73f2782020-06-10 14:10:46 -0600274 repo_path = os.path.join(constants.SOURCE_ROOT, 'src', 'third_party',
275 'virglrenderer')
276 manifest = git.ManifestCheckout.Cached(repo_path)
Navil Perezf57ba872020-06-04 22:38:37 +0000277
278 uprev_manager = uprev_lib.UprevOverlayManager([overlay], manifest)
279 # TODO(crbug.com/1066242): Ebuilds for virglrenderer are currently
Jose Magana03b5a842020-08-19 12:52:59 +1000280 # denylisted. Do not force uprevs after builder is stable and ebuilds are no
281 # longer denylisted.
Navil Perezf57ba872020-06-04 22:38:37 +0000282 uprev_manager.uprev(package_list=['media-libs/virglrenderer'], force=True)
283
George Engelbrechte73f2782020-06-10 14:10:46 -0600284 updated_files = uprev_manager.modified_ebuilds
Chris McDonald38409112020-09-24 11:24:51 -0600285 result = uprev_lib.UprevVersionedPackageResult()
Navil Perezf57ba872020-06-04 22:38:37 +0000286 result.add_result(refs[0].revision, updated_files)
287 return result
288
Jose Magana03b5a842020-08-19 12:52:59 +1000289@uprevs_versioned_package('chromeos-base/drivefs')
290def uprev_drivefs(_build_targets, refs, chroot):
291 """Updates drivefs ebuilds.
292
293 See: uprev_versioned_package.
294
295 Returns:
296 UprevVersionedPackageResult: The result of updating drivefs ebuilds.
297 """
298
Ben Reiche779cf42020-12-15 03:21:31 +0000299 DRIVEFS_PATH_PREFIX = 'src/private-overlays/chromeos-overlay/chromeos-base'
Jose Magana03b5a842020-08-19 12:52:59 +1000300
Ben Reiche779cf42020-12-15 03:21:31 +0000301 drivefs_version = get_latest_drivefs_version_from_refs(refs)
302 if not drivefs_version:
303 # No valid DriveFS version is identified.
Jose Magana03b5a842020-08-19 12:52:59 +1000304 return None
305
Ben Reiche779cf42020-12-15 03:21:31 +0000306 logging.debug('DriveFS version determined from refs: %s', drivefs_version)
Jose Magana03b5a842020-08-19 12:52:59 +1000307
308 result = uprev_lib.UprevVersionedPackageResult()
309
Ben Reiche779cf42020-12-15 03:21:31 +0000310 pkg_path = os.path.join(DRIVEFS_PATH_PREFIX, 'drivefs')
Jose Magana03b5a842020-08-19 12:52:59 +1000311 uprev_result = uprev_lib.uprev_workon_ebuild_to_version(pkg_path,
Ben Reiche779cf42020-12-15 03:21:31 +0000312 drivefs_version,
Jose Magana03b5a842020-08-19 12:52:59 +1000313 chroot)
314 all_changed_files = []
315
316 if not uprev_result:
317 return None # alternatively raise Exception
318
319 all_changed_files.extend(uprev_result.changed_files)
320
Ben Reiche779cf42020-12-15 03:21:31 +0000321 pkg_path = os.path.join(DRIVEFS_PATH_PREFIX, 'drivefs-ipc')
Jose Magana03b5a842020-08-19 12:52:59 +1000322
323 uprev_result = uprev_lib.uprev_workon_ebuild_to_version(pkg_path,
Ben Reiche779cf42020-12-15 03:21:31 +0000324 drivefs_version,
Jose Magana03b5a842020-08-19 12:52:59 +1000325 chroot)
326
327 if not uprev_result:
328 return None # alternatively raise Exception
329
330 all_changed_files.extend(uprev_result.changed_files)
331
Ben Reiche779cf42020-12-15 03:21:31 +0000332 result.add_result(drivefs_version, all_changed_files)
Jose Magana03b5a842020-08-19 12:52:59 +1000333
334 return result
335
Navil Perezf57ba872020-06-04 22:38:37 +0000336
Yaakov Shaul395ae832019-09-09 14:45:32 -0600337@uprevs_versioned_package('afdo/kernel-profiles')
338def uprev_kernel_afdo(*_args, **_kwargs):
David Burger92485342019-09-10 17:52:45 -0600339 """Updates kernel ebuilds with versions from kernel_afdo.json.
Yaakov Shaul395ae832019-09-09 14:45:32 -0600340
341 See: uprev_versioned_package.
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600342
343 Raises:
344 EbuildManifestError: When ebuild manifest does not complete successfuly.
Yaakov Shaul395ae832019-09-09 14:45:32 -0600345 """
346 path = os.path.join(constants.SOURCE_ROOT, 'src', 'third_party',
347 'toolchain-utils', 'afdo_metadata', 'kernel_afdo.json')
348
David Burger92485342019-09-10 17:52:45 -0600349 with open(path, 'r') as f:
350 versions = json.load(f)
Yaakov Shaul395ae832019-09-09 14:45:32 -0600351
Chris McDonald38409112020-09-24 11:24:51 -0600352 result = uprev_lib.UprevVersionedPackageResult()
Yaakov Shaul395ae832019-09-09 14:45:32 -0600353 for version, version_info in versions.items():
Yaakov Shauldd8b4112019-09-11 11:44:03 -0600354 path = os.path.join('src', 'third_party', 'chromiumos-overlay',
355 'sys-kernel', version)
356 ebuild_path = os.path.join(constants.SOURCE_ROOT, path,
357 '%s-9999.ebuild' % version)
Yaakov Shaula187b152019-09-11 12:41:32 -0600358 chroot_ebuild_path = os.path.join(constants.CHROOT_SOURCE_ROOT, path,
359 '%s-9999.ebuild' % version)
Yaakov Shaul730814a2019-09-10 13:58:25 -0600360 afdo_profile_version = version_info['name']
Yaakov Shaulcb1cfc32019-09-16 13:51:19 -0600361 patch_ebuild_vars(ebuild_path,
362 dict(AFDO_PROFILE_VERSION=afdo_profile_version))
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600363
364 try:
Yaakov Shaul730814a2019-09-10 13:58:25 -0600365 cmd = ['ebuild', chroot_ebuild_path, 'manifest', '--force']
Mike Frysinger45602c72019-09-22 02:15:11 -0400366 cros_build_lib.run(cmd, enter_chroot=True)
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600367 except cros_build_lib.RunCommandError as e:
Chris McDonald38409112020-09-24 11:24:51 -0600368 raise uprev_lib.EbuildManifestError(
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600369 'Error encountered when regenerating the manifest for ebuild: %s\n%s'
Yaakov Shaula187b152019-09-11 12:41:32 -0600370 % (chroot_ebuild_path, e), e)
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600371
Yaakov Shauldd8b4112019-09-11 11:44:03 -0600372 manifest_path = os.path.join(constants.SOURCE_ROOT, path, 'Manifest')
Yaakov Shaul1eafe832019-09-10 16:50:26 -0600373
Yaakov Shaul730814a2019-09-10 13:58:25 -0600374 result.add_result(afdo_profile_version, [ebuild_path, manifest_path])
375
376 return result
Yaakov Shaul395ae832019-09-09 14:45:32 -0600377
378
Trent Begineb624182020-07-14 10:09:45 -0600379@uprevs_versioned_package('chromeos-base/termina-dlc')
380def uprev_termina_dlc(_build_targets, _refs, chroot):
381 """Updates shared termina-dlc ebuild - chromeos-base/termina-dlc.
Trent Beginaf51f1b2020-03-09 17:35:31 -0600382
383 See: uprev_versioned_package.
384 """
Trent Begineb624182020-07-14 10:09:45 -0600385 package = 'termina-dlc'
Trent Beginaf51f1b2020-03-09 17:35:31 -0600386 package_path = os.path.join(constants.CHROMIUMOS_OVERLAY_DIR, 'chromeos-base',
387 package)
Patrick Meiring5897add2020-09-16 16:30:17 +1000388
389 version_pin_src_path = _get_version_pin_src_path(package_path)
390 version_no_rev = osutils.ReadFile(version_pin_src_path).strip()
391
Chris McDonald38409112020-09-24 11:24:51 -0600392 return uprev_lib.uprev_ebuild_from_pin(package_path, version_no_rev, chroot)
Patrick Meiring5897add2020-09-16 16:30:17 +1000393
394
395@uprevs_versioned_package('app-emulation/parallels-desktop')
396def uprev_parallels_desktop(_build_targets, _refs, chroot):
397 """Updates Parallels Desktop ebuild - app-emulation/parallels-desktop.
398
399 See: uprev_versioned_package
400
401 Returns:
402 UprevVersionedPackageResult: The result.
403 """
404 package = 'parallels-desktop'
405 package_path = os.path.join(constants.CHROMEOS_PARTNER_OVERLAY_DIR,
406 'app-emulation', package)
407 version_pin_src_path = _get_version_pin_src_path(package_path)
408
409 # Expect a JSON blob like the following:
410 # {
411 # "version": "1.2.3",
412 # "test_image": { "url": "...", "size": 12345678,
413 # "sha256sum": "<32 bytes of hexadecimal>" }
414 # }
415 with open(version_pin_src_path, 'r') as f:
416 pinned = json.load(f)
417
418 if 'version' not in pinned or 'test_image' not in pinned:
419 raise UprevError('VERSION-PIN for %s missing version and/or '
420 'test_image field' % package)
421
422 version = pinned['version']
423 if not isinstance(version, str):
424 raise UprevError('version in VERSION-PIN for %s not a string' % package)
425
426 # Update the ebuild.
Chris McDonald38409112020-09-24 11:24:51 -0600427 result = uprev_lib.uprev_ebuild_from_pin(package_path, version, chroot)
Patrick Meiring5897add2020-09-16 16:30:17 +1000428
429 # Update the VM image used for testing.
Patrick Meiring1342def2020-10-30 17:09:13 +1100430 test_image_path = ('src/platform/tast-tests-private/src/chromiumos/tast/'
431 'local/bundles/crosint/pita/data/'
432 'pluginvm_image.zip.external')
Patrick Meiring5897add2020-09-16 16:30:17 +1000433 test_image_src_path = os.path.join(constants.SOURCE_ROOT, test_image_path)
434 with open(test_image_src_path, 'w') as f:
435 json.dump(pinned['test_image'], f, indent=2)
436 result.add_result(version, [test_image_src_path])
437
438 return result
Trent Beginaf51f1b2020-03-09 17:35:31 -0600439
440
Trent Begin315d9d92019-12-03 21:55:53 -0700441@uprevs_versioned_package('chromeos-base/chromeos-dtc-vm')
Trent Beginaf51f1b2020-03-09 17:35:31 -0600442def uprev_sludge(_build_targets, _refs, chroot):
Trent Begin315d9d92019-12-03 21:55:53 -0700443 """Updates sludge VM - chromeos-base/chromeos-dtc-vm.
444
445 See: uprev_versioned_package.
446 """
447 package = 'chromeos-dtc-vm'
Trent Begind943df92020-02-25 10:30:10 -0700448 package_path = os.path.join('src', 'private-overlays',
449 'project-wilco-private', 'chromeos-base', package)
Patrick Meiring5897add2020-09-16 16:30:17 +1000450 version_pin_src_path = _get_version_pin_src_path(package_path)
451 version_no_rev = osutils.ReadFile(version_pin_src_path).strip()
Trent Begin315d9d92019-12-03 21:55:53 -0700452
Chris McDonald38409112020-09-24 11:24:51 -0600453 return uprev_lib.uprev_ebuild_from_pin(package_path, version_no_rev, chroot)
Trent Begin315d9d92019-12-03 21:55:53 -0700454
455
Patrick Meiring5897add2020-09-16 16:30:17 +1000456def _get_version_pin_src_path(package_path):
457 """Returns the path to the VERSION-PIN file for the given package."""
458 return os.path.join(constants.SOURCE_ROOT, package_path, 'VERSION-PIN')
459
460
Alex Klein87531182019-08-12 15:23:37 -0600461@uprevs_versioned_package(constants.CHROME_CP)
Andrew Lambea9a8a22019-12-12 14:03:43 -0700462def uprev_chrome(build_targets, refs, chroot):
Alex Klein87531182019-08-12 15:23:37 -0600463 """Uprev chrome and its related packages.
464
465 See: uprev_versioned_package.
466 """
467 # Determine the version from the refs (tags), i.e. the chrome versions are the
468 # tag names.
469 chrome_version = uprev_lib.get_chrome_version_from_refs(refs)
Chris McDonald25881af2020-05-12 03:17:53 -0600470 logging.debug('Chrome version determined from refs: %s', chrome_version)
Alex Klein87531182019-08-12 15:23:37 -0600471
472 uprev_manager = uprev_lib.UprevChromeManager(
473 chrome_version, build_targets=build_targets, chroot=chroot)
Chris McDonald38409112020-09-24 11:24:51 -0600474 result = uprev_lib.UprevVersionedPackageResult()
Alex Klein87531182019-08-12 15:23:37 -0600475 # Start with chrome itself, as we can't do anything else unless chrome
476 # uprevs successfully.
Chris McDonald25881af2020-05-12 03:17:53 -0600477 # TODO(crbug.com/1080429): Handle all possible outcomes of a Chrome uprev
478 # attempt. The expected behavior is documented in the following table:
479 #
480 # Outcome of Chrome uprev attempt:
481 # NEWER_VERSION_EXISTS:
482 # Do nothing.
483 # SAME_VERSION_EXISTS or REVISION_BUMP:
484 # Uprev followers
485 # Assert not VERSION_BUMP (any other outcome is fine)
486 # VERSION_BUMP or NEW_EBUILD_CREATED:
487 # Uprev followers
488 # Assert that Chrome & followers are at same package version
Alex Klein87531182019-08-12 15:23:37 -0600489 if not uprev_manager.uprev(constants.CHROME_CP):
David Burger37f48672019-09-18 17:07:56 -0600490 return result
Alex Klein87531182019-08-12 15:23:37 -0600491
492 # With a successful chrome rev, also uprev related packages.
493 for package in constants.OTHER_CHROME_PACKAGES:
494 uprev_manager.uprev(package)
495
David Burger37f48672019-09-18 17:07:56 -0600496 return result.add_result(chrome_version, uprev_manager.modified_ebuilds)
Alex Klein87531182019-08-12 15:23:37 -0600497
498
Ben Reiche779cf42020-12-15 03:21:31 +0000499def get_latest_drivefs_version_from_refs(refs: List[uprev_lib.GitRef]) -> str:
500 """Get the latest DriveFS version from refs
501
502 DriveFS versions follow the tag format of refs/tags/drivefs_1.2.3.
503 Versions are compared using |distutils.version.LooseVersion| and
504 the latest version is returned.
505
506 Args:
507 refs: The tags to parse for the latest DriveFS version.
508
509 Returns:
510 The latest DriveFS version to use.
511 """
512 DRIVEFS_REFS_PREFIX = 'refs/tags/drivefs_'
513
514 valid_refs = []
515 for gitiles in refs:
516 if gitiles.ref.startswith(DRIVEFS_REFS_PREFIX):
517 valid_refs.append(gitiles.ref)
518
519 if not valid_refs:
520 return None
521
522 # Sort by version and take the latest version.
523 target_version_ref = sorted(valid_refs,
524 key=LooseVersion,
525 reverse=True)[0]
526 return target_version_ref.replace(DRIVEFS_REFS_PREFIX, '')
527
528
Andrew Lamb9563a152019-12-04 11:42:18 -0700529def _generate_platform_c_files(replication_config, chroot):
530 """Generates platform C files from a platform JSON payload.
531
532 Args:
533 replication_config (replication_config_pb2.ReplicationConfig): A
534 ReplicationConfig that has already been run. If it produced a
535 build_config.json file, that file will be used to generate platform C
536 files. Otherwise, nothing will be generated.
537 chroot (chroot_lib.Chroot): The chroot to use to generate.
538
539 Returns:
540 A list of generated files.
541 """
542 # Generate the platform C files from the build config. Note that it would be
543 # more intuitive to generate the platform C files from the platform config;
544 # however, cros_config_schema does not allow this, because the platform config
545 # payload is not always valid input. For example, if a property is both
546 # 'required' and 'build-only', it will fail schema validation. Thus, use the
547 # build config, and use '-f' to filter.
548 build_config_path = [
549 rule.destination_path
550 for rule in replication_config.file_replication_rules
551 if rule.destination_path.endswith('build_config.json')
552 ]
553
554 if not build_config_path:
555 logging.info(
Alex Kleinad6b48a2020-01-08 16:57:41 -0700556 'No build_config.json found, will not generate platform C files. '
557 'Replication config: %s', replication_config)
Andrew Lamb9563a152019-12-04 11:42:18 -0700558 return []
559
560 if len(build_config_path) > 1:
Alex Kleinad6b48a2020-01-08 16:57:41 -0700561 raise ValueError('Expected at most one build_config.json destination path. '
562 'Replication config: %s' % replication_config)
Andrew Lamb9563a152019-12-04 11:42:18 -0700563
564 build_config_path = build_config_path[0]
565
566 # Paths to the build_config.json and dir to output C files to, in the
567 # chroot.
568 build_config_chroot_path = os.path.join(constants.CHROOT_SOURCE_ROOT,
569 build_config_path)
570 generated_output_chroot_dir = os.path.join(constants.CHROOT_SOURCE_ROOT,
571 os.path.dirname(build_config_path))
572
573 command = [
574 'cros_config_schema', '-m', build_config_chroot_path, '-g',
575 generated_output_chroot_dir, '-f', '"TRUE"'
576 ]
577
578 cros_build_lib.run(
579 command, enter_chroot=True, chroot_args=chroot.get_enter_args())
580
581 # A relative (to the source root) path to the generated C files.
582 generated_output_dir = os.path.dirname(build_config_path)
583 generated_files = []
584 expected_c_files = ['config.c', 'ec_config.c', 'ec_config.h']
585 for f in expected_c_files:
586 if os.path.exists(
587 os.path.join(constants.SOURCE_ROOT, generated_output_dir, f)):
588 generated_files.append(os.path.join(generated_output_dir, f))
589
590 if len(expected_c_files) != len(generated_files):
591 raise GeneratedCrosConfigFilesError(expected_c_files, generated_files)
592
593 return generated_files
594
595
Andrew Lambe836f222019-12-09 12:27:38 -0700596def _get_private_overlay_package_root(ref, package):
597 """Returns the absolute path to the root of a given private overlay.
598
599 Args:
600 ref (uprev_lib.GitRef): GitRef for the private overlay.
601 package (str): Path to the package in the overlay.
602 """
603 # There might be a cleaner way to map from package -> path within the source
604 # tree. For now, just use string patterns.
Andrew Lamb4aa09912020-01-08 13:55:56 -0700605 private_overlay_ref_pattern = r'/chromeos\/overlays\/overlay-([\w-]+)-private'
Andrew Lambe836f222019-12-09 12:27:38 -0700606 match = re.match(private_overlay_ref_pattern, ref.path)
607 if not match:
608 raise ValueError('ref.path must match the pattern: %s. Actual ref: %s' %
609 (private_overlay_ref_pattern, ref))
610
611 overlay = match.group(1)
612
613 return os.path.join(constants.SOURCE_ROOT,
614 'src/private-overlays/overlay-%s-private' % overlay,
615 package)
616
617
Andrew Lambea9a8a22019-12-12 14:03:43 -0700618@uprevs_versioned_package('chromeos-base/chromeos-config-bsp')
619def replicate_private_config(_build_targets, refs, chroot):
Andrew Lamb2bde9e42019-11-04 13:24:09 -0700620 """Replicate a private cros_config change to the corresponding public config.
621
Alex Kleinad6b48a2020-01-08 16:57:41 -0700622 See uprev_versioned_package for args
Andrew Lamb2bde9e42019-11-04 13:24:09 -0700623 """
Andrew Lambea9a8a22019-12-12 14:03:43 -0700624 package = 'chromeos-base/chromeos-config-bsp'
625
Andrew Lamb2bde9e42019-11-04 13:24:09 -0700626 if len(refs) != 1:
627 raise ValueError('Expected exactly one ref, actual %s' % refs)
628
629 # Expect a replication_config.jsonpb in the package root.
Andrew Lambe836f222019-12-09 12:27:38 -0700630 package_root = _get_private_overlay_package_root(refs[0], package)
Andrew Lamb2bde9e42019-11-04 13:24:09 -0700631 replication_config_path = os.path.join(package_root,
632 'replication_config.jsonpb')
633
634 try:
635 replication_config = json_format.Parse(
636 osutils.ReadFile(replication_config_path),
637 replication_config_pb2.ReplicationConfig())
638 except IOError:
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700639 raise ValueError(
640 'Expected ReplicationConfig missing at %s' % replication_config_path)
Andrew Lamb2bde9e42019-11-04 13:24:09 -0700641
642 replication_lib.Replicate(replication_config)
643
644 modified_files = [
645 rule.destination_path
646 for rule in replication_config.file_replication_rules
647 ]
648
Andrew Lamb9563a152019-12-04 11:42:18 -0700649 # The generated platform C files are not easily filtered by replication rules,
650 # i.e. JSON / proto filtering can be described by a FieldMask, arbitrary C
651 # files cannot. Therefore, replicate and filter the JSON payloads, and then
652 # generate filtered C files from the JSON payload.
653 modified_files.extend(_generate_platform_c_files(replication_config, chroot))
Andrew Lamb2bde9e42019-11-04 13:24:09 -0700654
655 # Use the private repo's commit hash as the new version.
656 new_private_version = refs[0].revision
657
Andrew Lamb988f4da2019-12-10 10:16:43 -0700658 # modified_files should contain only relative paths at this point, but the
659 # returned UprevVersionedPackageResult must contain only absolute paths.
660 for i, modified_file in enumerate(modified_files):
661 assert not os.path.isabs(modified_file)
662 modified_files[i] = os.path.join(constants.SOURCE_ROOT, modified_file)
663
Chris McDonald38409112020-09-24 11:24:51 -0600664 return uprev_lib.UprevVersionedPackageResult().add_result(
665 new_private_version, modified_files)
Andrew Lamb2bde9e42019-11-04 13:24:09 -0700666
667
Alex Kleinbbef2b32019-08-27 10:38:50 -0600668def get_best_visible(atom, build_target=None):
669 """Returns the best visible CPV for the given atom.
670
671 Args:
672 atom (str): The atom to look up.
Alex Klein2960c752020-03-09 13:43:38 -0600673 build_target (build_target_lib.BuildTarget): The build target whose
Alex Kleinda39c6d2019-09-16 14:36:36 -0600674 sysroot should be searched, or the SDK if not provided.
Alex Kleinad6b48a2020-01-08 16:57:41 -0700675
676 Returns:
Alex Klein75df1792020-06-11 14:42:49 -0600677 package_info.CPV|None: The best visible package.
Alex Kleinbbef2b32019-08-27 10:38:50 -0600678 """
David Burger1e0fe232019-07-01 14:52:07 -0600679 assert atom
Alex Kleinbbef2b32019-08-27 10:38:50 -0600680
681 board = build_target.name if build_target else None
682 return portage_util.PortageqBestVisible(atom, board=board)
Alex Kleinda39c6d2019-09-16 14:36:36 -0600683
684
Alex Klein149fd3b2019-12-16 16:01:05 -0700685def has_prebuilt(atom, build_target=None, useflags=None):
Alex Kleinda39c6d2019-09-16 14:36:36 -0600686 """Check if a prebuilt exists.
687
688 Args:
689 atom (str): The package whose prebuilt is being queried.
Alex Klein2960c752020-03-09 13:43:38 -0600690 build_target (build_target_lib.BuildTarget): The build target whose
Alex Kleinda39c6d2019-09-16 14:36:36 -0600691 sysroot should be searched, or the SDK if not provided.
Alex Klein149fd3b2019-12-16 16:01:05 -0700692 useflags: Any additional USE flags that should be set. May be a string
693 of properly formatted USE flags, or an iterable of individual flags.
Alex Kleinad6b48a2020-01-08 16:57:41 -0700694
695 Returns:
696 bool: True iff there is an available prebuilt, False otherwise.
Alex Kleinda39c6d2019-09-16 14:36:36 -0600697 """
698 assert atom
699
700 board = build_target.name if build_target else None
Alex Klein149fd3b2019-12-16 16:01:05 -0700701 extra_env = None
702 if useflags:
703 new_flags = useflags
Mike Frysingercfecd6b2020-12-14 23:54:05 -0500704 if not isinstance(useflags, str):
Alex Klein149fd3b2019-12-16 16:01:05 -0700705 new_flags = ' '.join(useflags)
706
707 existing = os.environ.get('USE', '')
708 final_flags = '%s %s' % (existing, new_flags)
709 extra_env = {'USE': final_flags.strip()}
710 return portage_util.HasPrebuilt(atom, board=board, extra_env=extra_env)
Alex Klein36b117f2019-09-30 15:13:46 -0600711
712
David Burger0f9dd4e2019-10-08 12:33:42 -0600713def builds(atom, build_target, packages=None):
Alex Klein36b117f2019-09-30 15:13:46 -0600714 """Check if |build_target| builds |atom| (has it in its depgraph)."""
715 cros_build_lib.AssertInsideChroot()
716
Alex Kleind8cd4c62020-09-14 13:37:47 -0600717 pkgs = tuple(packages) if packages else None
LaMont Jones4cbecba2020-05-12 11:54:27 -0600718 # TODO(crbug/1081828): Receive and use sysroot.
719 graph, _sdk_graph = dependency.GetBuildDependency(
Alex Kleind8cd4c62020-09-14 13:37:47 -0600720 build_target.root, build_target.name, pkgs)
Alex Klein36b117f2019-09-30 15:13:46 -0600721 return any(atom in package for package in graph['package_deps'])
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600722
723
Michael Mortensenb51a1f02019-10-16 13:28:20 -0600724def determine_chrome_version(build_target):
Michael Mortensenc2615b72019-10-15 08:12:24 -0600725 """Returns the current Chrome version for the board (or in buildroot).
726
727 Args:
Alex Klein2960c752020-03-09 13:43:38 -0600728 build_target (build_target_lib.BuildTarget): The board build target.
Alex Kleinad6b48a2020-01-08 16:57:41 -0700729
730 Returns:
731 str|None: The chrome version if available.
Michael Mortensenc2615b72019-10-15 08:12:24 -0600732 """
Michael Mortensen9fe740c2019-10-29 14:42:48 -0600733 # TODO(crbug/1019770): Long term we should not need the try/catch here once
734 # the builds function above only returns True for chrome when
735 # determine_chrome_version will succeed.
736 try:
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700737 cpv = portage_util.PortageqBestVisible(
738 constants.CHROME_CP, build_target.name, cwd=constants.SOURCE_ROOT)
Michael Mortensen9fe740c2019-10-29 14:42:48 -0600739 except cros_build_lib.RunCommandError as e:
740 # Return None because portage failed when trying to determine the chrome
741 # version.
742 logging.warning('Caught exception in determine_chrome_package: %s', e)
743 return None
Michael Mortensenc2615b72019-10-15 08:12:24 -0600744 # Something like 78.0.3877.4_rc -> 78.0.3877.4
745 return cpv.version_no_rev.partition('_')[0]
746
747
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600748def determine_android_package(board):
749 """Returns the active Android container package in use by the board.
750
751 Args:
752 board: The board name this is specific to.
Alex Kleinad6b48a2020-01-08 16:57:41 -0700753
754 Returns:
755 str|None: The android package string if there is one.
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600756 """
Michael Mortensene0f4b542019-10-24 15:30:23 -0600757 try:
758 packages = portage_util.GetPackageDependencies(board, 'virtual/target-os')
Michael Mortensene0f4b542019-10-24 15:30:23 -0600759 except cros_build_lib.RunCommandError as e:
760 # Return None because a command (likely portage) failed when trying to
761 # determine the package.
762 logging.warning('Caught exception in determine_android_package: %s', e)
763 return None
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600764
Alex Kleinad6b48a2020-01-08 16:57:41 -0700765 # We assume there is only one Android package in the depgraph.
766 for package in packages:
767 if package.startswith('chromeos-base/android-container-') or \
768 package.startswith('chromeos-base/android-vm-'):
769 return package
770 return None
771
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600772
773def determine_android_version(boards=None):
774 """Determine the current Android version in buildroot now and return it.
775
776 This uses the typical portage logic to determine which version of Android
777 is active right now in the buildroot.
778
779 Args:
780 boards: List of boards to check version of.
781
782 Returns:
783 The Android build ID of the container for the boards.
784
785 Raises:
786 NoAndroidVersionError: if no unique Android version can be determined.
787 """
788 if not boards:
789 return None
790 # Verify that all boards have the same version.
791 version = None
792 for board in boards:
793 package = determine_android_package(board)
794 if not package:
Michael Mortensenedf76532019-10-16 14:22:37 -0600795 return None
Alex Klein18a60af2020-06-11 12:08:47 -0600796 cpv = package_info.SplitCPV(package)
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600797 if not cpv:
798 raise NoAndroidVersionError(
799 'Android version could not be determined for %s' % board)
800 if not version:
801 version = cpv.version_no_rev
802 elif version != cpv.version_no_rev:
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700803 raise NoAndroidVersionError('Different Android versions (%s vs %s) for %s'
804 % (version, cpv.version_no_rev, boards))
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600805 return version
806
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700807
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600808def determine_android_branch(board):
809 """Returns the Android branch in use by the active container ebuild."""
810 try:
811 android_package = determine_android_package(board)
812 except cros_build_lib.RunCommandError:
813 raise NoAndroidBranchError(
814 'Android branch could not be determined for %s' % board)
815 if not android_package:
Michael Mortensenedf76532019-10-16 14:22:37 -0600816 return None
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600817 ebuild_path = portage_util.FindEbuildForBoardPackage(android_package, board)
818 # We assume all targets pull from the same branch and that we always
Federico 'Morg' Pareschicd9165a2020-05-29 09:45:55 +0900819 # have at least one of the following targets.
Shao-Chuan Lee73bba612020-06-17 11:47:04 +0900820 targets = constants.ANDROID_ALL_BUILD_TARGETS
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600821 ebuild_content = osutils.SourceEnvironment(ebuild_path, targets)
822 for target in targets:
823 if target in ebuild_content:
824 branch = re.search(r'(.*?)-linux-', ebuild_content[target])
825 if branch is not None:
826 return branch.group(1)
827 raise NoAndroidBranchError(
828 'Android branch could not be determined for %s (ebuild empty?)' % board)
829
830
831def determine_android_target(board):
Michael Mortensen14960d02019-10-18 07:53:59 -0600832 """Returns the Android target in use by the active container ebuild."""
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600833 try:
834 android_package = determine_android_package(board)
835 except cros_build_lib.RunCommandError:
836 raise NoAndroidTargetError(
837 'Android Target could not be determined for %s' % board)
838 if not android_package:
Michael Mortensenedf76532019-10-16 14:22:37 -0600839 return None
Michael Mortensenb70e8a82019-10-10 18:43:41 -0600840 if android_package.startswith('chromeos-base/android-vm-'):
841 return 'bertha'
842 elif android_package.startswith('chromeos-base/android-container-'):
843 return 'cheets'
844
845 raise NoAndroidTargetError(
846 'Android Target cannot be determined for the package: %s' %
847 android_package)
Michael Mortensen9fdb14b2019-10-17 11:17:30 -0600848
849
850def determine_platform_version():
851 """Returns the platform version from the source root."""
Michael Mortensen009cb662019-10-21 11:38:43 -0600852 # Platform version is something like '12575.0.0'.
Michael Mortensen9fdb14b2019-10-17 11:17:30 -0600853 version = manifest_version.VersionInfo.from_repo(constants.SOURCE_ROOT)
854 return version.VersionString()
Michael Mortensen009cb662019-10-21 11:38:43 -0600855
856
857def determine_milestone_version():
858 """Returns the platform version from the source root."""
859 # Milestone version is something like '79'.
860 version = manifest_version.VersionInfo.from_repo(constants.SOURCE_ROOT)
861 return version.chrome_branch
862
Alex Klein7a3a7dd2020-01-08 16:44:38 -0700863
Michael Mortensen009cb662019-10-21 11:38:43 -0600864def determine_full_version():
865 """Returns the full version from the source root."""
866 # Full version is something like 'R79-12575.0.0'.
867 milestone_version = determine_milestone_version()
868 platform_version = determine_platform_version()
869 full_version = ('R%s-%s' % (milestone_version, platform_version))
870 return full_version
Michael Mortensen71ef5682020-05-07 14:29:24 -0600871
872
Michael Mortensende716a12020-05-15 11:27:00 -0600873def find_fingerprints(build_target):
874 """Returns a list of fingerprints for this build.
875
876 Args:
877 build_target (build_target_lib.BuildTarget): The build target.
878
879 Returns:
880 list[str] - List of fingerprint strings.
881 """
882 cros_build_lib.AssertInsideChroot()
883 fp_file = 'cheets-fingerprint.txt'
884 fp_path = os.path.join(
885 image_lib.GetLatestImageLink(build_target.name),
886 fp_file)
887 if not os.path.isfile(fp_path):
888 logging.info('Fingerprint file not found: %s', fp_path)
Michael Mortensend81d81e2020-06-09 14:20:59 -0600889 return []
Michael Mortensende716a12020-05-15 11:27:00 -0600890 logging.info('Reading fingerprint file: %s', fp_path)
891 fingerprints = osutils.ReadFile(fp_path).splitlines()
892 return fingerprints
893
894
Michael Mortensen59e30872020-05-18 14:12:49 -0600895def get_all_firmware_versions(build_target):
896 """Extract firmware version for all models present.
897
898 Args:
899 build_target (build_target_lib.BuildTarget): The build target.
900
901 Returns:
902 A dict of FirmwareVersions namedtuple instances by model.
903 Each element will be populated based on whether it was present in the
904 command output.
905 """
906 cros_build_lib.AssertInsideChroot()
907 result = {}
908 # Note that example output for _get_firmware_version_cmd_result is available
909 # in the packages_unittest.py for testing get_all_firmware_versions.
910 cmd_result = _get_firmware_version_cmd_result(build_target)
911
912 # There is a blank line between the version info for each model.
913 firmware_version_payloads = cmd_result.split('\n\n')
914 for firmware_version_payload in firmware_version_payloads:
915 if 'BIOS' in firmware_version_payload:
916 firmware_version = _find_firmware_versions(firmware_version_payload)
917 result[firmware_version.model] = firmware_version
918 return result
919
920
Michael Mortensen71ef5682020-05-07 14:29:24 -0600921FirmwareVersions = collections.namedtuple(
922 'FirmwareVersions', ['model', 'main', 'main_rw', 'ec', 'ec_rw'])
923
924
925def get_firmware_versions(build_target):
926 """Extract version information from the firmware updater, if one exists.
927
928 Args:
929 build_target (build_target_lib.BuildTarget): The build target.
930
931 Returns:
932 A FirmwareVersions namedtuple instance.
933 Each element will either be set to the string output by the firmware
934 updater shellball, or None if there is no firmware updater.
935 """
936 cros_build_lib.AssertInsideChroot()
937 cmd_result = _get_firmware_version_cmd_result(build_target)
938 if cmd_result:
939 return _find_firmware_versions(cmd_result)
940 else:
941 return FirmwareVersions(None, None, None, None, None)
942
943
944def _get_firmware_version_cmd_result(build_target):
945 """Gets the raw result output of the firmware updater version command.
946
947 Args:
948 build_target (build_target_lib.BuildTarget): The build target.
949
950 Returns:
951 Command execution result.
952 """
953 updater = os.path.join(build_target.root,
954 'usr/sbin/chromeos-firmwareupdate')
955 logging.info('Calling updater %s', updater)
956 # Call the updater using the chroot-based path.
957 return cros_build_lib.run([updater, '-V'],
958 capture_output=True, log_output=True,
959 encoding='utf-8').stdout
960
961
962def _find_firmware_versions(cmd_output):
963 """Finds firmware version output via regex matches against the cmd_output.
964
965 Args:
966 cmd_output: The raw output to search against.
967
968 Returns:
969 FirmwareVersions namedtuple with results.
970 Each element will either be set to the string output by the firmware
971 updater shellball, or None if there is no match.
972 """
973
974 # Sometimes a firmware bundle includes a special combination of RO+RW
975 # firmware. In this case, the RW firmware version is indicated with a "(RW)
976 # version" field. In other cases, the "(RW) version" field is not present.
977 # Therefore, search for the "(RW)" fields first and if they aren't present,
978 # fallback to the other format. e.g. just "BIOS version:".
979 # TODO(mmortensen): Use JSON once the firmware updater supports it.
980 main = None
981 main_rw = None
982 ec = None
983 ec_rw = None
984 model = None
985
986 match = re.search(r'BIOS version:\s*(?P<version>.*)', cmd_output)
987 if match:
988 main = match.group('version')
989
990 match = re.search(r'BIOS \(RW\) version:\s*(?P<version>.*)', cmd_output)
991 if match:
992 main_rw = match.group('version')
993
994 match = re.search(r'EC version:\s*(?P<version>.*)', cmd_output)
995 if match:
996 ec = match.group('version')
997
998 match = re.search(r'EC \(RW\) version:\s*(?P<version>.*)', cmd_output)
999 if match:
1000 ec_rw = match.group('version')
1001
1002 match = re.search(r'Model:\s*(?P<model>.*)', cmd_output)
1003 if match:
1004 model = match.group('model')
1005
1006 return FirmwareVersions(model, main, main_rw, ec, ec_rw)
Michael Mortensena4af79e2020-05-06 16:18:48 -06001007
1008
1009MainEcFirmwareVersions = collections.namedtuple(
1010 'MainEcFirmwareVersions', ['main_fw_version', 'ec_fw_version'])
1011
1012def determine_firmware_versions(build_target):
1013 """Returns a namedtuple with main and ec firmware versions.
1014
1015 Args:
1016 build_target (build_target_lib.BuildTarget): The build target.
1017
1018 Returns:
1019 MainEcFirmwareVersions namedtuple with results.
1020 """
1021 fw_versions = get_firmware_versions(build_target)
1022 main_fw_version = fw_versions.main_rw or fw_versions.main
1023 ec_fw_version = fw_versions.ec_rw or fw_versions.ec
1024
1025 return MainEcFirmwareVersions(main_fw_version, ec_fw_version)
Michael Mortensenfbf2b2d2020-05-14 16:33:06 -06001026
1027def determine_kernel_version(build_target):
1028 """Returns a string containing the kernel version for this build target.
1029
1030 Args:
1031 build_target (build_target_lib.BuildTarget): The build target.
1032
1033 Returns:
1034 (str) The kernel versions, or None.
1035 """
1036 try:
1037 packages = portage_util.GetPackageDependencies(build_target.name,
1038 'virtual/linux-sources')
1039 except cros_build_lib.RunCommandError as e:
1040 logging.warning('Unable to get package list for metadata: %s', e)
1041 return None
1042 for package in packages:
1043 if package.startswith('sys-kernel/chromeos-kernel-'):
Alex Klein18a60af2020-06-11 12:08:47 -06001044 kernel_version = package_info.SplitCPV(package).version
Michael Mortensenfbf2b2d2020-05-14 16:33:06 -06001045 logging.info('Found active kernel version: %s', kernel_version)
1046 return kernel_version
1047 return None
Michael Mortensen125bb012020-05-21 14:02:10 -06001048
1049
1050def get_models(build_target, log_output=True):
1051 """Obtain a list of models supported by a unified board.
1052
1053 This ignored whitelabel models since GoldenEye has no specific support for
1054 these at present.
1055
1056 Args:
1057 build_target (build_target_lib.BuildTarget): The build target.
1058 log_output: Whether to log the output of the cros_config_host invocation.
1059
1060 Returns:
1061 A list of models supported by this board, if it is a unified build; None,
1062 if it is not a unified build.
1063 """
1064 return _run_cros_config_host(build_target, ['list-models'],
1065 log_output=log_output)
1066
1067
Michael Mortensen359c1f32020-05-28 19:35:42 -06001068def get_key_id(build_target, model):
1069 """Obtain the key_id for a model within the build_target.
1070
1071 Args:
1072 build_target (build_target_lib.BuildTarget): The build target.
1073 model (str): The model name
1074
1075 Returns:
1076 A key_id (str) or None.
1077 """
1078 model_arg = '--model=' + model
1079 key_id_list = _run_cros_config_host(
1080 build_target,
1081 [model_arg, 'get', '/firmware-signing', 'key-id'])
1082 key_id = None
1083 if len(key_id_list) == 1:
1084 key_id = key_id_list[0]
1085 return key_id
1086
1087
Michael Mortensen125bb012020-05-21 14:02:10 -06001088def _run_cros_config_host(build_target, args, log_output=True):
1089 """Run the cros_config_host tool.
1090
1091 Args:
1092 build_target (build_target_lib.BuildTarget): The build target.
1093 args: List of arguments to pass.
1094 log_output: Whether to log the output of the cros_config_host.
1095
1096 Returns:
1097 Output of the tool
1098 """
1099 cros_build_lib.AssertInsideChroot()
1100 tool = '/usr/bin/cros_config_host'
1101 if not os.path.isfile(tool):
1102 return None
1103
1104 config_fname = build_target.full_path(
1105 'usr/share/chromeos-config/yaml/config.yaml')
1106
1107 result = cros_build_lib.run(
1108 [tool, '-c', config_fname] + args,
1109 capture_output=True,
1110 encoding='utf-8',
1111 log_output=log_output,
1112 check=False)
1113 if result.returncode:
1114 # Show the output for debugging purposes.
1115 if 'No such file or directory' not in result.error:
1116 logging.error('cros_config_host failed: %s\n', result.error)
1117 return None
1118 return result.output.strip().splitlines()