blob: 8c11a73c35f13928cb0a53ebcfbef12fa5b75993 [file] [log] [blame]
Kuang-che Wu6e4beca2018-06-27 17:45:02 +08001# -*- coding: utf-8 -*-
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08002# Copyright 2017 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"""ChromeOS utility.
6
7Terminology used in this module.
8 short_version: ChromeOS version number without milestone, like "9876.0.0".
9 full_version: ChromeOS version number with milestone, like "R62-9876.0.0".
Zheng-Jie Chang127c3302019-09-10 17:17:04 +080010 snapshot_version: ChromeOS version number with milestone and snapshot id,
11 like "R62-9876.0.0-12345".
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080012 version: if not specified, it could be in short or full format.
13"""
14
15from __future__ import print_function
Kuang-che Wub9705bd2018-06-28 17:59:18 +080016import ast
Kuang-che Wu72b5a572019-10-29 20:37:57 +080017import calendar
Zheng-Jie Chang127c3302019-09-10 17:17:04 +080018import datetime
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080019import errno
20import json
21import logging
22import os
23import re
Kuang-che Wuad5ac7b2020-02-20 19:02:52 +080024import shutil
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080025import subprocess
Kuang-che Wud558a042020-06-06 02:11:00 +080026import sys
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080027import time
28
Zheng-Jie Chang4fabff62019-12-08 21:54:35 +080029from google.protobuf import json_format
30
Zheng-Jie Chang2b6d1472019-11-13 12:40:17 +080031from bisect_kit import buildbucket_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080032from bisect_kit import cli
Kuang-che Wue4bae0b2018-07-19 12:10:14 +080033from bisect_kit import codechange
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080034from bisect_kit import cr_util
Kuang-che Wue121fae2018-11-09 16:18:39 +080035from bisect_kit import errors
Kuang-che Wubfc4a642018-04-19 11:54:08 +080036from bisect_kit import git_util
Kuang-che Wufb553102018-10-02 18:14:29 +080037from bisect_kit import locking
Kuang-che Wubfc4a642018-04-19 11:54:08 +080038from bisect_kit import repo_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080039from bisect_kit import util
40
41logger = logging.getLogger(__name__)
42
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080043re_chromeos_full_version = r'^R\d+-\d+\.\d+\.\d+$'
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080044re_chromeos_localbuild_version = r'^\d+\.\d+\.\d{4}_\d\d_\d\d_\d{4}$'
45re_chromeos_short_version = r'^\d+\.\d+\.\d+$'
Zheng-Jie Chang127c3302019-09-10 17:17:04 +080046re_chromeos_snapshot_version = r'^R\d+-\d+\.\d+\.\d+-\d+$'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080047
48gs_archive_path = 'gs://chromeos-image-archive/{board}-release'
49gs_release_path = (
Kuang-che Wu80bf6a52019-05-31 12:48:06 +080050 'gs://chromeos-releases/{channel}-channel/{boardpath}/{short_version}')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080051
52# Assume gsutil is in PATH.
53gsutil_bin = 'gsutil'
Zheng-Jie Changb8697042019-10-29 16:03:26 +080054
55# Since snapshots with version >= 12618.0.0 have android and chrome version
56# info.
57snapshot_cutover_version = '12618.0.0'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080058
Zheng-Jie Chang61a645a2020-04-29 10:12:13 +080059# current earliest buildbucket buildable versions
60# picked from https://crrev.com/c/2072618
61buildbucket_cutover_versions = [
62 '12931.0.0',
63 '12871.26.0', # R81
64 '12871.24.2', # stabilize-12871.24.B
65 '12812.10.0', # factory-excelsior-12812.B
66 '12768.14.0', # firmware-servo-12768.B
67 '12739.85.0', # R80
68 '12739.67.1', # stabilize-excelsior-12739.67.B
69 '12692.36.0', # factory-hatch-12692.B
70 '12672.104.0', # firmware-hatch-12672.B
71 '12607.110.0', # R79
72 '12607.83.2', # stabilize-quickfix-12607.83.B
73 '12587.59.0', # factory-kukui-12587.B
74 '12573.78.0', # firmware-kukui-12573.B
75 '12499.96.0', # R78
76 '12422.33.0', # firmware-mistral-12422.B
77 '12371.190.0', # R77
78 '12361.38.0', # factory-mistral-12361.B
79 '12200.65.0', # firmware-sarien-12200.B
80 '12105.128.0', # R75
81 '12033.82.0', # factory-sarien-12033.B
82]
83
Kuang-che Wub9705bd2018-06-28 17:59:18 +080084chromeos_root_inside_chroot = '/mnt/host/source'
85# relative to chromeos_root
Kuang-che Wu7f82c6f2019-08-12 14:29:28 +080086prebuilt_autotest_dir = 'tmp/autotest-prebuilt'
Kuang-che Wu28980b22019-07-31 19:51:45 +080087# Relative to chromeos root. Images are cached_images_dir/$board/$image_name.
88cached_images_dir = 'src/build/images'
89test_image_filename = 'chromiumos_test_image.bin'
Kuang-che Wub9705bd2018-06-28 17:59:18 +080090
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080091VERSION_KEY_CROS_SHORT_VERSION = 'cros_short_version'
92VERSION_KEY_CROS_FULL_VERSION = 'cros_full_version'
93VERSION_KEY_MILESTONE = 'milestone'
94VERSION_KEY_CR_VERSION = 'cr_version'
Kuang-che Wu708310b2018-03-28 17:24:34 +080095VERSION_KEY_ANDROID_BUILD_ID = 'android_build_id'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080096VERSION_KEY_ANDROID_BRANCH = 'android_branch'
Zheng-Jie Chang5f9ae4e2020-02-07 14:26:06 +080097CROSLAND_URL_TEMPLATE = 'https://crosland.corp.google.com/log/%s..%s'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080098
99
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800100class NeedRecreateChrootException(Exception):
101 """Failed to build ChromeOS because of chroot mismatch or corruption"""
102
103
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800104def is_cros_short_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800105 """Determines if `s` is chromeos short version.
106
107 This function doesn't accept version number of local build.
108 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800109 return bool(re.match(re_chromeos_short_version, s))
110
111
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800112def is_cros_localbuild_version(s):
113 """Determines if `s` is chromeos local build version."""
114 return bool(re.match(re_chromeos_localbuild_version, s))
115
116
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800117def is_cros_full_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800118 """Determines if `s` is chromeos full version.
119
120 This function doesn't accept version number of local build.
121 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800122 return bool(re.match(re_chromeos_full_version, s))
123
124
125def is_cros_version(s):
126 """Determines if `s` is chromeos version (either short or full)"""
127 return is_cros_short_version(s) or is_cros_full_version(s)
128
129
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800130def is_cros_snapshot_version(s):
131 """Determines if `s` is chromeos snapshot version"""
132 return bool(re.match(re_chromeos_snapshot_version, s))
133
134
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800135def is_cros_version_lesseq(ver1, ver2):
136 """Determines if ver1 is less or equal to ver2.
137
138 Args:
139 ver1: a Chrome OS version in short, full, or snapshot format.
140 ver2: a Chrome OS version in short, full, or snapshot format.
141
142 Returns:
Zheng-Jie Chang61a645a2020-04-29 10:12:13 +0800143 True if ver1 is less or equal to ver2.
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800144 """
145 assert is_cros_version(ver1) or is_cros_snapshot_version(ver1)
146 assert is_cros_version(ver2) or is_cros_snapshot_version(ver2)
147
148 ver1 = [int(x) for x in re.split(r'[.-]', ver1) if not x.startswith('R')]
149 ver2 = [int(x) for x in re.split(r'[.-]', ver2) if not x.startswith('R')]
150 return ver1 <= ver2
151
152
Zheng-Jie Chang61a645a2020-04-29 10:12:13 +0800153def is_buildbucket_buildable(version):
154 """Determines if a version is buildable on buildbucket."""
155 short_version = version_to_short(version)
156 # If given version is child of any cutover, then it's buildable
157 return any([
158 util.is_direct_relative_version(x, short_version) and
159 is_cros_version_lesseq(x, version) for x in buildbucket_cutover_versions
160 ])
161
162
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800163def make_cros_full_version(milestone, short_version):
164 """Makes full_version from milestone and short_version"""
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800165 assert milestone
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800166 return 'R%s-%s' % (milestone, short_version)
167
168
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800169def make_cros_snapshot_version(milestone, short_version, snapshot_id):
170 """Makes snapshot version from milestone, short_version and snapshot id"""
171 return 'R%s-%s-%s' % (milestone, short_version, snapshot_id)
172
173
174def version_split(version):
175 """Splits full_version or snapshot_version into milestone and short_version"""
176 assert is_cros_full_version(version) or is_cros_snapshot_version(version)
177 if is_cros_snapshot_version(version):
178 return snapshot_version_split(version)[0:2]
179 milestone, short_version = version.split('-')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800180 return milestone[1:], short_version
181
182
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800183def snapshot_version_split(snapshot_version):
184 """Splits snapshot_version into milestone, short_version and snapshot_id"""
185 assert is_cros_snapshot_version(snapshot_version)
186 milestone, shot_version, snapshot_id = snapshot_version.split('-')
187 return milestone[1:], shot_version, snapshot_id
188
189
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800190def query_snapshot_buildbucket_id(board, snapshot_version):
191 """Query buildbucket id of a snapshot"""
192 assert is_cros_snapshot_version(snapshot_version)
Zheng-Jie Chang54020832020-04-21 15:52:48 +0800193 path = ('gs://chromeos-image-archive/{board}-snapshot'
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800194 '/{snapshot_version}-*/image.zip')
195 output = gsutil_ls(
196 '-d',
197 path.format(board=board, snapshot_version=snapshot_version),
198 ignore_errors=True)
199 for line in output:
Zheng-Jie Chang54020832020-04-21 15:52:48 +0800200 m = re.match(r'.*-snapshot/R\d+-\d+\.\d+\.\d+-\d+-(.+)/image\.zip', line)
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800201 if m:
202 return m.group(1)
203 return None
204
205
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800206def argtype_cros_version(s):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800207 if (not is_cros_version(s)) and (not is_cros_snapshot_version(s)):
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800208 msg = 'invalid cros version'
Kuang-che Wuce2f3be2019-10-28 19:44:54 +0800209 raise cli.ArgTypeError(msg, '9876.0.0, R62-9876.0.0 or R77-12369.0.0-11681')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800210 return s
211
212
213def query_dut_lsb_release(host):
214 """Query /etc/lsb-release of given DUT
215
216 Args:
217 host: the DUT address
218
219 Returns:
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800220 dict for keys and values of /etc/lsb-release.
221
222 Raises:
Kuang-che Wu44278142019-03-04 11:33:57 +0800223 errors.SshConnectionError: cannot connect to host
224 errors.ExternalError: lsb-release file doesn't exist
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800225 """
226 try:
Kuang-che Wu44278142019-03-04 11:33:57 +0800227 output = util.ssh_cmd(host, 'cat', '/etc/lsb-release')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800228 except subprocess.CalledProcessError:
Kuang-che Wu44278142019-03-04 11:33:57 +0800229 raise errors.ExternalError('unable to read /etc/lsb-release; not a DUT')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800230 return dict(re.findall(r'^(\w+)=(.*)$', output, re.M))
231
232
Kuang-che Wuf134ebf2020-08-18 21:06:47 +0800233def query_dut_os_release(host):
234 """Query /etc/os-release of given DUT
235
236 Args:
237 host: the DUT address
238
239 Returns:
240 dict for keys and values of /etc/os-release.
241
242 Raises:
243 errors.SshConnectionError: cannot connect to host
244 errors.ExternalError: lsb-release file doesn't exist
245 """
246 try:
247 output = util.ssh_cmd(host, 'cat', '/etc/os-release')
248 except subprocess.CalledProcessError:
249 raise errors.ExternalError('unable to read /etc/os-release; not a DUT')
250 return dict(re.findall(r'^(\w+)=(.*)$', output, re.M))
251
252
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800253def is_dut(host):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800254 """Determines whether a host is a chromeos device.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800255
256 Args:
257 host: the DUT address
258
259 Returns:
260 True if the host is a chromeos device.
261 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800262 try:
Kuang-che Wuf134ebf2020-08-18 21:06:47 +0800263 return query_dut_os_release(host).get('ID') in [
264 'chromiumos',
265 'chromeos',
Kuang-che Wu44278142019-03-04 11:33:57 +0800266 ]
267 except (errors.ExternalError, errors.SshConnectionError):
268 return False
269
270
271def is_good_dut(host):
272 if not is_dut(host):
273 return False
274
275 # Sometimes python is broken after 'cros flash'.
276 try:
277 util.ssh_cmd(host, 'python', '-c', '1')
278 return True
279 except (subprocess.CalledProcessError, errors.SshConnectionError):
280 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800281
282
283def query_dut_board(host):
284 """Query board name of a given DUT"""
285 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_BOARD')
286
287
288def query_dut_short_version(host):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800289 """Query short version of a given DUT.
290
291 This function may return version of local build, which
292 is_cros_short_version() is false.
293 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800294 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_VERSION')
295
296
Zheng-Jie Chang26084542020-04-29 06:34:33 +0800297def query_dut_prebuilt_version(host):
298 """Return a snapshot version or short version of a given DUT.
299
300 Args:
301 host: dut host
302
303 Returns:
304 Snapshot version or short version.
305 """
306 lsb_release = query_dut_lsb_release(host)
307 release_version = lsb_release.get('CHROMEOS_RELEASE_VERSION')
308 builder_path = lsb_release.get('CHROMEOS_RELEASE_BUILDER_PATH')
309 match = re.match(r'\S+-(?:snapshot|postsubmit)/(R\d+-\d+\.\d+\.\d+-\d+)-\d+',
310 builder_path)
311 if match:
312 return match.group(1)
313 return release_version
314
315
Zheng-Jie Chang181be6f2020-03-17 16:16:08 +0800316def query_dut_is_by_official_builder(host):
317 """Query if given DUT is build by buildbucket builder"""
318 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_BUILD_TYPE',
319 '').startswith('Continuous Builder')
320
321
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800322def query_dut_boot_id(host, connect_timeout=None):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800323 """Query boot id.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800324
325 Args:
326 host: DUT address
327 connect_timeout: connection timeout
328
329 Returns:
330 boot uuid
331 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800332 return util.ssh_cmd(
333 host,
334 'cat',
335 '/proc/sys/kernel/random/boot_id',
336 connect_timeout=connect_timeout).strip()
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800337
338
Kuang-che Wu2ac9a922020-09-03 16:50:12 +0800339def reboot(host, force_reboot_callback=None):
340 """Reboot a DUT and verify.
341
342 Args:
343 host: DUT address
344 force_reboot_callback: powerful reboot hook (via servo). This will be
345 invoked if normal reboot failed.
346 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800347 logger.debug('reboot %s', host)
348 boot_id = query_dut_boot_id(host)
349
Kuang-che Wu44278142019-03-04 11:33:57 +0800350 try:
351 util.ssh_cmd(host, 'reboot')
Kuang-che Wu5f662e82019-03-05 11:49:56 +0800352 except errors.SshConnectionError:
353 # Depends on timing, ssh may return failure due to broken pipe, which is
354 # working as intended. Ignore such kind of errors.
Kuang-che Wu44278142019-03-04 11:33:57 +0800355 pass
Kuang-che Wu2ac9a922020-09-03 16:50:12 +0800356
357 try:
358 wait_reboot_done(host, boot_id)
359 except (errors.SshConnectionError, errors.ExternalError):
360 if force_reboot_callback and force_reboot_callback(host):
361 wait_reboot_done(host, boot_id)
362 return
363 raise
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800364
Kuang-che Wu708310b2018-03-28 17:24:34 +0800365
366def wait_reboot_done(host, boot_id):
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800367 # For dev-mode test image, the reboot time is roughly at least 16 seconds
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800368 # (dev screen short delay) or more (long delay).
369 time.sleep(15)
370 for _ in range(100):
371 try:
372 # During boot, DUT does not response and thus ssh may hang a while. So
373 # set a connect timeout. 3 seconds are enough and 2 are not. It's okay to
374 # set tight limit because it's inside retry loop.
375 assert boot_id != query_dut_boot_id(host, connect_timeout=3)
376 return
Kuang-che Wu5f662e82019-03-05 11:49:56 +0800377 except errors.SshConnectionError:
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800378 logger.debug('reboot not ready? sleep wait 1 sec')
379 time.sleep(1)
380
Kuang-che Wue121fae2018-11-09 16:18:39 +0800381 raise errors.ExternalError('reboot failed?')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800382
383
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800384def gs_release_boardpath(board):
385 """Normalizes board name for gs://chromeos-releases/
386
387 This follows behavior of PushImage() in chromite/scripts/pushimage.py
388 Note, only gs://chromeos-releases/ needs normalization,
389 gs://chromeos-image-archive does not.
390
391 Args:
392 board: ChromeOS board name
393
394 Returns:
395 normalized board name
396 """
397 return board.replace('_', '-')
398
399
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800400def gsutil(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800401 """gsutil command line wrapper.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800402
403 Args:
404 args: command line arguments passed to gsutil
405 kwargs:
406 ignore_errors: if true, return '' for failures, for example 'gsutil ls'
407 but the path not found.
408
409 Returns:
410 stdout of gsutil
411
412 Raises:
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800413 errors.ExternalError: gsutil failed to run
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800414 subprocess.CalledProcessError: command failed
415 """
416 stderr_lines = []
417 try:
418 return util.check_output(
419 gsutil_bin, *args, stderr_callback=stderr_lines.append)
420 except subprocess.CalledProcessError as e:
421 stderr = ''.join(stderr_lines)
422 if re.search(r'ServiceException:.* does not have .*access', stderr):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800423 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800424 'gsutil failed due to permission. ' +
425 'Run "%s config" and follow its instruction. ' % gsutil_bin +
426 'Fill any string if it asks for project-id')
427 if kwargs.get('ignore_errors'):
428 return ''
429 raise
430 except OSError as e:
431 if e.errno == errno.ENOENT:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800432 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800433 'Unable to run %s. gsutil is not installed or not in PATH?' %
434 gsutil_bin)
435 raise
436
437
438def gsutil_ls(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800439 """gsutil ls.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800440
441 Args:
442 args: arguments passed to 'gsutil ls'
443 kwargs: extra parameters, where
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800444 ignore_errors: if true, return empty list instead of raising
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800445 exception, ex. path not found.
446
447 Returns:
448 list of 'gsutil ls' result. One element for one line of gsutil output.
449
450 Raises:
451 subprocess.CalledProcessError: gsutil failed, usually means path not found
452 """
453 return gsutil('ls', *args, **kwargs).splitlines()
454
455
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800456def gsutil_stat_update_time(*args, **kwargs):
457 """Returns the last modified time of a file or multiple files.
458
459 Args:
460 args: arguments passed to 'gsutil stat'.
461 kwargs: extra parameters for gsutil.
462
463 Returns:
464 A integer indicates the last modified timestamp.
465
466 Raises:
467 subprocess.CalledProcessError: gsutil failed, usually means path not found
468 errors.ExternalError: update time is not found
469 """
470 result = -1
471 # Currently we believe stat always returns a UTC time, and strptime also
472 # parses a UTC time by default.
473 time_format = '%a, %d %b %Y %H:%M:%S GMT'
474
475 for line in gsutil('stat', *args, **kwargs).splitlines():
476 if ':' not in line:
477 continue
Kuang-che Wuc89f2a22019-11-26 15:30:50 +0800478 key, value = line.split(':', 1)
479 key, value = key.strip(), value.strip()
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800480 if key != 'Update time':
481 continue
482 dt = datetime.datetime.strptime(value, time_format)
Kuang-che Wu72b5a572019-10-29 20:37:57 +0800483 unixtime = int(calendar.timegm(dt.utctimetuple()))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800484 result = max(result, unixtime)
485
486 if result == -1:
487 raise errors.ExternalError("didn't find update time")
488 return result
489
490
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800491def query_milestone_by_version(board, short_version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800492 """Query milestone by ChromeOS version number.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800493
494 Args:
495 board: ChromeOS board name
496 short_version: ChromeOS version number in short format, ex. 9300.0.0
497
498 Returns:
499 ChromeOS milestone number (string). For example, '58' for '9300.0.0'.
500 None if failed.
501 """
502 path = gs_archive_path.format(board=board) + '/R*-' + short_version
503 for line in gsutil_ls('-d', path, ignore_errors=True):
504 m = re.search(r'/R(\d+)-', line)
505 if not m:
506 continue
507 return m.group(1)
508
509 for channel in ['canary', 'dev', 'beta', 'stable']:
510 path = gs_release_path.format(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800511 channel=channel,
512 boardpath=gs_release_boardpath(board),
513 short_version=short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800514 for line in gsutil_ls(path, ignore_errors=True):
515 m = re.search(r'\bR(\d+)-' + short_version, line)
516 if not m:
517 continue
518 return m.group(1)
519
Zheng-Jie Chang4e25a8d2020-01-08 16:00:13 +0800520 logger.debug('unable to query milestone of %s for %s', short_version, board)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800521 return None
522
523
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800524def list_board_names(chromeos_root):
525 """List board names.
526
527 Args:
528 chromeos_root: chromeos tree root
529
530 Returns:
531 list of board names
532 """
533 # Following logic is simplified from chromite/lib/portage_util.py
534 cros_list_overlays = os.path.join(chromeos_root,
535 'chromite/bin/cros_list_overlays')
536 overlays = util.check_output(cros_list_overlays).splitlines()
537 result = set()
538 for overlay in overlays:
539 conf_file = os.path.join(overlay, 'metadata', 'layout.conf')
540 name = None
541 if os.path.exists(conf_file):
542 for line in open(conf_file):
543 m = re.match(r'^repo-name\s*=\s*(\S+)\s*$', line)
544 if m:
545 name = m.group(1)
546 break
547
548 if not name:
549 name_file = os.path.join(overlay, 'profiles', 'repo_name')
550 if os.path.exists(name_file):
Kuang-che Wua5723492019-11-25 20:59:34 +0800551 with open(name_file) as f:
552 name = f.read().strip()
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800553
554 if name:
555 name = re.sub(r'-private$', '', name)
556 result.add(name)
557
558 return list(result)
559
560
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800561def recognize_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800562 """Recognize ChromeOS version.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800563
564 Args:
565 board: ChromeOS board name
566 version: ChromeOS version number in short or full format
567
568 Returns:
569 (milestone, version in short format)
570 """
571 if is_cros_short_version(version):
572 milestone = query_milestone_by_version(board, version)
573 short_version = version
574 else:
575 milestone, short_version = version_split(version)
576 return milestone, short_version
577
578
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800579def extract_major_version(version):
580 """Converts a version to its major version.
581
582 Args:
Kuang-che Wu9501f342019-11-15 17:15:21 +0800583 version: ChromeOS version number or snapshot version
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800584
585 Returns:
586 major version number in string format
587 """
588 version = version_to_short(version)
589 m = re.match(r'^(\d+)\.\d+\.\d+$', version)
590 return m.group(1)
591
592
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800593def version_to_short(version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800594 """Convert ChromeOS version number to short format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800595
596 Args:
597 version: ChromeOS version number in short or full format
598
599 Returns:
600 version number in short format
601 """
602 if is_cros_short_version(version):
603 return version
604 _, short_version = version_split(version)
605 return short_version
606
607
608def version_to_full(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800609 """Convert ChromeOS version number to full format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800610
611 Args:
612 board: ChromeOS board name
613 version: ChromeOS version number in short or full format
614
615 Returns:
616 version number in full format
617 """
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800618 if is_cros_snapshot_version(version):
619 milestone, short_version, _ = snapshot_version_split(version)
620 return make_cros_full_version(milestone, short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800621 if is_cros_full_version(version):
622 return version
623 milestone = query_milestone_by_version(board, version)
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800624 if not milestone:
625 raise errors.ExternalError('incorrect board=%s or version=%s ?' %
626 (board, version))
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800627 return make_cros_full_version(milestone, version)
628
629
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800630def list_snapshots_from_image_archive(board, major_version):
Kuang-che Wu9501f342019-11-15 17:15:21 +0800631 """List ChromeOS snapshot image available from gs://chromeos-image-archive.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800632
633 Args:
634 board: ChromeOS board
635 major_version: ChromeOS major version
636
637 Returns:
638 list of (version, gs_path):
639 version: Chrome OS snapshot version
640 gs_path: gs path of test image
641 """
642
Zheng-Jie Chang43a08412019-12-05 17:05:45 +0800643 def extract_snapshot_id(result):
644 m = re.match(r'^R\d+-\d+\.\d+\.\d+-(\d+)', result[0])
645 assert m
646 return int(m.group(1))
647
Zheng-Jie Changa331b872020-01-06 17:09:32 +0800648 short_version = '%s.0.0' % major_version
649 milestone = query_milestone_by_version(board, short_version)
650 if not milestone:
651 milestone = '*'
652
Zheng-Jie Chang54020832020-04-21 15:52:48 +0800653 path = ('gs://chromeos-image-archive/{board}-snapshot/R{milestone}-'
Zheng-Jie Changa331b872020-01-06 17:09:32 +0800654 '{short_version}-*/image.zip')
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800655 result = []
656 output = gsutil_ls(
Zheng-Jie Changa331b872020-01-06 17:09:32 +0800657 path.format(
658 board=board, milestone=milestone, short_version=short_version),
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800659 ignore_errors=True)
660
Zheng-Jie Changa331b872020-01-06 17:09:32 +0800661 for gs_path in sorted(output):
662 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)', gs_path)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800663 if m:
664 snapshot_version = m.group(1)
Zheng-Jie Chang43a08412019-12-05 17:05:45 +0800665 # we should skip if there is duplicate snapshot
666 if result and result[-1][0] == snapshot_version:
667 continue
Zheng-Jie Chang1ae64c32020-03-10 14:08:28 +0800668
669 # b/151054108: snapshot version in [29288, 29439] is broken
670 _, _, snapshot_id = snapshot_version_split(snapshot_version)
671 if 29288 <= int(snapshot_id) <= 29439:
672 continue
673
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800674 result.append((snapshot_version, gs_path))
Zheng-Jie Chang43a08412019-12-05 17:05:45 +0800675
676 # sort by its snapshot_id
677 result.sort(key=extract_snapshot_id)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800678 return result
679
680
Kuang-che Wu575dc442019-03-05 10:30:55 +0800681def list_prebuilt_from_image_archive(board):
682 """Lists ChromeOS prebuilt image available from gs://chromeos-image-archive.
683
684 gs://chromeos-image-archive contains only recent builds (in two years).
685 We prefer this function to list_prebuilt_from_chromeos_releases() because
686 - this is what "cros flash" supports directly.
687 - the paths have milestone information, so we don't need to do slow query
688 by ourselves.
689
690 Args:
691 board: ChromeOS board name
692
693 Returns:
694 list of (version, gs_path):
695 version: Chrome OS version in full format
696 gs_path: gs path of test image
697 """
698 result = []
699 for line in gsutil_ls(gs_archive_path.format(board=board)):
700 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+)', line)
701 if m:
702 full_version = m.group(1)
703 test_image = 'chromiumos_test_image.tar.xz'
704 assert line.endswith('/')
705 gs_path = line + test_image
706 result.append((full_version, gs_path))
707 return result
708
709
710def list_prebuilt_from_chromeos_releases(board):
711 """Lists ChromeOS versions available from gs://chromeos-releases.
712
713 gs://chromeos-releases contains more builds. However, 'cros flash' doesn't
714 support it.
715
716 Args:
717 board: ChromeOS board name
718
719 Returns:
720 list of (version, gs_path):
721 version: Chrome OS version in short format
722 gs_path: gs path of test image (with wildcard)
723 """
724 result = []
725 for line in gsutil_ls(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800726 gs_release_path.format(
727 channel='*', boardpath=gs_release_boardpath(board), short_version=''),
Kuang-che Wu575dc442019-03-05 10:30:55 +0800728 ignore_errors=True):
729 m = re.match(r'gs:\S+/(\d+\.\d+\.\d+)/$', line)
730 if m:
731 short_version = m.group(1)
732 test_image = 'ChromeOS-test-R*-{short_version}-{board}.tar.xz'.format(
733 short_version=short_version, board=board)
734 gs_path = line + test_image
735 result.append((short_version, gs_path))
736 return result
737
738
Kuang-che Wue1808402020-01-06 20:27:45 +0800739def has_test_image(board, version):
740 if is_cros_snapshot_version(version):
741 return bool(query_snapshot_buildbucket_id(board, version))
742
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800743 try:
744 full_version = version_to_full(board, version)
745 except errors.ExternalError:
746 # version_to_full() is implemented by checking image, thus its failure
747 # means no image.
748 return False
Kuang-che Wue1808402020-01-06 20:27:45 +0800749 short_version = version_to_short(version)
750 paths = [
751 gs_archive_path.format(board=board) +
752 '/%s/chromiumos_test_image.tar.xz' % full_version,
753 gs_release_path.format(
754 channel='*',
755 boardpath=gs_release_boardpath(board),
756 short_version=short_version),
757 ]
758
759 for path in paths:
760 if gsutil_ls(path, ignore_errors=True):
761 return True
762 return False
763
764
Kuang-che Wu575dc442019-03-05 10:30:55 +0800765def list_chromeos_prebuilt_versions(board,
766 old,
767 new,
768 only_good_build=True,
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800769 include_older_build=True,
770 use_snapshot=False):
Kuang-che Wu575dc442019-03-05 10:30:55 +0800771 """Lists ChromeOS version numbers with prebuilt between given range
772
773 Args:
774 board: ChromeOS board name
775 old: start version (inclusive)
776 new: end version (inclusive)
777 only_good_build: only if test image is available
778 include_older_build: include prebuilt in gs://chromeos-releases
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800779 use_snapshot: return snapshot versions if found
Kuang-che Wu575dc442019-03-05 10:30:55 +0800780
781 Returns:
782 list of sorted version numbers (in full format) between [old, new] range
783 (inclusive).
784 """
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800785 old_short = version_to_short(old)
786 new_short = version_to_short(new)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800787
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800788 rev_map = {
789 } # dict: short version -> list of (short/full or snapshot version, gs path)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800790 for full_version, gs_path in list_prebuilt_from_image_archive(board):
791 short_version = version_to_short(full_version)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800792 rev_map[short_version] = [(full_version, gs_path)]
Kuang-che Wu575dc442019-03-05 10:30:55 +0800793
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800794 if include_older_build and old_short not in rev_map:
Kuang-che Wu575dc442019-03-05 10:30:55 +0800795 for short_version, gs_path in list_prebuilt_from_chromeos_releases(board):
796 if short_version not in rev_map:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800797 rev_map[short_version] = [(short_version, gs_path)]
798
799 if use_snapshot:
800 for major_version in range(
801 int(extract_major_version(old)),
802 int(extract_major_version(new)) + 1):
803 short_version = '%s.0.0' % major_version
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800804 next_short_version = '%s.0.0' % (major_version + 1)
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800805 # If current version is smaller than cutover, ignore it as it might not
806 # contain enough information for continuing android and chrome bisection.
807 if not util.is_version_lesseq(snapshot_cutover_version, short_version):
808 continue
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800809
810 # Given the fact that snapshots are images between two release versions.
811 # Adding snapshots of 12345.0.0 should be treated as adding commits
812 # between [12345.0.0, 12346.0.0).
813 # So in the following lines we check two facts:
814 # 1) If 12346.0.0(next_short_version) is a version between old and new
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800815 if not util.is_direct_relative_version(next_short_version, old_short):
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800816 continue
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800817 if not util.is_direct_relative_version(next_short_version, new_short):
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800818 continue
819 # 2) If 12345.0.0(short_version) is a version between old and new
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800820 if not util.is_direct_relative_version(short_version, old_short):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800821 continue
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800822 if not util.is_direct_relative_version(short_version, new_short):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800823 continue
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800824
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800825 snapshots = list_snapshots_from_image_archive(board, str(major_version))
826 if snapshots:
827 # if snapshots found, we can append them after the release version,
828 # so the prebuilt image list of this version will be
829 # release_image, snapshot1, snapshot2,...
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800830 if short_version not in rev_map:
831 rev_map[short_version] = []
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800832 rev_map[short_version] += snapshots
Kuang-che Wu575dc442019-03-05 10:30:55 +0800833
834 result = []
835 for rev in sorted(rev_map, key=util.version_key_func):
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800836 if not util.is_direct_relative_version(new_short, rev):
Kuang-che Wu575dc442019-03-05 10:30:55 +0800837 continue
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800838 if not util.is_version_lesseq(old_short, rev):
Kuang-che Wu575dc442019-03-05 10:30:55 +0800839 continue
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800840 if not util.is_version_lesseq(rev, new_short):
Kuang-che Wu575dc442019-03-05 10:30:55 +0800841 continue
842
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800843 for version, gs_path in rev_map[rev]:
Kuang-che Wu575dc442019-03-05 10:30:55 +0800844
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800845 # version_to_full() and gsutil_ls() may take long time if versions are a
846 # lot. This is acceptable because we usually bisect only short range.
Kuang-che Wu575dc442019-03-05 10:30:55 +0800847
Zheng-Jie Changa331b872020-01-06 17:09:32 +0800848 if only_good_build and not is_cros_snapshot_version(version):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800849 gs_result = gsutil_ls(gs_path, ignore_errors=True)
850 if not gs_result:
851 logger.warning('%s is not a good build, ignore', version)
852 continue
853 assert len(gs_result) == 1
854 m = re.search(r'(R\d+-\d+\.\d+\.\d+)', gs_result[0])
855 if not m:
856 logger.warning('format of image path is unexpected: %s', gs_result[0])
857 continue
Zheng-Jie Changa331b872020-01-06 17:09:32 +0800858 version = m.group(1)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800859 elif is_cros_short_version(version):
860 version = version_to_full(board, version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800861
Zheng-Jie Changaea4fba2020-02-17 17:12:09 +0800862 if is_cros_version_lesseq(old, version) and is_cros_version_lesseq(
863 version, new):
864 result.append(version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800865
866 return result
867
868
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800869def prepare_snapshot_image(chromeos_root, board, snapshot_version):
870 """Prepare chromeos snapshot image.
871
872 Args:
873 chromeos_root: chromeos tree root
874 board: ChromeOS board name
875 snapshot_version: ChromeOS snapshot version number
876
877 Returns:
878 local file path of test image relative to chromeos_root
879 """
880 assert is_cros_snapshot_version(snapshot_version)
881 milestone, short_version, snapshot_id = snapshot_version_split(
882 snapshot_version)
883 full_version = make_cros_full_version(milestone, short_version)
884 tmp_dir = os.path.join(
885 chromeos_root, 'tmp',
886 'ChromeOS-test-%s-%s-%s' % (full_version, board, snapshot_id))
887 if not os.path.exists(tmp_dir):
888 os.makedirs(tmp_dir)
889
Zheng-Jie Chang54020832020-04-21 15:52:48 +0800890 gs_path = ('gs://chromeos-image-archive/{board}-snapshot/' +
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800891 '{snapshot_version}-*/image.zip')
892 gs_path = gs_path.format(board=board, snapshot_version=snapshot_version)
893
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800894 full_path = os.path.join(tmp_dir, test_image_filename)
895 rel_path = os.path.relpath(full_path, chromeos_root)
896 if os.path.exists(full_path):
897 return rel_path
898
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800899 files = gsutil_ls(gs_path, ignore_errors=True)
Zheng-Jie Changeb7308f2019-12-05 14:25:05 +0800900 if len(files) >= 1:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800901 gs_path = files[0]
902 gsutil('cp', gs_path, tmp_dir)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800903 util.check_call(
904 'unzip', '-j', 'image.zip', test_image_filename, cwd=tmp_dir)
905 os.remove(os.path.join(tmp_dir, 'image.zip'))
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800906 return rel_path
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800907
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800908 assert False
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +0800909 return None
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800910
911
Kuang-che Wu28980b22019-07-31 19:51:45 +0800912def prepare_prebuilt_image(chromeos_root, board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800913 """Prepare chromeos prebuilt image.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800914
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800915 It searches for xbuddy image which "cros flash" can use, or fetch image to
916 local disk.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800917
918 Args:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800919 chromeos_root: chromeos tree root
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800920 board: ChromeOS board name
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800921 version: ChromeOS version number in short or full format
922
923 Returns:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800924 xbuddy path or file path (relative to chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800925 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800926 assert is_cros_version(version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800927 full_version = version_to_full(board, version)
928 short_version = version_to_short(full_version)
929
930 image_path = None
931 gs_path = gs_archive_path.format(board=board) + '/' + full_version
932 if gsutil_ls('-d', gs_path, ignore_errors=True):
933 image_path = 'xbuddy://remote/{board}/{full_version}/test'.format(
934 board=board, full_version=full_version)
935 else:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800936 tmp_dir = os.path.join(chromeos_root, 'tmp',
937 'ChromeOS-test-%s-%s' % (full_version, board))
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800938 full_path = os.path.join(tmp_dir, test_image_filename)
939 rel_path = os.path.relpath(full_path, chromeos_root)
940 if os.path.exists(full_path):
941 return rel_path
942
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800943 if not os.path.exists(tmp_dir):
944 os.makedirs(tmp_dir)
945 # gs://chromeos-releases may have more old images than
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800946 # gs://chromeos-image-archive, but 'cros flash' doesn't support it. We have
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800947 # to fetch the image by ourselves
948 for channel in ['canary', 'dev', 'beta', 'stable']:
949 fn = 'ChromeOS-test-{full_version}-{board}.tar.xz'.format(
950 full_version=full_version, board=board)
951 gs_path = gs_release_path.format(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800952 channel=channel,
953 boardpath=gs_release_boardpath(board),
954 short_version=short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800955 gs_path += '/' + fn
956 if gsutil_ls(gs_path, ignore_errors=True):
957 # TODO(kcwu): delete tmp
958 gsutil('cp', gs_path, tmp_dir)
959 util.check_call('tar', 'Jxvf', fn, cwd=tmp_dir)
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800960 image_path = os.path.relpath(full_path, chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800961 break
962
963 assert image_path
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800964 return image_path
965
966
967def cros_flash(chromeos_root,
968 host,
969 board,
970 image_path,
971 version=None,
972 clobber_stateful=False,
Kuang-che Wu2ac9a922020-09-03 16:50:12 +0800973 disable_rootfs_verification=True,
974 force_reboot_callback=None):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800975 """Flash a DUT with given ChromeOS image.
976
977 This is implemented by 'cros flash' command line.
978
979 Args:
980 chromeos_root: use 'cros flash' of which chromeos tree
981 host: DUT address
982 board: ChromeOS board name
Kuang-che Wu28980b22019-07-31 19:51:45 +0800983 image_path: chromeos image xbuddy path or file path. For relative
984 path, it should be relative to chromeos_root.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800985 version: ChromeOS version in short or full format
986 clobber_stateful: Clobber stateful partition when performing update
987 disable_rootfs_verification: Disable rootfs verification after update
988 is completed
Kuang-che Wu2ac9a922020-09-03 16:50:12 +0800989 force_reboot_callback: powerful reboot hook (via servo)
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800990
991 Raises:
992 errors.ExternalError: cros flash failed
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800993 """
994 logger.info('cros_flash %s %s %s %s', host, board, version, image_path)
995
996 # Reboot is necessary because sometimes previous 'cros flash' failed and
997 # entered a bad state.
Kuang-che Wu2ac9a922020-09-03 16:50:12 +0800998 reboot(host, force_reboot_callback=force_reboot_callback)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800999
Kuang-che Wu020a1182020-09-08 17:17:22 +08001000 # Stop service ap-update-manager to prevent rebooting during auto update.
Kuang-che Wu2e0680b2020-08-19 22:41:28 +08001001 # The service is used in jetstream boards, but not other CrOS devices.
1002 if query_dut_os_release(host).get('GOOGLE_CRASH_ID') == 'Jetstream':
1003 try:
Kuang-che Wu29e2eaf2020-08-21 16:51:26 +08001004 # Sleep to wait ap-update-manager start, which may take up to 27 seconds.
1005 # For simplicity, we wait 60 seconds here, which is the timeout value of
1006 # jetstream_host.
1007 # https://chromium.googlesource.com/chromiumos/third_party/autotest
1008 # /+/master/server/hosts/jetstream_host.py#27
1009 time.sleep(60)
Kuang-che Wu2e0680b2020-08-19 22:41:28 +08001010 util.ssh_cmd(host, 'stop', 'ap-update-manager')
1011 except subprocess.CalledProcessError:
1012 pass # not started; do nothing
1013
Kuang-che Wu28980b22019-07-31 19:51:45 +08001014 # Handle relative path.
1015 if '://' not in image_path and not os.path.isabs(image_path):
1016 assert os.path.exists(os.path.join(chromeos_root, image_path))
1017 image_path = os.path.join(chromeos_root_inside_chroot, image_path)
1018
Kuang-che Wuf3d03ca2019-03-11 17:31:40 +08001019 args = [
1020 '--debug', '--no-ping', '--send-payload-in-parallel', host, image_path
1021 ]
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08001022 if clobber_stateful:
1023 args.append('--clobber-stateful')
1024 if disable_rootfs_verification:
1025 args.append('--disable-rootfs-verification')
1026
Kuang-che Wu414d67f2019-05-28 11:28:57 +08001027 try:
1028 cros_sdk(chromeos_root, 'cros', 'flash', *args)
1029 except subprocess.CalledProcessError:
1030 raise errors.ExternalError('cros flash failed')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08001031
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001032 if version:
1033 # In the past, cros flash may fail with returncode=0
1034 # So let's have an extra check.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001035 if is_cros_snapshot_version(version):
1036 builder_path = query_dut_lsb_release(host).get(
1037 'CHROMEOS_RELEASE_BUILDER_PATH', '')
Zheng-Jie Chang54020832020-04-21 15:52:48 +08001038 expect_prefix = '%s-snapshot/%s-' % (board, version)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001039 if not builder_path.startswith(expect_prefix):
1040 raise errors.ExternalError(
1041 'although cros flash succeeded, the OS builder path is '
1042 'unexpected: actual=%s expect=%s' % (builder_path, expect_prefix))
1043 else:
1044 expect_version = version_to_short(version)
1045 dut_version = query_dut_short_version(host)
1046 if dut_version != expect_version:
1047 raise errors.ExternalError(
1048 'although cros flash succeeded, the OS version is unexpected: '
1049 'actual=%s expect=%s' % (dut_version, expect_version))
Kuang-che Wu414d67f2019-05-28 11:28:57 +08001050
Kuang-che Wu4a81ea72019-10-05 15:35:17 +08001051 # "cros flash" may terminate successfully but the DUT starts self-repairing
Kuang-che Wu414d67f2019-05-28 11:28:57 +08001052 # (b/130786578), so it's necessary to do sanity check.
1053 if not is_good_dut(host):
1054 raise errors.ExternalError(
1055 'although cros flash succeeded, the DUT is in bad state')
1056
1057
1058def cros_flash_with_retry(chromeos_root,
1059 host,
1060 board,
1061 image_path,
1062 version=None,
1063 clobber_stateful=False,
1064 disable_rootfs_verification=True,
Kuang-che Wu2ac9a922020-09-03 16:50:12 +08001065 repair_callback=None,
1066 force_reboot_callback=None):
Kuang-che Wu414d67f2019-05-28 11:28:57 +08001067 # 'cros flash' is not 100% reliable, retry if necessary.
1068 for attempt in range(2):
1069 if attempt > 0:
1070 logger.info('will retry 60 seconds later')
1071 time.sleep(60)
1072
1073 try:
1074 cros_flash(
1075 chromeos_root,
1076 host,
1077 board,
1078 image_path,
1079 version=version,
1080 clobber_stateful=clobber_stateful,
Kuang-che Wu2ac9a922020-09-03 16:50:12 +08001081 disable_rootfs_verification=disable_rootfs_verification,
1082 force_reboot_callback=force_reboot_callback)
Kuang-che Wu414d67f2019-05-28 11:28:57 +08001083 return True
1084 except errors.ExternalError:
1085 logger.exception('cros flash failed')
1086 if repair_callback and not repair_callback(host):
1087 logger.warning('not repaired, assume it is harmless')
1088 continue
1089 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08001090
1091
1092def version_info(board, version):
1093 """Query subcomponents version info of given version of ChromeOS
1094
1095 Args:
1096 board: ChromeOS board name
1097 version: ChromeOS version number in short or full format
1098
1099 Returns:
1100 dict of component and version info, including (if available):
1101 cros_short_version: ChromeOS version
1102 cros_full_version: ChromeOS version
1103 milestone: milestone of ChromeOS
1104 cr_version: Chrome version
Kuang-che Wu708310b2018-03-28 17:24:34 +08001105 android_build_id: Android build id
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08001106 android_branch: Android branch, in format like 'git_nyc-mr1-arc'
1107 """
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001108 if is_cros_snapshot_version(version):
Zheng-Jie Chang2b6d1472019-11-13 12:40:17 +08001109 api = buildbucket_util.BuildbucketApi()
Zheng-Jie Changb8697042019-10-29 16:03:26 +08001110 milestone, short_version, _ = snapshot_version_split(version)
1111 buildbucket_id = query_snapshot_buildbucket_id(board, version)
Zheng-Jie Chang597c38b2020-03-12 22:24:10 +08001112 data = api.get_build(int(buildbucket_id)).output.properties
Zheng-Jie Chang4fabff62019-12-08 21:54:35 +08001113 target_versions = json_format.MessageToDict(data['target_versions'])
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001114 return {
Zheng-Jie Changb8697042019-10-29 16:03:26 +08001115 VERSION_KEY_MILESTONE: milestone,
1116 VERSION_KEY_CROS_FULL_VERSION: version,
1117 VERSION_KEY_CROS_SHORT_VERSION: short_version,
Zheng-Jie Chang2d1dd9b2019-12-07 23:30:20 +08001118 VERSION_KEY_CR_VERSION: target_versions.get('chromeVersion'),
1119 VERSION_KEY_ANDROID_BUILD_ID: target_versions.get('androidVersion'),
1120 VERSION_KEY_ANDROID_BRANCH: target_versions.get('androidBranchVersion'),
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001121 }
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08001122 info = {}
1123 full_version = version_to_full(board, version)
1124
1125 # Some boards may have only partial-metadata.json but no metadata.json.
1126 # e.g. caroline R60-9462.0.0
1127 # Let's try both.
1128 metadata = None
1129 for metadata_filename in ['metadata.json', 'partial-metadata.json']:
Kuang-che Wu0768b972019-10-05 15:18:59 +08001130 path = gs_archive_path.format(
1131 board=board) + '/%s/%s' % (full_version, metadata_filename)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08001132 metadata = gsutil('cat', path, ignore_errors=True)
1133 if metadata:
1134 o = json.loads(metadata)
1135 v = o['version']
1136 board_metadata = o['board-metadata'][board]
1137 info.update({
1138 VERSION_KEY_CROS_SHORT_VERSION: v['platform'],
1139 VERSION_KEY_CROS_FULL_VERSION: v['full'],
1140 VERSION_KEY_MILESTONE: v['milestone'],
1141 VERSION_KEY_CR_VERSION: v['chrome'],
1142 })
1143
1144 if 'android' in v:
Kuang-che Wu708310b2018-03-28 17:24:34 +08001145 info[VERSION_KEY_ANDROID_BUILD_ID] = v['android']
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08001146 if 'android-branch' in v: # this appears since R58-9317.0.0
1147 info[VERSION_KEY_ANDROID_BRANCH] = v['android-branch']
1148 elif 'android-container-branch' in board_metadata:
1149 info[VERSION_KEY_ANDROID_BRANCH] = v['android-container-branch']
1150 break
1151 else:
1152 logger.error('Failed to read metadata from gs://chromeos-image-archive')
1153 logger.error(
1154 'Note, so far no quick way to look up version info for too old builds')
1155
1156 return info
Kuang-che Wu848b1af2018-02-01 20:59:36 +08001157
1158
1159def query_chrome_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001160 """Queries chrome version of chromeos build.
Kuang-che Wu848b1af2018-02-01 20:59:36 +08001161
1162 Args:
1163 board: ChromeOS board name
1164 version: ChromeOS version number in short or full format
1165
1166 Returns:
1167 Chrome version number
1168 """
1169 info = version_info(board, version)
1170 return info['cr_version']
Kuang-che Wu708310b2018-03-28 17:24:34 +08001171
1172
1173def query_android_build_id(board, rev):
1174 info = version_info(board, rev)
1175 rev = info['android_build_id']
1176 return rev
1177
1178
1179def query_android_branch(board, rev):
1180 info = version_info(board, rev)
1181 rev = info['android_branch']
1182 return rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001183
1184
Kuang-che Wu3eb6b502018-06-06 16:15:18 +08001185def guess_chrome_version(board, rev):
1186 """Guess chrome version number.
1187
1188 Args:
1189 board: chromeos board name
1190 rev: chrome or chromeos version
1191
1192 Returns:
1193 chrome version number
1194 """
1195 if is_cros_version(rev):
1196 assert board, 'need to specify BOARD for cros version'
1197 rev = query_chrome_version(board, rev)
1198 assert cr_util.is_chrome_version(rev)
1199
1200 return rev
1201
1202
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001203def is_inside_chroot():
1204 """Returns True if we are inside chroot."""
1205 return os.path.exists('/etc/cros_chroot_version')
1206
1207
Kuang-che Wuad5ac7b2020-02-20 19:02:52 +08001208def convert_path_outside_chroot(chromeos_root, path):
1209 """Converts path in chroot to outside.
1210
1211 Args:
1212 chromeos_root: chromeos tree root
1213 path: path inside chroot; support starting with '~/'
1214
1215 Returns:
1216 The corresponding path outside chroot assuming the chroot is mounted
1217 """
1218 if path.startswith('~/'):
1219 path = path.replace('~', '/home/' + os.environ['USER'])
1220 assert '~' not in path, 'tilde (~) character is not fully supported'
1221
1222 assert os.path.isabs(path)
1223 assert path[0] == os.sep
1224 return os.path.join(chromeos_root, 'chroot', path[1:])
1225
1226
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001227def cros_sdk(chromeos_root, *args, **kwargs):
1228 """Run commands inside chromeos chroot.
1229
1230 Args:
1231 chromeos_root: chromeos tree root
1232 *args: command to run
1233 **kwargs:
Kuang-che Wud4603d72018-11-29 17:51:21 +08001234 chrome_root: pass to cros_sdk; mount this path into the SDK chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001235 env: (dict) environment variables for the command
Kuang-che Wubcafc552019-08-15 15:27:02 +08001236 log_stdout: Whether write the stdout output of the child process to log.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001237 stdin: standard input file handle for the command
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001238 stderr_callback: Callback function for stderr. Called once per line.
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001239 goma_dir: Goma installed directory to mount into the chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001240 """
1241 envs = []
1242 for k, v in kwargs.get('env', {}).items():
1243 assert re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', k)
1244 envs.append('%s=%s' % (k, v))
1245
1246 # Use --no-ns-pid to prevent cros_sdk change our pgid, otherwise subsequent
1247 # commands would be considered as background process.
Kuang-che Wu399d4662019-06-06 15:23:37 +08001248 prefix = ['chromite/bin/cros_sdk', '--no-ns-pid']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001249
1250 if kwargs.get('chrome_root'):
Kuang-che Wu399d4662019-06-06 15:23:37 +08001251 prefix += ['--chrome_root', kwargs['chrome_root']]
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001252 if kwargs.get('goma_dir'):
1253 prefix += ['--goma_dir', kwargs['goma_dir']]
Kuang-che Wud4603d72018-11-29 17:51:21 +08001254
Kuang-che Wu399d4662019-06-06 15:23:37 +08001255 prefix += envs + ['--']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001256
Kuang-che Wu399d4662019-06-06 15:23:37 +08001257 # In addition to the output of command we are interested, cros_sdk may
1258 # generate its own messages. For example, chroot creation messages if we run
1259 # cros_sdk the first time.
1260 # This is the hack to run dummy command once, so we can get clean output for
1261 # the command we are interested.
1262 cmd = prefix + ['true']
Kuang-che Wu62677012020-07-13 14:25:18 +08001263 try:
1264 util.check_call(*cmd, cwd=chromeos_root)
1265 except subprocess.CalledProcessError:
1266 logger.exception('cros_sdk init/update failed')
1267 raise
Kuang-che Wu399d4662019-06-06 15:23:37 +08001268
1269 cmd = prefix + list(args)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001270 return util.check_output(
1271 *cmd,
1272 cwd=chromeos_root,
Kuang-che Wubcafc552019-08-15 15:27:02 +08001273 log_stdout=kwargs.get('log_stdout', True),
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001274 stdin=kwargs.get('stdin'),
1275 stderr_callback=kwargs.get('stderr_callback'))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001276
1277
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001278def create_chroot(chromeos_root):
Kuang-che Wuad5ac7b2020-02-20 19:02:52 +08001279 """Creates ChromeOS chroot if necessary.
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001280
1281 Args:
1282 chromeos_root: chromeos tree root
1283 """
1284 if os.path.exists(os.path.join(chromeos_root, 'chroot')):
1285 return
1286 if os.path.exists(os.path.join(chromeos_root, 'chroot.img')):
1287 return
1288
1289 util.check_output('chromite/bin/cros_sdk', '--create', cwd=chromeos_root)
1290
1291
Kuang-che Wuad5ac7b2020-02-20 19:02:52 +08001292def mount_chroot(chromeos_root):
1293 """Creates ChromeOS chroot if necessary.
1294
1295 Args:
1296 chromeos_root: chromeos tree root
1297 """
1298 # An arbitrary file must exist in chroot.
1299 path = convert_path_outside_chroot(chromeos_root, '/bin/ls')
1300
1301 # Not created or mounted yet.
1302 if not os.path.exists(path):
1303 create_chroot(chromeos_root)
1304 # After this command, the chroot is mounted.
1305 cros_sdk(chromeos_root, 'true')
1306 assert os.path.exists(path)
1307
1308
1309def copy_into_chroot(chromeos_root, src, dst, overwrite=True):
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001310 """Copies file into chromeos chroot.
1311
Kuang-che Wuad5ac7b2020-02-20 19:02:52 +08001312 The side effect is chroot created and mounted.
1313
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001314 Args:
1315 chromeos_root: chromeos tree root
1316 src: path outside chroot
1317 dst: path inside chroot
Kuang-che Wu020a1182020-09-08 17:17:22 +08001318 overwrite: overwrite if dst already exists
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001319 """
Kuang-che Wuad5ac7b2020-02-20 19:02:52 +08001320 mount_chroot(chromeos_root)
1321 src = os.path.expanduser(src)
1322 dst_outside = convert_path_outside_chroot(chromeos_root, dst)
1323 if not overwrite and os.path.exists(dst_outside):
1324 return
1325
1326 # Haven't support directory or special files yet.
1327 assert os.path.isfile(src)
1328 assert os.path.isfile(dst_outside) or not os.path.exists(dst_outside)
1329
1330 dirname = os.path.dirname(dst_outside)
1331 if not os.path.exists(dirname):
1332 os.makedirs(dirname)
1333 shutil.copy(src, dst_outside)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001334
1335
Kuang-che Wuad5ac7b2020-02-20 19:02:52 +08001336def prepare_chroot(chromeos_root):
1337 mount_chroot(chromeos_root)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001338
Kuang-che Wuad5ac7b2020-02-20 19:02:52 +08001339 # Work around b/149077936:
1340 # The creds file is copied into the chroot since 12866.0.0.
1341 # But earlier versions need this file as well because of cipd ACL change.
1342 creds_path = '~/.config/chrome_infra/auth/creds.json'
1343 if os.path.exists(os.path.expanduser(creds_path)):
1344 copy_into_chroot(chromeos_root, creds_path, creds_path, overwrite=False)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001345
1346
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001347def check_if_need_recreate_chroot(stdout, stderr):
1348 """Analyze build log and determine if chroot should be recreated.
1349
1350 Args:
1351 stdout: stdout output of build
1352 stderr: stderr output of build
1353
1354 Returns:
1355 the reason if chroot needs recreated; None otherwise
1356 """
Kuang-che Wu74768d32018-09-07 12:03:24 +08001357 if re.search(
1358 r"The current version of portage supports EAPI '\d+'. "
Kuang-che Wuae6824b2019-08-27 22:20:01 +08001359 'You must upgrade', stderr):
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001360 return 'EAPI version mismatch'
1361
Kuang-che Wu5ac81322018-11-26 14:04:06 +08001362 if 'Chroot is too new. Consider running:' in stderr:
1363 return 'chroot version is too new'
1364
1365 # old message before Oct 2018
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001366 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
1367 return 'chroot version is too new'
1368
Kuang-che Wu6fe987f2018-08-28 15:24:20 +08001369 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
1370 if "undefined reference to 'std::__1::basic_string" in stdout:
1371 return 'might be due to compiler change'
1372
Kuang-che Wu94e3b452019-11-21 12:49:18 +08001373 # Detect failures due to file collisions.
1374 # For example, kernel uprev from 3.x to 4.x, they are two separate packages
1375 # and conflict with each other. Other possible cases are package renaming or
1376 # refactoring. Let's recreate chroot to work around them.
1377 if 'Detected file collision' in stdout:
1378 # Using wildcard between words because the text wraps to the next line
1379 # depending on length of package name and each line is prefixed with
1380 # package name.
1381 # Using ".{,100}" instead of ".*" to prevent regex matching time explodes
1382 # exponentially. 100 is chosen arbitrarily. It should be longer than any
1383 # package name (65 now).
1384 m = re.search(
1385 r'Package (\S+).{,100}NOT.{,100}merged.{,100}'
1386 r'due.{,100}to.{,100}file.{,100}collisions', stdout, re.S)
1387 if m:
1388 return 'failed to install package due to file collision: ' + m.group(1)
Kuang-che Wu356c3522019-11-19 16:11:05 +08001389
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001390 return None
1391
1392
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001393def build_packages(chromeos_root,
1394 board,
1395 chrome_root=None,
1396 goma_dir=None,
1397 afdo_use=False):
Kuang-che Wu28980b22019-07-31 19:51:45 +08001398 """Build ChromeOS packages.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001399
1400 Args:
1401 chromeos_root: chromeos tree root
1402 board: ChromeOS board name
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001403 chrome_root: Chrome tree root. If specified, build chrome using the
1404 provided tree
1405 goma_dir: Goma installed directory to mount into the chroot. If specified,
1406 build chrome with goma.
1407 afdo_use: build chrome with AFDO optimization
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001408 """
Zheng-Jie Changffd49462019-12-16 12:15:18 +08001409
1410 def has_build_package_argument(argument):
1411 stderr_lines = []
1412 try:
1413 util.check_call(
1414 'src/scripts/build_packages',
1415 '--help',
1416 cwd=chromeos_root,
1417 stderr_callback=stderr_lines.append)
1418 except subprocess.CalledProcessError:
1419 help_output = ''.join(stderr_lines)
1420 return '--[no]%s' % argument in help_output
1421
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001422 common_env = {
1423 'USE': '-cros-debug chrome_internal',
1424 'FEATURES': 'separatedebug',
1425 }
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001426 stderr_lines = []
1427 try:
Kuang-che Wufb553102018-10-02 18:14:29 +08001428 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001429 env = common_env.copy()
1430 env['FEATURES'] += ' -separatedebug splitdebug'
Kuang-che Wufb553102018-10-02 18:14:29 +08001431 cros_sdk(
1432 chromeos_root,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001433 './update_chroot',
1434 '--toolchain_boards',
Kuang-che Wufb553102018-10-02 18:14:29 +08001435 board,
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001436 env=env,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001437 stderr_callback=stderr_lines.append)
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001438
1439 env = common_env.copy()
1440 cmd = [
Kuang-che Wu28980b22019-07-31 19:51:45 +08001441 './build_packages',
1442 '--board',
1443 board,
1444 '--withdev',
1445 '--noworkon',
1446 '--skip_chroot_upgrade',
1447 '--accept_licenses=@CHROMEOS',
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001448 ]
Zheng-Jie Changffd49462019-12-16 12:15:18 +08001449
1450 # `use_any_chrome` flag is default on and will force to use a chrome
1451 # prebuilt even if the version doesn't match.
1452
1453 # As this argument is landed in 12681, we should check if the argument
1454 # exists before adding this.
1455 if has_build_package_argument('use_any_chrome'):
1456 cmd.append('--nouse_any_chrome')
1457
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001458 if goma_dir:
1459 # Tell build_packages to start and stop goma
1460 cmd.append('--run_goma')
1461 env['USE_GOMA'] = 'true'
1462 if afdo_use:
1463 env['USE'] += ' afdo_use'
1464 cros_sdk(
1465 chromeos_root,
1466 *cmd,
1467 env=env,
1468 chrome_root=chrome_root,
1469 stderr_callback=stderr_lines.append,
1470 goma_dir=goma_dir)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001471 except subprocess.CalledProcessError as e:
1472 # Detect failures due to incompatibility between chroot and source tree. If
1473 # so, notify the caller to recreate chroot and retry.
1474 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1475 if reason:
1476 raise NeedRecreateChrootException(reason)
1477
1478 # For other failures, don't know how to handle. Just bail out.
1479 raise
1480
Kuang-che Wu28980b22019-07-31 19:51:45 +08001481
1482def build_image(chromeos_root, board):
1483 """Build ChromeOS image.
1484
1485 Args:
1486 chromeos_root: chromeos tree root
1487 board: ChromeOS board name
1488
1489 Returns:
1490 image folder; relative to chromeos_root
1491 """
1492 stderr_lines = []
1493 try:
1494 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
1495 cros_sdk(
1496 chromeos_root,
1497 './build_image',
1498 '--board',
1499 board,
1500 '--noenable_rootfs_verification',
1501 'test',
1502 env={
1503 'USE': '-cros-debug chrome_internal',
1504 'FEATURES': 'separatedebug',
1505 },
1506 stderr_callback=stderr_lines.append)
1507 except subprocess.CalledProcessError as e:
1508 # Detect failures due to incompatibility between chroot and source tree. If
1509 # so, notify the caller to recreate chroot and retry.
1510 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1511 if reason:
1512 raise NeedRecreateChrootException(reason)
1513
1514 # For other failures, don't know how to handle. Just bail out.
1515 raise
1516
1517 image_symlink = os.path.join(chromeos_root, cached_images_dir, board,
1518 'latest')
1519 assert os.path.exists(image_symlink)
1520 image_name = os.readlink(image_symlink)
1521 image_folder = os.path.join(cached_images_dir, board, image_name)
1522 assert os.path.exists(
1523 os.path.join(chromeos_root, image_folder, test_image_filename))
1524 return image_folder
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001525
1526
Kuang-che Wu23192ad2020-03-11 18:12:46 +08001527class AutotestControlInfo:
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001528 """Parsed content of autotest control file.
1529
1530 Attributes:
1531 name: test name
1532 path: control file path
1533 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
1534 DOC, ATTRIBUTES, DEPENDENCIES, etc.
1535 """
1536
1537 def __init__(self, path, variables):
1538 self.name = variables['NAME']
1539 self.path = path
1540 self.variables = variables
1541
1542
1543def parse_autotest_control_file(path):
1544 """Parses autotest control file.
1545
1546 This only parses simple top-level string assignments.
1547
1548 Returns:
1549 AutotestControlInfo object
1550 """
1551 variables = {}
Kuang-che Wua5723492019-11-25 20:59:34 +08001552 with open(path) as f:
1553 code = ast.parse(f.read())
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001554 for stmt in code.body:
1555 # Skip if not simple "NAME = *" assignment.
1556 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
1557 isinstance(stmt.targets[0], ast.Name)):
1558 continue
1559
1560 # Only support string value.
1561 if isinstance(stmt.value, ast.Str):
1562 variables[stmt.targets[0].id] = stmt.value.s
1563
1564 return AutotestControlInfo(path, variables)
1565
1566
1567def enumerate_autotest_control_files(autotest_dir):
1568 """Enumerate autotest control files.
1569
1570 Args:
1571 autotest_dir: autotest folder
1572
1573 Returns:
1574 list of paths to control files
1575 """
1576 # Where to find control files. Relative to autotest_dir.
1577 subpaths = [
1578 'server/site_tests',
1579 'client/site_tests',
1580 'server/tests',
1581 'client/tests',
1582 ]
1583
Kuang-che Wud6df63c2020-09-20 01:29:55 +08001584 denylist = ['site-packages', 'venv', 'results', 'logs', 'containers']
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001585 result = []
1586 for subpath in subpaths:
1587 path = os.path.join(autotest_dir, subpath)
1588 for root, dirs, files in os.walk(path):
1589
Kuang-che Wud6df63c2020-09-20 01:29:55 +08001590 for deny in denylist:
1591 if deny in dirs:
1592 dirs.remove(deny)
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001593
1594 for filename in files:
1595 if filename == 'control' or filename.startswith('control.'):
1596 result.append(os.path.join(root, filename))
1597
1598 return result
1599
1600
1601def get_autotest_test_info(autotest_dir, test_name):
1602 """Get metadata of given test.
1603
1604 Args:
1605 autotest_dir: autotest folder
1606 test_name: test name
1607
1608 Returns:
1609 AutotestControlInfo object. None if test not found.
1610 """
1611 for control_file in enumerate_autotest_control_files(autotest_dir):
Zheng-Jie Chang1504a552020-02-20 16:38:57 +08001612 try:
1613 info = parse_autotest_control_file(control_file)
1614 except SyntaxError:
1615 logger.warning('%s is not parsable, ignore', control_file)
1616 continue
1617
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001618 if info.name == test_name:
1619 return info
1620 return None
1621
1622
Zheng-Jie Chang868c1752020-01-21 14:42:41 +08001623def detect_branch_level(branch):
1624 """Given a branch name of manifest-internal, detect it's branch level.
1625
1626 level1: if ChromeOS version is x.0.0
1627 level2: if ChromeOS version is x.x.0
1628 level3: if ChromeOS version is x.x.x
1629 Where x is an non-zero integer.
1630
1631 Args:
1632 branch: branch name or ref name in manifest-internal
1633
1634 Returns:
1635 An integer indicates the branch level, or zero if not detectable.
1636 """
1637 level1 = r'^(refs\/\S+(\/\S+)?/)?master$'
1638 level2 = r'^\S+-(\d+)(\.0)?\.B$'
1639 level3 = r'^\S+-(\d+)\.(\d+)(\.0)?\.B$'
1640
1641 if re.match(level1, branch):
1642 return 1
1643 if re.match(level2, branch):
1644 return 2
1645 if re.match(level3, branch):
1646 return 3
1647 return 0
1648
1649
Zheng-Jie Chang5f9ae4e2020-02-07 14:26:06 +08001650def get_crosland_link(old, new):
1651 """Generates crosland link between two versions.
1652
1653 Args:
1654 old: ChromeOS version
1655 new: ChromeOS version
1656
1657 Returns:
1658 A crosland url.
1659 """
1660
1661 def version_to_url_parameter(ver):
1662 if is_cros_snapshot_version(ver):
1663 return snapshot_version_split(ver)[2]
1664 return version_to_short(ver)
1665
1666 old_parameter = version_to_url_parameter(old)
1667 new_parameter = version_to_url_parameter(new)
1668 return CROSLAND_URL_TEMPLATE % (old_parameter, new_parameter)
1669
1670
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001671class ChromeOSSpecManager(codechange.SpecManager):
1672 """Repo manifest related operations.
1673
1674 This class enumerates chromeos manifest files, parses them,
1675 and sync to disk state according to them.
1676 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001677
1678 def __init__(self, config):
1679 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001680 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
1681 'manifests')
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001682 self.manifest_internal_dir = os.path.join(self.config['chromeos_mirror'],
1683 'manifest-internal.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001684 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001685 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001686 if not os.path.exists(self.historical_manifest_git_dir):
Kuang-che Wue121fae2018-11-09 16:18:39 +08001687 raise errors.InternalError('Manifest snapshots should be cloned into %s' %
1688 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001689
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001690 def lookup_snapshot_manifest_revisions(self, old, new):
1691 """Get manifest commits between snapshot versions.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001692
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001693 Returns:
1694 list of (timestamp, commit_id, snapshot_id):
1695 timestamp: integer unix timestamp
1696 commit_id: a string indicates commit hash
1697 snapshot_id: a string indicates snapshot id
1698 """
1699 assert is_cros_snapshot_version(old)
1700 assert is_cros_snapshot_version(new)
1701
1702 gs_path = (
Zheng-Jie Chang54020832020-04-21 15:52:48 +08001703 'gs://chromeos-image-archive/{board}-snapshot/{version}-*/image.zip')
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001704 # Try to guess the commit time of a snapshot manifest, it is usually a few
1705 # minutes different between snapshot manifest commit and image.zip
1706 # generate.
1707 try:
1708 old_timestamp = gsutil_stat_update_time(
1709 gs_path.format(board=self.config['board'], version=old)) - 86400
1710 except subprocess.CalledProcessError:
1711 old_timestamp = None
1712 try:
1713 new_timestamp = gsutil_stat_update_time(
1714 gs_path.format(board=self.config['board'], version=new)) + 86400
1715 # 1558657989 is snapshot_id 5982's commit time, this ensures every time
1716 # we can find snapshot 5982
1717 # snapshot_id <= 5982 has different commit message format, so we need
1718 # to identify its id in different ways, see below comment for more info.
1719 new_timestamp = max(new_timestamp, 1558657989 + 1)
1720 except subprocess.CalledProcessError:
1721 new_timestamp = None
1722 result = []
1723 _, _, old_snapshot_id = snapshot_version_split(old)
1724 _, _, new_snapshot_id = snapshot_version_split(new)
1725 repo = self.manifest_internal_dir
1726 path = 'snapshot.xml'
1727 branch = 'snapshot'
1728 commits = git_util.get_history(
1729 repo,
1730 path,
1731 branch,
1732 after=old_timestamp,
1733 before=new_timestamp,
1734 with_subject=True)
1735
1736 # Unfortunately, we can not identify snapshot_id <= 5982 from its commit
1737 # subject, as their subjects are all `Annealing manifest snapshot.`.
1738 # So instead we count the snapshot_id manually.
1739 count = 5982
1740 # There are two snapshot_id = 2633 in commit history, ignore the former
1741 # one.
1742 ignore_list = ['95c8526a7f0798d02f692010669dcbd5a152439a']
1743 # We examine the commits in reverse order as there are some testing
1744 # commits before snapshot_id=2, this method works fine after
1745 # snapshot 2, except snapshot 2633
1746 for commit in reversed(commits):
1747 msg = commit[2]
1748 if commit[1] in ignore_list:
1749 continue
1750
1751 match = re.match(r'^annealing manifest snapshot (\d+)', msg)
1752 if match:
1753 snapshot_id = match.group(1)
1754 elif 'Annealing manifest snapshot' in msg:
1755 snapshot_id = str(count)
1756 count -= 1
1757 else:
1758 continue
Zheng-Jie Chang34595ea2020-03-10 13:04:22 +08001759 # b/151054108: snapshot version in [29288, 29439] is broken
1760 if 29288 <= int(snapshot_id) <= 29439:
1761 continue
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001762 if int(old_snapshot_id) <= int(snapshot_id) <= int(new_snapshot_id):
1763 result.append((commit[0], commit[1], snapshot_id))
1764 # We find commits in reversed order, now reverse it again to chronological
1765 # order.
1766 return list(reversed(result))
1767
1768 def lookup_build_timestamp(self, rev):
1769 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
1770 if is_cros_full_version(rev):
1771 return self.lookup_release_build_timestamp(rev)
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +08001772 return self.lookup_snapshot_build_timestamp(rev)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001773
1774 def lookup_snapshot_build_timestamp(self, rev):
1775 assert is_cros_snapshot_version(rev)
1776 return int(self.lookup_snapshot_manifest_revisions(rev, rev)[0][0])
1777
1778 def lookup_release_build_timestamp(self, rev):
1779 assert is_cros_full_version(rev)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001780 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001781 path = os.path.join('buildspecs', milestone, short_version + '.xml')
1782 try:
1783 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1784 'refs/heads/master', path)
1785 except ValueError:
Kuang-che Wud1b74152020-05-20 08:46:46 +08001786 raise errors.InternalError('%s does not have %s' %
1787 (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001788 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001789
Zheng-Jie Chang868c1752020-01-21 14:42:41 +08001790 def detect_float_spec_branch_level(self, spec):
1791 results = [
1792 detect_branch_level(branch) for branch in git_util.get_branches(
1793 self.manifest_dir, commit=spec.name)
1794 ]
1795 results = [x for x in results if x > 0]
1796 return min(results) if results else 0
1797
1798 def branch_between_float_specs(self, old_spec, new_spec):
1799 if old_spec.spec_type != codechange.SPEC_FLOAT:
1800 return False
1801 if new_spec.spec_type != codechange.SPEC_FLOAT:
1802 return False
1803
1804 level_old = self.detect_float_spec_branch_level(old_spec)
1805 level_new = self.detect_float_spec_branch_level(new_spec)
1806
1807 if not level_old or not level_new:
1808 logger.warning('branch level detect failed, assume master')
1809 return False
1810 return level_old != level_new
1811
Kuang-che Wud558a042020-06-06 02:11:00 +08001812 def _determine_float_branch(self, old, new, fixed_specs):
1813 # There is no revision tag in snapshot's xml. We know snapshot
1814 # builds are on master branch.
1815 master_refname = 'refs/remotes/origin/master'
Zheng-Jie Chang3e191962020-02-06 14:25:31 +08001816 if fixed_specs[0].revision:
1817 old_branches = git_util.get_branches(
Kuang-che Wud558a042020-06-06 02:11:00 +08001818 self.manifest_dir, commit=fixed_specs[0].revision, remote=True)
1819 else:
1820 old_branches = [master_refname]
1821
Zheng-Jie Chang3e191962020-02-06 14:25:31 +08001822 if fixed_specs[-1].revision:
1823 new_branches = git_util.get_branches(
Kuang-che Wud558a042020-06-06 02:11:00 +08001824 self.manifest_dir, commit=fixed_specs[-1].revision, remote=True)
Zheng-Jie Chang3e191962020-02-06 14:25:31 +08001825 else:
Kuang-che Wud558a042020-06-06 02:11:00 +08001826 new_branches = [master_refname]
Zheng-Jie Chang3e191962020-02-06 14:25:31 +08001827
Kuang-che Wud558a042020-06-06 02:11:00 +08001828 common_branches = list(set(old_branches) & set(new_branches))
1829 assert common_branches, '%s and %s are not on common branches?' % (old, new)
1830
1831 if len(common_branches) == 1:
1832 return common_branches[0]
1833
1834 # There are more than one common branches, use heuristic to tie breaking.
1835 # The heuristic is simple: choice the branch with "smallest" number.
1836 # "Smaller" means the more major branch (not branched) or branched later.
1837 #
1838 # Following is the commit graph of manifest-internal repo. It shows many
1839 # interesting cases.
1840 #
1841 # 84/13021.0.0 84/13022.0.0 84/13024.0.0
1842 # --A--+---X--------------X------B-------X-----------> master
1843 # \
1844 # \ 83/13020.1.0 83/13020.56.0 83/13020.68.0
1845 # C---X----D--+-------X-------+--------X-----> release-R83-13020.B
1846 # \ \
1847 # \ E------------> stabilize-13020.67.B
1848 # \ 83/13020.55.1
1849 # F-----X--------------------> stabilize-13020.55.B
1850 #
1851 # How to read this graph:
1852 # - Time goes from left to right. Branch names are on the right side of
1853 # arrows.
1854 # - Letters A-F are manifest commits.
1855 # - Marker X means release image build at that time, the version numbers
1856 # are labeled above the X marker.
1857 # For example,
1858 # 1) 13021.0.0 release is based on manifest A, which is on all branches
1859 # shown on the graph.
1860 # We know 13021.0.0 is on master (and R84 branch later, not shown in
1861 # this graph), not on 13020* branches.
1862 # 2) 13020.56.0 release is based on manifest D, which is on 3 branches
1863 # (R83-13020.B, 13020.67.B, and 13020.55.B).
1864 # We know 13020.56.0 is on R83-13020.B and 13020.67.B, but not
1865 # 13020.55.B.
1866 #
1867 # There is an important property here. Every time a new branch is created,
1868 # there will always be a commit (like C, E, and F) to fix "revision" field
1869 # in the manifest file. In other words, xxxxx.1.0 is impossible based on
1870 # manifest on master branch. xxxxx.yy.1 is impossible based on manifest on
1871 # xxxxx.B branch.
1872 #
1873 # With such property, among the branches containing the given manifest
1874 # file, the branch with "smallest" number guarantees where the release is.
1875
1876 def branch_key(s):
1877 if s == master_refname:
1878 return 0, 0, 0
1879 m = re.search(r'-(\d+)\.B$', s)
1880 if m:
1881 return int(m.group(1)), 0, 0
1882 m = re.search(r'-(\d+)\.(\d+)\.B$', s)
1883 if m:
1884 return int(m.group(1)), int(m.group(2)), 0
1885 m = re.search(r'-(\d+)\.(\d+)\.(\d+)\.B$', s)
1886 if m:
1887 return int(m.group(1)), int(m.group(2)), int(m.group(3))
1888
1889 logger.warning('unexpected branch name: %s', s)
1890 return (sys.maxsize, sys.maxsize, sys.maxsize, s)
1891
1892 common_branches.sort(key=branch_key)
1893 return common_branches[0]
1894
1895 def collect_float_spec(self, old, new, fixed_specs=None):
1896 assert fixed_specs
1897 branch = self._determine_float_branch(old, new, fixed_specs)
1898 logger.debug('float branch=%s', branch)
Zheng-Jie Changd968f552020-01-16 13:31:57 +08001899
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001900 old_timestamp = self.lookup_build_timestamp(old)
1901 new_timestamp = self.lookup_build_timestamp(new)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001902 # snapshot time is different from commit time
1903 # usually it's a few minutes different
1904 # 30 minutes should be safe in most cases
1905 if is_cros_snapshot_version(old):
1906 old_timestamp = old_timestamp - 1800
1907 if is_cros_snapshot_version(new):
1908 new_timestamp = new_timestamp + 1800
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001909
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +08001910 # TODO(zjchang): add logic to combine symlink target's (full.xml) history
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001911 result = []
Zheng-Jie Chang1ace3012020-02-15 04:51:05 +08001912 path = 'default.xml'
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001913 parser = repo_util.ManifestParser(self.manifest_dir)
1914 for timestamp, git_rev in parser.enumerate_manifest_commits(
Zheng-Jie Changd968f552020-01-16 13:31:57 +08001915 old_timestamp, new_timestamp, path, branch=branch):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001916 result.append(
1917 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
1918 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001919
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001920 def collect_fixed_spec(self, old, new):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001921 assert is_cros_full_version(old) or is_cros_snapshot_version(old)
1922 assert is_cros_full_version(new) or is_cros_snapshot_version(new)
1923
1924 # case 1: if both are snapshot, return a list of snapshot
1925 if is_cros_snapshot_version(old) and is_cros_snapshot_version(new):
1926 return self.collect_snapshot_specs(old, new)
1927
1928 # case 2: if both are release version
1929 # return a list of release version
1930 if is_cros_full_version(old) and is_cros_full_version(new):
1931 return self.collect_release_specs(old, new)
1932
1933 # case 3: return a list of release version and append a snapshot
1934 # before or at the end
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +08001935 result = self.collect_release_specs(
1936 version_to_full(self.config['board'], old),
1937 version_to_full(self.config['board'], new))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001938 if is_cros_snapshot_version(old):
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +08001939 result = self.collect_snapshot_specs(old, old) + result[1:]
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001940 elif is_cros_snapshot_version(new):
Zheng-Jie Chang5cd62dd2019-12-09 13:21:12 +08001941 result += self.collect_snapshot_specs(new, new)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001942 return result
1943
1944 def collect_snapshot_specs(self, old, new):
1945 assert is_cros_snapshot_version(old)
1946 assert is_cros_snapshot_version(new)
1947
1948 def guess_snapshot_version(board, snapshot_id, old, new):
1949 if old.endswith('-' + snapshot_id):
1950 return old
1951 if new.endswith('-' + snapshot_id):
1952 return new
Zheng-Jie Chang54020832020-04-21 15:52:48 +08001953 gs_path = ('gs://chromeos-image-archive/{board}-snapshot/'
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001954 'R*-{snapshot_id}-*'.format(
1955 board=board, snapshot_id=snapshot_id))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001956 for line in gsutil_ls(gs_path, ignore_errors=True):
1957 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)\S+', line)
1958 if m:
1959 return m.group(1)
Zheng-Jie Chang026cd5d2019-12-04 12:13:01 +08001960 return None
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001961
1962 result = []
1963 path = 'snapshot.xml'
1964 revisions = self.lookup_snapshot_manifest_revisions(old, new)
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001965 for timestamp, _git_rev, snapshot_id in revisions:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001966 snapshot_version = guess_snapshot_version(self.config['board'],
1967 snapshot_id, old, new)
Zheng-Jie Chang026cd5d2019-12-04 12:13:01 +08001968 if snapshot_version:
1969 result.append(
1970 codechange.Spec(codechange.SPEC_FIXED, snapshot_version, timestamp,
1971 path))
1972 else:
1973 logger.warning('snapshot id %s is not found, ignore', snapshot_id)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001974 return result
1975
1976 def collect_release_specs(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001977 assert is_cros_full_version(old)
1978 assert is_cros_full_version(new)
1979 old_milestone, old_short_version = version_split(old)
1980 new_milestone, new_short_version = version_split(new)
1981
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001982 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001983 for milestone in git_util.list_dir_from_revision(
1984 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
1985 if not milestone.isdigit():
1986 continue
1987 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
1988 continue
1989
Kuang-che Wu74768d32018-09-07 12:03:24 +08001990 files = git_util.list_dir_from_revision(
1991 self.historical_manifest_git_dir, 'refs/heads/master',
1992 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001993
1994 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001995 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001996 short_version, ext = os.path.splitext(fn)
1997 if ext != '.xml':
1998 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001999 if (util.is_version_lesseq(old_short_version, short_version) and
2000 util.is_version_lesseq(short_version, new_short_version) and
2001 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002002 rev = make_cros_full_version(milestone, short_version)
2003 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
2004 'refs/heads/master', path)
2005 result.append(
2006 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08002007
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002008 def version_key_func(spec):
2009 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08002010 return util.version_key_func(short_version)
2011
2012 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002013 assert result[0].name == old
2014 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +08002015 return result
2016
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002017 def get_manifest(self, rev):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08002018 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
2019 if is_cros_full_version(rev):
2020 milestone, short_version = version_split(rev)
2021 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
2022 manifest = git_util.get_file_from_revision(
2023 self.historical_manifest_git_dir, 'refs/heads/master', path)
2024 else:
2025 revisions = self.lookup_snapshot_manifest_revisions(rev, rev)
2026 commit_id = revisions[0][1]
2027 manifest = git_util.get_file_from_revision(self.manifest_internal_dir,
2028 commit_id, 'snapshot.xml')
Zheng-Jie Chang0fc704b2019-12-09 18:43:38 +08002029 return manifest
2030
2031 def get_manifest_file(self, rev):
2032 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002033 manifest_name = 'manifest_%s.xml' % rev
2034 manifest_path = os.path.join(self.manifest_dir, manifest_name)
2035 with open(manifest_path, 'w') as f:
Zheng-Jie Chang0fc704b2019-12-09 18:43:38 +08002036 f.write(self.get_manifest(rev))
Zheng-Jie Changec368b52020-03-02 16:25:25 +08002037
2038 # workaround for b/150572399
2039 # for chromeOS version < 12931.0.0, manifests are included from incorrect
2040 # folder .repo instead of.repo/manifests
2041 if is_cros_version_lesseq(rev, '12931.0.0'):
2042 repo_path = os.path.join(self.config['chromeos_root'], '.repo')
2043 manifest_patch_path = os.path.join(repo_path, manifest_name)
2044 with open(manifest_patch_path, 'w') as f:
2045 f.write(self.get_manifest(rev))
2046
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002047 return manifest_name
2048
2049 def parse_spec(self, spec):
2050 parser = repo_util.ManifestParser(self.manifest_dir)
2051 if spec.spec_type == codechange.SPEC_FIXED:
Zheng-Jie Chang0fc704b2019-12-09 18:43:38 +08002052 manifest_name = self.get_manifest_file(spec.name)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002053 manifest_path = os.path.join(self.manifest_dir, manifest_name)
Kuang-che Wua5723492019-11-25 20:59:34 +08002054 with open(manifest_path) as f:
2055 content = f.read()
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002056 root = parser.parse_single_xml(content, allow_include=False)
2057 else:
2058 root = parser.parse_xml_recursive(spec.name, spec.path)
2059
2060 spec.entries = parser.process_parsed_result(root)
2061 if spec.spec_type == codechange.SPEC_FIXED:
Kuang-che Wufe1e88a2019-09-10 21:52:25 +08002062 if not spec.is_static():
Kuang-che Wud1b74152020-05-20 08:46:46 +08002063 raise ValueError('fixed spec %r has unexpected floating entries' %
2064 spec.name)
Zheng-Jie Changd968f552020-01-16 13:31:57 +08002065 spec.revision = root.get('revision')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002066
2067 def sync_disk_state(self, rev):
Zheng-Jie Chang0fc704b2019-12-09 18:43:38 +08002068 manifest_name = self.get_manifest_file(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002069
2070 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
2071 # manifest. 'repo sync -m' is not enough
2072 repo_util.init(
2073 self.config['chromeos_root'],
2074 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
2075 manifest_name=manifest_name,
2076 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +08002077 reference=self.config['chromeos_mirror'],
Zheng-Jie Chang85529ad2020-03-06 18:40:18 +08002078 # b/150753074: moblab is in non-default group and causes mark_as_stable
2079 # fail
Kuang-che Wu084eef22020-03-11 18:29:48 +08002080 groups='default,moblab,platform-linux',
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08002081 )
2082
2083 # Note, don't sync with current_branch=True for chromeos. One of its
2084 # build steps (inside mark_as_stable) executes "git describe" which
2085 # needs git tag information.
2086 repo_util.sync(self.config['chromeos_root'])