blob: 8c94459a8e2a7cd7944ad43a52cefd67bb97f7a0 [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".
10 version: if not specified, it could be in short or full format.
11"""
12
13from __future__ import print_function
Kuang-che Wub9705bd2018-06-28 17:59:18 +080014import ast
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080015import errno
16import json
17import logging
18import os
19import re
20import subprocess
21import time
22
23from bisect_kit import cli
Kuang-che Wue4bae0b2018-07-19 12:10:14 +080024from bisect_kit import codechange
Kuang-che Wu3b46aa42019-03-14 15:59:52 +080025from bisect_kit import common
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080026from bisect_kit import cr_util
Kuang-che Wue121fae2018-11-09 16:18:39 +080027from bisect_kit import errors
Kuang-che Wubfc4a642018-04-19 11:54:08 +080028from bisect_kit import git_util
Kuang-che Wufb553102018-10-02 18:14:29 +080029from bisect_kit import locking
Kuang-che Wubfc4a642018-04-19 11:54:08 +080030from bisect_kit import repo_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080031from bisect_kit import util
32
33logger = logging.getLogger(__name__)
34
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080035re_chromeos_full_version = r'^R\d+-\d+\.\d+\.\d+$'
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080036re_chromeos_localbuild_version = r'^\d+\.\d+\.\d{4}_\d\d_\d\d_\d{4}$'
37re_chromeos_short_version = r'^\d+\.\d+\.\d+$'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080038
39gs_archive_path = 'gs://chromeos-image-archive/{board}-release'
40gs_release_path = (
41 'gs://chromeos-releases/{channel}-channel/{board}/{short_version}')
42
43# Assume gsutil is in PATH.
44gsutil_bin = 'gsutil'
45
Kuang-che Wub9705bd2018-06-28 17:59:18 +080046chromeos_root_inside_chroot = '/mnt/host/source'
47# relative to chromeos_root
48prebuilt_autotest_dir = 'tmp/autotest-prebuilt'
49
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080050VERSION_KEY_CROS_SHORT_VERSION = 'cros_short_version'
51VERSION_KEY_CROS_FULL_VERSION = 'cros_full_version'
52VERSION_KEY_MILESTONE = 'milestone'
53VERSION_KEY_CR_VERSION = 'cr_version'
Kuang-che Wu708310b2018-03-28 17:24:34 +080054VERSION_KEY_ANDROID_BUILD_ID = 'android_build_id'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080055VERSION_KEY_ANDROID_BRANCH = 'android_branch'
56
57
Kuang-che Wu9890ce82018-07-07 15:14:10 +080058class NeedRecreateChrootException(Exception):
59 """Failed to build ChromeOS because of chroot mismatch or corruption"""
60
61
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080062def is_cros_short_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080063 """Determines if `s` is chromeos short version.
64
65 This function doesn't accept version number of local build.
66 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080067 return bool(re.match(re_chromeos_short_version, s))
68
69
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080070def is_cros_localbuild_version(s):
71 """Determines if `s` is chromeos local build version."""
72 return bool(re.match(re_chromeos_localbuild_version, s))
73
74
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080075def is_cros_full_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080076 """Determines if `s` is chromeos full version.
77
78 This function doesn't accept version number of local build.
79 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080080 return bool(re.match(re_chromeos_full_version, s))
81
82
83def is_cros_version(s):
84 """Determines if `s` is chromeos version (either short or full)"""
85 return is_cros_short_version(s) or is_cros_full_version(s)
86
87
88def make_cros_full_version(milestone, short_version):
89 """Makes full_version from milestone and short_version"""
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080090 assert milestone
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080091 return 'R%s-%s' % (milestone, short_version)
92
93
94def version_split(full_version):
95 """Splits full_version into milestone and short_version"""
96 assert is_cros_full_version(full_version)
97 milestone, short_version = full_version.split('-')
98 return milestone[1:], short_version
99
100
101def argtype_cros_version(s):
102 if not is_cros_version(s):
103 msg = 'invalid cros version'
104 raise cli.ArgTypeError(msg, '9876.0.0 or R62-9876.0.0')
105 return s
106
107
108def query_dut_lsb_release(host):
109 """Query /etc/lsb-release of given DUT
110
111 Args:
112 host: the DUT address
113
114 Returns:
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800115 dict for keys and values of /etc/lsb-release.
116
117 Raises:
Kuang-che Wu44278142019-03-04 11:33:57 +0800118 errors.SshConnectionError: cannot connect to host
119 errors.ExternalError: lsb-release file doesn't exist
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800120 """
121 try:
Kuang-che Wu44278142019-03-04 11:33:57 +0800122 output = util.ssh_cmd(host, 'cat', '/etc/lsb-release')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800123 except subprocess.CalledProcessError:
Kuang-che Wu44278142019-03-04 11:33:57 +0800124 raise errors.ExternalError('unable to read /etc/lsb-release; not a DUT')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800125 return dict(re.findall(r'^(\w+)=(.*)$', output, re.M))
126
127
128def is_dut(host):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800129 """Determines whether a host is a chromeos device.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800130
131 Args:
132 host: the DUT address
133
134 Returns:
135 True if the host is a chromeos device.
136 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800137 try:
138 return query_dut_lsb_release(host).get('DEVICETYPE') in [
139 'CHROMEBASE',
140 'CHROMEBIT',
141 'CHROMEBOOK',
142 'CHROMEBOX',
143 'REFERENCE',
144 ]
145 except (errors.ExternalError, errors.SshConnectionError):
146 return False
147
148
149def is_good_dut(host):
150 if not is_dut(host):
151 return False
152
153 # Sometimes python is broken after 'cros flash'.
154 try:
155 util.ssh_cmd(host, 'python', '-c', '1')
156 return True
157 except (subprocess.CalledProcessError, errors.SshConnectionError):
158 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800159
160
161def query_dut_board(host):
162 """Query board name of a given DUT"""
163 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_BOARD')
164
165
166def query_dut_short_version(host):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800167 """Query short version of a given DUT.
168
169 This function may return version of local build, which
170 is_cros_short_version() is false.
171 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800172 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_VERSION')
173
174
175def query_dut_boot_id(host, connect_timeout=None):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800176 """Query boot id.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800177
178 Args:
179 host: DUT address
180 connect_timeout: connection timeout
181
182 Returns:
183 boot uuid
184 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800185 return util.ssh_cmd(
186 host,
187 'cat',
188 '/proc/sys/kernel/random/boot_id',
189 connect_timeout=connect_timeout).strip()
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800190
191
192def reboot(host):
193 """Reboot a DUT and verify"""
194 logger.debug('reboot %s', host)
195 boot_id = query_dut_boot_id(host)
196
Kuang-che Wu44278142019-03-04 11:33:57 +0800197 try:
198 util.ssh_cmd(host, 'reboot')
Kuang-che Wu5f662e82019-03-05 11:49:56 +0800199 except errors.SshConnectionError:
200 # Depends on timing, ssh may return failure due to broken pipe, which is
201 # working as intended. Ignore such kind of errors.
Kuang-che Wu44278142019-03-04 11:33:57 +0800202 pass
Kuang-che Wu708310b2018-03-28 17:24:34 +0800203 wait_reboot_done(host, boot_id)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800204
Kuang-che Wu708310b2018-03-28 17:24:34 +0800205
206def wait_reboot_done(host, boot_id):
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800207 # For dev-mode test image, the reboot time is roughly at least 16 seconds
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800208 # (dev screen short delay) or more (long delay).
209 time.sleep(15)
210 for _ in range(100):
211 try:
212 # During boot, DUT does not response and thus ssh may hang a while. So
213 # set a connect timeout. 3 seconds are enough and 2 are not. It's okay to
214 # set tight limit because it's inside retry loop.
215 assert boot_id != query_dut_boot_id(host, connect_timeout=3)
216 return
Kuang-che Wu5f662e82019-03-05 11:49:56 +0800217 except errors.SshConnectionError:
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800218 logger.debug('reboot not ready? sleep wait 1 sec')
219 time.sleep(1)
220
Kuang-che Wue121fae2018-11-09 16:18:39 +0800221 raise errors.ExternalError('reboot failed?')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800222
223
224def gsutil(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800225 """gsutil command line wrapper.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800226
227 Args:
228 args: command line arguments passed to gsutil
229 kwargs:
230 ignore_errors: if true, return '' for failures, for example 'gsutil ls'
231 but the path not found.
232
233 Returns:
234 stdout of gsutil
235
236 Raises:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800237 errors.InternalError: gsutil failed to run
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800238 subprocess.CalledProcessError: command failed
239 """
240 stderr_lines = []
241 try:
242 return util.check_output(
243 gsutil_bin, *args, stderr_callback=stderr_lines.append)
244 except subprocess.CalledProcessError as e:
245 stderr = ''.join(stderr_lines)
246 if re.search(r'ServiceException:.* does not have .*access', stderr):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800247 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800248 'gsutil failed due to permission. ' +
249 'Run "%s config" and follow its instruction. ' % gsutil_bin +
250 'Fill any string if it asks for project-id')
251 if kwargs.get('ignore_errors'):
252 return ''
253 raise
254 except OSError as e:
255 if e.errno == errno.ENOENT:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800256 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800257 'Unable to run %s. gsutil is not installed or not in PATH?' %
258 gsutil_bin)
259 raise
260
261
262def gsutil_ls(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800263 """gsutil ls.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800264
265 Args:
266 args: arguments passed to 'gsutil ls'
267 kwargs: extra parameters, where
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800268 ignore_errors: if true, return empty list instead of raising
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800269 exception, ex. path not found.
270
271 Returns:
272 list of 'gsutil ls' result. One element for one line of gsutil output.
273
274 Raises:
275 subprocess.CalledProcessError: gsutil failed, usually means path not found
276 """
277 return gsutil('ls', *args, **kwargs).splitlines()
278
279
280def query_milestone_by_version(board, short_version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800281 """Query milestone by ChromeOS version number.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800282
283 Args:
284 board: ChromeOS board name
285 short_version: ChromeOS version number in short format, ex. 9300.0.0
286
287 Returns:
288 ChromeOS milestone number (string). For example, '58' for '9300.0.0'.
289 None if failed.
290 """
291 path = gs_archive_path.format(board=board) + '/R*-' + short_version
292 for line in gsutil_ls('-d', path, ignore_errors=True):
293 m = re.search(r'/R(\d+)-', line)
294 if not m:
295 continue
296 return m.group(1)
297
298 for channel in ['canary', 'dev', 'beta', 'stable']:
299 path = gs_release_path.format(
300 channel=channel, board=board, short_version=short_version)
301 for line in gsutil_ls(path, ignore_errors=True):
302 m = re.search(r'\bR(\d+)-' + short_version, line)
303 if not m:
304 continue
305 return m.group(1)
306
307 logger.error('unable to query milestone of %s for %s', short_version, board)
308 return None
309
310
311def recognize_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800312 """Recognize ChromeOS version.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800313
314 Args:
315 board: ChromeOS board name
316 version: ChromeOS version number in short or full format
317
318 Returns:
319 (milestone, version in short format)
320 """
321 if is_cros_short_version(version):
322 milestone = query_milestone_by_version(board, version)
323 short_version = version
324 else:
325 milestone, short_version = version_split(version)
326 return milestone, short_version
327
328
329def version_to_short(version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800330 """Convert ChromeOS version number to short format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800331
332 Args:
333 version: ChromeOS version number in short or full format
334
335 Returns:
336 version number in short format
337 """
338 if is_cros_short_version(version):
339 return version
340 _, short_version = version_split(version)
341 return short_version
342
343
344def version_to_full(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800345 """Convert ChromeOS version number to full format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800346
347 Args:
348 board: ChromeOS board name
349 version: ChromeOS version number in short or full format
350
351 Returns:
352 version number in full format
353 """
354 if is_cros_full_version(version):
355 return version
356 milestone = query_milestone_by_version(board, version)
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800357 assert milestone
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800358 return make_cros_full_version(milestone, version)
359
360
Kuang-che Wu575dc442019-03-05 10:30:55 +0800361def list_prebuilt_from_image_archive(board):
362 """Lists ChromeOS prebuilt image available from gs://chromeos-image-archive.
363
364 gs://chromeos-image-archive contains only recent builds (in two years).
365 We prefer this function to list_prebuilt_from_chromeos_releases() because
366 - this is what "cros flash" supports directly.
367 - the paths have milestone information, so we don't need to do slow query
368 by ourselves.
369
370 Args:
371 board: ChromeOS board name
372
373 Returns:
374 list of (version, gs_path):
375 version: Chrome OS version in full format
376 gs_path: gs path of test image
377 """
378 result = []
379 for line in gsutil_ls(gs_archive_path.format(board=board)):
380 m = re.match(r'^gs:\S+(R\d+-\d+\.\d+\.\d+)', line)
381 if m:
382 full_version = m.group(1)
383 test_image = 'chromiumos_test_image.tar.xz'
384 assert line.endswith('/')
385 gs_path = line + test_image
386 result.append((full_version, gs_path))
387 return result
388
389
390def list_prebuilt_from_chromeos_releases(board):
391 """Lists ChromeOS versions available from gs://chromeos-releases.
392
393 gs://chromeos-releases contains more builds. However, 'cros flash' doesn't
394 support it.
395
396 Args:
397 board: ChromeOS board name
398
399 Returns:
400 list of (version, gs_path):
401 version: Chrome OS version in short format
402 gs_path: gs path of test image (with wildcard)
403 """
404 result = []
405 for line in gsutil_ls(
406 gs_release_path.format(channel='*', board=board, short_version=''),
407 ignore_errors=True):
408 m = re.match(r'gs:\S+/(\d+\.\d+\.\d+)/$', line)
409 if m:
410 short_version = m.group(1)
411 test_image = 'ChromeOS-test-R*-{short_version}-{board}.tar.xz'.format(
412 short_version=short_version, board=board)
413 gs_path = line + test_image
414 result.append((short_version, gs_path))
415 return result
416
417
418def list_chromeos_prebuilt_versions(board,
419 old,
420 new,
421 only_good_build=True,
422 include_older_build=True):
423 """Lists ChromeOS version numbers with prebuilt between given range
424
425 Args:
426 board: ChromeOS board name
427 old: start version (inclusive)
428 new: end version (inclusive)
429 only_good_build: only if test image is available
430 include_older_build: include prebuilt in gs://chromeos-releases
431
432 Returns:
433 list of sorted version numbers (in full format) between [old, new] range
434 (inclusive).
435 """
436 old = version_to_short(old)
437 new = version_to_short(new)
438
439 rev_map = {} # dict: short version -> (short or full version, gs line)
440 for full_version, gs_path in list_prebuilt_from_image_archive(board):
441 short_version = version_to_short(full_version)
442 rev_map[short_version] = full_version, gs_path
443
444 if include_older_build and old not in rev_map:
445 for short_version, gs_path in list_prebuilt_from_chromeos_releases(board):
446 if short_version not in rev_map:
447 rev_map[short_version] = short_version, gs_path
448
449 result = []
450 for rev in sorted(rev_map, key=util.version_key_func):
451 if not util.is_direct_relative_version(new, rev):
452 continue
453 if not util.is_version_lesseq(old, rev):
454 continue
455 if not util.is_version_lesseq(rev, new):
456 continue
457
458 version, gs_path = rev_map[rev]
459
460 # version_to_full() and gsutil_ls() may take long time if versions are a
461 # lot. This is acceptable because we usually bisect only short range.
462
463 if only_good_build:
464 gs_result = gsutil_ls(gs_path, ignore_errors=True)
465 if not gs_result:
466 logger.warning('%s is not a good build, ignore', version)
467 continue
468 assert len(gs_result) == 1
469 m = re.search(r'(R\d+-\d+\.\d+\.\d+)', gs_result[0])
470 if not m:
471 logger.warning('format of image path is unexpected: %s', gs_result[0])
472 continue
473 version = m.group(1)
474 elif is_cros_short_version(version):
475 version = version_to_full(board, version)
476
477 result.append(version)
478
479 return result
480
481
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800482def prepare_prebuilt_image(board, version):
483 """Prepare chromeos prebuilt image.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800484
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800485 It searches for xbuddy image which "cros flash" can use, or fetch image to
486 local disk.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800487
488 Args:
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800489 board: ChromeOS board name
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800490 version: ChromeOS version number in short or full format
491
492 Returns:
493 xbuddy path or file path (outside chroot)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800494 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800495 assert is_cros_version(version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800496 full_version = version_to_full(board, version)
497 short_version = version_to_short(full_version)
498
499 image_path = None
500 gs_path = gs_archive_path.format(board=board) + '/' + full_version
501 if gsutil_ls('-d', gs_path, ignore_errors=True):
502 image_path = 'xbuddy://remote/{board}/{full_version}/test'.format(
503 board=board, full_version=full_version)
504 else:
505 tmp_dir = 'tmp/ChromeOS-test-%s-%s' % (full_version, board)
506 if not os.path.exists(tmp_dir):
507 os.makedirs(tmp_dir)
508 # gs://chromeos-releases may have more old images than
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800509 # gs://chromeos-image-archive, but 'cros flash' doesn't support it. We have
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800510 # to fetch the image by ourselves
511 for channel in ['canary', 'dev', 'beta', 'stable']:
512 fn = 'ChromeOS-test-{full_version}-{board}.tar.xz'.format(
513 full_version=full_version, board=board)
514 gs_path = gs_release_path.format(
515 channel=channel, board=board, short_version=short_version)
516 gs_path += '/' + fn
517 if gsutil_ls(gs_path, ignore_errors=True):
518 # TODO(kcwu): delete tmp
519 gsutil('cp', gs_path, tmp_dir)
520 util.check_call('tar', 'Jxvf', fn, cwd=tmp_dir)
521 image_path = os.path.abspath(
522 os.path.join(tmp_dir, 'chromiumos_test_image.bin'))
523 break
524
525 assert image_path
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800526 return image_path
527
528
529def cros_flash(chromeos_root,
530 host,
531 board,
532 image_path,
533 version=None,
534 clobber_stateful=False,
Kuang-che Wu155fb6e2018-11-29 16:00:41 +0800535 disable_rootfs_verification=True):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800536 """Flash a DUT with given ChromeOS image.
537
538 This is implemented by 'cros flash' command line.
539
540 Args:
541 chromeos_root: use 'cros flash' of which chromeos tree
542 host: DUT address
543 board: ChromeOS board name
544 image_path: chromeos image xbuddy path or file path. If
545 run_inside_chroot is True, the file path is relative to src/scrips.
546 Otherwise, the file path is relative to chromeos_root.
547 version: ChromeOS version in short or full format
548 clobber_stateful: Clobber stateful partition when performing update
549 disable_rootfs_verification: Disable rootfs verification after update
550 is completed
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800551 """
552 logger.info('cros_flash %s %s %s %s', host, board, version, image_path)
553
554 # Reboot is necessary because sometimes previous 'cros flash' failed and
555 # entered a bad state.
556 reboot(host)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800557
Kuang-che Wuf3d03ca2019-03-11 17:31:40 +0800558 args = [
559 '--debug', '--no-ping', '--send-payload-in-parallel', host, image_path
560 ]
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800561 if clobber_stateful:
562 args.append('--clobber-stateful')
563 if disable_rootfs_verification:
564 args.append('--disable-rootfs-verification')
565
Kuang-che Wu155fb6e2018-11-29 16:00:41 +0800566 cros_sdk(chromeos_root, 'cros', 'flash', *args)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800567
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800568 if version:
569 # In the past, cros flash may fail with returncode=0
570 # So let's have an extra check.
571 short_version = version_to_short(version)
572 dut_version = query_dut_short_version(host)
573 assert dut_version == short_version
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800574
575
576def version_info(board, version):
577 """Query subcomponents version info of given version of ChromeOS
578
579 Args:
580 board: ChromeOS board name
581 version: ChromeOS version number in short or full format
582
583 Returns:
584 dict of component and version info, including (if available):
585 cros_short_version: ChromeOS version
586 cros_full_version: ChromeOS version
587 milestone: milestone of ChromeOS
588 cr_version: Chrome version
Kuang-che Wu708310b2018-03-28 17:24:34 +0800589 android_build_id: Android build id
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800590 android_branch: Android branch, in format like 'git_nyc-mr1-arc'
591 """
592 info = {}
593 full_version = version_to_full(board, version)
594
595 # Some boards may have only partial-metadata.json but no metadata.json.
596 # e.g. caroline R60-9462.0.0
597 # Let's try both.
598 metadata = None
599 for metadata_filename in ['metadata.json', 'partial-metadata.json']:
600 path = gs_archive_path.format(board=board) + '/%s/%s' % (full_version,
601 metadata_filename)
602 metadata = gsutil('cat', path, ignore_errors=True)
603 if metadata:
604 o = json.loads(metadata)
605 v = o['version']
606 board_metadata = o['board-metadata'][board]
607 info.update({
608 VERSION_KEY_CROS_SHORT_VERSION: v['platform'],
609 VERSION_KEY_CROS_FULL_VERSION: v['full'],
610 VERSION_KEY_MILESTONE: v['milestone'],
611 VERSION_KEY_CR_VERSION: v['chrome'],
612 })
613
614 if 'android' in v:
Kuang-che Wu708310b2018-03-28 17:24:34 +0800615 info[VERSION_KEY_ANDROID_BUILD_ID] = v['android']
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800616 if 'android-branch' in v: # this appears since R58-9317.0.0
617 info[VERSION_KEY_ANDROID_BRANCH] = v['android-branch']
618 elif 'android-container-branch' in board_metadata:
619 info[VERSION_KEY_ANDROID_BRANCH] = v['android-container-branch']
620 break
621 else:
622 logger.error('Failed to read metadata from gs://chromeos-image-archive')
623 logger.error(
624 'Note, so far no quick way to look up version info for too old builds')
625
626 return info
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800627
628
629def query_chrome_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800630 """Queries chrome version of chromeos build.
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800631
632 Args:
633 board: ChromeOS board name
634 version: ChromeOS version number in short or full format
635
636 Returns:
637 Chrome version number
638 """
639 info = version_info(board, version)
640 return info['cr_version']
Kuang-che Wu708310b2018-03-28 17:24:34 +0800641
642
643def query_android_build_id(board, rev):
644 info = version_info(board, rev)
645 rev = info['android_build_id']
646 return rev
647
648
649def query_android_branch(board, rev):
650 info = version_info(board, rev)
651 rev = info['android_branch']
652 return rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800653
654
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800655def guess_chrome_version(board, rev):
656 """Guess chrome version number.
657
658 Args:
659 board: chromeos board name
660 rev: chrome or chromeos version
661
662 Returns:
663 chrome version number
664 """
665 if is_cros_version(rev):
666 assert board, 'need to specify BOARD for cros version'
667 rev = query_chrome_version(board, rev)
668 assert cr_util.is_chrome_version(rev)
669
670 return rev
671
672
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800673def is_inside_chroot():
674 """Returns True if we are inside chroot."""
675 return os.path.exists('/etc/cros_chroot_version')
676
677
678def cros_sdk(chromeos_root, *args, **kwargs):
679 """Run commands inside chromeos chroot.
680
681 Args:
682 chromeos_root: chromeos tree root
683 *args: command to run
684 **kwargs:
Kuang-che Wud4603d72018-11-29 17:51:21 +0800685 chrome_root: pass to cros_sdk; mount this path into the SDK chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800686 env: (dict) environment variables for the command
687 stdin: standard input file handle for the command
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800688 stderr_callback: Callback function for stderr. Called once per line.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800689 """
690 envs = []
691 for k, v in kwargs.get('env', {}).items():
692 assert re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', k)
693 envs.append('%s=%s' % (k, v))
694
695 # Use --no-ns-pid to prevent cros_sdk change our pgid, otherwise subsequent
696 # commands would be considered as background process.
Kuang-che Wud4603d72018-11-29 17:51:21 +0800697 cmd = ['chromite/bin/cros_sdk', '--no-ns-pid']
698
699 if kwargs.get('chrome_root'):
700 cmd += ['--chrome_root', kwargs['chrome_root']]
701
702 cmd += envs + ['--'] + list(args)
703
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800704 return util.check_output(
705 *cmd,
706 cwd=chromeos_root,
707 stdin=kwargs.get('stdin'),
708 stderr_callback=kwargs.get('stderr_callback'))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800709
710
711def copy_into_chroot(chromeos_root, src, dst):
712 """Copies file into chromeos chroot.
713
714 Args:
715 chromeos_root: chromeos tree root
716 src: path outside chroot
717 dst: path inside chroot
718 """
719 # chroot may be an image, so we cannot copy to corresponding path
720 # directly.
721 cros_sdk(chromeos_root, 'sh', '-c', 'cat > %s' % dst, stdin=open(src))
722
723
724def exists_in_chroot(chromeos_root, path):
725 """Determine whether a path exists in the chroot.
726
727 Args:
728 chromeos_root: chromeos tree root
729 path: path inside chroot, relative to src/scripts
730
731 Returns:
732 True if a path exists
733 """
734 try:
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800735 cros_sdk(chromeos_root, 'test', '-e', path)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800736 except subprocess.CalledProcessError:
737 return False
738 return True
739
740
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800741def check_if_need_recreate_chroot(stdout, stderr):
742 """Analyze build log and determine if chroot should be recreated.
743
744 Args:
745 stdout: stdout output of build
746 stderr: stderr output of build
747
748 Returns:
749 the reason if chroot needs recreated; None otherwise
750 """
Kuang-che Wu74768d32018-09-07 12:03:24 +0800751 if re.search(
752 r"The current version of portage supports EAPI '\d+'. "
753 "You must upgrade", stderr):
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800754 return 'EAPI version mismatch'
755
Kuang-che Wu5ac81322018-11-26 14:04:06 +0800756 if 'Chroot is too new. Consider running:' in stderr:
757 return 'chroot version is too new'
758
759 # old message before Oct 2018
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800760 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
761 return 'chroot version is too new'
762
Kuang-che Wu6fe987f2018-08-28 15:24:20 +0800763 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
764 if "undefined reference to 'std::__1::basic_string" in stdout:
765 return 'might be due to compiler change'
766
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800767 return None
768
769
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800770def build_image(chromeos_root, board, rev):
771 """Build ChromeOS image.
772
773 Args:
774 chromeos_root: chromeos tree root
775 board: ChromeOS board name
776 rev: the version name to build
777
778 Returns:
779 Image path
780 """
781
782 # If the given version is already built, reuse it.
Kuang-che Wuf41599c2018-08-03 16:11:11 +0800783 image_name = 'bisect-%s' % rev.replace('/', '_')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800784 image_path = os.path.join('../build/images', board, image_name,
785 'chromiumos_test_image.bin')
786 if exists_in_chroot(chromeos_root, image_path):
787 logger.info('"%s" already exists, skip build step', image_path)
788 return image_path
789
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800790 script_name = 'build_cros_helper.sh'
Kuang-che Wu3b46aa42019-03-14 15:59:52 +0800791 copy_into_chroot(chromeos_root,
792 os.path.join(common.BISECT_KIT_ROOT, script_name),
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800793 script_name)
794 cros_sdk(chromeos_root, 'chmod', '+x', script_name)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800795
796 stderr_lines = []
797 try:
Kuang-che Wufb553102018-10-02 18:14:29 +0800798 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
799 cros_sdk(
800 chromeos_root,
801 './%s' % script_name,
802 board,
803 image_name,
804 stderr_callback=stderr_lines.append)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800805 except subprocess.CalledProcessError as e:
806 # Detect failures due to incompatibility between chroot and source tree. If
807 # so, notify the caller to recreate chroot and retry.
808 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
809 if reason:
810 raise NeedRecreateChrootException(reason)
811
812 # For other failures, don't know how to handle. Just bail out.
813 raise
814
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800815 return image_path
816
817
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800818class AutotestControlInfo(object):
819 """Parsed content of autotest control file.
820
821 Attributes:
822 name: test name
823 path: control file path
824 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
825 DOC, ATTRIBUTES, DEPENDENCIES, etc.
826 """
827
828 def __init__(self, path, variables):
829 self.name = variables['NAME']
830 self.path = path
831 self.variables = variables
832
833
834def parse_autotest_control_file(path):
835 """Parses autotest control file.
836
837 This only parses simple top-level string assignments.
838
839 Returns:
840 AutotestControlInfo object
841 """
842 variables = {}
843 code = ast.parse(open(path).read())
844 for stmt in code.body:
845 # Skip if not simple "NAME = *" assignment.
846 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
847 isinstance(stmt.targets[0], ast.Name)):
848 continue
849
850 # Only support string value.
851 if isinstance(stmt.value, ast.Str):
852 variables[stmt.targets[0].id] = stmt.value.s
853
854 return AutotestControlInfo(path, variables)
855
856
857def enumerate_autotest_control_files(autotest_dir):
858 """Enumerate autotest control files.
859
860 Args:
861 autotest_dir: autotest folder
862
863 Returns:
864 list of paths to control files
865 """
866 # Where to find control files. Relative to autotest_dir.
867 subpaths = [
868 'server/site_tests',
869 'client/site_tests',
870 'server/tests',
871 'client/tests',
872 ]
873
874 blacklist = ['site-packages', 'venv', 'results', 'logs', 'containers']
875 result = []
876 for subpath in subpaths:
877 path = os.path.join(autotest_dir, subpath)
878 for root, dirs, files in os.walk(path):
879
880 for black in blacklist:
881 if black in dirs:
882 dirs.remove(black)
883
884 for filename in files:
885 if filename == 'control' or filename.startswith('control.'):
886 result.append(os.path.join(root, filename))
887
888 return result
889
890
891def get_autotest_test_info(autotest_dir, test_name):
892 """Get metadata of given test.
893
894 Args:
895 autotest_dir: autotest folder
896 test_name: test name
897
898 Returns:
899 AutotestControlInfo object. None if test not found.
900 """
901 for control_file in enumerate_autotest_control_files(autotest_dir):
902 info = parse_autotest_control_file(control_file)
903 if info.name == test_name:
904 return info
905 return None
906
907
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800908class ChromeOSSpecManager(codechange.SpecManager):
909 """Repo manifest related operations.
910
911 This class enumerates chromeos manifest files, parses them,
912 and sync to disk state according to them.
913 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800914
915 def __init__(self, config):
916 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800917 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
918 'manifests')
919 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +0800920 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800921 if not os.path.exists(self.historical_manifest_git_dir):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800922 raise errors.InternalError('Manifest snapshots should be cloned into %s' %
923 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800924
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800925 def lookup_build_timestamp(self, rev):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800926 assert is_cros_full_version(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800927
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800928 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800929 path = os.path.join('buildspecs', milestone, short_version + '.xml')
930 try:
931 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
932 'refs/heads/master', path)
933 except ValueError:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800934 raise errors.InternalError(
Kuang-che Wu74768d32018-09-07 12:03:24 +0800935 '%s does not have %s' % (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800936 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800937
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800938 def collect_float_spec(self, old, new):
939 old_timestamp = self.lookup_build_timestamp(old)
940 new_timestamp = self.lookup_build_timestamp(new)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800941
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800942 path = os.path.join(self.manifest_dir, 'default.xml')
943 if not os.path.islink(path) or os.readlink(path) != 'full.xml':
Kuang-che Wue121fae2018-11-09 16:18:39 +0800944 raise errors.InternalError(
945 'default.xml not symlink to full.xml is not supported')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800946
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800947 result = []
948 path = 'full.xml'
949 parser = repo_util.ManifestParser(self.manifest_dir)
950 for timestamp, git_rev in parser.enumerate_manifest_commits(
951 old_timestamp, new_timestamp, path):
952 result.append(
953 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
954 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800955
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800956 def collect_fixed_spec(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800957 assert is_cros_full_version(old)
958 assert is_cros_full_version(new)
959 old_milestone, old_short_version = version_split(old)
960 new_milestone, new_short_version = version_split(new)
961
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800962 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800963 for milestone in git_util.list_dir_from_revision(
964 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
965 if not milestone.isdigit():
966 continue
967 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
968 continue
969
Kuang-che Wu74768d32018-09-07 12:03:24 +0800970 files = git_util.list_dir_from_revision(
971 self.historical_manifest_git_dir, 'refs/heads/master',
972 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800973
974 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800975 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800976 short_version, ext = os.path.splitext(fn)
977 if ext != '.xml':
978 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800979 if (util.is_version_lesseq(old_short_version, short_version) and
980 util.is_version_lesseq(short_version, new_short_version) and
981 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800982 rev = make_cros_full_version(milestone, short_version)
983 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
984 'refs/heads/master', path)
985 result.append(
986 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800987
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800988 def version_key_func(spec):
989 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800990 return util.version_key_func(short_version)
991
992 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800993 assert result[0].name == old
994 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800995 return result
996
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800997 def get_manifest(self, rev):
998 assert is_cros_full_version(rev)
999 milestone, short_version = version_split(rev)
1000 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
1001 manifest = git_util.get_file_from_revision(self.historical_manifest_git_dir,
1002 'refs/heads/master', path)
1003
1004 manifest_name = 'manifest_%s.xml' % rev
1005 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1006 with open(manifest_path, 'w') as f:
1007 f.write(manifest)
1008
1009 return manifest_name
1010
1011 def parse_spec(self, spec):
1012 parser = repo_util.ManifestParser(self.manifest_dir)
1013 if spec.spec_type == codechange.SPEC_FIXED:
1014 manifest_name = self.get_manifest(spec.name)
1015 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1016 content = open(manifest_path).read()
1017 root = parser.parse_single_xml(content, allow_include=False)
1018 else:
1019 root = parser.parse_xml_recursive(spec.name, spec.path)
1020
1021 spec.entries = parser.process_parsed_result(root)
1022 if spec.spec_type == codechange.SPEC_FIXED:
1023 assert spec.is_static()
1024
1025 def sync_disk_state(self, rev):
1026 manifest_name = self.get_manifest(rev)
1027
1028 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
1029 # manifest. 'repo sync -m' is not enough
1030 repo_util.init(
1031 self.config['chromeos_root'],
1032 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
1033 manifest_name=manifest_name,
1034 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001035 reference=self.config['chromeos_mirror'],
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001036 )
1037
1038 # Note, don't sync with current_branch=True for chromeos. One of its
1039 # build steps (inside mark_as_stable) executes "git describe" which
1040 # needs git tag information.
1041 repo_util.sync(self.config['chromeos_root'])