blob: 3dc1ddac3e446ba3872846c29d65ae782d7c3108 [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
27from bisect_kit import cli
Kuang-che Wue4bae0b2018-07-19 12:10:14 +080028from bisect_kit import codechange
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080029from bisect_kit import cr_util
Kuang-che Wue121fae2018-11-09 16:18:39 +080030from bisect_kit import errors
Kuang-che Wubfc4a642018-04-19 11:54:08 +080031from bisect_kit import git_util
Kuang-che Wufb553102018-10-02 18:14:29 +080032from bisect_kit import locking
Kuang-che Wubfc4a642018-04-19 11:54:08 +080033from bisect_kit import repo_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080034from bisect_kit import util
35
36logger = logging.getLogger(__name__)
37
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080038re_chromeos_full_version = r'^R\d+-\d+\.\d+\.\d+$'
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080039re_chromeos_localbuild_version = r'^\d+\.\d+\.\d{4}_\d\d_\d\d_\d{4}$'
40re_chromeos_short_version = r'^\d+\.\d+\.\d+$'
Zheng-Jie Chang127c3302019-09-10 17:17:04 +080041re_chromeos_snapshot_version = r'^R\d+-\d+\.\d+\.\d+-\d+$'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080042
43gs_archive_path = 'gs://chromeos-image-archive/{board}-release'
44gs_release_path = (
Kuang-che Wu80bf6a52019-05-31 12:48:06 +080045 'gs://chromeos-releases/{channel}-channel/{boardpath}/{short_version}')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080046
47# Assume gsutil is in PATH.
48gsutil_bin = 'gsutil'
Zheng-Jie Changb8697042019-10-29 16:03:26 +080049bb_bin = 'bb'
50
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
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800293def bb(*args, **kwargs):
294 """bb command line wrapper.
295
296 Args:
297 args: command line arguments passed to bb
298 kwargs:
299 parse_json: if True, return json parsed object of output
300
301 Returns:
302 stdout of bb
303
304 Raises:
305 errors.ExternalError: bb failed to run
306 subprocess.CalledProcessError: command failed
307 """
308 stderr_lines = []
309 try:
310 result = util.check_output(
311 bb_bin, *args, stderr_callback=stderr_lines.append)
312 if kwargs.get('parse_json'):
313 result = json.loads(result)
314 return result
315 except subprocess.CalledProcessError as e:
316 stderr = ''.join(stderr_lines)
317 if 'interactive login is required' in stderr:
318 raise errors.ExternalError(
319 '%s command is permission denied, please run %s auth-login' %
320 (bb_bin, bb_bin))
321 raise
322 except OSError as e:
323 if e.errno == errno.ENOENT:
324 raise errors.ExternalError('%s command is not found' % bb_bin)
325 raise
326
327
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800328def gsutil(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800329 """gsutil command line wrapper.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800330
331 Args:
332 args: command line arguments passed to gsutil
333 kwargs:
334 ignore_errors: if true, return '' for failures, for example 'gsutil ls'
335 but the path not found.
336
337 Returns:
338 stdout of gsutil
339
340 Raises:
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800341 errors.ExternalError: gsutil failed to run
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800342 subprocess.CalledProcessError: command failed
343 """
344 stderr_lines = []
345 try:
346 return util.check_output(
347 gsutil_bin, *args, stderr_callback=stderr_lines.append)
348 except subprocess.CalledProcessError as e:
349 stderr = ''.join(stderr_lines)
350 if re.search(r'ServiceException:.* does not have .*access', stderr):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800351 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800352 'gsutil failed due to permission. ' +
353 'Run "%s config" and follow its instruction. ' % gsutil_bin +
354 'Fill any string if it asks for project-id')
355 if kwargs.get('ignore_errors'):
356 return ''
357 raise
358 except OSError as e:
359 if e.errno == errno.ENOENT:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800360 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800361 'Unable to run %s. gsutil is not installed or not in PATH?' %
362 gsutil_bin)
363 raise
364
365
366def gsutil_ls(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800367 """gsutil ls.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800368
369 Args:
370 args: arguments passed to 'gsutil ls'
371 kwargs: extra parameters, where
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800372 ignore_errors: if true, return empty list instead of raising
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800373 exception, ex. path not found.
374
375 Returns:
376 list of 'gsutil ls' result. One element for one line of gsutil output.
377
378 Raises:
379 subprocess.CalledProcessError: gsutil failed, usually means path not found
380 """
381 return gsutil('ls', *args, **kwargs).splitlines()
382
383
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800384def gsutil_stat_update_time(*args, **kwargs):
385 """Returns the last modified time of a file or multiple files.
386
387 Args:
388 args: arguments passed to 'gsutil stat'.
389 kwargs: extra parameters for gsutil.
390
391 Returns:
392 A integer indicates the last modified timestamp.
393
394 Raises:
395 subprocess.CalledProcessError: gsutil failed, usually means path not found
396 errors.ExternalError: update time is not found
397 """
398 result = -1
399 # Currently we believe stat always returns a UTC time, and strptime also
400 # parses a UTC time by default.
401 time_format = '%a, %d %b %Y %H:%M:%S GMT'
402
403 for line in gsutil('stat', *args, **kwargs).splitlines():
404 if ':' not in line:
405 continue
406 key, value = map(str.strip, line.split(':', 1))
407 if key != 'Update time':
408 continue
409 dt = datetime.datetime.strptime(value, time_format)
Kuang-che Wu72b5a572019-10-29 20:37:57 +0800410 unixtime = int(calendar.timegm(dt.utctimetuple()))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800411 result = max(result, unixtime)
412
413 if result == -1:
414 raise errors.ExternalError("didn't find update time")
415 return result
416
417
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800418def query_milestone_by_version(board, short_version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800419 """Query milestone by ChromeOS version number.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800420
421 Args:
422 board: ChromeOS board name
423 short_version: ChromeOS version number in short format, ex. 9300.0.0
424
425 Returns:
426 ChromeOS milestone number (string). For example, '58' for '9300.0.0'.
427 None if failed.
428 """
429 path = gs_archive_path.format(board=board) + '/R*-' + short_version
430 for line in gsutil_ls('-d', path, ignore_errors=True):
431 m = re.search(r'/R(\d+)-', line)
432 if not m:
433 continue
434 return m.group(1)
435
436 for channel in ['canary', 'dev', 'beta', 'stable']:
437 path = gs_release_path.format(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800438 channel=channel,
439 boardpath=gs_release_boardpath(board),
440 short_version=short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800441 for line in gsutil_ls(path, ignore_errors=True):
442 m = re.search(r'\bR(\d+)-' + short_version, line)
443 if not m:
444 continue
445 return m.group(1)
446
447 logger.error('unable to query milestone of %s for %s', short_version, board)
448 return None
449
450
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800451def list_board_names(chromeos_root):
452 """List board names.
453
454 Args:
455 chromeos_root: chromeos tree root
456
457 Returns:
458 list of board names
459 """
460 # Following logic is simplified from chromite/lib/portage_util.py
461 cros_list_overlays = os.path.join(chromeos_root,
462 'chromite/bin/cros_list_overlays')
463 overlays = util.check_output(cros_list_overlays).splitlines()
464 result = set()
465 for overlay in overlays:
466 conf_file = os.path.join(overlay, 'metadata', 'layout.conf')
467 name = None
468 if os.path.exists(conf_file):
469 for line in open(conf_file):
470 m = re.match(r'^repo-name\s*=\s*(\S+)\s*$', line)
471 if m:
472 name = m.group(1)
473 break
474
475 if not name:
476 name_file = os.path.join(overlay, 'profiles', 'repo_name')
477 if os.path.exists(name_file):
478 name = open(name_file).read().strip()
479
480 if name:
481 name = re.sub(r'-private$', '', name)
482 result.add(name)
483
484 return list(result)
485
486
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800487def recognize_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800488 """Recognize ChromeOS version.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800489
490 Args:
491 board: ChromeOS board name
492 version: ChromeOS version number in short or full format
493
494 Returns:
495 (milestone, version in short format)
496 """
497 if is_cros_short_version(version):
498 milestone = query_milestone_by_version(board, version)
499 short_version = version
500 else:
501 milestone, short_version = version_split(version)
502 return milestone, short_version
503
504
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800505def extract_major_version(version):
506 """Converts a version to its major version.
507
508 Args:
509 version: ChromsOS version number or snapshot version
510
511 Returns:
512 major version number in string format
513 """
514 version = version_to_short(version)
515 m = re.match(r'^(\d+)\.\d+\.\d+$', version)
516 return m.group(1)
517
518
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800519def version_to_short(version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800520 """Convert ChromeOS version number to short format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800521
522 Args:
523 version: ChromeOS version number in short or full format
524
525 Returns:
526 version number in short format
527 """
528 if is_cros_short_version(version):
529 return version
530 _, short_version = version_split(version)
531 return short_version
532
533
534def version_to_full(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800535 """Convert ChromeOS version number to full format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800536
537 Args:
538 board: ChromeOS board name
539 version: ChromeOS version number in short or full format
540
541 Returns:
542 version number in full format
543 """
544 if is_cros_full_version(version):
545 return version
546 milestone = query_milestone_by_version(board, version)
Kuang-che Wu0205f052019-05-23 12:48:37 +0800547 assert milestone, 'incorrect board=%s or version=%s ?' % (board, version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800548 return make_cros_full_version(milestone, version)
549
550
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800551def list_snapshots_from_image_archive(board, major_version):
552 """List ChromeOS snapshot image avaliable from gs://chromeos-image-archive.
553
554 Args:
555 board: ChromeOS board
556 major_version: ChromeOS major version
557
558 Returns:
559 list of (version, gs_path):
560 version: Chrome OS snapshot version
561 gs_path: gs path of test image
562 """
563
564 path = (
565 'gs://chromeos-image-archive/{board}-postsubmit/R*-{major_version}.0.0-*')
566 result = []
567 output = gsutil_ls(
568 '-d',
569 path.format(board=board, major_version=major_version),
570 ignore_errors=True)
571
572 for path in output:
573 if not path.endswith('/'):
574 continue
575 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)', path)
576 if m:
577 snapshot_version = m.group(1)
578 test_image = 'image.zip'
579 gs_path = path + test_image
580 result.append((snapshot_version, gs_path))
581 return result
582
583
Kuang-che Wu575dc442019-03-05 10:30:55 +0800584def list_prebuilt_from_image_archive(board):
585 """Lists ChromeOS prebuilt image available from gs://chromeos-image-archive.
586
587 gs://chromeos-image-archive contains only recent builds (in two years).
588 We prefer this function to list_prebuilt_from_chromeos_releases() because
589 - this is what "cros flash" supports directly.
590 - the paths have milestone information, so we don't need to do slow query
591 by ourselves.
592
593 Args:
594 board: ChromeOS board name
595
596 Returns:
597 list of (version, gs_path):
598 version: Chrome OS version in full format
599 gs_path: gs path of test image
600 """
601 result = []
602 for line in gsutil_ls(gs_archive_path.format(board=board)):
603 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+)', line)
604 if m:
605 full_version = m.group(1)
606 test_image = 'chromiumos_test_image.tar.xz'
607 assert line.endswith('/')
608 gs_path = line + test_image
609 result.append((full_version, gs_path))
610 return result
611
612
613def list_prebuilt_from_chromeos_releases(board):
614 """Lists ChromeOS versions available from gs://chromeos-releases.
615
616 gs://chromeos-releases contains more builds. However, 'cros flash' doesn't
617 support it.
618
619 Args:
620 board: ChromeOS board name
621
622 Returns:
623 list of (version, gs_path):
624 version: Chrome OS version in short format
625 gs_path: gs path of test image (with wildcard)
626 """
627 result = []
628 for line in gsutil_ls(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800629 gs_release_path.format(
630 channel='*', boardpath=gs_release_boardpath(board), short_version=''),
Kuang-che Wu575dc442019-03-05 10:30:55 +0800631 ignore_errors=True):
632 m = re.match(r'gs:\S+/(\d+\.\d+\.\d+)/$', line)
633 if m:
634 short_version = m.group(1)
635 test_image = 'ChromeOS-test-R*-{short_version}-{board}.tar.xz'.format(
636 short_version=short_version, board=board)
637 gs_path = line + test_image
638 result.append((short_version, gs_path))
639 return result
640
641
642def list_chromeos_prebuilt_versions(board,
643 old,
644 new,
645 only_good_build=True,
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800646 include_older_build=True,
647 use_snapshot=False):
Kuang-che Wu575dc442019-03-05 10:30:55 +0800648 """Lists ChromeOS version numbers with prebuilt between given range
649
650 Args:
651 board: ChromeOS board name
652 old: start version (inclusive)
653 new: end version (inclusive)
654 only_good_build: only if test image is available
655 include_older_build: include prebuilt in gs://chromeos-releases
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800656 use_snapshot: return snapshot versions if found
Kuang-che Wu575dc442019-03-05 10:30:55 +0800657
658 Returns:
659 list of sorted version numbers (in full format) between [old, new] range
660 (inclusive).
661 """
662 old = version_to_short(old)
663 new = version_to_short(new)
664
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800665 rev_map = {
666 } # dict: short version -> list of (short/full or snapshot version, gs path)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800667 for full_version, gs_path in list_prebuilt_from_image_archive(board):
668 short_version = version_to_short(full_version)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800669 rev_map[short_version] = [(full_version, gs_path)]
Kuang-che Wu575dc442019-03-05 10:30:55 +0800670
671 if include_older_build and old not in rev_map:
672 for short_version, gs_path in list_prebuilt_from_chromeos_releases(board):
673 if short_version not in rev_map:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800674 rev_map[short_version] = [(short_version, gs_path)]
675
676 if use_snapshot:
677 for major_version in range(
678 int(extract_major_version(old)),
679 int(extract_major_version(new)) + 1):
680 short_version = '%s.0.0' % major_version
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800681 # If current version is smaller than cutover, ignore it as it might not
682 # contain enough information for continuing android and chrome bisection.
683 if not util.is_version_lesseq(snapshot_cutover_version, short_version):
684 continue
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800685 if not util.is_direct_relative_version(short_version, old):
686 continue
687 if not util.is_direct_relative_version(short_version, new):
688 continue
689 snapshots = list_snapshots_from_image_archive(board, str(major_version))
690 if snapshots:
691 # if snapshots found, we can append them after the release version,
692 # so the prebuilt image list of this version will be
693 # release_image, snapshot1, snapshot2,...
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800694 if short_version not in rev_map:
695 rev_map[short_version] = []
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800696 rev_map[short_version] += snapshots
Kuang-che Wu575dc442019-03-05 10:30:55 +0800697
698 result = []
699 for rev in sorted(rev_map, key=util.version_key_func):
700 if not util.is_direct_relative_version(new, rev):
701 continue
702 if not util.is_version_lesseq(old, rev):
703 continue
704 if not util.is_version_lesseq(rev, new):
705 continue
706
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800707 for version, gs_path in rev_map[rev]:
Kuang-che Wu575dc442019-03-05 10:30:55 +0800708
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800709 # version_to_full() and gsutil_ls() may take long time if versions are a
710 # lot. This is acceptable because we usually bisect only short range.
Kuang-che Wu575dc442019-03-05 10:30:55 +0800711
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800712 if only_good_build:
713 gs_result = gsutil_ls(gs_path, ignore_errors=True)
714 if not gs_result:
715 logger.warning('%s is not a good build, ignore', version)
716 continue
717 assert len(gs_result) == 1
718 m = re.search(r'(R\d+-\d+\.\d+\.\d+)', gs_result[0])
719 if not m:
720 logger.warning('format of image path is unexpected: %s', gs_result[0])
721 continue
722 if not is_cros_snapshot_version(version):
723 version = m.group(1)
724 elif is_cros_short_version(version):
725 version = version_to_full(board, version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800726
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800727 result.append(version)
Kuang-che Wu575dc442019-03-05 10:30:55 +0800728
729 return result
730
731
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800732def prepare_snapshot_image(chromeos_root, board, snapshot_version):
733 """Prepare chromeos snapshot image.
734
735 Args:
736 chromeos_root: chromeos tree root
737 board: ChromeOS board name
738 snapshot_version: ChromeOS snapshot version number
739
740 Returns:
741 local file path of test image relative to chromeos_root
742 """
743 assert is_cros_snapshot_version(snapshot_version)
744 milestone, short_version, snapshot_id = snapshot_version_split(
745 snapshot_version)
746 full_version = make_cros_full_version(milestone, short_version)
747 tmp_dir = os.path.join(
748 chromeos_root, 'tmp',
749 'ChromeOS-test-%s-%s-%s' % (full_version, board, snapshot_id))
750 if not os.path.exists(tmp_dir):
751 os.makedirs(tmp_dir)
752
753 gs_path = ('gs://chromeos-image-archive/{board}-postsubmit/' +
754 '{snapshot_version}-*/image.zip')
755 gs_path = gs_path.format(board=board, snapshot_version=snapshot_version)
756
757 files = gsutil_ls(gs_path, ignore_errors=True)
758 if len(files) == 1:
759 gs_path = files[0]
760 gsutil('cp', gs_path, tmp_dir)
761 image_path = os.path.relpath(
762 os.path.join(tmp_dir, test_image_filename), chromeos_root)
763 util.check_call(
764 'unzip', '-j', 'image.zip', test_image_filename, cwd=tmp_dir)
765 os.remove(os.path.join(tmp_dir, 'image.zip'))
766
767 assert image_path
768 return image_path
769
770
Kuang-che Wu28980b22019-07-31 19:51:45 +0800771def prepare_prebuilt_image(chromeos_root, board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800772 """Prepare chromeos prebuilt image.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800773
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800774 It searches for xbuddy image which "cros flash" can use, or fetch image to
775 local disk.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800776
777 Args:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800778 chromeos_root: chromeos tree root
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800779 board: ChromeOS board name
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800780 version: ChromeOS version number in short or full format
781
782 Returns:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800783 xbuddy path or file path (relative to chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800784 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800785 assert is_cros_version(version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800786 full_version = version_to_full(board, version)
787 short_version = version_to_short(full_version)
788
789 image_path = None
790 gs_path = gs_archive_path.format(board=board) + '/' + full_version
791 if gsutil_ls('-d', gs_path, ignore_errors=True):
792 image_path = 'xbuddy://remote/{board}/{full_version}/test'.format(
793 board=board, full_version=full_version)
794 else:
Kuang-che Wu28980b22019-07-31 19:51:45 +0800795 tmp_dir = os.path.join(chromeos_root, 'tmp',
796 'ChromeOS-test-%s-%s' % (full_version, board))
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800797 if not os.path.exists(tmp_dir):
798 os.makedirs(tmp_dir)
799 # gs://chromeos-releases may have more old images than
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800800 # gs://chromeos-image-archive, but 'cros flash' doesn't support it. We have
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800801 # to fetch the image by ourselves
802 for channel in ['canary', 'dev', 'beta', 'stable']:
803 fn = 'ChromeOS-test-{full_version}-{board}.tar.xz'.format(
804 full_version=full_version, board=board)
805 gs_path = gs_release_path.format(
Kuang-che Wu80bf6a52019-05-31 12:48:06 +0800806 channel=channel,
807 boardpath=gs_release_boardpath(board),
808 short_version=short_version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800809 gs_path += '/' + fn
810 if gsutil_ls(gs_path, ignore_errors=True):
811 # TODO(kcwu): delete tmp
812 gsutil('cp', gs_path, tmp_dir)
813 util.check_call('tar', 'Jxvf', fn, cwd=tmp_dir)
Kuang-che Wu28980b22019-07-31 19:51:45 +0800814 image_path = os.path.relpath(
815 os.path.join(tmp_dir, test_image_filename), chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800816 break
817
818 assert image_path
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800819 return image_path
820
821
822def cros_flash(chromeos_root,
823 host,
824 board,
825 image_path,
826 version=None,
827 clobber_stateful=False,
Kuang-che Wu155fb6e2018-11-29 16:00:41 +0800828 disable_rootfs_verification=True):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800829 """Flash a DUT with given ChromeOS image.
830
831 This is implemented by 'cros flash' command line.
832
833 Args:
834 chromeos_root: use 'cros flash' of which chromeos tree
835 host: DUT address
836 board: ChromeOS board name
Kuang-che Wu28980b22019-07-31 19:51:45 +0800837 image_path: chromeos image xbuddy path or file path. For relative
838 path, it should be relative to chromeos_root.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800839 version: ChromeOS version in short or full format
840 clobber_stateful: Clobber stateful partition when performing update
841 disable_rootfs_verification: Disable rootfs verification after update
842 is completed
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800843
844 Raises:
845 errors.ExternalError: cros flash failed
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800846 """
847 logger.info('cros_flash %s %s %s %s', host, board, version, image_path)
848
849 # Reboot is necessary because sometimes previous 'cros flash' failed and
850 # entered a bad state.
851 reboot(host)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800852
Kuang-che Wu28980b22019-07-31 19:51:45 +0800853 # Handle relative path.
854 if '://' not in image_path and not os.path.isabs(image_path):
855 assert os.path.exists(os.path.join(chromeos_root, image_path))
856 image_path = os.path.join(chromeos_root_inside_chroot, image_path)
857
Kuang-che Wuf3d03ca2019-03-11 17:31:40 +0800858 args = [
859 '--debug', '--no-ping', '--send-payload-in-parallel', host, image_path
860 ]
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800861 if clobber_stateful:
862 args.append('--clobber-stateful')
863 if disable_rootfs_verification:
864 args.append('--disable-rootfs-verification')
865
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800866 try:
867 cros_sdk(chromeos_root, 'cros', 'flash', *args)
868 except subprocess.CalledProcessError:
869 raise errors.ExternalError('cros flash failed')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800870
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800871 if version:
872 # In the past, cros flash may fail with returncode=0
873 # So let's have an extra check.
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800874 if is_cros_snapshot_version(version):
875 builder_path = query_dut_lsb_release(host).get(
876 'CHROMEOS_RELEASE_BUILDER_PATH', '')
877 expect_prefix = '%s-postsubmit/%s-' % (board, version)
878 if not builder_path.startswith(expect_prefix):
879 raise errors.ExternalError(
880 'although cros flash succeeded, the OS builder path is '
881 'unexpected: actual=%s expect=%s' % (builder_path, expect_prefix))
882 else:
883 expect_version = version_to_short(version)
884 dut_version = query_dut_short_version(host)
885 if dut_version != expect_version:
886 raise errors.ExternalError(
887 'although cros flash succeeded, the OS version is unexpected: '
888 'actual=%s expect=%s' % (dut_version, expect_version))
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800889
Kuang-che Wu4a81ea72019-10-05 15:35:17 +0800890 # "cros flash" may terminate successfully but the DUT starts self-repairing
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800891 # (b/130786578), so it's necessary to do sanity check.
892 if not is_good_dut(host):
893 raise errors.ExternalError(
894 'although cros flash succeeded, the DUT is in bad state')
895
896
897def cros_flash_with_retry(chromeos_root,
898 host,
899 board,
900 image_path,
901 version=None,
902 clobber_stateful=False,
903 disable_rootfs_verification=True,
904 repair_callback=None):
905 # 'cros flash' is not 100% reliable, retry if necessary.
906 for attempt in range(2):
907 if attempt > 0:
908 logger.info('will retry 60 seconds later')
909 time.sleep(60)
910
911 try:
912 cros_flash(
913 chromeos_root,
914 host,
915 board,
916 image_path,
917 version=version,
918 clobber_stateful=clobber_stateful,
919 disable_rootfs_verification=disable_rootfs_verification)
920 return True
921 except errors.ExternalError:
922 logger.exception('cros flash failed')
923 if repair_callback and not repair_callback(host):
924 logger.warning('not repaired, assume it is harmless')
925 continue
926 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800927
928
929def version_info(board, version):
930 """Query subcomponents version info of given version of ChromeOS
931
932 Args:
933 board: ChromeOS board name
934 version: ChromeOS version number in short or full format
935
936 Returns:
937 dict of component and version info, including (if available):
938 cros_short_version: ChromeOS version
939 cros_full_version: ChromeOS version
940 milestone: milestone of ChromeOS
941 cr_version: Chrome version
Kuang-che Wu708310b2018-03-28 17:24:34 +0800942 android_build_id: Android build id
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800943 android_branch: Android branch, in format like 'git_nyc-mr1-arc'
944 """
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800945 if is_cros_snapshot_version(version):
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800946 milestone, short_version, _ = snapshot_version_split(version)
947 buildbucket_id = query_snapshot_buildbucket_id(board, version)
948 data = bb('get', buildbucket_id, '-json', '-p', parse_json=True)
949 target_versions = data['output']['properties']['target_versions']
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800950 return {
Zheng-Jie Changb8697042019-10-29 16:03:26 +0800951 VERSION_KEY_MILESTONE: milestone,
952 VERSION_KEY_CROS_FULL_VERSION: version,
953 VERSION_KEY_CROS_SHORT_VERSION: short_version,
954 VERSION_KEY_CR_VERSION: target_versions['chromeVersion'],
955 VERSION_KEY_ANDROID_BUILD_ID: target_versions['androidVersion'],
956 VERSION_KEY_ANDROID_BRANCH: target_versions['androidBranchVersion'],
Zheng-Jie Chang127c3302019-09-10 17:17:04 +0800957 }
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800958 info = {}
959 full_version = version_to_full(board, version)
960
961 # Some boards may have only partial-metadata.json but no metadata.json.
962 # e.g. caroline R60-9462.0.0
963 # Let's try both.
964 metadata = None
965 for metadata_filename in ['metadata.json', 'partial-metadata.json']:
Kuang-che Wu0768b972019-10-05 15:18:59 +0800966 path = gs_archive_path.format(
967 board=board) + '/%s/%s' % (full_version, metadata_filename)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800968 metadata = gsutil('cat', path, ignore_errors=True)
969 if metadata:
970 o = json.loads(metadata)
971 v = o['version']
972 board_metadata = o['board-metadata'][board]
973 info.update({
974 VERSION_KEY_CROS_SHORT_VERSION: v['platform'],
975 VERSION_KEY_CROS_FULL_VERSION: v['full'],
976 VERSION_KEY_MILESTONE: v['milestone'],
977 VERSION_KEY_CR_VERSION: v['chrome'],
978 })
979
980 if 'android' in v:
Kuang-che Wu708310b2018-03-28 17:24:34 +0800981 info[VERSION_KEY_ANDROID_BUILD_ID] = v['android']
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800982 if 'android-branch' in v: # this appears since R58-9317.0.0
983 info[VERSION_KEY_ANDROID_BRANCH] = v['android-branch']
984 elif 'android-container-branch' in board_metadata:
985 info[VERSION_KEY_ANDROID_BRANCH] = v['android-container-branch']
986 break
987 else:
988 logger.error('Failed to read metadata from gs://chromeos-image-archive')
989 logger.error(
990 'Note, so far no quick way to look up version info for too old builds')
991
992 return info
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800993
994
995def query_chrome_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800996 """Queries chrome version of chromeos build.
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800997
998 Args:
999 board: ChromeOS board name
1000 version: ChromeOS version number in short or full format
1001
1002 Returns:
1003 Chrome version number
1004 """
1005 info = version_info(board, version)
1006 return info['cr_version']
Kuang-che Wu708310b2018-03-28 17:24:34 +08001007
1008
1009def query_android_build_id(board, rev):
1010 info = version_info(board, rev)
1011 rev = info['android_build_id']
1012 return rev
1013
1014
1015def query_android_branch(board, rev):
1016 info = version_info(board, rev)
1017 rev = info['android_branch']
1018 return rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001019
1020
Kuang-che Wu3eb6b502018-06-06 16:15:18 +08001021def guess_chrome_version(board, rev):
1022 """Guess chrome version number.
1023
1024 Args:
1025 board: chromeos board name
1026 rev: chrome or chromeos version
1027
1028 Returns:
1029 chrome version number
1030 """
1031 if is_cros_version(rev):
1032 assert board, 'need to specify BOARD for cros version'
1033 rev = query_chrome_version(board, rev)
1034 assert cr_util.is_chrome_version(rev)
1035
1036 return rev
1037
1038
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001039def is_inside_chroot():
1040 """Returns True if we are inside chroot."""
1041 return os.path.exists('/etc/cros_chroot_version')
1042
1043
1044def cros_sdk(chromeos_root, *args, **kwargs):
1045 """Run commands inside chromeos chroot.
1046
1047 Args:
1048 chromeos_root: chromeos tree root
1049 *args: command to run
1050 **kwargs:
Kuang-che Wud4603d72018-11-29 17:51:21 +08001051 chrome_root: pass to cros_sdk; mount this path into the SDK chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001052 env: (dict) environment variables for the command
Kuang-che Wubcafc552019-08-15 15:27:02 +08001053 log_stdout: Whether write the stdout output of the child process to log.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001054 stdin: standard input file handle for the command
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001055 stderr_callback: Callback function for stderr. Called once per line.
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001056 goma_dir: Goma installed directory to mount into the chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001057 """
1058 envs = []
1059 for k, v in kwargs.get('env', {}).items():
1060 assert re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', k)
1061 envs.append('%s=%s' % (k, v))
1062
1063 # Use --no-ns-pid to prevent cros_sdk change our pgid, otherwise subsequent
1064 # commands would be considered as background process.
Kuang-che Wu399d4662019-06-06 15:23:37 +08001065 prefix = ['chromite/bin/cros_sdk', '--no-ns-pid']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001066
1067 if kwargs.get('chrome_root'):
Kuang-che Wu399d4662019-06-06 15:23:37 +08001068 prefix += ['--chrome_root', kwargs['chrome_root']]
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001069 if kwargs.get('goma_dir'):
1070 prefix += ['--goma_dir', kwargs['goma_dir']]
Kuang-che Wud4603d72018-11-29 17:51:21 +08001071
Kuang-che Wu399d4662019-06-06 15:23:37 +08001072 prefix += envs + ['--']
Kuang-che Wud4603d72018-11-29 17:51:21 +08001073
Kuang-che Wu399d4662019-06-06 15:23:37 +08001074 # In addition to the output of command we are interested, cros_sdk may
1075 # generate its own messages. For example, chroot creation messages if we run
1076 # cros_sdk the first time.
1077 # This is the hack to run dummy command once, so we can get clean output for
1078 # the command we are interested.
1079 cmd = prefix + ['true']
1080 util.check_call(*cmd, cwd=chromeos_root)
1081
1082 cmd = prefix + list(args)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001083 return util.check_output(
1084 *cmd,
1085 cwd=chromeos_root,
Kuang-che Wubcafc552019-08-15 15:27:02 +08001086 log_stdout=kwargs.get('log_stdout', True),
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001087 stdin=kwargs.get('stdin'),
1088 stderr_callback=kwargs.get('stderr_callback'))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001089
1090
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001091def create_chroot(chromeos_root):
1092 """Creates ChromeOS chroot.
1093
1094 Args:
1095 chromeos_root: chromeos tree root
1096 """
1097 if os.path.exists(os.path.join(chromeos_root, 'chroot')):
1098 return
1099 if os.path.exists(os.path.join(chromeos_root, 'chroot.img')):
1100 return
1101
1102 util.check_output('chromite/bin/cros_sdk', '--create', cwd=chromeos_root)
1103
1104
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001105def copy_into_chroot(chromeos_root, src, dst):
1106 """Copies file into chromeos chroot.
1107
1108 Args:
1109 chromeos_root: chromeos tree root
1110 src: path outside chroot
1111 dst: path inside chroot
1112 """
1113 # chroot may be an image, so we cannot copy to corresponding path
1114 # directly.
1115 cros_sdk(chromeos_root, 'sh', '-c', 'cat > %s' % dst, stdin=open(src))
1116
1117
1118def exists_in_chroot(chromeos_root, path):
1119 """Determine whether a path exists in the chroot.
1120
1121 Args:
1122 chromeos_root: chromeos tree root
1123 path: path inside chroot, relative to src/scripts
1124
1125 Returns:
1126 True if a path exists
1127 """
1128 try:
Kuang-che Wuacb6efd2018-04-25 18:52:58 +08001129 cros_sdk(chromeos_root, 'test', '-e', path)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001130 except subprocess.CalledProcessError:
1131 return False
1132 return True
1133
1134
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001135def check_if_need_recreate_chroot(stdout, stderr):
1136 """Analyze build log and determine if chroot should be recreated.
1137
1138 Args:
1139 stdout: stdout output of build
1140 stderr: stderr output of build
1141
1142 Returns:
1143 the reason if chroot needs recreated; None otherwise
1144 """
Kuang-che Wu74768d32018-09-07 12:03:24 +08001145 if re.search(
1146 r"The current version of portage supports EAPI '\d+'. "
Kuang-che Wuae6824b2019-08-27 22:20:01 +08001147 'You must upgrade', stderr):
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001148 return 'EAPI version mismatch'
1149
Kuang-che Wu5ac81322018-11-26 14:04:06 +08001150 if 'Chroot is too new. Consider running:' in stderr:
1151 return 'chroot version is too new'
1152
1153 # old message before Oct 2018
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001154 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
1155 return 'chroot version is too new'
1156
Kuang-che Wu6fe987f2018-08-28 15:24:20 +08001157 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
1158 if "undefined reference to 'std::__1::basic_string" in stdout:
1159 return 'might be due to compiler change'
1160
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001161 return None
1162
1163
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001164def build_packages(chromeos_root,
1165 board,
1166 chrome_root=None,
1167 goma_dir=None,
1168 afdo_use=False):
Kuang-che Wu28980b22019-07-31 19:51:45 +08001169 """Build ChromeOS packages.
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001170
1171 Args:
1172 chromeos_root: chromeos tree root
1173 board: ChromeOS board name
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001174 chrome_root: Chrome tree root. If specified, build chrome using the
1175 provided tree
1176 goma_dir: Goma installed directory to mount into the chroot. If specified,
1177 build chrome with goma.
1178 afdo_use: build chrome with AFDO optimization
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001179 """
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001180 common_env = {
1181 'USE': '-cros-debug chrome_internal',
1182 'FEATURES': 'separatedebug',
1183 }
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001184 stderr_lines = []
1185 try:
Kuang-che Wufb553102018-10-02 18:14:29 +08001186 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001187 env = common_env.copy()
1188 env['FEATURES'] += ' -separatedebug splitdebug'
Kuang-che Wufb553102018-10-02 18:14:29 +08001189 cros_sdk(
1190 chromeos_root,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001191 './update_chroot',
1192 '--toolchain_boards',
Kuang-che Wufb553102018-10-02 18:14:29 +08001193 board,
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001194 env=env,
Kuang-che Wu28980b22019-07-31 19:51:45 +08001195 stderr_callback=stderr_lines.append)
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001196
1197 env = common_env.copy()
1198 cmd = [
Kuang-che Wu28980b22019-07-31 19:51:45 +08001199 './build_packages',
1200 '--board',
1201 board,
1202 '--withdev',
1203 '--noworkon',
1204 '--skip_chroot_upgrade',
1205 '--accept_licenses=@CHROMEOS',
Kuang-che Wua9a20bb2019-09-05 22:24:04 +08001206 ]
1207 if goma_dir:
1208 # Tell build_packages to start and stop goma
1209 cmd.append('--run_goma')
1210 env['USE_GOMA'] = 'true'
1211 if afdo_use:
1212 env['USE'] += ' afdo_use'
1213 cros_sdk(
1214 chromeos_root,
1215 *cmd,
1216 env=env,
1217 chrome_root=chrome_root,
1218 stderr_callback=stderr_lines.append,
1219 goma_dir=goma_dir)
Kuang-che Wu9890ce82018-07-07 15:14:10 +08001220 except subprocess.CalledProcessError as e:
1221 # Detect failures due to incompatibility between chroot and source tree. If
1222 # so, notify the caller to recreate chroot and retry.
1223 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1224 if reason:
1225 raise NeedRecreateChrootException(reason)
1226
1227 # For other failures, don't know how to handle. Just bail out.
1228 raise
1229
Kuang-che Wu28980b22019-07-31 19:51:45 +08001230
1231def build_image(chromeos_root, board):
1232 """Build ChromeOS image.
1233
1234 Args:
1235 chromeos_root: chromeos tree root
1236 board: ChromeOS board name
1237
1238 Returns:
1239 image folder; relative to chromeos_root
1240 """
1241 stderr_lines = []
1242 try:
1243 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
1244 cros_sdk(
1245 chromeos_root,
1246 './build_image',
1247 '--board',
1248 board,
1249 '--noenable_rootfs_verification',
1250 'test',
1251 env={
1252 'USE': '-cros-debug chrome_internal',
1253 'FEATURES': 'separatedebug',
1254 },
1255 stderr_callback=stderr_lines.append)
1256 except subprocess.CalledProcessError as e:
1257 # Detect failures due to incompatibility between chroot and source tree. If
1258 # so, notify the caller to recreate chroot and retry.
1259 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
1260 if reason:
1261 raise NeedRecreateChrootException(reason)
1262
1263 # For other failures, don't know how to handle. Just bail out.
1264 raise
1265
1266 image_symlink = os.path.join(chromeos_root, cached_images_dir, board,
1267 'latest')
1268 assert os.path.exists(image_symlink)
1269 image_name = os.readlink(image_symlink)
1270 image_folder = os.path.join(cached_images_dir, board, image_name)
1271 assert os.path.exists(
1272 os.path.join(chromeos_root, image_folder, test_image_filename))
1273 return image_folder
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001274
1275
Kuang-che Wub9705bd2018-06-28 17:59:18 +08001276class AutotestControlInfo(object):
1277 """Parsed content of autotest control file.
1278
1279 Attributes:
1280 name: test name
1281 path: control file path
1282 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
1283 DOC, ATTRIBUTES, DEPENDENCIES, etc.
1284 """
1285
1286 def __init__(self, path, variables):
1287 self.name = variables['NAME']
1288 self.path = path
1289 self.variables = variables
1290
1291
1292def parse_autotest_control_file(path):
1293 """Parses autotest control file.
1294
1295 This only parses simple top-level string assignments.
1296
1297 Returns:
1298 AutotestControlInfo object
1299 """
1300 variables = {}
1301 code = ast.parse(open(path).read())
1302 for stmt in code.body:
1303 # Skip if not simple "NAME = *" assignment.
1304 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
1305 isinstance(stmt.targets[0], ast.Name)):
1306 continue
1307
1308 # Only support string value.
1309 if isinstance(stmt.value, ast.Str):
1310 variables[stmt.targets[0].id] = stmt.value.s
1311
1312 return AutotestControlInfo(path, variables)
1313
1314
1315def enumerate_autotest_control_files(autotest_dir):
1316 """Enumerate autotest control files.
1317
1318 Args:
1319 autotest_dir: autotest folder
1320
1321 Returns:
1322 list of paths to control files
1323 """
1324 # Where to find control files. Relative to autotest_dir.
1325 subpaths = [
1326 'server/site_tests',
1327 'client/site_tests',
1328 'server/tests',
1329 'client/tests',
1330 ]
1331
1332 blacklist = ['site-packages', 'venv', 'results', 'logs', 'containers']
1333 result = []
1334 for subpath in subpaths:
1335 path = os.path.join(autotest_dir, subpath)
1336 for root, dirs, files in os.walk(path):
1337
1338 for black in blacklist:
1339 if black in dirs:
1340 dirs.remove(black)
1341
1342 for filename in files:
1343 if filename == 'control' or filename.startswith('control.'):
1344 result.append(os.path.join(root, filename))
1345
1346 return result
1347
1348
1349def get_autotest_test_info(autotest_dir, test_name):
1350 """Get metadata of given test.
1351
1352 Args:
1353 autotest_dir: autotest folder
1354 test_name: test name
1355
1356 Returns:
1357 AutotestControlInfo object. None if test not found.
1358 """
1359 for control_file in enumerate_autotest_control_files(autotest_dir):
1360 info = parse_autotest_control_file(control_file)
1361 if info.name == test_name:
1362 return info
1363 return None
1364
1365
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001366class ChromeOSSpecManager(codechange.SpecManager):
1367 """Repo manifest related operations.
1368
1369 This class enumerates chromeos manifest files, parses them,
1370 and sync to disk state according to them.
1371 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001372
1373 def __init__(self, config):
1374 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001375 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
1376 'manifests')
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001377 self.manifest_internal_dir = os.path.join(self.config['chromeos_mirror'],
1378 'manifest-internal.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001379 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001380 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001381 if not os.path.exists(self.historical_manifest_git_dir):
Kuang-che Wue121fae2018-11-09 16:18:39 +08001382 raise errors.InternalError('Manifest snapshots should be cloned into %s' %
1383 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001384
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001385 def lookup_snapshot_manifest_revisions(self, old, new):
1386 """Get manifest commits between snapshot versions.
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001387
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001388 Returns:
1389 list of (timestamp, commit_id, snapshot_id):
1390 timestamp: integer unix timestamp
1391 commit_id: a string indicates commit hash
1392 snapshot_id: a string indicates snapshot id
1393 """
1394 assert is_cros_snapshot_version(old)
1395 assert is_cros_snapshot_version(new)
1396
1397 gs_path = (
1398 'gs://chromeos-image-archive/{board}-postsubmit/{version}-*/image.zip')
1399 # Try to guess the commit time of a snapshot manifest, it is usually a few
1400 # minutes different between snapshot manifest commit and image.zip
1401 # generate.
1402 try:
1403 old_timestamp = gsutil_stat_update_time(
1404 gs_path.format(board=self.config['board'], version=old)) - 86400
1405 except subprocess.CalledProcessError:
1406 old_timestamp = None
1407 try:
1408 new_timestamp = gsutil_stat_update_time(
1409 gs_path.format(board=self.config['board'], version=new)) + 86400
1410 # 1558657989 is snapshot_id 5982's commit time, this ensures every time
1411 # we can find snapshot 5982
1412 # snapshot_id <= 5982 has different commit message format, so we need
1413 # to identify its id in different ways, see below comment for more info.
1414 new_timestamp = max(new_timestamp, 1558657989 + 1)
1415 except subprocess.CalledProcessError:
1416 new_timestamp = None
1417 result = []
1418 _, _, old_snapshot_id = snapshot_version_split(old)
1419 _, _, new_snapshot_id = snapshot_version_split(new)
1420 repo = self.manifest_internal_dir
1421 path = 'snapshot.xml'
1422 branch = 'snapshot'
1423 commits = git_util.get_history(
1424 repo,
1425 path,
1426 branch,
1427 after=old_timestamp,
1428 before=new_timestamp,
1429 with_subject=True)
1430
1431 # Unfortunately, we can not identify snapshot_id <= 5982 from its commit
1432 # subject, as their subjects are all `Annealing manifest snapshot.`.
1433 # So instead we count the snapshot_id manually.
1434 count = 5982
1435 # There are two snapshot_id = 2633 in commit history, ignore the former
1436 # one.
1437 ignore_list = ['95c8526a7f0798d02f692010669dcbd5a152439a']
1438 # We examine the commits in reverse order as there are some testing
1439 # commits before snapshot_id=2, this method works fine after
1440 # snapshot 2, except snapshot 2633
1441 for commit in reversed(commits):
1442 msg = commit[2]
1443 if commit[1] in ignore_list:
1444 continue
1445
1446 match = re.match(r'^annealing manifest snapshot (\d+)', msg)
1447 if match:
1448 snapshot_id = match.group(1)
1449 elif 'Annealing manifest snapshot' in msg:
1450 snapshot_id = str(count)
1451 count -= 1
1452 else:
1453 continue
1454 if int(old_snapshot_id) <= int(snapshot_id) <= int(new_snapshot_id):
1455 result.append((commit[0], commit[1], snapshot_id))
1456 # We find commits in reversed order, now reverse it again to chronological
1457 # order.
1458 return list(reversed(result))
1459
1460 def lookup_build_timestamp(self, rev):
1461 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
1462 if is_cros_full_version(rev):
1463 return self.lookup_release_build_timestamp(rev)
1464 else:
1465 return self.lookup_snapshot_build_timestamp(rev)
1466
1467 def lookup_snapshot_build_timestamp(self, rev):
1468 assert is_cros_snapshot_version(rev)
1469 return int(self.lookup_snapshot_manifest_revisions(rev, rev)[0][0])
1470
1471 def lookup_release_build_timestamp(self, rev):
1472 assert is_cros_full_version(rev)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001473 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001474 path = os.path.join('buildspecs', milestone, short_version + '.xml')
1475 try:
1476 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1477 'refs/heads/master', path)
1478 except ValueError:
Kuang-che Wuce2f3be2019-10-28 19:44:54 +08001479 raise errors.InternalError(
1480 '%s does not have %s' % (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001481 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001482
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001483 def collect_float_spec(self, old, new):
1484 old_timestamp = self.lookup_build_timestamp(old)
1485 new_timestamp = self.lookup_build_timestamp(new)
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001486 # snapshot time is different from commit time
1487 # usually it's a few minutes different
1488 # 30 minutes should be safe in most cases
1489 if is_cros_snapshot_version(old):
1490 old_timestamp = old_timestamp - 1800
1491 if is_cros_snapshot_version(new):
1492 new_timestamp = new_timestamp + 1800
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001493
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001494 path = os.path.join(self.manifest_dir, 'default.xml')
1495 if not os.path.islink(path) or os.readlink(path) != 'full.xml':
Kuang-che Wue121fae2018-11-09 16:18:39 +08001496 raise errors.InternalError(
1497 'default.xml not symlink to full.xml is not supported')
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001498
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001499 result = []
1500 path = 'full.xml'
1501 parser = repo_util.ManifestParser(self.manifest_dir)
1502 for timestamp, git_rev in parser.enumerate_manifest_commits(
1503 old_timestamp, new_timestamp, path):
1504 result.append(
1505 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
1506 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001507
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001508 def collect_fixed_spec(self, old, new):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001509 assert is_cros_full_version(old) or is_cros_snapshot_version(old)
1510 assert is_cros_full_version(new) or is_cros_snapshot_version(new)
1511
1512 # case 1: if both are snapshot, return a list of snapshot
1513 if is_cros_snapshot_version(old) and is_cros_snapshot_version(new):
1514 return self.collect_snapshot_specs(old, new)
1515
1516 # case 2: if both are release version
1517 # return a list of release version
1518 if is_cros_full_version(old) and is_cros_full_version(new):
1519 return self.collect_release_specs(old, new)
1520
1521 # case 3: return a list of release version and append a snapshot
1522 # before or at the end
1523 result = self.collect_release_specs(old, new)
1524 if is_cros_snapshot_version(old):
1525 result = self.collect_release_specs(old, old) + result[1:]
1526 elif is_cros_snapshot_version(new):
1527 result = result[:-1] + self.collect_release_specs(new, new)
1528 return result
1529
1530 def collect_snapshot_specs(self, old, new):
1531 assert is_cros_snapshot_version(old)
1532 assert is_cros_snapshot_version(new)
1533
1534 def guess_snapshot_version(board, snapshot_id, old, new):
1535 if old.endswith('-' + snapshot_id):
1536 return old
1537 if new.endswith('-' + snapshot_id):
1538 return new
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001539 gs_path = ('gs://chromeos-image-archive/{board}-postsubmit/'
1540 'R*-{snapshot_id}-*'.format(
1541 board=board, snapshot_id=snapshot_id))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001542 for line in gsutil_ls(gs_path, ignore_errors=True):
1543 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+-\d+)\S+', line)
1544 if m:
1545 return m.group(1)
1546 raise errors.ExternalError(
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001547 'guess_snapshot_version failed, board=%s snapshot_id=%s '
1548 'old=%s new=%s' % (board, snapshot_id, old, new))
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001549
1550 result = []
1551 path = 'snapshot.xml'
1552 revisions = self.lookup_snapshot_manifest_revisions(old, new)
Kuang-che Wuf791afa2019-10-28 19:53:26 +08001553 for timestamp, _git_rev, snapshot_id in revisions:
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001554 snapshot_version = guess_snapshot_version(self.config['board'],
1555 snapshot_id, old, new)
1556 result.append(
1557 codechange.Spec(codechange.SPEC_FIXED, snapshot_version, timestamp,
1558 path))
1559 return result
1560
1561 def collect_release_specs(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001562 assert is_cros_full_version(old)
1563 assert is_cros_full_version(new)
1564 old_milestone, old_short_version = version_split(old)
1565 new_milestone, new_short_version = version_split(new)
1566
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001567 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001568 for milestone in git_util.list_dir_from_revision(
1569 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
1570 if not milestone.isdigit():
1571 continue
1572 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
1573 continue
1574
Kuang-che Wu74768d32018-09-07 12:03:24 +08001575 files = git_util.list_dir_from_revision(
1576 self.historical_manifest_git_dir, 'refs/heads/master',
1577 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001578
1579 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001580 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001581 short_version, ext = os.path.splitext(fn)
1582 if ext != '.xml':
1583 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001584 if (util.is_version_lesseq(old_short_version, short_version) and
1585 util.is_version_lesseq(short_version, new_short_version) and
1586 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001587 rev = make_cros_full_version(milestone, short_version)
1588 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1589 'refs/heads/master', path)
1590 result.append(
1591 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001592
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001593 def version_key_func(spec):
1594 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001595 return util.version_key_func(short_version)
1596
1597 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001598 assert result[0].name == old
1599 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001600 return result
1601
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001602 def get_manifest(self, rev):
Zheng-Jie Chang127c3302019-09-10 17:17:04 +08001603 assert is_cros_full_version(rev) or is_cros_snapshot_version(rev)
1604 if is_cros_full_version(rev):
1605 milestone, short_version = version_split(rev)
1606 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
1607 manifest = git_util.get_file_from_revision(
1608 self.historical_manifest_git_dir, 'refs/heads/master', path)
1609 else:
1610 revisions = self.lookup_snapshot_manifest_revisions(rev, rev)
1611 commit_id = revisions[0][1]
1612 manifest = git_util.get_file_from_revision(self.manifest_internal_dir,
1613 commit_id, 'snapshot.xml')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001614 manifest_name = 'manifest_%s.xml' % rev
1615 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1616 with open(manifest_path, 'w') as f:
1617 f.write(manifest)
1618
1619 return manifest_name
1620
1621 def parse_spec(self, spec):
1622 parser = repo_util.ManifestParser(self.manifest_dir)
1623 if spec.spec_type == codechange.SPEC_FIXED:
1624 manifest_name = self.get_manifest(spec.name)
1625 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1626 content = open(manifest_path).read()
1627 root = parser.parse_single_xml(content, allow_include=False)
1628 else:
1629 root = parser.parse_xml_recursive(spec.name, spec.path)
1630
1631 spec.entries = parser.process_parsed_result(root)
1632 if spec.spec_type == codechange.SPEC_FIXED:
Kuang-che Wufe1e88a2019-09-10 21:52:25 +08001633 if not spec.is_static():
1634 raise ValueError(
1635 'fixed spec %r has unexpected floating entries' % spec.name)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001636
1637 def sync_disk_state(self, rev):
1638 manifest_name = self.get_manifest(rev)
1639
1640 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
1641 # manifest. 'repo sync -m' is not enough
1642 repo_util.init(
1643 self.config['chromeos_root'],
1644 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
1645 manifest_name=manifest_name,
1646 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001647 reference=self.config['chromeos_mirror'],
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001648 )
1649
1650 # Note, don't sync with current_branch=True for chromeos. One of its
1651 # build steps (inside mark_as_stable) executes "git describe" which
1652 # needs git tag information.
1653 repo_util.sync(self.config['chromeos_root'])