blob: b1fd776a682915229f7b092f4b33ffade4837dde [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):
443 name = open(name_file).read().strip()
444
445 if name:
446 name = re.sub(r'-private$', '', name)
447 result.add(name)
448
449 return list(result)
450
451
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800452def recognize_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800453 """Recognize ChromeOS version.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800454
455 Args:
456 board: ChromeOS board name
457 version: ChromeOS version number in short or full format
458
459 Returns:
460 (milestone, version in short format)
461 """
462 if is_cros_short_version(version):
463 milestone = query_milestone_by_version(board, version)
464 short_version = version
465 else:
466 milestone, short_version = version_split(version)
467 return milestone, short_version
468
469
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800470def extract_major_version(version):
471 """Converts a version to its major version.
472
473 Args:
Kuang-che Wu9501f342019-11-15 17:15:21 +0800474 version: ChromeOS version number or snapshot version
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800475
476 Returns:
477 major version number in string format
478 """
479 version = version_to_short(version)
480 m = re.match(r'^(\d+)\.\d+\.\d+$', version)
481 return m.group(1)
482
483
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800484def version_to_short(version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800485 """Convert ChromeOS version number to short format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800486
487 Args:
488 version: ChromeOS version number in short or full format
489
490 Returns:
491 version number in short format
492 """
493 if is_cros_short_version(version):
494 return version
495 _, short_version = version_split(version)
496 return short_version
497
498
499def version_to_full(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800500 """Convert ChromeOS version number to full format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800501
502 Args:
503 board: ChromeOS board name
504 version: ChromeOS version number in short or full format
505
506 Returns:
507 version number in full format
508 """
509 if is_cros_full_version(version):
510 return version
511 milestone = query_milestone_by_version(board, version)
Kuang-che Wu0205f052019-05-23 12:48:37 +0800512 assert milestone, 'incorrect board=%s or version=%s ?' % (board, version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800513 return make_cros_full_version(milestone, version)
514
515
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800516def list_snapshots_from_image_archive(board, major_version):
Kuang-che Wu9501f342019-11-15 17:15:21 +0800517 """List ChromeOS snapshot image available from gs://chromeos-image-archive.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800518
519 Args:
520 board: ChromeOS board
521 major_version: ChromeOS major version
522
523 Returns:
524 list of (version, gs_path):
525 version: Chrome OS snapshot version
526 gs_path: gs path of test image
527 """
528
529 path = (
530 'gs://chromeos-image-archive/{board}-postsubmit/R*-{major_version}.0.0-*')
531 result = []
532 output = gsutil_ls(
533 '-d',
534 path.format(board=board, major_version=major_version),
535 ignore_errors=True)
536
537 for path in output:
538 if not path.endswith('/'):
539 continue
540 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)', path)
541 if m:
542 snapshot_version = m.group(1)
543 test_image = 'image.zip'
544 gs_path = path + test_image
545 result.append((snapshot_version, gs_path))
546 return result
547
548
Kuang-che Wu575dc442019-03-05 10:30:55 +0800549def list_prebuilt_from_image_archive(board):
550 """Lists ChromeOS prebuilt image available from gs://chromeos-image-archive.
551
552 gs://chromeos-image-archive contains only recent builds (in two years).
553 We prefer this function to list_prebuilt_from_chromeos_releases() because
554 - this is what "cros flash" supports directly.
555 - the paths have milestone information, so we don't need to do slow query
556 by ourselves.
557
558 Args:
559 board: ChromeOS board name
560
561 Returns:
562 list of (version, gs_path):
563 version: Chrome OS version in full format
564 gs_path: gs path of test image
565 """
566 result = []
567 for line in gsutil_ls(gs_archive_path.format(board=board)):
568 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+)', line)
569 if m:
570 full_version = m.group(1)
571 test_image = 'chromiumos_test_image.tar.xz'
572 assert line.endswith('/')
573 gs_path = line + test_image
574 result.append((full_version, gs_path))
575 return result
576
577
578def list_prebuilt_from_chromeos_releases(board):
579 """Lists ChromeOS versions available from gs://chromeos-releases.
580
581 gs://chromeos-releases contains more builds. However, 'cros flash' doesn't
582 support it.
583
584 Args:
585 board: ChromeOS board name
586
587 Returns:
588 list of (version, gs_path):
589 version: Chrome OS version in short format
590 gs_path: gs path of test image (with wildcard)
591 """
592 result = []
593 for line in gsutil_ls(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800594 gs_release_path.format(
595 channel='*', boardpath=gs_release_boardpath(board), short_version=''),
Kuang-che Wu575dc442019-03-05 10:30:55 +0800596 ignore_errors=True):
597 m = re.match(r'gs:\S+/(\d+\.\d+\.\d+)/$', line)
598 if m:
599 short_version = m.group(1)
600 test_image = 'ChromeOS-test-R*-{short_version}-{board}.tar.xz'.format(
601 short_version=short_version, board=board)
602 gs_path = line + test_image
603 result.append((short_version, gs_path))
604 return result
605
606
607def list_chromeos_prebuilt_versions(board,
608 old,
609 new,
610 only_good_build=True,
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800611 include_older_build=True,
612 use_snapshot=False):
Kuang-che Wu575dc442019-03-05 10:30:55 +0800613 """Lists ChromeOS version numbers with prebuilt between given range
614
615 Args:
616 board: ChromeOS board name
617 old: start version (inclusive)
618 new: end version (inclusive)
619 only_good_build: only if test image is available
620 include_older_build: include prebuilt in gs://chromeos-releases
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800621 use_snapshot: return snapshot versions if found
Kuang-che Wu575dc442019-03-05 10:30:55 +0800622
623 Returns:
624 list of sorted version numbers (in full format) between [old, new] range
625 (inclusive).
626 """
627 old = version_to_short(old)
628 new = version_to_short(new)
629
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800630 rev_map = {
631 } # dict: short version -> list of (short/full or snapshot version, gs path)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800632 for full_version, gs_path in list_prebuilt_from_image_archive(board):
633 short_version = version_to_short(full_version)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800634 rev_map[short_version] = [(full_version, gs_path)]
Kuang-che Wu575dc442019-03-05 10:30:55 +0800635
636 if include_older_build and old not in rev_map:
637 for short_version, gs_path in list_prebuilt_from_chromeos_releases(board):
638 if short_version not in rev_map:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800639 rev_map[short_version] = [(short_version, gs_path)]
640
641 if use_snapshot:
642 for major_version in range(
643 int(extract_major_version(old)),
644 int(extract_major_version(new)) + 1):
645 short_version = '%s.0.0' % major_version
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800646 # If current version is smaller than cutover, ignore it as it might not
647 # contain enough information for continuing android and chrome bisection.
648 if not util.is_version_lesseq(snapshot_cutover_version, short_version):
649 continue
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800650 if not util.is_direct_relative_version(short_version, old):
651 continue
652 if not util.is_direct_relative_version(short_version, new):
653 continue
654 snapshots = list_snapshots_from_image_archive(board, str(major_version))
655 if snapshots:
656 # if snapshots found, we can append them after the release version,
657 # so the prebuilt image list of this version will be
658 # release_image, snapshot1, snapshot2,...
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800659 if short_version not in rev_map:
660 rev_map[short_version] = []
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800661 rev_map[short_version] += snapshots
Kuang-che Wu575dc442019-03-05 10:30:55 +0800662
663 result = []
664 for rev in sorted(rev_map, key=util.version_key_func):
665 if not util.is_direct_relative_version(new, rev):
666 continue
667 if not util.is_version_lesseq(old, rev):
668 continue
669 if not util.is_version_lesseq(rev, new):
670 continue
671
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800672 for version, gs_path in rev_map[rev]:
Kuang-che Wu575dc442019-03-05 10:30:55 +0800673
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800674 # version_to_full() and gsutil_ls() may take long time if versions are a
675 # lot. This is acceptable because we usually bisect only short range.
Kuang-che Wu575dc442019-03-05 10:30:55 +0800676
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800677 if only_good_build:
678 gs_result = gsutil_ls(gs_path, ignore_errors=True)
679 if not gs_result:
680 logger.warning('%s is not a good build, ignore', version)
681 continue
682 assert len(gs_result) == 1
683 m = re.search(r'(R\d+-\d+\.\d+\.\d+)', gs_result[0])
684 if not m:
685 logger.warning('format of image path is unexpected: %s', gs_result[0])
686 continue
687 if not is_cros_snapshot_version(version):
688 version = m.group(1)
689 elif is_cros_short_version(version):
690 version = version_to_full(board, version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800691
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800692 result.append(version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800693
694 return result
695
696
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800697def prepare_snapshot_image(chromeos_root, board, snapshot_version):
698 """Prepare chromeos snapshot image.
699
700 Args:
701 chromeos_root: chromeos tree root
702 board: ChromeOS board name
703 snapshot_version: ChromeOS snapshot version number
704
705 Returns:
706 local file path of test image relative to chromeos_root
707 """
708 assert is_cros_snapshot_version(snapshot_version)
709 milestone, short_version, snapshot_id = snapshot_version_split(
710 snapshot_version)
711 full_version = make_cros_full_version(milestone, short_version)
712 tmp_dir = os.path.join(
713 chromeos_root, 'tmp',
714 'ChromeOS-test-%s-%s-%s' % (full_version, board, snapshot_id))
715 if not os.path.exists(tmp_dir):
716 os.makedirs(tmp_dir)
717
718 gs_path = ('gs://chromeos-image-archive/{board}-postsubmit/' +
719 '{snapshot_version}-*/image.zip')
720 gs_path = gs_path.format(board=board, snapshot_version=snapshot_version)
721
722 files = gsutil_ls(gs_path, ignore_errors=True)
723 if len(files) == 1:
724 gs_path = files[0]
725 gsutil('cp', gs_path, tmp_dir)
726 image_path = os.path.relpath(
727 os.path.join(tmp_dir, test_image_filename), chromeos_root)
728 util.check_call(
729 'unzip', '-j', 'image.zip', test_image_filename, cwd=tmp_dir)
730 os.remove(os.path.join(tmp_dir, 'image.zip'))
731
732 assert image_path
733 return image_path
734
735
Kuang-che Wu28980b22019-07-31 19:51:45 +0800736def prepare_prebuilt_image(chromeos_root, board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800737 """Prepare chromeos prebuilt image.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800738
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800739 It searches for xbuddy image which "cros flash" can use, or fetch image to
740 local disk.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800741
742 Args:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800743 chromeos_root: chromeos tree root
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800744 board: ChromeOS board name
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800745 version: ChromeOS version number in short or full format
746
747 Returns:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800748 xbuddy path or file path (relative to chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800749 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800750 assert is_cros_version(version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800751 full_version = version_to_full(board, version)
752 short_version = version_to_short(full_version)
753
754 image_path = None
755 gs_path = gs_archive_path.format(board=board) + '/' + full_version
756 if gsutil_ls('-d', gs_path, ignore_errors=True):
757 image_path = 'xbuddy://remote/{board}/{full_version}/test'.format(
758 board=board, full_version=full_version)
759 else:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800760 tmp_dir = os.path.join(chromeos_root, 'tmp',
761 'ChromeOS-test-%s-%s' % (full_version, board))
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800762 if not os.path.exists(tmp_dir):
763 os.makedirs(tmp_dir)
764 # gs://chromeos-releases may have more old images than
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800765 # gs://chromeos-image-archive, but 'cros flash' doesn't support it. We have
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800766 # to fetch the image by ourselves
767 for channel in ['canary', 'dev', 'beta', 'stable']:
768 fn = 'ChromeOS-test-{full_version}-{board}.tar.xz'.format(
769 full_version=full_version, board=board)
770 gs_path = gs_release_path.format(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800771 channel=channel,
772 boardpath=gs_release_boardpath(board),
773 short_version=short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800774 gs_path += '/' + fn
775 if gsutil_ls(gs_path, ignore_errors=True):
776 # TODO(kcwu): delete tmp
777 gsutil('cp', gs_path, tmp_dir)
778 util.check_call('tar', 'Jxvf', fn, cwd=tmp_dir)
Kuang-che Wu28980b22019-07-31 19:51:45 +0800779 image_path = os.path.relpath(
780 os.path.join(tmp_dir, test_image_filename), chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800781 break
782
783 assert image_path
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800784 return image_path
785
786
787def cros_flash(chromeos_root,
788 host,
789 board,
790 image_path,
791 version=None,
792 clobber_stateful=False,
Kuang-che Wu155fb6e2018-11-29 16:00:41 +0800793 disable_rootfs_verification=True):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800794 """Flash a DUT with given ChromeOS image.
795
796 This is implemented by 'cros flash' command line.
797
798 Args:
799 chromeos_root: use 'cros flash' of which chromeos tree
800 host: DUT address
801 board: ChromeOS board name
Kuang-che Wu28980b22019-07-31 19:51:45 +0800802 image_path: chromeos image xbuddy path or file path. For relative
803 path, it should be relative to chromeos_root.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800804 version: ChromeOS version in short or full format
805 clobber_stateful: Clobber stateful partition when performing update
806 disable_rootfs_verification: Disable rootfs verification after update
807 is completed
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800808
809 Raises:
810 errors.ExternalError: cros flash failed
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800811 """
812 logger.info('cros_flash %s %s %s %s', host, board, version, image_path)
813
814 # Reboot is necessary because sometimes previous 'cros flash' failed and
815 # entered a bad state.
816 reboot(host)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800817
Kuang-che Wu28980b22019-07-31 19:51:45 +0800818 # Handle relative path.
819 if '://' not in image_path and not os.path.isabs(image_path):
820 assert os.path.exists(os.path.join(chromeos_root, image_path))
821 image_path = os.path.join(chromeos_root_inside_chroot, image_path)
822
Kuang-che Wuf3d03ca2019-03-11 17:31:40 +0800823 args = [
824 '--debug', '--no-ping', '--send-payload-in-parallel', host, image_path
825 ]
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800826 if clobber_stateful:
827 args.append('--clobber-stateful')
828 if disable_rootfs_verification:
829 args.append('--disable-rootfs-verification')
830
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800831 try:
832 cros_sdk(chromeos_root, 'cros', 'flash', *args)
833 except subprocess.CalledProcessError:
834 raise errors.ExternalError('cros flash failed')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800835
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800836 if version:
837 # In the past, cros flash may fail with returncode=0
838 # So let's have an extra check.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800839 if is_cros_snapshot_version(version):
840 builder_path = query_dut_lsb_release(host).get(
841 'CHROMEOS_RELEASE_BUILDER_PATH', '')
842 expect_prefix = '%s-postsubmit/%s-' % (board, version)
843 if not builder_path.startswith(expect_prefix):
844 raise errors.ExternalError(
845 'although cros flash succeeded, the OS builder path is '
846 'unexpected: actual=%s expect=%s' % (builder_path, expect_prefix))
847 else:
848 expect_version = version_to_short(version)
849 dut_version = query_dut_short_version(host)
850 if dut_version != expect_version:
851 raise errors.ExternalError(
852 'although cros flash succeeded, the OS version is unexpected: '
853 'actual=%s expect=%s' % (dut_version, expect_version))
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800854
Kuang-che Wu4a81ea72019-10-05 15:35:17 +0800855 # "cros flash" may terminate successfully but the DUT starts self-repairing
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800856 # (b/130786578), so it's necessary to do sanity check.
857 if not is_good_dut(host):
858 raise errors.ExternalError(
859 'although cros flash succeeded, the DUT is in bad state')
860
861
862def cros_flash_with_retry(chromeos_root,
863 host,
864 board,
865 image_path,
866 version=None,
867 clobber_stateful=False,
868 disable_rootfs_verification=True,
869 repair_callback=None):
870 # 'cros flash' is not 100% reliable, retry if necessary.
871 for attempt in range(2):
872 if attempt > 0:
873 logger.info('will retry 60 seconds later')
874 time.sleep(60)
875
876 try:
877 cros_flash(
878 chromeos_root,
879 host,
880 board,
881 image_path,
882 version=version,
883 clobber_stateful=clobber_stateful,
884 disable_rootfs_verification=disable_rootfs_verification)
885 return True
886 except errors.ExternalError:
887 logger.exception('cros flash failed')
888 if repair_callback and not repair_callback(host):
889 logger.warning('not repaired, assume it is harmless')
890 continue
891 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800892
893
894def version_info(board, version):
895 """Query subcomponents version info of given version of ChromeOS
896
897 Args:
898 board: ChromeOS board name
899 version: ChromeOS version number in short or full format
900
901 Returns:
902 dict of component and version info, including (if available):
903 cros_short_version: ChromeOS version
904 cros_full_version: ChromeOS version
905 milestone: milestone of ChromeOS
906 cr_version: Chrome version
Kuang-che Wu708310b2018-03-28 17:24:34 +0800907 android_build_id: Android build id
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800908 android_branch: Android branch, in format like 'git_nyc-mr1-arc'
909 """
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800910 if is_cros_snapshot_version(version):
Zheng-Jie Chang2b6d1472019-11-13 12:40:17 +0800911 api = buildbucket_util.BuildbucketApi()
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800912 milestone, short_version, _ = snapshot_version_split(version)
913 buildbucket_id = query_snapshot_buildbucket_id(board, version)
Zheng-Jie Chang2b6d1472019-11-13 12:40:17 +0800914 data = api.get(int(buildbucket_id)).output.properties
915 target_versions = data['target_versions']
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800916 return {
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800917 VERSION_KEY_MILESTONE: milestone,
918 VERSION_KEY_CROS_FULL_VERSION: version,
919 VERSION_KEY_CROS_SHORT_VERSION: short_version,
920 VERSION_KEY_CR_VERSION: target_versions['chromeVersion'],
921 VERSION_KEY_ANDROID_BUILD_ID: target_versions['androidVersion'],
922 VERSION_KEY_ANDROID_BRANCH: target_versions['androidBranchVersion'],
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800923 }
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800924 info = {}
925 full_version = version_to_full(board, version)
926
927 # Some boards may have only partial-metadata.json but no metadata.json.
928 # e.g. caroline R60-9462.0.0
929 # Let's try both.
930 metadata = None
931 for metadata_filename in ['metadata.json', 'partial-metadata.json']:
Kuang-che Wu0768b972019-10-05 15:18:59 +0800932 path = gs_archive_path.format(
933 board=board) + '/%s/%s' % (full_version, metadata_filename)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800934 metadata = gsutil('cat', path, ignore_errors=True)
935 if metadata:
936 o = json.loads(metadata)
937 v = o['version']
938 board_metadata = o['board-metadata'][board]
939 info.update({
940 VERSION_KEY_CROS_SHORT_VERSION: v['platform'],
941 VERSION_KEY_CROS_FULL_VERSION: v['full'],
942 VERSION_KEY_MILESTONE: v['milestone'],
943 VERSION_KEY_CR_VERSION: v['chrome'],
944 })
945
946 if 'android' in v:
Kuang-che Wu708310b2018-03-28 17:24:34 +0800947 info[VERSION_KEY_ANDROID_BUILD_ID] = v['android']
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800948 if 'android-branch' in v: # this appears since R58-9317.0.0
949 info[VERSION_KEY_ANDROID_BRANCH] = v['android-branch']
950 elif 'android-container-branch' in board_metadata:
951 info[VERSION_KEY_ANDROID_BRANCH] = v['android-container-branch']
952 break
953 else:
954 logger.error('Failed to read metadata from gs://chromeos-image-archive')
955 logger.error(
956 'Note, so far no quick way to look up version info for too old builds')
957
958 return info
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800959
960
961def query_chrome_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800962 """Queries chrome version of chromeos build.
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800963
964 Args:
965 board: ChromeOS board name
966 version: ChromeOS version number in short or full format
967
968 Returns:
969 Chrome version number
970 """
971 info = version_info(board, version)
972 return info['cr_version']
Kuang-che Wu708310b2018-03-28 17:24:34 +0800973
974
975def query_android_build_id(board, rev):
976 info = version_info(board, rev)
977 rev = info['android_build_id']
978 return rev
979
980
981def query_android_branch(board, rev):
982 info = version_info(board, rev)
983 rev = info['android_branch']
984 return rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800985
986
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800987def guess_chrome_version(board, rev):
988 """Guess chrome version number.
989
990 Args:
991 board: chromeos board name
992 rev: chrome or chromeos version
993
994 Returns:
995 chrome version number
996 """
997 if is_cros_version(rev):
998 assert board, 'need to specify BOARD for cros version'
999 rev = query_chrome_version(board, rev)
1000 assert cr_util.is_chrome_version(rev)
1001
1002 return rev
1003
1004
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001005def is_inside_chroot():
1006 """Returns True if we are inside chroot."""
1007 return os.path.exists('/etc/cros_chroot_version')
1008
1009
1010def cros_sdk(chromeos_root, *args, **kwargs):
1011 """Run commands inside chromeos chroot.
1012
1013 Args:
1014 chromeos_root: chromeos tree root
1015 *args: command to run
1016 **kwargs:
Kuang-che Wud4603d72018-11-29 17:51:21 +08001017 chrome_root: pass to cros_sdk; mount this path into the SDK chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001018 env: (dict) environment variables for the command
Kuang-che Wubcafc552019-08-15 15:27:02 +08001019 log_stdout: Whether write the stdout output of the child process to log.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001020 stdin: standard input file handle for the command
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001021 stderr_callback: Callback function for stderr. Called once per line.
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001022 goma_dir: Goma installed directory to mount into the chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001023 """
1024 envs = []
1025 for k, v in kwargs.get('env', {}).items():
1026 assert re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', k)
1027 envs.append('%s=%s' % (k, v))
1028
1029 # Use --no-ns-pid to prevent cros_sdk change our pgid, otherwise subsequent
1030 # commands would be considered as background process.
Kuang-che Wu399d4662019-06-06 15:23:37 +08001031 prefix = ['chromite/bin/cros_sdk', '--no-ns-pid']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001032
1033 if kwargs.get('chrome_root'):
Kuang-che Wu399d4662019-06-06 15:23:37 +08001034 prefix += ['--chrome_root', kwargs['chrome_root']]
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001035 if kwargs.get('goma_dir'):
1036 prefix += ['--goma_dir', kwargs['goma_dir']]
Kuang-che Wud4603d72018-11-29 17:51:21 +08001037
Kuang-che Wu399d4662019-06-06 15:23:37 +08001038 prefix += envs + ['--']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001039
Kuang-che Wu399d4662019-06-06 15:23:37 +08001040 # In addition to the output of command we are interested, cros_sdk may
1041 # generate its own messages. For example, chroot creation messages if we run
1042 # cros_sdk the first time.
1043 # This is the hack to run dummy command once, so we can get clean output for
1044 # the command we are interested.
1045 cmd = prefix + ['true']
1046 util.check_call(*cmd, cwd=chromeos_root)
1047
1048 cmd = prefix + list(args)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001049 return util.check_output(
1050 *cmd,
1051 cwd=chromeos_root,
Kuang-che Wubcafc552019-08-15 15:27:02 +08001052 log_stdout=kwargs.get('log_stdout', True),
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001053 stdin=kwargs.get('stdin'),
1054 stderr_callback=kwargs.get('stderr_callback'))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001055
1056
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001057def create_chroot(chromeos_root):
1058 """Creates ChromeOS chroot.
1059
1060 Args:
1061 chromeos_root: chromeos tree root
1062 """
1063 if os.path.exists(os.path.join(chromeos_root, 'chroot')):
1064 return
1065 if os.path.exists(os.path.join(chromeos_root, 'chroot.img')):
1066 return
1067
1068 util.check_output('chromite/bin/cros_sdk', '--create', cwd=chromeos_root)
1069
1070
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001071def copy_into_chroot(chromeos_root, src, dst):
1072 """Copies file into chromeos chroot.
1073
1074 Args:
1075 chromeos_root: chromeos tree root
1076 src: path outside chroot
1077 dst: path inside chroot
1078 """
1079 # chroot may be an image, so we cannot copy to corresponding path
1080 # directly.
1081 cros_sdk(chromeos_root, 'sh', '-c', 'cat > %s' % dst, stdin=open(src))
1082
1083
1084def exists_in_chroot(chromeos_root, path):
1085 """Determine whether a path exists in the chroot.
1086
1087 Args:
1088 chromeos_root: chromeos tree root
1089 path: path inside chroot, relative to src/scripts
1090
1091 Returns:
1092 True if a path exists
1093 """
1094 try:
Kuang-che Wuacb6efd2018-04-25 18:52:58 +08001095 cros_sdk(chromeos_root, 'test', '-e', path)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001096 except subprocess.CalledProcessError:
1097 return False
1098 return True
1099
1100
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001101def check_if_need_recreate_chroot(stdout, stderr):
1102 """Analyze build log and determine if chroot should be recreated.
1103
1104 Args:
1105 stdout: stdout output of build
1106 stderr: stderr output of build
1107
1108 Returns:
1109 the reason if chroot needs recreated; None otherwise
1110 """
Kuang-che Wu74768d32018-09-07 12:03:24 +08001111 if re.search(
1112 r"The current version of portage supports EAPI '\d+'. "
Kuang-che Wuae6824b2019-08-27 22:20:01 +08001113 'You must upgrade', stderr):
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001114 return 'EAPI version mismatch'
1115
Kuang-che Wu5ac81322018-11-26 14:04:06 +08001116 if 'Chroot is too new. Consider running:' in stderr:
1117 return 'chroot version is too new'
1118
1119 # old message before Oct 2018
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001120 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
1121 return 'chroot version is too new'
1122
Kuang-che Wu6fe987f2018-08-28 15:24:20 +08001123 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
1124 if "undefined reference to 'std::__1::basic_string" in stdout:
1125 return 'might be due to compiler change'
1126
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001127 return None
1128
1129
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001130def build_packages(chromeos_root,
1131 board,
1132 chrome_root=None,
1133 goma_dir=None,
1134 afdo_use=False):
Kuang-che Wu28980b22019-07-31 19:51:45 +08001135 """Build ChromeOS packages.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001136
1137 Args:
1138 chromeos_root: chromeos tree root
1139 board: ChromeOS board name
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001140 chrome_root: Chrome tree root. If specified, build chrome using the
1141 provided tree
1142 goma_dir: Goma installed directory to mount into the chroot. If specified,
1143 build chrome with goma.
1144 afdo_use: build chrome with AFDO optimization
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001145 """
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001146 common_env = {
1147 'USE': '-cros-debug chrome_internal',
1148 'FEATURES': 'separatedebug',
1149 }
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001150 stderr_lines = []
1151 try:
Kuang-che Wufb553102018-10-02 18:14:29 +08001152 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001153 env = common_env.copy()
1154 env['FEATURES'] += ' -separatedebug splitdebug'
Kuang-che Wufb553102018-10-02 18:14:29 +08001155 cros_sdk(
1156 chromeos_root,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001157 './update_chroot',
1158 '--toolchain_boards',
Kuang-che Wufb553102018-10-02 18:14:29 +08001159 board,
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001160 env=env,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001161 stderr_callback=stderr_lines.append)
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001162
1163 env = common_env.copy()
1164 cmd = [
Kuang-che Wu28980b22019-07-31 19:51:45 +08001165 './build_packages',
1166 '--board',
1167 board,
1168 '--withdev',
1169 '--noworkon',
1170 '--skip_chroot_upgrade',
1171 '--accept_licenses=@CHROMEOS',
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001172 ]
1173 if goma_dir:
1174 # Tell build_packages to start and stop goma
1175 cmd.append('--run_goma')
1176 env['USE_GOMA'] = 'true'
1177 if afdo_use:
1178 env['USE'] += ' afdo_use'
1179 cros_sdk(
1180 chromeos_root,
1181 *cmd,
1182 env=env,
1183 chrome_root=chrome_root,
1184 stderr_callback=stderr_lines.append,
1185 goma_dir=goma_dir)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001186 except subprocess.CalledProcessError as e:
1187 # Detect failures due to incompatibility between chroot and source tree. If
1188 # so, notify the caller to recreate chroot and retry.
1189 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1190 if reason:
1191 raise NeedRecreateChrootException(reason)
1192
1193 # For other failures, don't know how to handle. Just bail out.
1194 raise
1195
Kuang-che Wu28980b22019-07-31 19:51:45 +08001196
1197def build_image(chromeos_root, board):
1198 """Build ChromeOS image.
1199
1200 Args:
1201 chromeos_root: chromeos tree root
1202 board: ChromeOS board name
1203
1204 Returns:
1205 image folder; relative to chromeos_root
1206 """
1207 stderr_lines = []
1208 try:
1209 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
1210 cros_sdk(
1211 chromeos_root,
1212 './build_image',
1213 '--board',
1214 board,
1215 '--noenable_rootfs_verification',
1216 'test',
1217 env={
1218 'USE': '-cros-debug chrome_internal',
1219 'FEATURES': 'separatedebug',
1220 },
1221 stderr_callback=stderr_lines.append)
1222 except subprocess.CalledProcessError as e:
1223 # Detect failures due to incompatibility between chroot and source tree. If
1224 # so, notify the caller to recreate chroot and retry.
1225 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1226 if reason:
1227 raise NeedRecreateChrootException(reason)
1228
1229 # For other failures, don't know how to handle. Just bail out.
1230 raise
1231
1232 image_symlink = os.path.join(chromeos_root, cached_images_dir, board,
1233 'latest')
1234 assert os.path.exists(image_symlink)
1235 image_name = os.readlink(image_symlink)
1236 image_folder = os.path.join(cached_images_dir, board, image_name)
1237 assert os.path.exists(
1238 os.path.join(chromeos_root, image_folder, test_image_filename))
1239 return image_folder
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001240
1241
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001242class AutotestControlInfo(object):
1243 """Parsed content of autotest control file.
1244
1245 Attributes:
1246 name: test name
1247 path: control file path
1248 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
1249 DOC, ATTRIBUTES, DEPENDENCIES, etc.
1250 """
1251
1252 def __init__(self, path, variables):
1253 self.name = variables['NAME']
1254 self.path = path
1255 self.variables = variables
1256
1257
1258def parse_autotest_control_file(path):
1259 """Parses autotest control file.
1260
1261 This only parses simple top-level string assignments.
1262
1263 Returns:
1264 AutotestControlInfo object
1265 """
1266 variables = {}
1267 code = ast.parse(open(path).read())
1268 for stmt in code.body:
1269 # Skip if not simple "NAME = *" assignment.
1270 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
1271 isinstance(stmt.targets[0], ast.Name)):
1272 continue
1273
1274 # Only support string value.
1275 if isinstance(stmt.value, ast.Str):
1276 variables[stmt.targets[0].id] = stmt.value.s
1277
1278 return AutotestControlInfo(path, variables)
1279
1280
1281def enumerate_autotest_control_files(autotest_dir):
1282 """Enumerate autotest control files.
1283
1284 Args:
1285 autotest_dir: autotest folder
1286
1287 Returns:
1288 list of paths to control files
1289 """
1290 # Where to find control files. Relative to autotest_dir.
1291 subpaths = [
1292 'server/site_tests',
1293 'client/site_tests',
1294 'server/tests',
1295 'client/tests',
1296 ]
1297
1298 blacklist = ['site-packages', 'venv', 'results', 'logs', 'containers']
1299 result = []
1300 for subpath in subpaths:
1301 path = os.path.join(autotest_dir, subpath)
1302 for root, dirs, files in os.walk(path):
1303
1304 for black in blacklist:
1305 if black in dirs:
1306 dirs.remove(black)
1307
1308 for filename in files:
1309 if filename == 'control' or filename.startswith('control.'):
1310 result.append(os.path.join(root, filename))
1311
1312 return result
1313
1314
1315def get_autotest_test_info(autotest_dir, test_name):
1316 """Get metadata of given test.
1317
1318 Args:
1319 autotest_dir: autotest folder
1320 test_name: test name
1321
1322 Returns:
1323 AutotestControlInfo object. None if test not found.
1324 """
1325 for control_file in enumerate_autotest_control_files(autotest_dir):
1326 info = parse_autotest_control_file(control_file)
1327 if info.name == test_name:
1328 return info
1329 return None
1330
1331
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001332class ChromeOSSpecManager(codechange.SpecManager):
1333 """Repo manifest related operations.
1334
1335 This class enumerates chromeos manifest files, parses them,
1336 and sync to disk state according to them.
1337 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001338
1339 def __init__(self, config):
1340 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001341 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
1342 'manifests')
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001343 self.manifest_internal_dir = os.path.join(self.config['chromeos_mirror'],
1344 'manifest-internal.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001345 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001346 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001347 if not os.path.exists(self.historical_manifest_git_dir):
Kuang-che Wue121fae2018-11-09 16:18:39 +08001348 raise errors.InternalError('Manifest snapshots should be cloned into %s' %
1349 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001350
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001351 def lookup_snapshot_manifest_revisions(self, old, new):
1352 """Get manifest commits between snapshot versions.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001353
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001354 Returns:
1355 list of (timestamp, commit_id, snapshot_id):
1356 timestamp: integer unix timestamp
1357 commit_id: a string indicates commit hash
1358 snapshot_id: a string indicates snapshot id
1359 """
1360 assert is_cros_snapshot_version(old)
1361 assert is_cros_snapshot_version(new)
1362
1363 gs_path = (
1364 'gs://chromeos-image-archive/{board}-postsubmit/{version}-*/image.zip')
1365 # Try to guess the commit time of a snapshot manifest, it is usually a few
1366 # minutes different between snapshot manifest commit and image.zip
1367 # generate.
1368 try:
1369 old_timestamp = gsutil_stat_update_time(
1370 gs_path.format(board=self.config['board'], version=old)) - 86400
1371 except subprocess.CalledProcessError:
1372 old_timestamp = None
1373 try:
1374 new_timestamp = gsutil_stat_update_time(
1375 gs_path.format(board=self.config['board'], version=new)) + 86400
1376 # 1558657989 is snapshot_id 5982's commit time, this ensures every time
1377 # we can find snapshot 5982
1378 # snapshot_id <= 5982 has different commit message format, so we need
1379 # to identify its id in different ways, see below comment for more info.
1380 new_timestamp = max(new_timestamp, 1558657989 + 1)
1381 except subprocess.CalledProcessError:
1382 new_timestamp = None
1383 result = []
1384 _, _, old_snapshot_id = snapshot_version_split(old)
1385 _, _, new_snapshot_id = snapshot_version_split(new)
1386 repo = self.manifest_internal_dir
1387 path = 'snapshot.xml'
1388 branch = 'snapshot'
1389 commits = git_util.get_history(
1390 repo,
1391 path,
1392 branch,
1393 after=old_timestamp,
1394 before=new_timestamp,
1395 with_subject=True)
1396
1397 # Unfortunately, we can not identify snapshot_id <= 5982 from its commit
1398 # subject, as their subjects are all `Annealing manifest snapshot.`.
1399 # So instead we count the snapshot_id manually.
1400 count = 5982
1401 # There are two snapshot_id = 2633 in commit history, ignore the former
1402 # one.
1403 ignore_list = ['95c8526a7f0798d02f692010669dcbd5a152439a']
1404 # We examine the commits in reverse order as there are some testing
1405 # commits before snapshot_id=2, this method works fine after
1406 # snapshot 2, except snapshot 2633
1407 for commit in reversed(commits):
1408 msg = commit[2]
1409 if commit[1] in ignore_list:
1410 continue
1411
1412 match = re.match(r'^annealing manifest snapshot (\d+)', msg)
1413 if match:
1414 snapshot_id = match.group(1)
1415 elif 'Annealing manifest snapshot' in msg:
1416 snapshot_id = str(count)
1417 count -= 1
1418 else:
1419 continue
1420 if int(old_snapshot_id) <= int(snapshot_id) <= int(new_snapshot_id):
1421 result.append((commit[0], commit[1], snapshot_id))
1422 # We find commits in reversed order, now reverse it again to chronological
1423 # order.
1424 return list(reversed(result))
1425
1426 def lookup_build_timestamp(self, rev):
1427 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
1428 if is_cros_full_version(rev):
1429 return self.lookup_release_build_timestamp(rev)
1430 else:
1431 return self.lookup_snapshot_build_timestamp(rev)
1432
1433 def lookup_snapshot_build_timestamp(self, rev):
1434 assert is_cros_snapshot_version(rev)
1435 return int(self.lookup_snapshot_manifest_revisions(rev, rev)[0][0])
1436
1437 def lookup_release_build_timestamp(self, rev):
1438 assert is_cros_full_version(rev)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001439 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001440 path = os.path.join('buildspecs', milestone, short_version + '.xml')
1441 try:
1442 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1443 'refs/heads/master', path)
1444 except ValueError:
Kuang-che Wuce2f3be2019-10-28 19:44:54 +08001445 raise errors.InternalError(
1446 '%s does not have %s' % (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001447 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001448
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001449 def collect_float_spec(self, old, new):
1450 old_timestamp = self.lookup_build_timestamp(old)
1451 new_timestamp = self.lookup_build_timestamp(new)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001452 # snapshot time is different from commit time
1453 # usually it's a few minutes different
1454 # 30 minutes should be safe in most cases
1455 if is_cros_snapshot_version(old):
1456 old_timestamp = old_timestamp - 1800
1457 if is_cros_snapshot_version(new):
1458 new_timestamp = new_timestamp + 1800
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001459
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001460 path = os.path.join(self.manifest_dir, 'default.xml')
1461 if not os.path.islink(path) or os.readlink(path) != 'full.xml':
Kuang-che Wue121fae2018-11-09 16:18:39 +08001462 raise errors.InternalError(
1463 'default.xml not symlink to full.xml is not supported')
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001464
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001465 result = []
1466 path = 'full.xml'
1467 parser = repo_util.ManifestParser(self.manifest_dir)
1468 for timestamp, git_rev in parser.enumerate_manifest_commits(
1469 old_timestamp, new_timestamp, path):
1470 result.append(
1471 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
1472 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001473
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001474 def collect_fixed_spec(self, old, new):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001475 assert is_cros_full_version(old) or is_cros_snapshot_version(old)
1476 assert is_cros_full_version(new) or is_cros_snapshot_version(new)
1477
1478 # case 1: if both are snapshot, return a list of snapshot
1479 if is_cros_snapshot_version(old) and is_cros_snapshot_version(new):
1480 return self.collect_snapshot_specs(old, new)
1481
1482 # case 2: if both are release version
1483 # return a list of release version
1484 if is_cros_full_version(old) and is_cros_full_version(new):
1485 return self.collect_release_specs(old, new)
1486
1487 # case 3: return a list of release version and append a snapshot
1488 # before or at the end
1489 result = self.collect_release_specs(old, new)
1490 if is_cros_snapshot_version(old):
1491 result = self.collect_release_specs(old, old) + result[1:]
1492 elif is_cros_snapshot_version(new):
1493 result = result[:-1] + self.collect_release_specs(new, new)
1494 return result
1495
1496 def collect_snapshot_specs(self, old, new):
1497 assert is_cros_snapshot_version(old)
1498 assert is_cros_snapshot_version(new)
1499
1500 def guess_snapshot_version(board, snapshot_id, old, new):
1501 if old.endswith('-' + snapshot_id):
1502 return old
1503 if new.endswith('-' + snapshot_id):
1504 return new
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001505 gs_path = ('gs://chromeos-image-archive/{board}-postsubmit/'
1506 'R*-{snapshot_id}-*'.format(
1507 board=board, snapshot_id=snapshot_id))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001508 for line in gsutil_ls(gs_path, ignore_errors=True):
1509 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)\S+', line)
1510 if m:
1511 return m.group(1)
1512 raise errors.ExternalError(
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001513 'guess_snapshot_version failed, board=%s snapshot_id=%s '
1514 'old=%s new=%s' % (board, snapshot_id, old, new))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001515
1516 result = []
1517 path = 'snapshot.xml'
1518 revisions = self.lookup_snapshot_manifest_revisions(old, new)
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001519 for timestamp, _git_rev, snapshot_id in revisions:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001520 snapshot_version = guess_snapshot_version(self.config['board'],
1521 snapshot_id, old, new)
1522 result.append(
1523 codechange.Spec(codechange.SPEC_FIXED, snapshot_version, timestamp,
1524 path))
1525 return result
1526
1527 def collect_release_specs(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001528 assert is_cros_full_version(old)
1529 assert is_cros_full_version(new)
1530 old_milestone, old_short_version = version_split(old)
1531 new_milestone, new_short_version = version_split(new)
1532
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001533 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001534 for milestone in git_util.list_dir_from_revision(
1535 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
1536 if not milestone.isdigit():
1537 continue
1538 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
1539 continue
1540
Kuang-che Wu74768d32018-09-07 12:03:24 +08001541 files = git_util.list_dir_from_revision(
1542 self.historical_manifest_git_dir, 'refs/heads/master',
1543 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001544
1545 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001546 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001547 short_version, ext = os.path.splitext(fn)
1548 if ext != '.xml':
1549 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001550 if (util.is_version_lesseq(old_short_version, short_version) and
1551 util.is_version_lesseq(short_version, new_short_version) and
1552 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001553 rev = make_cros_full_version(milestone, short_version)
1554 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1555 'refs/heads/master', path)
1556 result.append(
1557 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001558
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001559 def version_key_func(spec):
1560 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001561 return util.version_key_func(short_version)
1562
1563 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001564 assert result[0].name == old
1565 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001566 return result
1567
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001568 def get_manifest(self, rev):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001569 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
1570 if is_cros_full_version(rev):
1571 milestone, short_version = version_split(rev)
1572 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
1573 manifest = git_util.get_file_from_revision(
1574 self.historical_manifest_git_dir, 'refs/heads/master', path)
1575 else:
1576 revisions = self.lookup_snapshot_manifest_revisions(rev, rev)
1577 commit_id = revisions[0][1]
1578 manifest = git_util.get_file_from_revision(self.manifest_internal_dir,
1579 commit_id, 'snapshot.xml')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001580 manifest_name = 'manifest_%s.xml' % rev
1581 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1582 with open(manifest_path, 'w') as f:
1583 f.write(manifest)
1584
1585 return manifest_name
1586
1587 def parse_spec(self, spec):
1588 parser = repo_util.ManifestParser(self.manifest_dir)
1589 if spec.spec_type == codechange.SPEC_FIXED:
1590 manifest_name = self.get_manifest(spec.name)
1591 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1592 content = open(manifest_path).read()
1593 root = parser.parse_single_xml(content, allow_include=False)
1594 else:
1595 root = parser.parse_xml_recursive(spec.name, spec.path)
1596
1597 spec.entries = parser.process_parsed_result(root)
1598 if spec.spec_type == codechange.SPEC_FIXED:
Kuang-che Wufe1e88a2019-09-10 21:52:25 +08001599 if not spec.is_static():
1600 raise ValueError(
1601 'fixed spec %r has unexpected floating entries' % spec.name)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001602
1603 def sync_disk_state(self, rev):
1604 manifest_name = self.get_manifest(rev)
1605
1606 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
1607 # manifest. 'repo sync -m' is not enough
1608 repo_util.init(
1609 self.config['chromeos_root'],
1610 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
1611 manifest_name=manifest_name,
1612 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001613 reference=self.config['chromeos_mirror'],
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001614 )
1615
1616 # Note, don't sync with current_branch=True for chromeos. One of its
1617 # build steps (inside mark_as_stable) executes "git describe" which
1618 # needs git tag information.
1619 repo_util.sync(self.config['chromeos_root'])