blob: 49974c70d8c6715acfa65d7b44cafb65c77e8539 [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
24import subprocess
25import time
26
Zheng-Jie Chang4fabff62019-12-08 21:54:35 +080027from google.protobuf import json_format
28
Zheng-Jie Chang2b6d1472019-11-13 12:40:17 +080029from bisect_kit import buildbucket_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080030from bisect_kit import cli
Kuang-che Wue4bae0b2018-07-19 12:10:14 +080031from bisect_kit import codechange
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080032from bisect_kit import cr_util
Kuang-che Wue121fae2018-11-09 16:18:39 +080033from bisect_kit import errors
Kuang-che Wubfc4a642018-04-19 11:54:08 +080034from bisect_kit import git_util
Kuang-che Wufb553102018-10-02 18:14:29 +080035from bisect_kit import locking
Kuang-che Wubfc4a642018-04-19 11:54:08 +080036from bisect_kit import repo_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080037from bisect_kit import util
38
39logger = logging.getLogger(__name__)
40
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080041re_chromeos_full_version = r'^R\d+-\d+\.\d+\.\d+$'
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080042re_chromeos_localbuild_version = r'^\d+\.\d+\.\d{4}_\d\d_\d\d_\d{4}$'
43re_chromeos_short_version = r'^\d+\.\d+\.\d+$'
Zheng-Jie Chang127c3302019-09-10 17:17:04 +080044re_chromeos_snapshot_version = r'^R\d+-\d+\.\d+\.\d+-\d+$'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080045
46gs_archive_path = 'gs://chromeos-image-archive/{board}-release'
47gs_release_path = (
Kuang-che Wu80bf6a52019-05-31 12:48:06 +080048 'gs://chromeos-releases/{channel}-channel/{boardpath}/{short_version}')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080049
50# Assume gsutil is in PATH.
51gsutil_bin = 'gsutil'
Zheng-Jie Changb8697042019-10-29 16:03:26 +080052
53# Since snapshots with version >= 12618.0.0 have android and chrome version
54# info.
55snapshot_cutover_version = '12618.0.0'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080056
Kuang-che Wub9705bd2018-06-28 17:59:18 +080057chromeos_root_inside_chroot = '/mnt/host/source'
58# relative to chromeos_root
Kuang-che Wu7f82c6f2019-08-12 14:29:28 +080059prebuilt_autotest_dir = 'tmp/autotest-prebuilt'
Kuang-che Wu28980b22019-07-31 19:51:45 +080060# Relative to chromeos root. Images are cached_images_dir/$board/$image_name.
61cached_images_dir = 'src/build/images'
62test_image_filename = 'chromiumos_test_image.bin'
Kuang-che Wub9705bd2018-06-28 17:59:18 +080063
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080064VERSION_KEY_CROS_SHORT_VERSION = 'cros_short_version'
65VERSION_KEY_CROS_FULL_VERSION = 'cros_full_version'
66VERSION_KEY_MILESTONE = 'milestone'
67VERSION_KEY_CR_VERSION = 'cr_version'
Kuang-che Wu708310b2018-03-28 17:24:34 +080068VERSION_KEY_ANDROID_BUILD_ID = 'android_build_id'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080069VERSION_KEY_ANDROID_BRANCH = 'android_branch'
70
71
Kuang-che Wu9890ce82018-07-07 15:14:10 +080072class NeedRecreateChrootException(Exception):
73 """Failed to build ChromeOS because of chroot mismatch or corruption"""
74
75
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080076def is_cros_short_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080077 """Determines if `s` is chromeos short version.
78
79 This function doesn't accept version number of local build.
80 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080081 return bool(re.match(re_chromeos_short_version, s))
82
83
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080084def is_cros_localbuild_version(s):
85 """Determines if `s` is chromeos local build version."""
86 return bool(re.match(re_chromeos_localbuild_version, s))
87
88
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080089def is_cros_full_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080090 """Determines if `s` is chromeos full version.
91
92 This function doesn't accept version number of local build.
93 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080094 return bool(re.match(re_chromeos_full_version, s))
95
96
97def is_cros_version(s):
98 """Determines if `s` is chromeos version (either short or full)"""
99 return is_cros_short_version(s) or is_cros_full_version(s)
100
101
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800102def is_cros_snapshot_version(s):
103 """Determines if `s` is chromeos snapshot version"""
104 return bool(re.match(re_chromeos_snapshot_version, s))
105
106
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800107def make_cros_full_version(milestone, short_version):
108 """Makes full_version from milestone and short_version"""
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800109 assert milestone
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800110 return 'R%s-%s' % (milestone, short_version)
111
112
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800113def make_cros_snapshot_version(milestone, short_version, snapshot_id):
114 """Makes snapshot version from milestone, short_version and snapshot id"""
115 return 'R%s-%s-%s' % (milestone, short_version, snapshot_id)
116
117
118def version_split(version):
119 """Splits full_version or snapshot_version into milestone and short_version"""
120 assert is_cros_full_version(version) or is_cros_snapshot_version(version)
121 if is_cros_snapshot_version(version):
122 return snapshot_version_split(version)[0:2]
123 milestone, short_version = version.split('-')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800124 return milestone[1:], short_version
125
126
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800127def snapshot_version_split(snapshot_version):
128 """Splits snapshot_version into milestone, short_version and snapshot_id"""
129 assert is_cros_snapshot_version(snapshot_version)
130 milestone, shot_version, snapshot_id = snapshot_version.split('-')
131 return milestone[1:], shot_version, snapshot_id
132
133
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800134def query_snapshot_buildbucket_id(board, snapshot_version):
135 """Query buildbucket id of a snapshot"""
136 assert is_cros_snapshot_version(snapshot_version)
137 path = ('gs://chromeos-image-archive/{board}-postsubmit'
138 '/{snapshot_version}-*/image.zip')
139 output = gsutil_ls(
140 '-d',
141 path.format(board=board, snapshot_version=snapshot_version),
142 ignore_errors=True)
143 for line in output:
144 m = re.match(r'.*-postsubmit/R\d+-\d+\.\d+\.\d+-\d+-(.+)/image\.zip', line)
145 if m:
146 return m.group(1)
147 return None
148
149
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800150def argtype_cros_version(s):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800151 if (not is_cros_version(s)) and (not is_cros_snapshot_version(s)):
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800152 msg = 'invalid cros version'
Kuang-che Wuce2f3be2019-10-28 19:44:54 +0800153 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 +0800154 return s
155
156
157def query_dut_lsb_release(host):
158 """Query /etc/lsb-release of given DUT
159
160 Args:
161 host: the DUT address
162
163 Returns:
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800164 dict for keys and values of /etc/lsb-release.
165
166 Raises:
Kuang-che Wu44278142019-03-04 11:33:57 +0800167 errors.SshConnectionError: cannot connect to host
168 errors.ExternalError: lsb-release file doesn't exist
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800169 """
170 try:
Kuang-che Wu44278142019-03-04 11:33:57 +0800171 output = util.ssh_cmd(host, 'cat', '/etc/lsb-release')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800172 except subprocess.CalledProcessError:
Kuang-che Wu44278142019-03-04 11:33:57 +0800173 raise errors.ExternalError('unable to read /etc/lsb-release; not a DUT')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800174 return dict(re.findall(r'^(\w+)=(.*)$', output, re.M))
175
176
177def is_dut(host):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800178 """Determines whether a host is a chromeos device.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800179
180 Args:
181 host: the DUT address
182
183 Returns:
184 True if the host is a chromeos device.
185 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800186 try:
187 return query_dut_lsb_release(host).get('DEVICETYPE') in [
188 'CHROMEBASE',
189 'CHROMEBIT',
190 'CHROMEBOOK',
191 'CHROMEBOX',
192 'REFERENCE',
193 ]
194 except (errors.ExternalError, errors.SshConnectionError):
195 return False
196
197
198def is_good_dut(host):
199 if not is_dut(host):
200 return False
201
202 # Sometimes python is broken after 'cros flash'.
203 try:
204 util.ssh_cmd(host, 'python', '-c', '1')
205 return True
206 except (subprocess.CalledProcessError, errors.SshConnectionError):
207 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800208
209
210def query_dut_board(host):
211 """Query board name of a given DUT"""
212 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_BOARD')
213
214
215def query_dut_short_version(host):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800216 """Query short version of a given DUT.
217
218 This function may return version of local build, which
219 is_cros_short_version() is false.
220 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800221 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_VERSION')
222
223
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800224def query_dut_is_snapshot(host):
225 """Query if given DUT is a snapshot version."""
226 path = query_dut_lsb_release(host).get('CHROMEOS_RELEASE_BUILDER_PATH', '')
227 return '-postsubmit' in path
228
229
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800230def query_dut_boot_id(host, connect_timeout=None):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800231 """Query boot id.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800232
233 Args:
234 host: DUT address
235 connect_timeout: connection timeout
236
237 Returns:
238 boot uuid
239 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800240 return util.ssh_cmd(
241 host,
242 'cat',
243 '/proc/sys/kernel/random/boot_id',
244 connect_timeout=connect_timeout).strip()
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800245
246
247def reboot(host):
248 """Reboot a DUT and verify"""
249 logger.debug('reboot %s', host)
250 boot_id = query_dut_boot_id(host)
251
Kuang-che Wu44278142019-03-04 11:33:57 +0800252 try:
253 util.ssh_cmd(host, 'reboot')
Kuang-che Wu5f662e82019-03-05 11:49:56 +0800254 except errors.SshConnectionError:
255 # Depends on timing, ssh may return failure due to broken pipe, which is
256 # working as intended. Ignore such kind of errors.
Kuang-che Wu44278142019-03-04 11:33:57 +0800257 pass
Kuang-che Wu708310b2018-03-28 17:24:34 +0800258 wait_reboot_done(host, boot_id)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800259
Kuang-che Wu708310b2018-03-28 17:24:34 +0800260
261def wait_reboot_done(host, boot_id):
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800262 # For dev-mode test image, the reboot time is roughly at least 16 seconds
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800263 # (dev screen short delay) or more (long delay).
264 time.sleep(15)
265 for _ in range(100):
266 try:
267 # During boot, DUT does not response and thus ssh may hang a while. So
268 # set a connect timeout. 3 seconds are enough and 2 are not. It's okay to
269 # set tight limit because it's inside retry loop.
270 assert boot_id != query_dut_boot_id(host, connect_timeout=3)
271 return
Kuang-che Wu5f662e82019-03-05 11:49:56 +0800272 except errors.SshConnectionError:
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800273 logger.debug('reboot not ready? sleep wait 1 sec')
274 time.sleep(1)
275
Kuang-che Wue121fae2018-11-09 16:18:39 +0800276 raise errors.ExternalError('reboot failed?')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800277
278
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800279def gs_release_boardpath(board):
280 """Normalizes board name for gs://chromeos-releases/
281
282 This follows behavior of PushImage() in chromite/scripts/pushimage.py
283 Note, only gs://chromeos-releases/ needs normalization,
284 gs://chromeos-image-archive does not.
285
286 Args:
287 board: ChromeOS board name
288
289 Returns:
290 normalized board name
291 """
292 return board.replace('_', '-')
293
294
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800295def gsutil(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800296 """gsutil command line wrapper.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800297
298 Args:
299 args: command line arguments passed to gsutil
300 kwargs:
301 ignore_errors: if true, return '' for failures, for example 'gsutil ls'
302 but the path not found.
303
304 Returns:
305 stdout of gsutil
306
307 Raises:
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800308 errors.ExternalError: gsutil failed to run
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800309 subprocess.CalledProcessError: command failed
310 """
311 stderr_lines = []
312 try:
313 return util.check_output(
314 gsutil_bin, *args, stderr_callback=stderr_lines.append)
315 except subprocess.CalledProcessError as e:
316 stderr = ''.join(stderr_lines)
317 if re.search(r'ServiceException:.* does not have .*access', stderr):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800318 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800319 'gsutil failed due to permission. ' +
320 'Run "%s config" and follow its instruction. ' % gsutil_bin +
321 'Fill any string if it asks for project-id')
322 if kwargs.get('ignore_errors'):
323 return ''
324 raise
325 except OSError as e:
326 if e.errno == errno.ENOENT:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800327 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800328 'Unable to run %s. gsutil is not installed or not in PATH?' %
329 gsutil_bin)
330 raise
331
332
333def gsutil_ls(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800334 """gsutil ls.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800335
336 Args:
337 args: arguments passed to 'gsutil ls'
338 kwargs: extra parameters, where
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800339 ignore_errors: if true, return empty list instead of raising
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800340 exception, ex. path not found.
341
342 Returns:
343 list of 'gsutil ls' result. One element for one line of gsutil output.
344
345 Raises:
346 subprocess.CalledProcessError: gsutil failed, usually means path not found
347 """
348 return gsutil('ls', *args, **kwargs).splitlines()
349
350
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800351def gsutil_stat_update_time(*args, **kwargs):
352 """Returns the last modified time of a file or multiple files.
353
354 Args:
355 args: arguments passed to 'gsutil stat'.
356 kwargs: extra parameters for gsutil.
357
358 Returns:
359 A integer indicates the last modified timestamp.
360
361 Raises:
362 subprocess.CalledProcessError: gsutil failed, usually means path not found
363 errors.ExternalError: update time is not found
364 """
365 result = -1
366 # Currently we believe stat always returns a UTC time, and strptime also
367 # parses a UTC time by default.
368 time_format = '%a, %d %b %Y %H:%M:%S GMT'
369
370 for line in gsutil('stat', *args, **kwargs).splitlines():
371 if ':' not in line:
372 continue
Kuang-che Wuc89f2a22019-11-26 15:30:50 +0800373 key, value = line.split(':', 1)
374 key, value = key.strip(), value.strip()
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800375 if key != 'Update time':
376 continue
377 dt = datetime.datetime.strptime(value, time_format)
Kuang-che Wu72b5a572019-10-29 20:37:57 +0800378 unixtime = int(calendar.timegm(dt.utctimetuple()))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800379 result = max(result, unixtime)
380
381 if result == -1:
382 raise errors.ExternalError("didn't find update time")
383 return result
384
385
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800386def query_milestone_by_version(board, short_version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800387 """Query milestone by ChromeOS version number.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800388
389 Args:
390 board: ChromeOS board name
391 short_version: ChromeOS version number in short format, ex. 9300.0.0
392
393 Returns:
394 ChromeOS milestone number (string). For example, '58' for '9300.0.0'.
395 None if failed.
396 """
397 path = gs_archive_path.format(board=board) + '/R*-' + short_version
398 for line in gsutil_ls('-d', path, ignore_errors=True):
399 m = re.search(r'/R(\d+)-', line)
400 if not m:
401 continue
402 return m.group(1)
403
404 for channel in ['canary', 'dev', 'beta', 'stable']:
405 path = gs_release_path.format(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800406 channel=channel,
407 boardpath=gs_release_boardpath(board),
408 short_version=short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800409 for line in gsutil_ls(path, ignore_errors=True):
410 m = re.search(r'\bR(\d+)-' + short_version, line)
411 if not m:
412 continue
413 return m.group(1)
414
415 logger.error('unable to query milestone of %s for %s', short_version, board)
416 return None
417
418
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800419def list_board_names(chromeos_root):
420 """List board names.
421
422 Args:
423 chromeos_root: chromeos tree root
424
425 Returns:
426 list of board names
427 """
428 # Following logic is simplified from chromite/lib/portage_util.py
429 cros_list_overlays = os.path.join(chromeos_root,
430 'chromite/bin/cros_list_overlays')
431 overlays = util.check_output(cros_list_overlays).splitlines()
432 result = set()
433 for overlay in overlays:
434 conf_file = os.path.join(overlay, 'metadata', 'layout.conf')
435 name = None
436 if os.path.exists(conf_file):
437 for line in open(conf_file):
438 m = re.match(r'^repo-name\s*=\s*(\S+)\s*$', line)
439 if m:
440 name = m.group(1)
441 break
442
443 if not name:
444 name_file = os.path.join(overlay, 'profiles', 'repo_name')
445 if os.path.exists(name_file):
Kuang-che Wua5723492019-11-25 20:59:34 +0800446 with open(name_file) as f:
447 name = f.read().strip()
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800448
449 if name:
450 name = re.sub(r'-private$', '', name)
451 result.add(name)
452
453 return list(result)
454
455
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800456def recognize_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800457 """Recognize ChromeOS version.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800458
459 Args:
460 board: ChromeOS board name
461 version: ChromeOS version number in short or full format
462
463 Returns:
464 (milestone, version in short format)
465 """
466 if is_cros_short_version(version):
467 milestone = query_milestone_by_version(board, version)
468 short_version = version
469 else:
470 milestone, short_version = version_split(version)
471 return milestone, short_version
472
473
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800474def extract_major_version(version):
475 """Converts a version to its major version.
476
477 Args:
Kuang-che Wu9501f342019-11-15 17:15:21 +0800478 version: ChromeOS version number or snapshot version
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800479
480 Returns:
481 major version number in string format
482 """
483 version = version_to_short(version)
484 m = re.match(r'^(\d+)\.\d+\.\d+$', version)
485 return m.group(1)
486
487
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800488def version_to_short(version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800489 """Convert ChromeOS version number to short format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800490
491 Args:
492 version: ChromeOS version number in short or full format
493
494 Returns:
495 version number in short format
496 """
497 if is_cros_short_version(version):
498 return version
499 _, short_version = version_split(version)
500 return short_version
501
502
503def version_to_full(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800504 """Convert ChromeOS version number to full format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800505
506 Args:
507 board: ChromeOS board name
508 version: ChromeOS version number in short or full format
509
510 Returns:
511 version number in full format
512 """
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800513 if is_cros_snapshot_version(version):
514 milestone, short_version, _ = snapshot_version_split(version)
515 return make_cros_full_version(milestone, short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800516 if is_cros_full_version(version):
517 return version
518 milestone = query_milestone_by_version(board, version)
Kuang-che Wu0205f052019-05-23 12:48:37 +0800519 assert milestone, 'incorrect board=%s or version=%s ?' % (board, version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800520 return make_cros_full_version(milestone, version)
521
522
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800523def list_snapshots_from_image_archive(board, major_version):
Kuang-che Wu9501f342019-11-15 17:15:21 +0800524 """List ChromeOS snapshot image available from gs://chromeos-image-archive.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800525
526 Args:
527 board: ChromeOS board
528 major_version: ChromeOS major version
529
530 Returns:
531 list of (version, gs_path):
532 version: Chrome OS snapshot version
533 gs_path: gs path of test image
534 """
535
Zheng-Jie Chang43a08412019-12-05 17:05:45 +0800536 def extract_snapshot_id(result):
537 m = re.match(r'^R\d+-\d+\.\d+\.\d+-(\d+)', result[0])
538 assert m
539 return int(m.group(1))
540
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800541 path = (
542 'gs://chromeos-image-archive/{board}-postsubmit/R*-{major_version}.0.0-*')
543 result = []
544 output = gsutil_ls(
545 '-d',
546 path.format(board=board, major_version=major_version),
547 ignore_errors=True)
548
Zheng-Jie Chang43a08412019-12-05 17:05:45 +0800549 for path in sorted(output):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800550 if not path.endswith('/'):
551 continue
552 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)', path)
553 if m:
554 snapshot_version = m.group(1)
555 test_image = 'image.zip'
556 gs_path = path + test_image
Zheng-Jie Chang43a08412019-12-05 17:05:45 +0800557 # we should skip if there is duplicate snapshot
558 if result and result[-1][0] == snapshot_version:
559 continue
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800560 result.append((snapshot_version, gs_path))
Zheng-Jie Chang43a08412019-12-05 17:05:45 +0800561
562 # sort by its snapshot_id
563 result.sort(key=extract_snapshot_id)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800564 return result
565
566
Kuang-che Wu575dc442019-03-05 10:30:55 +0800567def list_prebuilt_from_image_archive(board):
568 """Lists ChromeOS prebuilt image available from gs://chromeos-image-archive.
569
570 gs://chromeos-image-archive contains only recent builds (in two years).
571 We prefer this function to list_prebuilt_from_chromeos_releases() because
572 - this is what "cros flash" supports directly.
573 - the paths have milestone information, so we don't need to do slow query
574 by ourselves.
575
576 Args:
577 board: ChromeOS board name
578
579 Returns:
580 list of (version, gs_path):
581 version: Chrome OS version in full format
582 gs_path: gs path of test image
583 """
584 result = []
585 for line in gsutil_ls(gs_archive_path.format(board=board)):
586 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+)', line)
587 if m:
588 full_version = m.group(1)
589 test_image = 'chromiumos_test_image.tar.xz'
590 assert line.endswith('/')
591 gs_path = line + test_image
592 result.append((full_version, gs_path))
593 return result
594
595
596def list_prebuilt_from_chromeos_releases(board):
597 """Lists ChromeOS versions available from gs://chromeos-releases.
598
599 gs://chromeos-releases contains more builds. However, 'cros flash' doesn't
600 support it.
601
602 Args:
603 board: ChromeOS board name
604
605 Returns:
606 list of (version, gs_path):
607 version: Chrome OS version in short format
608 gs_path: gs path of test image (with wildcard)
609 """
610 result = []
611 for line in gsutil_ls(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800612 gs_release_path.format(
613 channel='*', boardpath=gs_release_boardpath(board), short_version=''),
Kuang-che Wu575dc442019-03-05 10:30:55 +0800614 ignore_errors=True):
615 m = re.match(r'gs:\S+/(\d+\.\d+\.\d+)/$', line)
616 if m:
617 short_version = m.group(1)
618 test_image = 'ChromeOS-test-R*-{short_version}-{board}.tar.xz'.format(
619 short_version=short_version, board=board)
620 gs_path = line + test_image
621 result.append((short_version, gs_path))
622 return result
623
624
625def list_chromeos_prebuilt_versions(board,
626 old,
627 new,
628 only_good_build=True,
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800629 include_older_build=True,
630 use_snapshot=False):
Kuang-che Wu575dc442019-03-05 10:30:55 +0800631 """Lists ChromeOS version numbers with prebuilt between given range
632
633 Args:
634 board: ChromeOS board name
635 old: start version (inclusive)
636 new: end version (inclusive)
637 only_good_build: only if test image is available
638 include_older_build: include prebuilt in gs://chromeos-releases
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800639 use_snapshot: return snapshot versions if found
Kuang-che Wu575dc442019-03-05 10:30:55 +0800640
641 Returns:
642 list of sorted version numbers (in full format) between [old, new] range
643 (inclusive).
644 """
645 old = version_to_short(old)
646 new = version_to_short(new)
647
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800648 rev_map = {
649 } # dict: short version -> list of (short/full or snapshot version, gs path)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800650 for full_version, gs_path in list_prebuilt_from_image_archive(board):
651 short_version = version_to_short(full_version)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800652 rev_map[short_version] = [(full_version, gs_path)]
Kuang-che Wu575dc442019-03-05 10:30:55 +0800653
654 if include_older_build and old not in rev_map:
655 for short_version, gs_path in list_prebuilt_from_chromeos_releases(board):
656 if short_version not in rev_map:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800657 rev_map[short_version] = [(short_version, gs_path)]
658
659 if use_snapshot:
660 for major_version in range(
661 int(extract_major_version(old)),
662 int(extract_major_version(new)) + 1):
663 short_version = '%s.0.0' % major_version
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800664 next_short_version = '%s.0.0' % (major_version + 1)
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800665 # If current version is smaller than cutover, ignore it as it might not
666 # contain enough information for continuing android and chrome bisection.
667 if not util.is_version_lesseq(snapshot_cutover_version, short_version):
668 continue
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800669
670 # Given the fact that snapshots are images between two release versions.
671 # Adding snapshots of 12345.0.0 should be treated as adding commits
672 # between [12345.0.0, 12346.0.0).
673 # So in the following lines we check two facts:
674 # 1) If 12346.0.0(next_short_version) is a version between old and new
675 if not util.is_direct_relative_version(next_short_version, old):
676 continue
677 if not util.is_direct_relative_version(next_short_version, new):
678 continue
679 # 2) If 12345.0.0(short_version) is a version between old and new
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800680 if not util.is_direct_relative_version(short_version, old):
681 continue
682 if not util.is_direct_relative_version(short_version, new):
683 continue
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800684
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800685 snapshots = list_snapshots_from_image_archive(board, str(major_version))
686 if snapshots:
687 # if snapshots found, we can append them after the release version,
688 # so the prebuilt image list of this version will be
689 # release_image, snapshot1, snapshot2,...
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800690 if short_version not in rev_map:
691 rev_map[short_version] = []
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800692 rev_map[short_version] += snapshots
Kuang-che Wu575dc442019-03-05 10:30:55 +0800693
694 result = []
695 for rev in sorted(rev_map, key=util.version_key_func):
696 if not util.is_direct_relative_version(new, rev):
697 continue
698 if not util.is_version_lesseq(old, rev):
699 continue
700 if not util.is_version_lesseq(rev, new):
701 continue
702
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800703 for version, gs_path in rev_map[rev]:
Kuang-che Wu575dc442019-03-05 10:30:55 +0800704
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800705 # version_to_full() and gsutil_ls() may take long time if versions are a
706 # lot. This is acceptable because we usually bisect only short range.
Kuang-che Wu575dc442019-03-05 10:30:55 +0800707
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800708 if only_good_build:
709 gs_result = gsutil_ls(gs_path, ignore_errors=True)
710 if not gs_result:
711 logger.warning('%s is not a good build, ignore', version)
712 continue
713 assert len(gs_result) == 1
714 m = re.search(r'(R\d+-\d+\.\d+\.\d+)', gs_result[0])
715 if not m:
716 logger.warning('format of image path is unexpected: %s', gs_result[0])
717 continue
718 if not is_cros_snapshot_version(version):
719 version = m.group(1)
720 elif is_cros_short_version(version):
721 version = version_to_full(board, version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800722
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800723 result.append(version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800724
725 return result
726
727
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800728def prepare_snapshot_image(chromeos_root, board, snapshot_version):
729 """Prepare chromeos snapshot image.
730
731 Args:
732 chromeos_root: chromeos tree root
733 board: ChromeOS board name
734 snapshot_version: ChromeOS snapshot version number
735
736 Returns:
737 local file path of test image relative to chromeos_root
738 """
739 assert is_cros_snapshot_version(snapshot_version)
740 milestone, short_version, snapshot_id = snapshot_version_split(
741 snapshot_version)
742 full_version = make_cros_full_version(milestone, short_version)
743 tmp_dir = os.path.join(
744 chromeos_root, 'tmp',
745 'ChromeOS-test-%s-%s-%s' % (full_version, board, snapshot_id))
746 if not os.path.exists(tmp_dir):
747 os.makedirs(tmp_dir)
748
749 gs_path = ('gs://chromeos-image-archive/{board}-postsubmit/' +
750 '{snapshot_version}-*/image.zip')
751 gs_path = gs_path.format(board=board, snapshot_version=snapshot_version)
752
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800753 full_path = os.path.join(tmp_dir, test_image_filename)
754 rel_path = os.path.relpath(full_path, chromeos_root)
755 if os.path.exists(full_path):
756 return rel_path
757
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800758 files = gsutil_ls(gs_path, ignore_errors=True)
Zheng-Jie Changeb7308f2019-12-05 14:25:05 +0800759 if len(files) >= 1:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800760 gs_path = files[0]
761 gsutil('cp', gs_path, tmp_dir)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800762 util.check_call(
763 'unzip', '-j', 'image.zip', test_image_filename, cwd=tmp_dir)
764 os.remove(os.path.join(tmp_dir, 'image.zip'))
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800765 return rel_path
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800766
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800767 assert False
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +0800768 return None
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800769
770
Kuang-che Wu28980b22019-07-31 19:51:45 +0800771def prepare_prebuilt_image(chromeos_root, board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800772 """Prepare chromeos prebuilt image.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800773
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800774 It searches for xbuddy image which "cros flash" can use, or fetch image to
775 local disk.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800776
777 Args:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800778 chromeos_root: chromeos tree root
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800779 board: ChromeOS board name
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800780 version: ChromeOS version number in short or full format
781
782 Returns:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800783 xbuddy path or file path (relative to chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800784 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800785 assert is_cros_version(version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800786 full_version = version_to_full(board, version)
787 short_version = version_to_short(full_version)
788
789 image_path = None
790 gs_path = gs_archive_path.format(board=board) + '/' + full_version
791 if gsutil_ls('-d', gs_path, ignore_errors=True):
792 image_path = 'xbuddy://remote/{board}/{full_version}/test'.format(
793 board=board, full_version=full_version)
794 else:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800795 tmp_dir = os.path.join(chromeos_root, 'tmp',
796 'ChromeOS-test-%s-%s' % (full_version, board))
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800797 full_path = os.path.join(tmp_dir, test_image_filename)
798 rel_path = os.path.relpath(full_path, chromeos_root)
799 if os.path.exists(full_path):
800 return rel_path
801
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800802 if not os.path.exists(tmp_dir):
803 os.makedirs(tmp_dir)
804 # gs://chromeos-releases may have more old images than
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800805 # gs://chromeos-image-archive, but 'cros flash' doesn't support it. We have
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800806 # to fetch the image by ourselves
807 for channel in ['canary', 'dev', 'beta', 'stable']:
808 fn = 'ChromeOS-test-{full_version}-{board}.tar.xz'.format(
809 full_version=full_version, board=board)
810 gs_path = gs_release_path.format(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800811 channel=channel,
812 boardpath=gs_release_boardpath(board),
813 short_version=short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800814 gs_path += '/' + fn
815 if gsutil_ls(gs_path, ignore_errors=True):
816 # TODO(kcwu): delete tmp
817 gsutil('cp', gs_path, tmp_dir)
818 util.check_call('tar', 'Jxvf', fn, cwd=tmp_dir)
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800819 image_path = os.path.relpath(full_path, chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800820 break
821
822 assert image_path
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800823 return image_path
824
825
826def cros_flash(chromeos_root,
827 host,
828 board,
829 image_path,
830 version=None,
831 clobber_stateful=False,
Kuang-che Wu155fb6e2018-11-29 16:00:41 +0800832 disable_rootfs_verification=True):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800833 """Flash a DUT with given ChromeOS image.
834
835 This is implemented by 'cros flash' command line.
836
837 Args:
838 chromeos_root: use 'cros flash' of which chromeos tree
839 host: DUT address
840 board: ChromeOS board name
Kuang-che Wu28980b22019-07-31 19:51:45 +0800841 image_path: chromeos image xbuddy path or file path. For relative
842 path, it should be relative to chromeos_root.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800843 version: ChromeOS version in short or full format
844 clobber_stateful: Clobber stateful partition when performing update
845 disable_rootfs_verification: Disable rootfs verification after update
846 is completed
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800847
848 Raises:
849 errors.ExternalError: cros flash failed
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800850 """
851 logger.info('cros_flash %s %s %s %s', host, board, version, image_path)
852
853 # Reboot is necessary because sometimes previous 'cros flash' failed and
854 # entered a bad state.
855 reboot(host)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800856
Kuang-che Wu28980b22019-07-31 19:51:45 +0800857 # Handle relative path.
858 if '://' not in image_path and not os.path.isabs(image_path):
859 assert os.path.exists(os.path.join(chromeos_root, image_path))
860 image_path = os.path.join(chromeos_root_inside_chroot, image_path)
861
Kuang-che Wuf3d03ca2019-03-11 17:31:40 +0800862 args = [
863 '--debug', '--no-ping', '--send-payload-in-parallel', host, image_path
864 ]
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800865 if clobber_stateful:
866 args.append('--clobber-stateful')
867 if disable_rootfs_verification:
868 args.append('--disable-rootfs-verification')
869
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800870 try:
871 cros_sdk(chromeos_root, 'cros', 'flash', *args)
872 except subprocess.CalledProcessError:
873 raise errors.ExternalError('cros flash failed')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800874
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800875 if version:
876 # In the past, cros flash may fail with returncode=0
877 # So let's have an extra check.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800878 if is_cros_snapshot_version(version):
879 builder_path = query_dut_lsb_release(host).get(
880 'CHROMEOS_RELEASE_BUILDER_PATH', '')
881 expect_prefix = '%s-postsubmit/%s-' % (board, version)
882 if not builder_path.startswith(expect_prefix):
883 raise errors.ExternalError(
884 'although cros flash succeeded, the OS builder path is '
885 'unexpected: actual=%s expect=%s' % (builder_path, expect_prefix))
886 else:
887 expect_version = version_to_short(version)
888 dut_version = query_dut_short_version(host)
889 if dut_version != expect_version:
890 raise errors.ExternalError(
891 'although cros flash succeeded, the OS version is unexpected: '
892 'actual=%s expect=%s' % (dut_version, expect_version))
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800893
Kuang-che Wu4a81ea72019-10-05 15:35:17 +0800894 # "cros flash" may terminate successfully but the DUT starts self-repairing
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800895 # (b/130786578), so it's necessary to do sanity check.
896 if not is_good_dut(host):
897 raise errors.ExternalError(
898 'although cros flash succeeded, the DUT is in bad state')
899
900
901def cros_flash_with_retry(chromeos_root,
902 host,
903 board,
904 image_path,
905 version=None,
906 clobber_stateful=False,
907 disable_rootfs_verification=True,
908 repair_callback=None):
909 # 'cros flash' is not 100% reliable, retry if necessary.
910 for attempt in range(2):
911 if attempt > 0:
912 logger.info('will retry 60 seconds later')
913 time.sleep(60)
914
915 try:
916 cros_flash(
917 chromeos_root,
918 host,
919 board,
920 image_path,
921 version=version,
922 clobber_stateful=clobber_stateful,
923 disable_rootfs_verification=disable_rootfs_verification)
924 return True
925 except errors.ExternalError:
926 logger.exception('cros flash failed')
927 if repair_callback and not repair_callback(host):
928 logger.warning('not repaired, assume it is harmless')
929 continue
930 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800931
932
933def version_info(board, version):
934 """Query subcomponents version info of given version of ChromeOS
935
936 Args:
937 board: ChromeOS board name
938 version: ChromeOS version number in short or full format
939
940 Returns:
941 dict of component and version info, including (if available):
942 cros_short_version: ChromeOS version
943 cros_full_version: ChromeOS version
944 milestone: milestone of ChromeOS
945 cr_version: Chrome version
Kuang-che Wu708310b2018-03-28 17:24:34 +0800946 android_build_id: Android build id
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800947 android_branch: Android branch, in format like 'git_nyc-mr1-arc'
948 """
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800949 if is_cros_snapshot_version(version):
Zheng-Jie Chang2b6d1472019-11-13 12:40:17 +0800950 api = buildbucket_util.BuildbucketApi()
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800951 milestone, short_version, _ = snapshot_version_split(version)
952 buildbucket_id = query_snapshot_buildbucket_id(board, version)
Zheng-Jie Chang2b6d1472019-11-13 12:40:17 +0800953 data = api.get(int(buildbucket_id)).output.properties
Zheng-Jie Chang4fabff62019-12-08 21:54:35 +0800954 target_versions = json_format.MessageToDict(data['target_versions'])
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800955 return {
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800956 VERSION_KEY_MILESTONE: milestone,
957 VERSION_KEY_CROS_FULL_VERSION: version,
958 VERSION_KEY_CROS_SHORT_VERSION: short_version,
Zheng-Jie Chang2d1dd9b2019-12-07 23:30:20 +0800959 VERSION_KEY_CR_VERSION: target_versions.get('chromeVersion'),
960 VERSION_KEY_ANDROID_BUILD_ID: target_versions.get('androidVersion'),
961 VERSION_KEY_ANDROID_BRANCH: target_versions.get('androidBranchVersion'),
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800962 }
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800963 info = {}
964 full_version = version_to_full(board, version)
965
966 # Some boards may have only partial-metadata.json but no metadata.json.
967 # e.g. caroline R60-9462.0.0
968 # Let's try both.
969 metadata = None
970 for metadata_filename in ['metadata.json', 'partial-metadata.json']:
Kuang-che Wu0768b972019-10-05 15:18:59 +0800971 path = gs_archive_path.format(
972 board=board) + '/%s/%s' % (full_version, metadata_filename)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800973 metadata = gsutil('cat', path, ignore_errors=True)
974 if metadata:
975 o = json.loads(metadata)
976 v = o['version']
977 board_metadata = o['board-metadata'][board]
978 info.update({
979 VERSION_KEY_CROS_SHORT_VERSION: v['platform'],
980 VERSION_KEY_CROS_FULL_VERSION: v['full'],
981 VERSION_KEY_MILESTONE: v['milestone'],
982 VERSION_KEY_CR_VERSION: v['chrome'],
983 })
984
985 if 'android' in v:
Kuang-che Wu708310b2018-03-28 17:24:34 +0800986 info[VERSION_KEY_ANDROID_BUILD_ID] = v['android']
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800987 if 'android-branch' in v: # this appears since R58-9317.0.0
988 info[VERSION_KEY_ANDROID_BRANCH] = v['android-branch']
989 elif 'android-container-branch' in board_metadata:
990 info[VERSION_KEY_ANDROID_BRANCH] = v['android-container-branch']
991 break
992 else:
993 logger.error('Failed to read metadata from gs://chromeos-image-archive')
994 logger.error(
995 'Note, so far no quick way to look up version info for too old builds')
996
997 return info
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800998
999
1000def query_chrome_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001001 """Queries chrome version of chromeos build.
Kuang-che Wu848b1af2018-02-01 20:59:36 +08001002
1003 Args:
1004 board: ChromeOS board name
1005 version: ChromeOS version number in short or full format
1006
1007 Returns:
1008 Chrome version number
1009 """
1010 info = version_info(board, version)
1011 return info['cr_version']
Kuang-che Wu708310b2018-03-28 17:24:34 +08001012
1013
1014def query_android_build_id(board, rev):
1015 info = version_info(board, rev)
1016 rev = info['android_build_id']
1017 return rev
1018
1019
1020def query_android_branch(board, rev):
1021 info = version_info(board, rev)
1022 rev = info['android_branch']
1023 return rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001024
1025
Kuang-che Wu3eb6b502018-06-06 16:15:18 +08001026def guess_chrome_version(board, rev):
1027 """Guess chrome version number.
1028
1029 Args:
1030 board: chromeos board name
1031 rev: chrome or chromeos version
1032
1033 Returns:
1034 chrome version number
1035 """
1036 if is_cros_version(rev):
1037 assert board, 'need to specify BOARD for cros version'
1038 rev = query_chrome_version(board, rev)
1039 assert cr_util.is_chrome_version(rev)
1040
1041 return rev
1042
1043
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001044def is_inside_chroot():
1045 """Returns True if we are inside chroot."""
1046 return os.path.exists('/etc/cros_chroot_version')
1047
1048
1049def cros_sdk(chromeos_root, *args, **kwargs):
1050 """Run commands inside chromeos chroot.
1051
1052 Args:
1053 chromeos_root: chromeos tree root
1054 *args: command to run
1055 **kwargs:
Kuang-che Wud4603d72018-11-29 17:51:21 +08001056 chrome_root: pass to cros_sdk; mount this path into the SDK chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001057 env: (dict) environment variables for the command
Kuang-che Wubcafc552019-08-15 15:27:02 +08001058 log_stdout: Whether write the stdout output of the child process to log.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001059 stdin: standard input file handle for the command
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001060 stderr_callback: Callback function for stderr. Called once per line.
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001061 goma_dir: Goma installed directory to mount into the chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001062 """
1063 envs = []
1064 for k, v in kwargs.get('env', {}).items():
1065 assert re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', k)
1066 envs.append('%s=%s' % (k, v))
1067
1068 # Use --no-ns-pid to prevent cros_sdk change our pgid, otherwise subsequent
1069 # commands would be considered as background process.
Kuang-che Wu399d4662019-06-06 15:23:37 +08001070 prefix = ['chromite/bin/cros_sdk', '--no-ns-pid']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001071
1072 if kwargs.get('chrome_root'):
Kuang-che Wu399d4662019-06-06 15:23:37 +08001073 prefix += ['--chrome_root', kwargs['chrome_root']]
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001074 if kwargs.get('goma_dir'):
1075 prefix += ['--goma_dir', kwargs['goma_dir']]
Kuang-che Wud4603d72018-11-29 17:51:21 +08001076
Kuang-che Wu399d4662019-06-06 15:23:37 +08001077 prefix += envs + ['--']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001078
Kuang-che Wu399d4662019-06-06 15:23:37 +08001079 # In addition to the output of command we are interested, cros_sdk may
1080 # generate its own messages. For example, chroot creation messages if we run
1081 # cros_sdk the first time.
1082 # This is the hack to run dummy command once, so we can get clean output for
1083 # the command we are interested.
1084 cmd = prefix + ['true']
1085 util.check_call(*cmd, cwd=chromeos_root)
1086
1087 cmd = prefix + list(args)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001088 return util.check_output(
1089 *cmd,
1090 cwd=chromeos_root,
Kuang-che Wubcafc552019-08-15 15:27:02 +08001091 log_stdout=kwargs.get('log_stdout', True),
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001092 stdin=kwargs.get('stdin'),
1093 stderr_callback=kwargs.get('stderr_callback'))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001094
1095
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001096def create_chroot(chromeos_root):
1097 """Creates ChromeOS chroot.
1098
1099 Args:
1100 chromeos_root: chromeos tree root
1101 """
1102 if os.path.exists(os.path.join(chromeos_root, 'chroot')):
1103 return
1104 if os.path.exists(os.path.join(chromeos_root, 'chroot.img')):
1105 return
1106
1107 util.check_output('chromite/bin/cros_sdk', '--create', cwd=chromeos_root)
1108
1109
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001110def copy_into_chroot(chromeos_root, src, dst):
1111 """Copies file into chromeos chroot.
1112
1113 Args:
1114 chromeos_root: chromeos tree root
1115 src: path outside chroot
1116 dst: path inside chroot
1117 """
1118 # chroot may be an image, so we cannot copy to corresponding path
1119 # directly.
1120 cros_sdk(chromeos_root, 'sh', '-c', 'cat > %s' % dst, stdin=open(src))
1121
1122
1123def exists_in_chroot(chromeos_root, path):
1124 """Determine whether a path exists in the chroot.
1125
1126 Args:
1127 chromeos_root: chromeos tree root
1128 path: path inside chroot, relative to src/scripts
1129
1130 Returns:
1131 True if a path exists
1132 """
1133 try:
Kuang-che Wuacb6efd2018-04-25 18:52:58 +08001134 cros_sdk(chromeos_root, 'test', '-e', path)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001135 except subprocess.CalledProcessError:
1136 return False
1137 return True
1138
1139
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001140def check_if_need_recreate_chroot(stdout, stderr):
1141 """Analyze build log and determine if chroot should be recreated.
1142
1143 Args:
1144 stdout: stdout output of build
1145 stderr: stderr output of build
1146
1147 Returns:
1148 the reason if chroot needs recreated; None otherwise
1149 """
Kuang-che Wu74768d32018-09-07 12:03:24 +08001150 if re.search(
1151 r"The current version of portage supports EAPI '\d+'. "
Kuang-che Wuae6824b2019-08-27 22:20:01 +08001152 'You must upgrade', stderr):
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001153 return 'EAPI version mismatch'
1154
Kuang-che Wu5ac81322018-11-26 14:04:06 +08001155 if 'Chroot is too new. Consider running:' in stderr:
1156 return 'chroot version is too new'
1157
1158 # old message before Oct 2018
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001159 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
1160 return 'chroot version is too new'
1161
Kuang-che Wu6fe987f2018-08-28 15:24:20 +08001162 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
1163 if "undefined reference to 'std::__1::basic_string" in stdout:
1164 return 'might be due to compiler change'
1165
Kuang-che Wu94e3b452019-11-21 12:49:18 +08001166 # Detect failures due to file collisions.
1167 # For example, kernel uprev from 3.x to 4.x, they are two separate packages
1168 # and conflict with each other. Other possible cases are package renaming or
1169 # refactoring. Let's recreate chroot to work around them.
1170 if 'Detected file collision' in stdout:
1171 # Using wildcard between words because the text wraps to the next line
1172 # depending on length of package name and each line is prefixed with
1173 # package name.
1174 # Using ".{,100}" instead of ".*" to prevent regex matching time explodes
1175 # exponentially. 100 is chosen arbitrarily. It should be longer than any
1176 # package name (65 now).
1177 m = re.search(
1178 r'Package (\S+).{,100}NOT.{,100}merged.{,100}'
1179 r'due.{,100}to.{,100}file.{,100}collisions', stdout, re.S)
1180 if m:
1181 return 'failed to install package due to file collision: ' + m.group(1)
Kuang-che Wu356c3522019-11-19 16:11:05 +08001182
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001183 return None
1184
1185
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001186def build_packages(chromeos_root,
1187 board,
1188 chrome_root=None,
1189 goma_dir=None,
1190 afdo_use=False):
Kuang-che Wu28980b22019-07-31 19:51:45 +08001191 """Build ChromeOS packages.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001192
1193 Args:
1194 chromeos_root: chromeos tree root
1195 board: ChromeOS board name
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001196 chrome_root: Chrome tree root. If specified, build chrome using the
1197 provided tree
1198 goma_dir: Goma installed directory to mount into the chroot. If specified,
1199 build chrome with goma.
1200 afdo_use: build chrome with AFDO optimization
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001201 """
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001202 common_env = {
1203 'USE': '-cros-debug chrome_internal',
1204 'FEATURES': 'separatedebug',
1205 }
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001206 stderr_lines = []
1207 try:
Kuang-che Wufb553102018-10-02 18:14:29 +08001208 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001209 env = common_env.copy()
1210 env['FEATURES'] += ' -separatedebug splitdebug'
Kuang-che Wufb553102018-10-02 18:14:29 +08001211 cros_sdk(
1212 chromeos_root,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001213 './update_chroot',
1214 '--toolchain_boards',
Kuang-che Wufb553102018-10-02 18:14:29 +08001215 board,
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001216 env=env,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001217 stderr_callback=stderr_lines.append)
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001218
1219 env = common_env.copy()
1220 cmd = [
Kuang-che Wu28980b22019-07-31 19:51:45 +08001221 './build_packages',
1222 '--board',
1223 board,
1224 '--withdev',
1225 '--noworkon',
1226 '--skip_chroot_upgrade',
1227 '--accept_licenses=@CHROMEOS',
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001228 ]
1229 if goma_dir:
1230 # Tell build_packages to start and stop goma
1231 cmd.append('--run_goma')
1232 env['USE_GOMA'] = 'true'
1233 if afdo_use:
1234 env['USE'] += ' afdo_use'
1235 cros_sdk(
1236 chromeos_root,
1237 *cmd,
1238 env=env,
1239 chrome_root=chrome_root,
1240 stderr_callback=stderr_lines.append,
1241 goma_dir=goma_dir)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001242 except subprocess.CalledProcessError as e:
1243 # Detect failures due to incompatibility between chroot and source tree. If
1244 # so, notify the caller to recreate chroot and retry.
1245 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1246 if reason:
1247 raise NeedRecreateChrootException(reason)
1248
1249 # For other failures, don't know how to handle. Just bail out.
1250 raise
1251
Kuang-che Wu28980b22019-07-31 19:51:45 +08001252
1253def build_image(chromeos_root, board):
1254 """Build ChromeOS image.
1255
1256 Args:
1257 chromeos_root: chromeos tree root
1258 board: ChromeOS board name
1259
1260 Returns:
1261 image folder; relative to chromeos_root
1262 """
1263 stderr_lines = []
1264 try:
1265 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
1266 cros_sdk(
1267 chromeos_root,
1268 './build_image',
1269 '--board',
1270 board,
1271 '--noenable_rootfs_verification',
1272 'test',
1273 env={
1274 'USE': '-cros-debug chrome_internal',
1275 'FEATURES': 'separatedebug',
1276 },
1277 stderr_callback=stderr_lines.append)
1278 except subprocess.CalledProcessError as e:
1279 # Detect failures due to incompatibility between chroot and source tree. If
1280 # so, notify the caller to recreate chroot and retry.
1281 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1282 if reason:
1283 raise NeedRecreateChrootException(reason)
1284
1285 # For other failures, don't know how to handle. Just bail out.
1286 raise
1287
1288 image_symlink = os.path.join(chromeos_root, cached_images_dir, board,
1289 'latest')
1290 assert os.path.exists(image_symlink)
1291 image_name = os.readlink(image_symlink)
1292 image_folder = os.path.join(cached_images_dir, board, image_name)
1293 assert os.path.exists(
1294 os.path.join(chromeos_root, image_folder, test_image_filename))
1295 return image_folder
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001296
1297
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001298class AutotestControlInfo(object):
1299 """Parsed content of autotest control file.
1300
1301 Attributes:
1302 name: test name
1303 path: control file path
1304 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
1305 DOC, ATTRIBUTES, DEPENDENCIES, etc.
1306 """
1307
1308 def __init__(self, path, variables):
1309 self.name = variables['NAME']
1310 self.path = path
1311 self.variables = variables
1312
1313
1314def parse_autotest_control_file(path):
1315 """Parses autotest control file.
1316
1317 This only parses simple top-level string assignments.
1318
1319 Returns:
1320 AutotestControlInfo object
1321 """
1322 variables = {}
Kuang-che Wua5723492019-11-25 20:59:34 +08001323 with open(path) as f:
1324 code = ast.parse(f.read())
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001325 for stmt in code.body:
1326 # Skip if not simple "NAME = *" assignment.
1327 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
1328 isinstance(stmt.targets[0], ast.Name)):
1329 continue
1330
1331 # Only support string value.
1332 if isinstance(stmt.value, ast.Str):
1333 variables[stmt.targets[0].id] = stmt.value.s
1334
1335 return AutotestControlInfo(path, variables)
1336
1337
1338def enumerate_autotest_control_files(autotest_dir):
1339 """Enumerate autotest control files.
1340
1341 Args:
1342 autotest_dir: autotest folder
1343
1344 Returns:
1345 list of paths to control files
1346 """
1347 # Where to find control files. Relative to autotest_dir.
1348 subpaths = [
1349 'server/site_tests',
1350 'client/site_tests',
1351 'server/tests',
1352 'client/tests',
1353 ]
1354
1355 blacklist = ['site-packages', 'venv', 'results', 'logs', 'containers']
1356 result = []
1357 for subpath in subpaths:
1358 path = os.path.join(autotest_dir, subpath)
1359 for root, dirs, files in os.walk(path):
1360
1361 for black in blacklist:
1362 if black in dirs:
1363 dirs.remove(black)
1364
1365 for filename in files:
1366 if filename == 'control' or filename.startswith('control.'):
1367 result.append(os.path.join(root, filename))
1368
1369 return result
1370
1371
1372def get_autotest_test_info(autotest_dir, test_name):
1373 """Get metadata of given test.
1374
1375 Args:
1376 autotest_dir: autotest folder
1377 test_name: test name
1378
1379 Returns:
1380 AutotestControlInfo object. None if test not found.
1381 """
1382 for control_file in enumerate_autotest_control_files(autotest_dir):
1383 info = parse_autotest_control_file(control_file)
1384 if info.name == test_name:
1385 return info
1386 return None
1387
1388
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001389class ChromeOSSpecManager(codechange.SpecManager):
1390 """Repo manifest related operations.
1391
1392 This class enumerates chromeos manifest files, parses them,
1393 and sync to disk state according to them.
1394 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001395
1396 def __init__(self, config):
1397 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001398 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
1399 'manifests')
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001400 self.manifest_internal_dir = os.path.join(self.config['chromeos_mirror'],
1401 'manifest-internal.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001402 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001403 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001404 if not os.path.exists(self.historical_manifest_git_dir):
Kuang-che Wue121fae2018-11-09 16:18:39 +08001405 raise errors.InternalError('Manifest snapshots should be cloned into %s' %
1406 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001407
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001408 def lookup_snapshot_manifest_revisions(self, old, new):
1409 """Get manifest commits between snapshot versions.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001410
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001411 Returns:
1412 list of (timestamp, commit_id, snapshot_id):
1413 timestamp: integer unix timestamp
1414 commit_id: a string indicates commit hash
1415 snapshot_id: a string indicates snapshot id
1416 """
1417 assert is_cros_snapshot_version(old)
1418 assert is_cros_snapshot_version(new)
1419
1420 gs_path = (
1421 'gs://chromeos-image-archive/{board}-postsubmit/{version}-*/image.zip')
1422 # Try to guess the commit time of a snapshot manifest, it is usually a few
1423 # minutes different between snapshot manifest commit and image.zip
1424 # generate.
1425 try:
1426 old_timestamp = gsutil_stat_update_time(
1427 gs_path.format(board=self.config['board'], version=old)) - 86400
1428 except subprocess.CalledProcessError:
1429 old_timestamp = None
1430 try:
1431 new_timestamp = gsutil_stat_update_time(
1432 gs_path.format(board=self.config['board'], version=new)) + 86400
1433 # 1558657989 is snapshot_id 5982's commit time, this ensures every time
1434 # we can find snapshot 5982
1435 # snapshot_id <= 5982 has different commit message format, so we need
1436 # to identify its id in different ways, see below comment for more info.
1437 new_timestamp = max(new_timestamp, 1558657989 + 1)
1438 except subprocess.CalledProcessError:
1439 new_timestamp = None
1440 result = []
1441 _, _, old_snapshot_id = snapshot_version_split(old)
1442 _, _, new_snapshot_id = snapshot_version_split(new)
1443 repo = self.manifest_internal_dir
1444 path = 'snapshot.xml'
1445 branch = 'snapshot'
1446 commits = git_util.get_history(
1447 repo,
1448 path,
1449 branch,
1450 after=old_timestamp,
1451 before=new_timestamp,
1452 with_subject=True)
1453
1454 # Unfortunately, we can not identify snapshot_id <= 5982 from its commit
1455 # subject, as their subjects are all `Annealing manifest snapshot.`.
1456 # So instead we count the snapshot_id manually.
1457 count = 5982
1458 # There are two snapshot_id = 2633 in commit history, ignore the former
1459 # one.
1460 ignore_list = ['95c8526a7f0798d02f692010669dcbd5a152439a']
1461 # We examine the commits in reverse order as there are some testing
1462 # commits before snapshot_id=2, this method works fine after
1463 # snapshot 2, except snapshot 2633
1464 for commit in reversed(commits):
1465 msg = commit[2]
1466 if commit[1] in ignore_list:
1467 continue
1468
1469 match = re.match(r'^annealing manifest snapshot (\d+)', msg)
1470 if match:
1471 snapshot_id = match.group(1)
1472 elif 'Annealing manifest snapshot' in msg:
1473 snapshot_id = str(count)
1474 count -= 1
1475 else:
1476 continue
1477 if int(old_snapshot_id) <= int(snapshot_id) <= int(new_snapshot_id):
1478 result.append((commit[0], commit[1], snapshot_id))
1479 # We find commits in reversed order, now reverse it again to chronological
1480 # order.
1481 return list(reversed(result))
1482
1483 def lookup_build_timestamp(self, rev):
1484 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
1485 if is_cros_full_version(rev):
1486 return self.lookup_release_build_timestamp(rev)
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +08001487 return self.lookup_snapshot_build_timestamp(rev)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001488
1489 def lookup_snapshot_build_timestamp(self, rev):
1490 assert is_cros_snapshot_version(rev)
1491 return int(self.lookup_snapshot_manifest_revisions(rev, rev)[0][0])
1492
1493 def lookup_release_build_timestamp(self, rev):
1494 assert is_cros_full_version(rev)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001495 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001496 path = os.path.join('buildspecs', milestone, short_version + '.xml')
1497 try:
1498 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1499 'refs/heads/master', path)
1500 except ValueError:
Kuang-che Wuce2f3be2019-10-28 19:44:54 +08001501 raise errors.InternalError(
1502 '%s does not have %s' % (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001503 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001504
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001505 def collect_float_spec(self, old, new):
1506 old_timestamp = self.lookup_build_timestamp(old)
1507 new_timestamp = self.lookup_build_timestamp(new)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001508 # snapshot time is different from commit time
1509 # usually it's a few minutes different
1510 # 30 minutes should be safe in most cases
1511 if is_cros_snapshot_version(old):
1512 old_timestamp = old_timestamp - 1800
1513 if is_cros_snapshot_version(new):
1514 new_timestamp = new_timestamp + 1800
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001515
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001516 path = os.path.join(self.manifest_dir, 'default.xml')
1517 if not os.path.islink(path) or os.readlink(path) != 'full.xml':
Kuang-che Wue121fae2018-11-09 16:18:39 +08001518 raise errors.InternalError(
1519 'default.xml not symlink to full.xml is not supported')
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001520
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001521 result = []
1522 path = 'full.xml'
1523 parser = repo_util.ManifestParser(self.manifest_dir)
1524 for timestamp, git_rev in parser.enumerate_manifest_commits(
1525 old_timestamp, new_timestamp, path):
1526 result.append(
1527 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
1528 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001529
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001530 def collect_fixed_spec(self, old, new):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001531 assert is_cros_full_version(old) or is_cros_snapshot_version(old)
1532 assert is_cros_full_version(new) or is_cros_snapshot_version(new)
1533
1534 # case 1: if both are snapshot, return a list of snapshot
1535 if is_cros_snapshot_version(old) and is_cros_snapshot_version(new):
1536 return self.collect_snapshot_specs(old, new)
1537
1538 # case 2: if both are release version
1539 # return a list of release version
1540 if is_cros_full_version(old) and is_cros_full_version(new):
1541 return self.collect_release_specs(old, new)
1542
1543 # case 3: return a list of release version and append a snapshot
1544 # before or at the end
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +08001545 result = self.collect_release_specs(
1546 version_to_full(self.config['board'], old),
1547 version_to_full(self.config['board'], new))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001548 if is_cros_snapshot_version(old):
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +08001549 result = self.collect_snapshot_specs(old, old) + result[1:]
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001550 elif is_cros_snapshot_version(new):
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +08001551 result = result[:-1] + self.collect_snapshot_specs(new, new)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001552 return result
1553
1554 def collect_snapshot_specs(self, old, new):
1555 assert is_cros_snapshot_version(old)
1556 assert is_cros_snapshot_version(new)
1557
1558 def guess_snapshot_version(board, snapshot_id, old, new):
1559 if old.endswith('-' + snapshot_id):
1560 return old
1561 if new.endswith('-' + snapshot_id):
1562 return new
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001563 gs_path = ('gs://chromeos-image-archive/{board}-postsubmit/'
1564 'R*-{snapshot_id}-*'.format(
1565 board=board, snapshot_id=snapshot_id))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001566 for line in gsutil_ls(gs_path, ignore_errors=True):
1567 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)\S+', line)
1568 if m:
1569 return m.group(1)
Zheng-Jie Chang026cd5d2019-12-04 12:13:01 +08001570 return None
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001571
1572 result = []
1573 path = 'snapshot.xml'
1574 revisions = self.lookup_snapshot_manifest_revisions(old, new)
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001575 for timestamp, _git_rev, snapshot_id in revisions:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001576 snapshot_version = guess_snapshot_version(self.config['board'],
1577 snapshot_id, old, new)
Zheng-Jie Chang026cd5d2019-12-04 12:13:01 +08001578 if snapshot_version:
1579 result.append(
1580 codechange.Spec(codechange.SPEC_FIXED, snapshot_version, timestamp,
1581 path))
1582 else:
1583 logger.warning('snapshot id %s is not found, ignore', snapshot_id)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001584 return result
1585
1586 def collect_release_specs(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001587 assert is_cros_full_version(old)
1588 assert is_cros_full_version(new)
1589 old_milestone, old_short_version = version_split(old)
1590 new_milestone, new_short_version = version_split(new)
1591
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001592 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001593 for milestone in git_util.list_dir_from_revision(
1594 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
1595 if not milestone.isdigit():
1596 continue
1597 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
1598 continue
1599
Kuang-che Wu74768d32018-09-07 12:03:24 +08001600 files = git_util.list_dir_from_revision(
1601 self.historical_manifest_git_dir, 'refs/heads/master',
1602 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001603
1604 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001605 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001606 short_version, ext = os.path.splitext(fn)
1607 if ext != '.xml':
1608 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001609 if (util.is_version_lesseq(old_short_version, short_version) and
1610 util.is_version_lesseq(short_version, new_short_version) and
1611 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001612 rev = make_cros_full_version(milestone, short_version)
1613 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1614 'refs/heads/master', path)
1615 result.append(
1616 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001617
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001618 def version_key_func(spec):
1619 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001620 return util.version_key_func(short_version)
1621
1622 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001623 assert result[0].name == old
1624 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001625 return result
1626
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001627 def get_manifest(self, rev):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001628 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
1629 if is_cros_full_version(rev):
1630 milestone, short_version = version_split(rev)
1631 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
1632 manifest = git_util.get_file_from_revision(
1633 self.historical_manifest_git_dir, 'refs/heads/master', path)
1634 else:
1635 revisions = self.lookup_snapshot_manifest_revisions(rev, rev)
1636 commit_id = revisions[0][1]
1637 manifest = git_util.get_file_from_revision(self.manifest_internal_dir,
1638 commit_id, 'snapshot.xml')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001639 manifest_name = 'manifest_%s.xml' % rev
1640 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1641 with open(manifest_path, 'w') as f:
1642 f.write(manifest)
1643
1644 return manifest_name
1645
1646 def parse_spec(self, spec):
1647 parser = repo_util.ManifestParser(self.manifest_dir)
1648 if spec.spec_type == codechange.SPEC_FIXED:
1649 manifest_name = self.get_manifest(spec.name)
1650 manifest_path = os.path.join(self.manifest_dir, manifest_name)
Kuang-che Wua5723492019-11-25 20:59:34 +08001651 with open(manifest_path) as f:
1652 content = f.read()
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001653 root = parser.parse_single_xml(content, allow_include=False)
1654 else:
1655 root = parser.parse_xml_recursive(spec.name, spec.path)
1656
1657 spec.entries = parser.process_parsed_result(root)
1658 if spec.spec_type == codechange.SPEC_FIXED:
Kuang-che Wufe1e88a2019-09-10 21:52:25 +08001659 if not spec.is_static():
1660 raise ValueError(
1661 'fixed spec %r has unexpected floating entries' % spec.name)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001662
1663 def sync_disk_state(self, rev):
1664 manifest_name = self.get_manifest(rev)
1665
1666 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
1667 # manifest. 'repo sync -m' is not enough
1668 repo_util.init(
1669 self.config['chromeos_root'],
1670 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
1671 manifest_name=manifest_name,
1672 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001673 reference=self.config['chromeos_mirror'],
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001674 )
1675
1676 # Note, don't sync with current_branch=True for chromeos. One of its
1677 # build steps (inside mark_as_stable) executes "git describe" which
1678 # needs git tag information.
1679 repo_util.sync(self.config['chromeos_root'])