blob: 6650ed83478eb83d67f88fa78bf787712b66c991 [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 Chang2b6d1472019-11-13 12:40:17 +080027from bisect_kit import buildbucket_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080028from bisect_kit import cli
Kuang-che Wue4bae0b2018-07-19 12:10:14 +080029from bisect_kit import codechange
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080030from bisect_kit import cr_util
Kuang-che Wue121fae2018-11-09 16:18:39 +080031from bisect_kit import errors
Kuang-che Wubfc4a642018-04-19 11:54:08 +080032from bisect_kit import git_util
Kuang-che Wufb553102018-10-02 18:14:29 +080033from bisect_kit import locking
Kuang-che Wubfc4a642018-04-19 11:54:08 +080034from bisect_kit import repo_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080035from bisect_kit import util
36
37logger = logging.getLogger(__name__)
38
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080039re_chromeos_full_version = r'^R\d+-\d+\.\d+\.\d+$'
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080040re_chromeos_localbuild_version = r'^\d+\.\d+\.\d{4}_\d\d_\d\d_\d{4}$'
41re_chromeos_short_version = r'^\d+\.\d+\.\d+$'
Zheng-Jie Chang127c3302019-09-10 17:17:04 +080042re_chromeos_snapshot_version = r'^R\d+-\d+\.\d+\.\d+-\d+$'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080043
44gs_archive_path = 'gs://chromeos-image-archive/{board}-release'
45gs_release_path = (
Kuang-che Wu80bf6a52019-05-31 12:48:06 +080046 'gs://chromeos-releases/{channel}-channel/{boardpath}/{short_version}')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080047
48# Assume gsutil is in PATH.
49gsutil_bin = 'gsutil'
Zheng-Jie Changb8697042019-10-29 16:03:26 +080050
51# Since snapshots with version >= 12618.0.0 have android and chrome version
52# info.
53snapshot_cutover_version = '12618.0.0'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080054
Kuang-che Wub9705bd2018-06-28 17:59:18 +080055chromeos_root_inside_chroot = '/mnt/host/source'
56# relative to chromeos_root
Kuang-che Wu7f82c6f2019-08-12 14:29:28 +080057prebuilt_autotest_dir = 'tmp/autotest-prebuilt'
Kuang-che Wu28980b22019-07-31 19:51:45 +080058# Relative to chromeos root. Images are cached_images_dir/$board/$image_name.
59cached_images_dir = 'src/build/images'
60test_image_filename = 'chromiumos_test_image.bin'
Kuang-che Wub9705bd2018-06-28 17:59:18 +080061
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080062VERSION_KEY_CROS_SHORT_VERSION = 'cros_short_version'
63VERSION_KEY_CROS_FULL_VERSION = 'cros_full_version'
64VERSION_KEY_MILESTONE = 'milestone'
65VERSION_KEY_CR_VERSION = 'cr_version'
Kuang-che Wu708310b2018-03-28 17:24:34 +080066VERSION_KEY_ANDROID_BUILD_ID = 'android_build_id'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080067VERSION_KEY_ANDROID_BRANCH = 'android_branch'
68
69
Kuang-che Wu9890ce82018-07-07 15:14:10 +080070class NeedRecreateChrootException(Exception):
71 """Failed to build ChromeOS because of chroot mismatch or corruption"""
72
73
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080074def is_cros_short_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080075 """Determines if `s` is chromeos short version.
76
77 This function doesn't accept version number of local build.
78 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080079 return bool(re.match(re_chromeos_short_version, s))
80
81
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080082def is_cros_localbuild_version(s):
83 """Determines if `s` is chromeos local build version."""
84 return bool(re.match(re_chromeos_localbuild_version, s))
85
86
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080087def is_cros_full_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080088 """Determines if `s` is chromeos full version.
89
90 This function doesn't accept version number of local build.
91 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080092 return bool(re.match(re_chromeos_full_version, s))
93
94
95def is_cros_version(s):
96 """Determines if `s` is chromeos version (either short or full)"""
97 return is_cros_short_version(s) or is_cros_full_version(s)
98
99
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800100def is_cros_snapshot_version(s):
101 """Determines if `s` is chromeos snapshot version"""
102 return bool(re.match(re_chromeos_snapshot_version, s))
103
104
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800105def make_cros_full_version(milestone, short_version):
106 """Makes full_version from milestone and short_version"""
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800107 assert milestone
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800108 return 'R%s-%s' % (milestone, short_version)
109
110
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800111def make_cros_snapshot_version(milestone, short_version, snapshot_id):
112 """Makes snapshot version from milestone, short_version and snapshot id"""
113 return 'R%s-%s-%s' % (milestone, short_version, snapshot_id)
114
115
116def version_split(version):
117 """Splits full_version or snapshot_version into milestone and short_version"""
118 assert is_cros_full_version(version) or is_cros_snapshot_version(version)
119 if is_cros_snapshot_version(version):
120 return snapshot_version_split(version)[0:2]
121 milestone, short_version = version.split('-')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800122 return milestone[1:], short_version
123
124
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800125def snapshot_version_split(snapshot_version):
126 """Splits snapshot_version into milestone, short_version and snapshot_id"""
127 assert is_cros_snapshot_version(snapshot_version)
128 milestone, shot_version, snapshot_id = snapshot_version.split('-')
129 return milestone[1:], shot_version, snapshot_id
130
131
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800132def query_snapshot_buildbucket_id(board, snapshot_version):
133 """Query buildbucket id of a snapshot"""
134 assert is_cros_snapshot_version(snapshot_version)
135 path = ('gs://chromeos-image-archive/{board}-postsubmit'
136 '/{snapshot_version}-*/image.zip')
137 output = gsutil_ls(
138 '-d',
139 path.format(board=board, snapshot_version=snapshot_version),
140 ignore_errors=True)
141 for line in output:
142 m = re.match(r'.*-postsubmit/R\d+-\d+\.\d+\.\d+-\d+-(.+)/image\.zip', line)
143 if m:
144 return m.group(1)
145 return None
146
147
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800148def argtype_cros_version(s):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800149 if (not is_cros_version(s)) and (not is_cros_snapshot_version(s)):
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800150 msg = 'invalid cros version'
Kuang-che Wuce2f3be2019-10-28 19:44:54 +0800151 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 +0800152 return s
153
154
155def query_dut_lsb_release(host):
156 """Query /etc/lsb-release of given DUT
157
158 Args:
159 host: the DUT address
160
161 Returns:
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800162 dict for keys and values of /etc/lsb-release.
163
164 Raises:
Kuang-che Wu44278142019-03-04 11:33:57 +0800165 errors.SshConnectionError: cannot connect to host
166 errors.ExternalError: lsb-release file doesn't exist
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800167 """
168 try:
Kuang-che Wu44278142019-03-04 11:33:57 +0800169 output = util.ssh_cmd(host, 'cat', '/etc/lsb-release')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800170 except subprocess.CalledProcessError:
Kuang-che Wu44278142019-03-04 11:33:57 +0800171 raise errors.ExternalError('unable to read /etc/lsb-release; not a DUT')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800172 return dict(re.findall(r'^(\w+)=(.*)$', output, re.M))
173
174
175def is_dut(host):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800176 """Determines whether a host is a chromeos device.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800177
178 Args:
179 host: the DUT address
180
181 Returns:
182 True if the host is a chromeos device.
183 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800184 try:
185 return query_dut_lsb_release(host).get('DEVICETYPE') in [
186 'CHROMEBASE',
187 'CHROMEBIT',
188 'CHROMEBOOK',
189 'CHROMEBOX',
190 'REFERENCE',
191 ]
192 except (errors.ExternalError, errors.SshConnectionError):
193 return False
194
195
196def is_good_dut(host):
197 if not is_dut(host):
198 return False
199
200 # Sometimes python is broken after 'cros flash'.
201 try:
202 util.ssh_cmd(host, 'python', '-c', '1')
203 return True
204 except (subprocess.CalledProcessError, errors.SshConnectionError):
205 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800206
207
208def query_dut_board(host):
209 """Query board name of a given DUT"""
210 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_BOARD')
211
212
213def query_dut_short_version(host):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800214 """Query short version of a given DUT.
215
216 This function may return version of local build, which
217 is_cros_short_version() is false.
218 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800219 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_VERSION')
220
221
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800222def query_dut_is_snapshot(host):
223 """Query if given DUT is a snapshot version."""
224 path = query_dut_lsb_release(host).get('CHROMEOS_RELEASE_BUILDER_PATH', '')
225 return '-postsubmit' in path
226
227
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800228def query_dut_boot_id(host, connect_timeout=None):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800229 """Query boot id.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800230
231 Args:
232 host: DUT address
233 connect_timeout: connection timeout
234
235 Returns:
236 boot uuid
237 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800238 return util.ssh_cmd(
239 host,
240 'cat',
241 '/proc/sys/kernel/random/boot_id',
242 connect_timeout=connect_timeout).strip()
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800243
244
245def reboot(host):
246 """Reboot a DUT and verify"""
247 logger.debug('reboot %s', host)
248 boot_id = query_dut_boot_id(host)
249
Kuang-che Wu44278142019-03-04 11:33:57 +0800250 try:
251 util.ssh_cmd(host, 'reboot')
Kuang-che Wu5f662e82019-03-05 11:49:56 +0800252 except errors.SshConnectionError:
253 # Depends on timing, ssh may return failure due to broken pipe, which is
254 # working as intended. Ignore such kind of errors.
Kuang-che Wu44278142019-03-04 11:33:57 +0800255 pass
Kuang-che Wu708310b2018-03-28 17:24:34 +0800256 wait_reboot_done(host, boot_id)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800257
Kuang-che Wu708310b2018-03-28 17:24:34 +0800258
259def wait_reboot_done(host, boot_id):
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800260 # For dev-mode test image, the reboot time is roughly at least 16 seconds
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800261 # (dev screen short delay) or more (long delay).
262 time.sleep(15)
263 for _ in range(100):
264 try:
265 # During boot, DUT does not response and thus ssh may hang a while. So
266 # set a connect timeout. 3 seconds are enough and 2 are not. It's okay to
267 # set tight limit because it's inside retry loop.
268 assert boot_id != query_dut_boot_id(host, connect_timeout=3)
269 return
Kuang-che Wu5f662e82019-03-05 11:49:56 +0800270 except errors.SshConnectionError:
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800271 logger.debug('reboot not ready? sleep wait 1 sec')
272 time.sleep(1)
273
Kuang-che Wue121fae2018-11-09 16:18:39 +0800274 raise errors.ExternalError('reboot failed?')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800275
276
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800277def gs_release_boardpath(board):
278 """Normalizes board name for gs://chromeos-releases/
279
280 This follows behavior of PushImage() in chromite/scripts/pushimage.py
281 Note, only gs://chromeos-releases/ needs normalization,
282 gs://chromeos-image-archive does not.
283
284 Args:
285 board: ChromeOS board name
286
287 Returns:
288 normalized board name
289 """
290 return board.replace('_', '-')
291
292
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800293def gsutil(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800294 """gsutil command line wrapper.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800295
296 Args:
297 args: command line arguments passed to gsutil
298 kwargs:
299 ignore_errors: if true, return '' for failures, for example 'gsutil ls'
300 but the path not found.
301
302 Returns:
303 stdout of gsutil
304
305 Raises:
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800306 errors.ExternalError: gsutil failed to run
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800307 subprocess.CalledProcessError: command failed
308 """
309 stderr_lines = []
310 try:
311 return util.check_output(
312 gsutil_bin, *args, stderr_callback=stderr_lines.append)
313 except subprocess.CalledProcessError as e:
314 stderr = ''.join(stderr_lines)
315 if re.search(r'ServiceException:.* does not have .*access', stderr):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800316 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800317 'gsutil failed due to permission. ' +
318 'Run "%s config" and follow its instruction. ' % gsutil_bin +
319 'Fill any string if it asks for project-id')
320 if kwargs.get('ignore_errors'):
321 return ''
322 raise
323 except OSError as e:
324 if e.errno == errno.ENOENT:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800325 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800326 'Unable to run %s. gsutil is not installed or not in PATH?' %
327 gsutil_bin)
328 raise
329
330
331def gsutil_ls(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800332 """gsutil ls.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800333
334 Args:
335 args: arguments passed to 'gsutil ls'
336 kwargs: extra parameters, where
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800337 ignore_errors: if true, return empty list instead of raising
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800338 exception, ex. path not found.
339
340 Returns:
341 list of 'gsutil ls' result. One element for one line of gsutil output.
342
343 Raises:
344 subprocess.CalledProcessError: gsutil failed, usually means path not found
345 """
346 return gsutil('ls', *args, **kwargs).splitlines()
347
348
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800349def gsutil_stat_update_time(*args, **kwargs):
350 """Returns the last modified time of a file or multiple files.
351
352 Args:
353 args: arguments passed to 'gsutil stat'.
354 kwargs: extra parameters for gsutil.
355
356 Returns:
357 A integer indicates the last modified timestamp.
358
359 Raises:
360 subprocess.CalledProcessError: gsutil failed, usually means path not found
361 errors.ExternalError: update time is not found
362 """
363 result = -1
364 # Currently we believe stat always returns a UTC time, and strptime also
365 # parses a UTC time by default.
366 time_format = '%a, %d %b %Y %H:%M:%S GMT'
367
368 for line in gsutil('stat', *args, **kwargs).splitlines():
369 if ':' not in line:
370 continue
371 key, value = map(str.strip, line.split(':', 1))
372 if key != 'Update time':
373 continue
374 dt = datetime.datetime.strptime(value, time_format)
Kuang-che Wu72b5a572019-10-29 20:37:57 +0800375 unixtime = int(calendar.timegm(dt.utctimetuple()))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800376 result = max(result, unixtime)
377
378 if result == -1:
379 raise errors.ExternalError("didn't find update time")
380 return result
381
382
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800383def query_milestone_by_version(board, short_version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800384 """Query milestone by ChromeOS version number.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800385
386 Args:
387 board: ChromeOS board name
388 short_version: ChromeOS version number in short format, ex. 9300.0.0
389
390 Returns:
391 ChromeOS milestone number (string). For example, '58' for '9300.0.0'.
392 None if failed.
393 """
394 path = gs_archive_path.format(board=board) + '/R*-' + short_version
395 for line in gsutil_ls('-d', path, ignore_errors=True):
396 m = re.search(r'/R(\d+)-', line)
397 if not m:
398 continue
399 return m.group(1)
400
401 for channel in ['canary', 'dev', 'beta', 'stable']:
402 path = gs_release_path.format(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800403 channel=channel,
404 boardpath=gs_release_boardpath(board),
405 short_version=short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800406 for line in gsutil_ls(path, ignore_errors=True):
407 m = re.search(r'\bR(\d+)-' + short_version, line)
408 if not m:
409 continue
410 return m.group(1)
411
412 logger.error('unable to query milestone of %s for %s', short_version, board)
413 return None
414
415
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800416def list_board_names(chromeos_root):
417 """List board names.
418
419 Args:
420 chromeos_root: chromeos tree root
421
422 Returns:
423 list of board names
424 """
425 # Following logic is simplified from chromite/lib/portage_util.py
426 cros_list_overlays = os.path.join(chromeos_root,
427 'chromite/bin/cros_list_overlays')
428 overlays = util.check_output(cros_list_overlays).splitlines()
429 result = set()
430 for overlay in overlays:
431 conf_file = os.path.join(overlay, 'metadata', 'layout.conf')
432 name = None
433 if os.path.exists(conf_file):
434 for line in open(conf_file):
435 m = re.match(r'^repo-name\s*=\s*(\S+)\s*$', line)
436 if m:
437 name = m.group(1)
438 break
439
440 if not name:
441 name_file = os.path.join(overlay, 'profiles', 'repo_name')
442 if os.path.exists(name_file):
Kuang-che Wua5723492019-11-25 20:59:34 +0800443 with open(name_file) as f:
444 name = f.read().strip()
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800445
446 if name:
447 name = re.sub(r'-private$', '', name)
448 result.add(name)
449
450 return list(result)
451
452
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800453def recognize_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800454 """Recognize ChromeOS version.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800455
456 Args:
457 board: ChromeOS board name
458 version: ChromeOS version number in short or full format
459
460 Returns:
461 (milestone, version in short format)
462 """
463 if is_cros_short_version(version):
464 milestone = query_milestone_by_version(board, version)
465 short_version = version
466 else:
467 milestone, short_version = version_split(version)
468 return milestone, short_version
469
470
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800471def extract_major_version(version):
472 """Converts a version to its major version.
473
474 Args:
Kuang-che Wu9501f342019-11-15 17:15:21 +0800475 version: ChromeOS version number or snapshot version
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800476
477 Returns:
478 major version number in string format
479 """
480 version = version_to_short(version)
481 m = re.match(r'^(\d+)\.\d+\.\d+$', version)
482 return m.group(1)
483
484
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800485def version_to_short(version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800486 """Convert ChromeOS version number to short format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800487
488 Args:
489 version: ChromeOS version number in short or full format
490
491 Returns:
492 version number in short format
493 """
494 if is_cros_short_version(version):
495 return version
496 _, short_version = version_split(version)
497 return short_version
498
499
500def version_to_full(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800501 """Convert ChromeOS version number to full format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800502
503 Args:
504 board: ChromeOS board name
505 version: ChromeOS version number in short or full format
506
507 Returns:
508 version number in full format
509 """
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800510 if is_cros_snapshot_version(version):
511 milestone, short_version, _ = snapshot_version_split(version)
512 return make_cros_full_version(milestone, short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800513 if is_cros_full_version(version):
514 return version
515 milestone = query_milestone_by_version(board, version)
Kuang-che Wu0205f052019-05-23 12:48:37 +0800516 assert milestone, 'incorrect board=%s or version=%s ?' % (board, version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800517 return make_cros_full_version(milestone, version)
518
519
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800520def list_snapshots_from_image_archive(board, major_version):
Kuang-che Wu9501f342019-11-15 17:15:21 +0800521 """List ChromeOS snapshot image available from gs://chromeos-image-archive.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800522
523 Args:
524 board: ChromeOS board
525 major_version: ChromeOS major version
526
527 Returns:
528 list of (version, gs_path):
529 version: Chrome OS snapshot version
530 gs_path: gs path of test image
531 """
532
533 path = (
534 'gs://chromeos-image-archive/{board}-postsubmit/R*-{major_version}.0.0-*')
535 result = []
536 output = gsutil_ls(
537 '-d',
538 path.format(board=board, major_version=major_version),
539 ignore_errors=True)
540
541 for path in output:
542 if not path.endswith('/'):
543 continue
544 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)', path)
545 if m:
546 snapshot_version = m.group(1)
547 test_image = 'image.zip'
548 gs_path = path + test_image
549 result.append((snapshot_version, gs_path))
550 return result
551
552
Kuang-che Wu575dc442019-03-05 10:30:55 +0800553def list_prebuilt_from_image_archive(board):
554 """Lists ChromeOS prebuilt image available from gs://chromeos-image-archive.
555
556 gs://chromeos-image-archive contains only recent builds (in two years).
557 We prefer this function to list_prebuilt_from_chromeos_releases() because
558 - this is what "cros flash" supports directly.
559 - the paths have milestone information, so we don't need to do slow query
560 by ourselves.
561
562 Args:
563 board: ChromeOS board name
564
565 Returns:
566 list of (version, gs_path):
567 version: Chrome OS version in full format
568 gs_path: gs path of test image
569 """
570 result = []
571 for line in gsutil_ls(gs_archive_path.format(board=board)):
572 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+)', line)
573 if m:
574 full_version = m.group(1)
575 test_image = 'chromiumos_test_image.tar.xz'
576 assert line.endswith('/')
577 gs_path = line + test_image
578 result.append((full_version, gs_path))
579 return result
580
581
582def list_prebuilt_from_chromeos_releases(board):
583 """Lists ChromeOS versions available from gs://chromeos-releases.
584
585 gs://chromeos-releases contains more builds. However, 'cros flash' doesn't
586 support it.
587
588 Args:
589 board: ChromeOS board name
590
591 Returns:
592 list of (version, gs_path):
593 version: Chrome OS version in short format
594 gs_path: gs path of test image (with wildcard)
595 """
596 result = []
597 for line in gsutil_ls(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800598 gs_release_path.format(
599 channel='*', boardpath=gs_release_boardpath(board), short_version=''),
Kuang-che Wu575dc442019-03-05 10:30:55 +0800600 ignore_errors=True):
601 m = re.match(r'gs:\S+/(\d+\.\d+\.\d+)/$', line)
602 if m:
603 short_version = m.group(1)
604 test_image = 'ChromeOS-test-R*-{short_version}-{board}.tar.xz'.format(
605 short_version=short_version, board=board)
606 gs_path = line + test_image
607 result.append((short_version, gs_path))
608 return result
609
610
611def list_chromeos_prebuilt_versions(board,
612 old,
613 new,
614 only_good_build=True,
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800615 include_older_build=True,
616 use_snapshot=False):
Kuang-che Wu575dc442019-03-05 10:30:55 +0800617 """Lists ChromeOS version numbers with prebuilt between given range
618
619 Args:
620 board: ChromeOS board name
621 old: start version (inclusive)
622 new: end version (inclusive)
623 only_good_build: only if test image is available
624 include_older_build: include prebuilt in gs://chromeos-releases
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800625 use_snapshot: return snapshot versions if found
Kuang-che Wu575dc442019-03-05 10:30:55 +0800626
627 Returns:
628 list of sorted version numbers (in full format) between [old, new] range
629 (inclusive).
630 """
631 old = version_to_short(old)
632 new = version_to_short(new)
633
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800634 rev_map = {
635 } # dict: short version -> list of (short/full or snapshot version, gs path)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800636 for full_version, gs_path in list_prebuilt_from_image_archive(board):
637 short_version = version_to_short(full_version)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800638 rev_map[short_version] = [(full_version, gs_path)]
Kuang-che Wu575dc442019-03-05 10:30:55 +0800639
640 if include_older_build and old not in rev_map:
641 for short_version, gs_path in list_prebuilt_from_chromeos_releases(board):
642 if short_version not in rev_map:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800643 rev_map[short_version] = [(short_version, gs_path)]
644
645 if use_snapshot:
646 for major_version in range(
647 int(extract_major_version(old)),
648 int(extract_major_version(new)) + 1):
649 short_version = '%s.0.0' % major_version
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800650 next_short_version = '%s.0.0' % (major_version + 1)
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800651 # If current version is smaller than cutover, ignore it as it might not
652 # contain enough information for continuing android and chrome bisection.
653 if not util.is_version_lesseq(snapshot_cutover_version, short_version):
654 continue
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800655
656 # Given the fact that snapshots are images between two release versions.
657 # Adding snapshots of 12345.0.0 should be treated as adding commits
658 # between [12345.0.0, 12346.0.0).
659 # So in the following lines we check two facts:
660 # 1) If 12346.0.0(next_short_version) is a version between old and new
661 if not util.is_direct_relative_version(next_short_version, old):
662 continue
663 if not util.is_direct_relative_version(next_short_version, new):
664 continue
665 # 2) If 12345.0.0(short_version) is a version between old and new
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800666 if not util.is_direct_relative_version(short_version, old):
667 continue
668 if not util.is_direct_relative_version(short_version, new):
669 continue
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800670
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800671 snapshots = list_snapshots_from_image_archive(board, str(major_version))
672 if snapshots:
673 # if snapshots found, we can append them after the release version,
674 # so the prebuilt image list of this version will be
675 # release_image, snapshot1, snapshot2,...
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800676 if short_version not in rev_map:
677 rev_map[short_version] = []
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800678 rev_map[short_version] += snapshots
Kuang-che Wu575dc442019-03-05 10:30:55 +0800679
680 result = []
681 for rev in sorted(rev_map, key=util.version_key_func):
682 if not util.is_direct_relative_version(new, rev):
683 continue
684 if not util.is_version_lesseq(old, rev):
685 continue
686 if not util.is_version_lesseq(rev, new):
687 continue
688
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800689 for version, gs_path in rev_map[rev]:
Kuang-che Wu575dc442019-03-05 10:30:55 +0800690
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800691 # version_to_full() and gsutil_ls() may take long time if versions are a
692 # lot. This is acceptable because we usually bisect only short range.
Kuang-che Wu575dc442019-03-05 10:30:55 +0800693
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800694 if only_good_build:
695 gs_result = gsutil_ls(gs_path, ignore_errors=True)
696 if not gs_result:
697 logger.warning('%s is not a good build, ignore', version)
698 continue
699 assert len(gs_result) == 1
700 m = re.search(r'(R\d+-\d+\.\d+\.\d+)', gs_result[0])
701 if not m:
702 logger.warning('format of image path is unexpected: %s', gs_result[0])
703 continue
704 if not is_cros_snapshot_version(version):
705 version = m.group(1)
706 elif is_cros_short_version(version):
707 version = version_to_full(board, version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800708
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800709 result.append(version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800710
711 return result
712
713
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800714def prepare_snapshot_image(chromeos_root, board, snapshot_version):
715 """Prepare chromeos snapshot image.
716
717 Args:
718 chromeos_root: chromeos tree root
719 board: ChromeOS board name
720 snapshot_version: ChromeOS snapshot version number
721
722 Returns:
723 local file path of test image relative to chromeos_root
724 """
725 assert is_cros_snapshot_version(snapshot_version)
726 milestone, short_version, snapshot_id = snapshot_version_split(
727 snapshot_version)
728 full_version = make_cros_full_version(milestone, short_version)
729 tmp_dir = os.path.join(
730 chromeos_root, 'tmp',
731 'ChromeOS-test-%s-%s-%s' % (full_version, board, snapshot_id))
732 if not os.path.exists(tmp_dir):
733 os.makedirs(tmp_dir)
734
735 gs_path = ('gs://chromeos-image-archive/{board}-postsubmit/' +
736 '{snapshot_version}-*/image.zip')
737 gs_path = gs_path.format(board=board, snapshot_version=snapshot_version)
738
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800739 full_path = os.path.join(tmp_dir, test_image_filename)
740 rel_path = os.path.relpath(full_path, chromeos_root)
741 if os.path.exists(full_path):
742 return rel_path
743
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800744 files = gsutil_ls(gs_path, ignore_errors=True)
745 if len(files) == 1:
746 gs_path = files[0]
747 gsutil('cp', gs_path, tmp_dir)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800748 util.check_call(
749 'unzip', '-j', 'image.zip', test_image_filename, cwd=tmp_dir)
750 os.remove(os.path.join(tmp_dir, 'image.zip'))
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800751 return rel_path
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800752
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800753 assert False
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +0800754 return None
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800755
756
Kuang-che Wu28980b22019-07-31 19:51:45 +0800757def prepare_prebuilt_image(chromeos_root, board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800758 """Prepare chromeos prebuilt image.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800759
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800760 It searches for xbuddy image which "cros flash" can use, or fetch image to
761 local disk.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800762
763 Args:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800764 chromeos_root: chromeos tree root
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800765 board: ChromeOS board name
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800766 version: ChromeOS version number in short or full format
767
768 Returns:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800769 xbuddy path or file path (relative to chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800770 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800771 assert is_cros_version(version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800772 full_version = version_to_full(board, version)
773 short_version = version_to_short(full_version)
774
775 image_path = None
776 gs_path = gs_archive_path.format(board=board) + '/' + full_version
777 if gsutil_ls('-d', gs_path, ignore_errors=True):
778 image_path = 'xbuddy://remote/{board}/{full_version}/test'.format(
779 board=board, full_version=full_version)
780 else:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800781 tmp_dir = os.path.join(chromeos_root, 'tmp',
782 'ChromeOS-test-%s-%s' % (full_version, board))
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800783 full_path = os.path.join(tmp_dir, test_image_filename)
784 rel_path = os.path.relpath(full_path, chromeos_root)
785 if os.path.exists(full_path):
786 return rel_path
787
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800788 if not os.path.exists(tmp_dir):
789 os.makedirs(tmp_dir)
790 # gs://chromeos-releases may have more old images than
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800791 # gs://chromeos-image-archive, but 'cros flash' doesn't support it. We have
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800792 # to fetch the image by ourselves
793 for channel in ['canary', 'dev', 'beta', 'stable']:
794 fn = 'ChromeOS-test-{full_version}-{board}.tar.xz'.format(
795 full_version=full_version, board=board)
796 gs_path = gs_release_path.format(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800797 channel=channel,
798 boardpath=gs_release_boardpath(board),
799 short_version=short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800800 gs_path += '/' + fn
801 if gsutil_ls(gs_path, ignore_errors=True):
802 # TODO(kcwu): delete tmp
803 gsutil('cp', gs_path, tmp_dir)
804 util.check_call('tar', 'Jxvf', fn, cwd=tmp_dir)
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +0800805 image_path = os.path.relpath(full_path, chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800806 break
807
808 assert image_path
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800809 return image_path
810
811
812def cros_flash(chromeos_root,
813 host,
814 board,
815 image_path,
816 version=None,
817 clobber_stateful=False,
Kuang-che Wu155fb6e2018-11-29 16:00:41 +0800818 disable_rootfs_verification=True):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800819 """Flash a DUT with given ChromeOS image.
820
821 This is implemented by 'cros flash' command line.
822
823 Args:
824 chromeos_root: use 'cros flash' of which chromeos tree
825 host: DUT address
826 board: ChromeOS board name
Kuang-che Wu28980b22019-07-31 19:51:45 +0800827 image_path: chromeos image xbuddy path or file path. For relative
828 path, it should be relative to chromeos_root.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800829 version: ChromeOS version in short or full format
830 clobber_stateful: Clobber stateful partition when performing update
831 disable_rootfs_verification: Disable rootfs verification after update
832 is completed
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800833
834 Raises:
835 errors.ExternalError: cros flash failed
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800836 """
837 logger.info('cros_flash %s %s %s %s', host, board, version, image_path)
838
839 # Reboot is necessary because sometimes previous 'cros flash' failed and
840 # entered a bad state.
841 reboot(host)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800842
Kuang-che Wu28980b22019-07-31 19:51:45 +0800843 # Handle relative path.
844 if '://' not in image_path and not os.path.isabs(image_path):
845 assert os.path.exists(os.path.join(chromeos_root, image_path))
846 image_path = os.path.join(chromeos_root_inside_chroot, image_path)
847
Kuang-che Wuf3d03ca2019-03-11 17:31:40 +0800848 args = [
849 '--debug', '--no-ping', '--send-payload-in-parallel', host, image_path
850 ]
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800851 if clobber_stateful:
852 args.append('--clobber-stateful')
853 if disable_rootfs_verification:
854 args.append('--disable-rootfs-verification')
855
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800856 try:
857 cros_sdk(chromeos_root, 'cros', 'flash', *args)
858 except subprocess.CalledProcessError:
859 raise errors.ExternalError('cros flash failed')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800860
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800861 if version:
862 # In the past, cros flash may fail with returncode=0
863 # So let's have an extra check.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800864 if is_cros_snapshot_version(version):
865 builder_path = query_dut_lsb_release(host).get(
866 'CHROMEOS_RELEASE_BUILDER_PATH', '')
867 expect_prefix = '%s-postsubmit/%s-' % (board, version)
868 if not builder_path.startswith(expect_prefix):
869 raise errors.ExternalError(
870 'although cros flash succeeded, the OS builder path is '
871 'unexpected: actual=%s expect=%s' % (builder_path, expect_prefix))
872 else:
873 expect_version = version_to_short(version)
874 dut_version = query_dut_short_version(host)
875 if dut_version != expect_version:
876 raise errors.ExternalError(
877 'although cros flash succeeded, the OS version is unexpected: '
878 'actual=%s expect=%s' % (dut_version, expect_version))
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800879
Kuang-che Wu4a81ea72019-10-05 15:35:17 +0800880 # "cros flash" may terminate successfully but the DUT starts self-repairing
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800881 # (b/130786578), so it's necessary to do sanity check.
882 if not is_good_dut(host):
883 raise errors.ExternalError(
884 'although cros flash succeeded, the DUT is in bad state')
885
886
887def cros_flash_with_retry(chromeos_root,
888 host,
889 board,
890 image_path,
891 version=None,
892 clobber_stateful=False,
893 disable_rootfs_verification=True,
894 repair_callback=None):
895 # 'cros flash' is not 100% reliable, retry if necessary.
896 for attempt in range(2):
897 if attempt > 0:
898 logger.info('will retry 60 seconds later')
899 time.sleep(60)
900
901 try:
902 cros_flash(
903 chromeos_root,
904 host,
905 board,
906 image_path,
907 version=version,
908 clobber_stateful=clobber_stateful,
909 disable_rootfs_verification=disable_rootfs_verification)
910 return True
911 except errors.ExternalError:
912 logger.exception('cros flash failed')
913 if repair_callback and not repair_callback(host):
914 logger.warning('not repaired, assume it is harmless')
915 continue
916 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800917
918
919def version_info(board, version):
920 """Query subcomponents version info of given version of ChromeOS
921
922 Args:
923 board: ChromeOS board name
924 version: ChromeOS version number in short or full format
925
926 Returns:
927 dict of component and version info, including (if available):
928 cros_short_version: ChromeOS version
929 cros_full_version: ChromeOS version
930 milestone: milestone of ChromeOS
931 cr_version: Chrome version
Kuang-che Wu708310b2018-03-28 17:24:34 +0800932 android_build_id: Android build id
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800933 android_branch: Android branch, in format like 'git_nyc-mr1-arc'
934 """
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800935 if is_cros_snapshot_version(version):
Zheng-Jie Chang2b6d1472019-11-13 12:40:17 +0800936 api = buildbucket_util.BuildbucketApi()
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800937 milestone, short_version, _ = snapshot_version_split(version)
938 buildbucket_id = query_snapshot_buildbucket_id(board, version)
Zheng-Jie Chang2b6d1472019-11-13 12:40:17 +0800939 data = api.get(int(buildbucket_id)).output.properties
940 target_versions = data['target_versions']
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800941 return {
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800942 VERSION_KEY_MILESTONE: milestone,
943 VERSION_KEY_CROS_FULL_VERSION: version,
944 VERSION_KEY_CROS_SHORT_VERSION: short_version,
945 VERSION_KEY_CR_VERSION: target_versions['chromeVersion'],
946 VERSION_KEY_ANDROID_BUILD_ID: target_versions['androidVersion'],
947 VERSION_KEY_ANDROID_BRANCH: target_versions['androidBranchVersion'],
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800948 }
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800949 info = {}
950 full_version = version_to_full(board, version)
951
952 # Some boards may have only partial-metadata.json but no metadata.json.
953 # e.g. caroline R60-9462.0.0
954 # Let's try both.
955 metadata = None
956 for metadata_filename in ['metadata.json', 'partial-metadata.json']:
Kuang-che Wu0768b972019-10-05 15:18:59 +0800957 path = gs_archive_path.format(
958 board=board) + '/%s/%s' % (full_version, metadata_filename)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800959 metadata = gsutil('cat', path, ignore_errors=True)
960 if metadata:
961 o = json.loads(metadata)
962 v = o['version']
963 board_metadata = o['board-metadata'][board]
964 info.update({
965 VERSION_KEY_CROS_SHORT_VERSION: v['platform'],
966 VERSION_KEY_CROS_FULL_VERSION: v['full'],
967 VERSION_KEY_MILESTONE: v['milestone'],
968 VERSION_KEY_CR_VERSION: v['chrome'],
969 })
970
971 if 'android' in v:
Kuang-che Wu708310b2018-03-28 17:24:34 +0800972 info[VERSION_KEY_ANDROID_BUILD_ID] = v['android']
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800973 if 'android-branch' in v: # this appears since R58-9317.0.0
974 info[VERSION_KEY_ANDROID_BRANCH] = v['android-branch']
975 elif 'android-container-branch' in board_metadata:
976 info[VERSION_KEY_ANDROID_BRANCH] = v['android-container-branch']
977 break
978 else:
979 logger.error('Failed to read metadata from gs://chromeos-image-archive')
980 logger.error(
981 'Note, so far no quick way to look up version info for too old builds')
982
983 return info
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800984
985
986def query_chrome_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800987 """Queries chrome version of chromeos build.
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800988
989 Args:
990 board: ChromeOS board name
991 version: ChromeOS version number in short or full format
992
993 Returns:
994 Chrome version number
995 """
996 info = version_info(board, version)
997 return info['cr_version']
Kuang-che Wu708310b2018-03-28 17:24:34 +0800998
999
1000def query_android_build_id(board, rev):
1001 info = version_info(board, rev)
1002 rev = info['android_build_id']
1003 return rev
1004
1005
1006def query_android_branch(board, rev):
1007 info = version_info(board, rev)
1008 rev = info['android_branch']
1009 return rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001010
1011
Kuang-che Wu3eb6b502018-06-06 16:15:18 +08001012def guess_chrome_version(board, rev):
1013 """Guess chrome version number.
1014
1015 Args:
1016 board: chromeos board name
1017 rev: chrome or chromeos version
1018
1019 Returns:
1020 chrome version number
1021 """
1022 if is_cros_version(rev):
1023 assert board, 'need to specify BOARD for cros version'
1024 rev = query_chrome_version(board, rev)
1025 assert cr_util.is_chrome_version(rev)
1026
1027 return rev
1028
1029
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001030def is_inside_chroot():
1031 """Returns True if we are inside chroot."""
1032 return os.path.exists('/etc/cros_chroot_version')
1033
1034
1035def cros_sdk(chromeos_root, *args, **kwargs):
1036 """Run commands inside chromeos chroot.
1037
1038 Args:
1039 chromeos_root: chromeos tree root
1040 *args: command to run
1041 **kwargs:
Kuang-che Wud4603d72018-11-29 17:51:21 +08001042 chrome_root: pass to cros_sdk; mount this path into the SDK chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001043 env: (dict) environment variables for the command
Kuang-che Wubcafc552019-08-15 15:27:02 +08001044 log_stdout: Whether write the stdout output of the child process to log.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001045 stdin: standard input file handle for the command
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001046 stderr_callback: Callback function for stderr. Called once per line.
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001047 goma_dir: Goma installed directory to mount into the chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001048 """
1049 envs = []
1050 for k, v in kwargs.get('env', {}).items():
1051 assert re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', k)
1052 envs.append('%s=%s' % (k, v))
1053
1054 # Use --no-ns-pid to prevent cros_sdk change our pgid, otherwise subsequent
1055 # commands would be considered as background process.
Kuang-che Wu399d4662019-06-06 15:23:37 +08001056 prefix = ['chromite/bin/cros_sdk', '--no-ns-pid']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001057
1058 if kwargs.get('chrome_root'):
Kuang-che Wu399d4662019-06-06 15:23:37 +08001059 prefix += ['--chrome_root', kwargs['chrome_root']]
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001060 if kwargs.get('goma_dir'):
1061 prefix += ['--goma_dir', kwargs['goma_dir']]
Kuang-che Wud4603d72018-11-29 17:51:21 +08001062
Kuang-che Wu399d4662019-06-06 15:23:37 +08001063 prefix += envs + ['--']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001064
Kuang-che Wu399d4662019-06-06 15:23:37 +08001065 # In addition to the output of command we are interested, cros_sdk may
1066 # generate its own messages. For example, chroot creation messages if we run
1067 # cros_sdk the first time.
1068 # This is the hack to run dummy command once, so we can get clean output for
1069 # the command we are interested.
1070 cmd = prefix + ['true']
1071 util.check_call(*cmd, cwd=chromeos_root)
1072
1073 cmd = prefix + list(args)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001074 return util.check_output(
1075 *cmd,
1076 cwd=chromeos_root,
Kuang-che Wubcafc552019-08-15 15:27:02 +08001077 log_stdout=kwargs.get('log_stdout', True),
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001078 stdin=kwargs.get('stdin'),
1079 stderr_callback=kwargs.get('stderr_callback'))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001080
1081
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001082def create_chroot(chromeos_root):
1083 """Creates ChromeOS chroot.
1084
1085 Args:
1086 chromeos_root: chromeos tree root
1087 """
1088 if os.path.exists(os.path.join(chromeos_root, 'chroot')):
1089 return
1090 if os.path.exists(os.path.join(chromeos_root, 'chroot.img')):
1091 return
1092
1093 util.check_output('chromite/bin/cros_sdk', '--create', cwd=chromeos_root)
1094
1095
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001096def copy_into_chroot(chromeos_root, src, dst):
1097 """Copies file into chromeos chroot.
1098
1099 Args:
1100 chromeos_root: chromeos tree root
1101 src: path outside chroot
1102 dst: path inside chroot
1103 """
1104 # chroot may be an image, so we cannot copy to corresponding path
1105 # directly.
1106 cros_sdk(chromeos_root, 'sh', '-c', 'cat > %s' % dst, stdin=open(src))
1107
1108
1109def exists_in_chroot(chromeos_root, path):
1110 """Determine whether a path exists in the chroot.
1111
1112 Args:
1113 chromeos_root: chromeos tree root
1114 path: path inside chroot, relative to src/scripts
1115
1116 Returns:
1117 True if a path exists
1118 """
1119 try:
Kuang-che Wuacb6efd2018-04-25 18:52:58 +08001120 cros_sdk(chromeos_root, 'test', '-e', path)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001121 except subprocess.CalledProcessError:
1122 return False
1123 return True
1124
1125
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001126def check_if_need_recreate_chroot(stdout, stderr):
1127 """Analyze build log and determine if chroot should be recreated.
1128
1129 Args:
1130 stdout: stdout output of build
1131 stderr: stderr output of build
1132
1133 Returns:
1134 the reason if chroot needs recreated; None otherwise
1135 """
Kuang-che Wu74768d32018-09-07 12:03:24 +08001136 if re.search(
1137 r"The current version of portage supports EAPI '\d+'. "
Kuang-che Wuae6824b2019-08-27 22:20:01 +08001138 'You must upgrade', stderr):
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001139 return 'EAPI version mismatch'
1140
Kuang-che Wu5ac81322018-11-26 14:04:06 +08001141 if 'Chroot is too new. Consider running:' in stderr:
1142 return 'chroot version is too new'
1143
1144 # old message before Oct 2018
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001145 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
1146 return 'chroot version is too new'
1147
Kuang-che Wu6fe987f2018-08-28 15:24:20 +08001148 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
1149 if "undefined reference to 'std::__1::basic_string" in stdout:
1150 return 'might be due to compiler change'
1151
Kuang-che Wu94e3b452019-11-21 12:49:18 +08001152 # Detect failures due to file collisions.
1153 # For example, kernel uprev from 3.x to 4.x, they are two separate packages
1154 # and conflict with each other. Other possible cases are package renaming or
1155 # refactoring. Let's recreate chroot to work around them.
1156 if 'Detected file collision' in stdout:
1157 # Using wildcard between words because the text wraps to the next line
1158 # depending on length of package name and each line is prefixed with
1159 # package name.
1160 # Using ".{,100}" instead of ".*" to prevent regex matching time explodes
1161 # exponentially. 100 is chosen arbitrarily. It should be longer than any
1162 # package name (65 now).
1163 m = re.search(
1164 r'Package (\S+).{,100}NOT.{,100}merged.{,100}'
1165 r'due.{,100}to.{,100}file.{,100}collisions', stdout, re.S)
1166 if m:
1167 return 'failed to install package due to file collision: ' + m.group(1)
Kuang-che Wu356c3522019-11-19 16:11:05 +08001168
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001169 return None
1170
1171
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001172def build_packages(chromeos_root,
1173 board,
1174 chrome_root=None,
1175 goma_dir=None,
1176 afdo_use=False):
Kuang-che Wu28980b22019-07-31 19:51:45 +08001177 """Build ChromeOS packages.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001178
1179 Args:
1180 chromeos_root: chromeos tree root
1181 board: ChromeOS board name
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001182 chrome_root: Chrome tree root. If specified, build chrome using the
1183 provided tree
1184 goma_dir: Goma installed directory to mount into the chroot. If specified,
1185 build chrome with goma.
1186 afdo_use: build chrome with AFDO optimization
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001187 """
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001188 common_env = {
1189 'USE': '-cros-debug chrome_internal',
1190 'FEATURES': 'separatedebug',
1191 }
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001192 stderr_lines = []
1193 try:
Kuang-che Wufb553102018-10-02 18:14:29 +08001194 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001195 env = common_env.copy()
1196 env['FEATURES'] += ' -separatedebug splitdebug'
Kuang-che Wufb553102018-10-02 18:14:29 +08001197 cros_sdk(
1198 chromeos_root,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001199 './update_chroot',
1200 '--toolchain_boards',
Kuang-che Wufb553102018-10-02 18:14:29 +08001201 board,
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001202 env=env,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001203 stderr_callback=stderr_lines.append)
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001204
1205 env = common_env.copy()
1206 cmd = [
Kuang-che Wu28980b22019-07-31 19:51:45 +08001207 './build_packages',
1208 '--board',
1209 board,
1210 '--withdev',
1211 '--noworkon',
1212 '--skip_chroot_upgrade',
1213 '--accept_licenses=@CHROMEOS',
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001214 ]
1215 if goma_dir:
1216 # Tell build_packages to start and stop goma
1217 cmd.append('--run_goma')
1218 env['USE_GOMA'] = 'true'
1219 if afdo_use:
1220 env['USE'] += ' afdo_use'
1221 cros_sdk(
1222 chromeos_root,
1223 *cmd,
1224 env=env,
1225 chrome_root=chrome_root,
1226 stderr_callback=stderr_lines.append,
1227 goma_dir=goma_dir)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001228 except subprocess.CalledProcessError as e:
1229 # Detect failures due to incompatibility between chroot and source tree. If
1230 # so, notify the caller to recreate chroot and retry.
1231 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1232 if reason:
1233 raise NeedRecreateChrootException(reason)
1234
1235 # For other failures, don't know how to handle. Just bail out.
1236 raise
1237
Kuang-che Wu28980b22019-07-31 19:51:45 +08001238
1239def build_image(chromeos_root, board):
1240 """Build ChromeOS image.
1241
1242 Args:
1243 chromeos_root: chromeos tree root
1244 board: ChromeOS board name
1245
1246 Returns:
1247 image folder; relative to chromeos_root
1248 """
1249 stderr_lines = []
1250 try:
1251 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
1252 cros_sdk(
1253 chromeos_root,
1254 './build_image',
1255 '--board',
1256 board,
1257 '--noenable_rootfs_verification',
1258 'test',
1259 env={
1260 'USE': '-cros-debug chrome_internal',
1261 'FEATURES': 'separatedebug',
1262 },
1263 stderr_callback=stderr_lines.append)
1264 except subprocess.CalledProcessError as e:
1265 # Detect failures due to incompatibility between chroot and source tree. If
1266 # so, notify the caller to recreate chroot and retry.
1267 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1268 if reason:
1269 raise NeedRecreateChrootException(reason)
1270
1271 # For other failures, don't know how to handle. Just bail out.
1272 raise
1273
1274 image_symlink = os.path.join(chromeos_root, cached_images_dir, board,
1275 'latest')
1276 assert os.path.exists(image_symlink)
1277 image_name = os.readlink(image_symlink)
1278 image_folder = os.path.join(cached_images_dir, board, image_name)
1279 assert os.path.exists(
1280 os.path.join(chromeos_root, image_folder, test_image_filename))
1281 return image_folder
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001282
1283
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001284class AutotestControlInfo(object):
1285 """Parsed content of autotest control file.
1286
1287 Attributes:
1288 name: test name
1289 path: control file path
1290 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
1291 DOC, ATTRIBUTES, DEPENDENCIES, etc.
1292 """
1293
1294 def __init__(self, path, variables):
1295 self.name = variables['NAME']
1296 self.path = path
1297 self.variables = variables
1298
1299
1300def parse_autotest_control_file(path):
1301 """Parses autotest control file.
1302
1303 This only parses simple top-level string assignments.
1304
1305 Returns:
1306 AutotestControlInfo object
1307 """
1308 variables = {}
Kuang-che Wua5723492019-11-25 20:59:34 +08001309 with open(path) as f:
1310 code = ast.parse(f.read())
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001311 for stmt in code.body:
1312 # Skip if not simple "NAME = *" assignment.
1313 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
1314 isinstance(stmt.targets[0], ast.Name)):
1315 continue
1316
1317 # Only support string value.
1318 if isinstance(stmt.value, ast.Str):
1319 variables[stmt.targets[0].id] = stmt.value.s
1320
1321 return AutotestControlInfo(path, variables)
1322
1323
1324def enumerate_autotest_control_files(autotest_dir):
1325 """Enumerate autotest control files.
1326
1327 Args:
1328 autotest_dir: autotest folder
1329
1330 Returns:
1331 list of paths to control files
1332 """
1333 # Where to find control files. Relative to autotest_dir.
1334 subpaths = [
1335 'server/site_tests',
1336 'client/site_tests',
1337 'server/tests',
1338 'client/tests',
1339 ]
1340
1341 blacklist = ['site-packages', 'venv', 'results', 'logs', 'containers']
1342 result = []
1343 for subpath in subpaths:
1344 path = os.path.join(autotest_dir, subpath)
1345 for root, dirs, files in os.walk(path):
1346
1347 for black in blacklist:
1348 if black in dirs:
1349 dirs.remove(black)
1350
1351 for filename in files:
1352 if filename == 'control' or filename.startswith('control.'):
1353 result.append(os.path.join(root, filename))
1354
1355 return result
1356
1357
1358def get_autotest_test_info(autotest_dir, test_name):
1359 """Get metadata of given test.
1360
1361 Args:
1362 autotest_dir: autotest folder
1363 test_name: test name
1364
1365 Returns:
1366 AutotestControlInfo object. None if test not found.
1367 """
1368 for control_file in enumerate_autotest_control_files(autotest_dir):
1369 info = parse_autotest_control_file(control_file)
1370 if info.name == test_name:
1371 return info
1372 return None
1373
1374
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001375class ChromeOSSpecManager(codechange.SpecManager):
1376 """Repo manifest related operations.
1377
1378 This class enumerates chromeos manifest files, parses them,
1379 and sync to disk state according to them.
1380 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001381
1382 def __init__(self, config):
1383 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001384 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
1385 'manifests')
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001386 self.manifest_internal_dir = os.path.join(self.config['chromeos_mirror'],
1387 'manifest-internal.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001388 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001389 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001390 if not os.path.exists(self.historical_manifest_git_dir):
Kuang-che Wue121fae2018-11-09 16:18:39 +08001391 raise errors.InternalError('Manifest snapshots should be cloned into %s' %
1392 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001393
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001394 def lookup_snapshot_manifest_revisions(self, old, new):
1395 """Get manifest commits between snapshot versions.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001396
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001397 Returns:
1398 list of (timestamp, commit_id, snapshot_id):
1399 timestamp: integer unix timestamp
1400 commit_id: a string indicates commit hash
1401 snapshot_id: a string indicates snapshot id
1402 """
1403 assert is_cros_snapshot_version(old)
1404 assert is_cros_snapshot_version(new)
1405
1406 gs_path = (
1407 'gs://chromeos-image-archive/{board}-postsubmit/{version}-*/image.zip')
1408 # Try to guess the commit time of a snapshot manifest, it is usually a few
1409 # minutes different between snapshot manifest commit and image.zip
1410 # generate.
1411 try:
1412 old_timestamp = gsutil_stat_update_time(
1413 gs_path.format(board=self.config['board'], version=old)) - 86400
1414 except subprocess.CalledProcessError:
1415 old_timestamp = None
1416 try:
1417 new_timestamp = gsutil_stat_update_time(
1418 gs_path.format(board=self.config['board'], version=new)) + 86400
1419 # 1558657989 is snapshot_id 5982's commit time, this ensures every time
1420 # we can find snapshot 5982
1421 # snapshot_id <= 5982 has different commit message format, so we need
1422 # to identify its id in different ways, see below comment for more info.
1423 new_timestamp = max(new_timestamp, 1558657989 + 1)
1424 except subprocess.CalledProcessError:
1425 new_timestamp = None
1426 result = []
1427 _, _, old_snapshot_id = snapshot_version_split(old)
1428 _, _, new_snapshot_id = snapshot_version_split(new)
1429 repo = self.manifest_internal_dir
1430 path = 'snapshot.xml'
1431 branch = 'snapshot'
1432 commits = git_util.get_history(
1433 repo,
1434 path,
1435 branch,
1436 after=old_timestamp,
1437 before=new_timestamp,
1438 with_subject=True)
1439
1440 # Unfortunately, we can not identify snapshot_id <= 5982 from its commit
1441 # subject, as their subjects are all `Annealing manifest snapshot.`.
1442 # So instead we count the snapshot_id manually.
1443 count = 5982
1444 # There are two snapshot_id = 2633 in commit history, ignore the former
1445 # one.
1446 ignore_list = ['95c8526a7f0798d02f692010669dcbd5a152439a']
1447 # We examine the commits in reverse order as there are some testing
1448 # commits before snapshot_id=2, this method works fine after
1449 # snapshot 2, except snapshot 2633
1450 for commit in reversed(commits):
1451 msg = commit[2]
1452 if commit[1] in ignore_list:
1453 continue
1454
1455 match = re.match(r'^annealing manifest snapshot (\d+)', msg)
1456 if match:
1457 snapshot_id = match.group(1)
1458 elif 'Annealing manifest snapshot' in msg:
1459 snapshot_id = str(count)
1460 count -= 1
1461 else:
1462 continue
1463 if int(old_snapshot_id) <= int(snapshot_id) <= int(new_snapshot_id):
1464 result.append((commit[0], commit[1], snapshot_id))
1465 # We find commits in reversed order, now reverse it again to chronological
1466 # order.
1467 return list(reversed(result))
1468
1469 def lookup_build_timestamp(self, rev):
1470 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
1471 if is_cros_full_version(rev):
1472 return self.lookup_release_build_timestamp(rev)
Kuang-che Wua7ddf9b2019-11-25 18:59:57 +08001473 return self.lookup_snapshot_build_timestamp(rev)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001474
1475 def lookup_snapshot_build_timestamp(self, rev):
1476 assert is_cros_snapshot_version(rev)
1477 return int(self.lookup_snapshot_manifest_revisions(rev, rev)[0][0])
1478
1479 def lookup_release_build_timestamp(self, rev):
1480 assert is_cros_full_version(rev)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001481 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001482 path = os.path.join('buildspecs', milestone, short_version + '.xml')
1483 try:
1484 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1485 'refs/heads/master', path)
1486 except ValueError:
Kuang-che Wuce2f3be2019-10-28 19:44:54 +08001487 raise errors.InternalError(
1488 '%s does not have %s' % (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001489 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001490
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001491 def collect_float_spec(self, old, new):
1492 old_timestamp = self.lookup_build_timestamp(old)
1493 new_timestamp = self.lookup_build_timestamp(new)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001494 # snapshot time is different from commit time
1495 # usually it's a few minutes different
1496 # 30 minutes should be safe in most cases
1497 if is_cros_snapshot_version(old):
1498 old_timestamp = old_timestamp - 1800
1499 if is_cros_snapshot_version(new):
1500 new_timestamp = new_timestamp + 1800
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001501
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001502 path = os.path.join(self.manifest_dir, 'default.xml')
1503 if not os.path.islink(path) or os.readlink(path) != 'full.xml':
Kuang-che Wue121fae2018-11-09 16:18:39 +08001504 raise errors.InternalError(
1505 'default.xml not symlink to full.xml is not supported')
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001506
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001507 result = []
1508 path = 'full.xml'
1509 parser = repo_util.ManifestParser(self.manifest_dir)
1510 for timestamp, git_rev in parser.enumerate_manifest_commits(
1511 old_timestamp, new_timestamp, path):
1512 result.append(
1513 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
1514 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001515
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001516 def collect_fixed_spec(self, old, new):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001517 assert is_cros_full_version(old) or is_cros_snapshot_version(old)
1518 assert is_cros_full_version(new) or is_cros_snapshot_version(new)
1519
1520 # case 1: if both are snapshot, return a list of snapshot
1521 if is_cros_snapshot_version(old) and is_cros_snapshot_version(new):
1522 return self.collect_snapshot_specs(old, new)
1523
1524 # case 2: if both are release version
1525 # return a list of release version
1526 if is_cros_full_version(old) and is_cros_full_version(new):
1527 return self.collect_release_specs(old, new)
1528
1529 # case 3: return a list of release version and append a snapshot
1530 # before or at the end
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +08001531 result = self.collect_release_specs(
1532 version_to_full(self.config['board'], old),
1533 version_to_full(self.config['board'], new))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001534 if is_cros_snapshot_version(old):
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +08001535 result = self.collect_snapshot_specs(old, old) + result[1:]
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001536 elif is_cros_snapshot_version(new):
Zheng-Jie Changc47af3a2019-11-11 17:28:58 +08001537 result = result[:-1] + self.collect_snapshot_specs(new, new)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001538 return result
1539
1540 def collect_snapshot_specs(self, old, new):
1541 assert is_cros_snapshot_version(old)
1542 assert is_cros_snapshot_version(new)
1543
1544 def guess_snapshot_version(board, snapshot_id, old, new):
1545 if old.endswith('-' + snapshot_id):
1546 return old
1547 if new.endswith('-' + snapshot_id):
1548 return new
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001549 gs_path = ('gs://chromeos-image-archive/{board}-postsubmit/'
1550 'R*-{snapshot_id}-*'.format(
1551 board=board, snapshot_id=snapshot_id))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001552 for line in gsutil_ls(gs_path, ignore_errors=True):
1553 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)\S+', line)
1554 if m:
1555 return m.group(1)
1556 raise errors.ExternalError(
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001557 'guess_snapshot_version failed, board=%s snapshot_id=%s '
1558 'old=%s new=%s' % (board, snapshot_id, old, new))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001559
1560 result = []
1561 path = 'snapshot.xml'
1562 revisions = self.lookup_snapshot_manifest_revisions(old, new)
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001563 for timestamp, _git_rev, snapshot_id in revisions:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001564 snapshot_version = guess_snapshot_version(self.config['board'],
1565 snapshot_id, old, new)
1566 result.append(
1567 codechange.Spec(codechange.SPEC_FIXED, snapshot_version, timestamp,
1568 path))
1569 return result
1570
1571 def collect_release_specs(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001572 assert is_cros_full_version(old)
1573 assert is_cros_full_version(new)
1574 old_milestone, old_short_version = version_split(old)
1575 new_milestone, new_short_version = version_split(new)
1576
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001577 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001578 for milestone in git_util.list_dir_from_revision(
1579 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
1580 if not milestone.isdigit():
1581 continue
1582 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
1583 continue
1584
Kuang-che Wu74768d32018-09-07 12:03:24 +08001585 files = git_util.list_dir_from_revision(
1586 self.historical_manifest_git_dir, 'refs/heads/master',
1587 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001588
1589 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001590 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001591 short_version, ext = os.path.splitext(fn)
1592 if ext != '.xml':
1593 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001594 if (util.is_version_lesseq(old_short_version, short_version) and
1595 util.is_version_lesseq(short_version, new_short_version) and
1596 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001597 rev = make_cros_full_version(milestone, short_version)
1598 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1599 'refs/heads/master', path)
1600 result.append(
1601 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001602
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001603 def version_key_func(spec):
1604 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001605 return util.version_key_func(short_version)
1606
1607 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001608 assert result[0].name == old
1609 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001610 return result
1611
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001612 def get_manifest(self, rev):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001613 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
1614 if is_cros_full_version(rev):
1615 milestone, short_version = version_split(rev)
1616 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
1617 manifest = git_util.get_file_from_revision(
1618 self.historical_manifest_git_dir, 'refs/heads/master', path)
1619 else:
1620 revisions = self.lookup_snapshot_manifest_revisions(rev, rev)
1621 commit_id = revisions[0][1]
1622 manifest = git_util.get_file_from_revision(self.manifest_internal_dir,
1623 commit_id, 'snapshot.xml')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001624 manifest_name = 'manifest_%s.xml' % rev
1625 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1626 with open(manifest_path, 'w') as f:
1627 f.write(manifest)
1628
1629 return manifest_name
1630
1631 def parse_spec(self, spec):
1632 parser = repo_util.ManifestParser(self.manifest_dir)
1633 if spec.spec_type == codechange.SPEC_FIXED:
1634 manifest_name = self.get_manifest(spec.name)
1635 manifest_path = os.path.join(self.manifest_dir, manifest_name)
Kuang-che Wua5723492019-11-25 20:59:34 +08001636 with open(manifest_path) as f:
1637 content = f.read()
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001638 root = parser.parse_single_xml(content, allow_include=False)
1639 else:
1640 root = parser.parse_xml_recursive(spec.name, spec.path)
1641
1642 spec.entries = parser.process_parsed_result(root)
1643 if spec.spec_type == codechange.SPEC_FIXED:
Kuang-che Wufe1e88a2019-09-10 21:52:25 +08001644 if not spec.is_static():
1645 raise ValueError(
1646 'fixed spec %r has unexpected floating entries' % spec.name)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001647
1648 def sync_disk_state(self, rev):
1649 manifest_name = self.get_manifest(rev)
1650
1651 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
1652 # manifest. 'repo sync -m' is not enough
1653 repo_util.init(
1654 self.config['chromeos_root'],
1655 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
1656 manifest_name=manifest_name,
1657 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001658 reference=self.config['chromeos_mirror'],
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001659 )
1660
1661 # Note, don't sync with current_branch=True for chromeos. One of its
1662 # build steps (inside mark_as_stable) executes "git describe" which
1663 # needs git tag information.
1664 repo_util.sync(self.config['chromeos_root'])