blob: 7ab4f025f4dd61f42d89ea57eeae7b57094d7e12 [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 Wu0205f052019-05-23 12:48:37 +0800357 assert milestone, 'incorrect board=%s or version=%s ?' % (board, version)
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 Wu414d67f2019-05-28 11:28:57 +0800551
552 Raises:
553 errors.ExternalError: cros flash failed
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800554 """
555 logger.info('cros_flash %s %s %s %s', host, board, version, image_path)
556
557 # Reboot is necessary because sometimes previous 'cros flash' failed and
558 # entered a bad state.
559 reboot(host)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800560
Kuang-che Wuf3d03ca2019-03-11 17:31:40 +0800561 args = [
562 '--debug', '--no-ping', '--send-payload-in-parallel', host, image_path
563 ]
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800564 if clobber_stateful:
565 args.append('--clobber-stateful')
566 if disable_rootfs_verification:
567 args.append('--disable-rootfs-verification')
568
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800569 try:
570 cros_sdk(chromeos_root, 'cros', 'flash', *args)
571 except subprocess.CalledProcessError:
572 raise errors.ExternalError('cros flash failed')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800573
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800574 if version:
575 # In the past, cros flash may fail with returncode=0
576 # So let's have an extra check.
577 short_version = version_to_short(version)
578 dut_version = query_dut_short_version(host)
Kuang-che Wu414d67f2019-05-28 11:28:57 +0800579 if dut_version != short_version:
580 raise errors.ExternalError(
581 'although cros flash succeeded, the OS version is unexpected: '
582 'actual=%s expect=%s' % (dut_version, short_version))
583
584 # "cros flash" may terminate sucessfully but the DUT starts self-repairing
585 # (b/130786578), so it's necessary to do sanity check.
586 if not is_good_dut(host):
587 raise errors.ExternalError(
588 'although cros flash succeeded, the DUT is in bad state')
589
590
591def cros_flash_with_retry(chromeos_root,
592 host,
593 board,
594 image_path,
595 version=None,
596 clobber_stateful=False,
597 disable_rootfs_verification=True,
598 repair_callback=None):
599 # 'cros flash' is not 100% reliable, retry if necessary.
600 for attempt in range(2):
601 if attempt > 0:
602 logger.info('will retry 60 seconds later')
603 time.sleep(60)
604
605 try:
606 cros_flash(
607 chromeos_root,
608 host,
609 board,
610 image_path,
611 version=version,
612 clobber_stateful=clobber_stateful,
613 disable_rootfs_verification=disable_rootfs_verification)
614 return True
615 except errors.ExternalError:
616 logger.exception('cros flash failed')
617 if repair_callback and not repair_callback(host):
618 logger.warning('not repaired, assume it is harmless')
619 continue
620 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800621
622
623def version_info(board, version):
624 """Query subcomponents version info of given version of ChromeOS
625
626 Args:
627 board: ChromeOS board name
628 version: ChromeOS version number in short or full format
629
630 Returns:
631 dict of component and version info, including (if available):
632 cros_short_version: ChromeOS version
633 cros_full_version: ChromeOS version
634 milestone: milestone of ChromeOS
635 cr_version: Chrome version
Kuang-che Wu708310b2018-03-28 17:24:34 +0800636 android_build_id: Android build id
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800637 android_branch: Android branch, in format like 'git_nyc-mr1-arc'
638 """
639 info = {}
640 full_version = version_to_full(board, version)
641
642 # Some boards may have only partial-metadata.json but no metadata.json.
643 # e.g. caroline R60-9462.0.0
644 # Let's try both.
645 metadata = None
646 for metadata_filename in ['metadata.json', 'partial-metadata.json']:
647 path = gs_archive_path.format(board=board) + '/%s/%s' % (full_version,
648 metadata_filename)
649 metadata = gsutil('cat', path, ignore_errors=True)
650 if metadata:
651 o = json.loads(metadata)
652 v = o['version']
653 board_metadata = o['board-metadata'][board]
654 info.update({
655 VERSION_KEY_CROS_SHORT_VERSION: v['platform'],
656 VERSION_KEY_CROS_FULL_VERSION: v['full'],
657 VERSION_KEY_MILESTONE: v['milestone'],
658 VERSION_KEY_CR_VERSION: v['chrome'],
659 })
660
661 if 'android' in v:
Kuang-che Wu708310b2018-03-28 17:24:34 +0800662 info[VERSION_KEY_ANDROID_BUILD_ID] = v['android']
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800663 if 'android-branch' in v: # this appears since R58-9317.0.0
664 info[VERSION_KEY_ANDROID_BRANCH] = v['android-branch']
665 elif 'android-container-branch' in board_metadata:
666 info[VERSION_KEY_ANDROID_BRANCH] = v['android-container-branch']
667 break
668 else:
669 logger.error('Failed to read metadata from gs://chromeos-image-archive')
670 logger.error(
671 'Note, so far no quick way to look up version info for too old builds')
672
673 return info
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800674
675
676def query_chrome_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800677 """Queries chrome version of chromeos build.
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800678
679 Args:
680 board: ChromeOS board name
681 version: ChromeOS version number in short or full format
682
683 Returns:
684 Chrome version number
685 """
686 info = version_info(board, version)
687 return info['cr_version']
Kuang-che Wu708310b2018-03-28 17:24:34 +0800688
689
690def query_android_build_id(board, rev):
691 info = version_info(board, rev)
692 rev = info['android_build_id']
693 return rev
694
695
696def query_android_branch(board, rev):
697 info = version_info(board, rev)
698 rev = info['android_branch']
699 return rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800700
701
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800702def guess_chrome_version(board, rev):
703 """Guess chrome version number.
704
705 Args:
706 board: chromeos board name
707 rev: chrome or chromeos version
708
709 Returns:
710 chrome version number
711 """
712 if is_cros_version(rev):
713 assert board, 'need to specify BOARD for cros version'
714 rev = query_chrome_version(board, rev)
715 assert cr_util.is_chrome_version(rev)
716
717 return rev
718
719
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800720def is_inside_chroot():
721 """Returns True if we are inside chroot."""
722 return os.path.exists('/etc/cros_chroot_version')
723
724
725def cros_sdk(chromeos_root, *args, **kwargs):
726 """Run commands inside chromeos chroot.
727
728 Args:
729 chromeos_root: chromeos tree root
730 *args: command to run
731 **kwargs:
Kuang-che Wud4603d72018-11-29 17:51:21 +0800732 chrome_root: pass to cros_sdk; mount this path into the SDK chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800733 env: (dict) environment variables for the command
734 stdin: standard input file handle for the command
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800735 stderr_callback: Callback function for stderr. Called once per line.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800736 """
737 envs = []
738 for k, v in kwargs.get('env', {}).items():
739 assert re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', k)
740 envs.append('%s=%s' % (k, v))
741
742 # Use --no-ns-pid to prevent cros_sdk change our pgid, otherwise subsequent
743 # commands would be considered as background process.
Kuang-che Wud4603d72018-11-29 17:51:21 +0800744 cmd = ['chromite/bin/cros_sdk', '--no-ns-pid']
745
746 if kwargs.get('chrome_root'):
747 cmd += ['--chrome_root', kwargs['chrome_root']]
748
749 cmd += envs + ['--'] + list(args)
750
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800751 return util.check_output(
752 *cmd,
753 cwd=chromeos_root,
754 stdin=kwargs.get('stdin'),
755 stderr_callback=kwargs.get('stderr_callback'))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800756
757
758def copy_into_chroot(chromeos_root, src, dst):
759 """Copies file into chromeos chroot.
760
761 Args:
762 chromeos_root: chromeos tree root
763 src: path outside chroot
764 dst: path inside chroot
765 """
766 # chroot may be an image, so we cannot copy to corresponding path
767 # directly.
768 cros_sdk(chromeos_root, 'sh', '-c', 'cat > %s' % dst, stdin=open(src))
769
770
771def exists_in_chroot(chromeos_root, path):
772 """Determine whether a path exists in the chroot.
773
774 Args:
775 chromeos_root: chromeos tree root
776 path: path inside chroot, relative to src/scripts
777
778 Returns:
779 True if a path exists
780 """
781 try:
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800782 cros_sdk(chromeos_root, 'test', '-e', path)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800783 except subprocess.CalledProcessError:
784 return False
785 return True
786
787
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800788def check_if_need_recreate_chroot(stdout, stderr):
789 """Analyze build log and determine if chroot should be recreated.
790
791 Args:
792 stdout: stdout output of build
793 stderr: stderr output of build
794
795 Returns:
796 the reason if chroot needs recreated; None otherwise
797 """
Kuang-che Wu74768d32018-09-07 12:03:24 +0800798 if re.search(
799 r"The current version of portage supports EAPI '\d+'. "
800 "You must upgrade", stderr):
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800801 return 'EAPI version mismatch'
802
Kuang-che Wu5ac81322018-11-26 14:04:06 +0800803 if 'Chroot is too new. Consider running:' in stderr:
804 return 'chroot version is too new'
805
806 # old message before Oct 2018
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800807 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
808 return 'chroot version is too new'
809
Kuang-che Wu6fe987f2018-08-28 15:24:20 +0800810 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
811 if "undefined reference to 'std::__1::basic_string" in stdout:
812 return 'might be due to compiler change'
813
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800814 return None
815
816
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800817def build_image(chromeos_root, board, rev):
818 """Build ChromeOS image.
819
820 Args:
821 chromeos_root: chromeos tree root
822 board: ChromeOS board name
823 rev: the version name to build
824
825 Returns:
826 Image path
827 """
828
829 # If the given version is already built, reuse it.
Kuang-che Wuf41599c2018-08-03 16:11:11 +0800830 image_name = 'bisect-%s' % rev.replace('/', '_')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800831 image_path = os.path.join('../build/images', board, image_name,
832 'chromiumos_test_image.bin')
833 if exists_in_chroot(chromeos_root, image_path):
834 logger.info('"%s" already exists, skip build step', image_path)
835 return image_path
836
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800837 script_name = 'build_cros_helper.sh'
Kuang-che Wu3b46aa42019-03-14 15:59:52 +0800838 copy_into_chroot(chromeos_root,
839 os.path.join(common.BISECT_KIT_ROOT, script_name),
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800840 script_name)
841 cros_sdk(chromeos_root, 'chmod', '+x', script_name)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800842
843 stderr_lines = []
844 try:
Kuang-che Wufb553102018-10-02 18:14:29 +0800845 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
846 cros_sdk(
847 chromeos_root,
848 './%s' % script_name,
849 board,
850 image_name,
851 stderr_callback=stderr_lines.append)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800852 except subprocess.CalledProcessError as e:
853 # Detect failures due to incompatibility between chroot and source tree. If
854 # so, notify the caller to recreate chroot and retry.
855 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
856 if reason:
857 raise NeedRecreateChrootException(reason)
858
859 # For other failures, don't know how to handle. Just bail out.
860 raise
861
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800862 return image_path
863
864
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800865class AutotestControlInfo(object):
866 """Parsed content of autotest control file.
867
868 Attributes:
869 name: test name
870 path: control file path
871 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
872 DOC, ATTRIBUTES, DEPENDENCIES, etc.
873 """
874
875 def __init__(self, path, variables):
876 self.name = variables['NAME']
877 self.path = path
878 self.variables = variables
879
880
881def parse_autotest_control_file(path):
882 """Parses autotest control file.
883
884 This only parses simple top-level string assignments.
885
886 Returns:
887 AutotestControlInfo object
888 """
889 variables = {}
890 code = ast.parse(open(path).read())
891 for stmt in code.body:
892 # Skip if not simple "NAME = *" assignment.
893 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
894 isinstance(stmt.targets[0], ast.Name)):
895 continue
896
897 # Only support string value.
898 if isinstance(stmt.value, ast.Str):
899 variables[stmt.targets[0].id] = stmt.value.s
900
901 return AutotestControlInfo(path, variables)
902
903
904def enumerate_autotest_control_files(autotest_dir):
905 """Enumerate autotest control files.
906
907 Args:
908 autotest_dir: autotest folder
909
910 Returns:
911 list of paths to control files
912 """
913 # Where to find control files. Relative to autotest_dir.
914 subpaths = [
915 'server/site_tests',
916 'client/site_tests',
917 'server/tests',
918 'client/tests',
919 ]
920
921 blacklist = ['site-packages', 'venv', 'results', 'logs', 'containers']
922 result = []
923 for subpath in subpaths:
924 path = os.path.join(autotest_dir, subpath)
925 for root, dirs, files in os.walk(path):
926
927 for black in blacklist:
928 if black in dirs:
929 dirs.remove(black)
930
931 for filename in files:
932 if filename == 'control' or filename.startswith('control.'):
933 result.append(os.path.join(root, filename))
934
935 return result
936
937
938def get_autotest_test_info(autotest_dir, test_name):
939 """Get metadata of given test.
940
941 Args:
942 autotest_dir: autotest folder
943 test_name: test name
944
945 Returns:
946 AutotestControlInfo object. None if test not found.
947 """
948 for control_file in enumerate_autotest_control_files(autotest_dir):
949 info = parse_autotest_control_file(control_file)
950 if info.name == test_name:
951 return info
952 return None
953
954
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800955class ChromeOSSpecManager(codechange.SpecManager):
956 """Repo manifest related operations.
957
958 This class enumerates chromeos manifest files, parses them,
959 and sync to disk state according to them.
960 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800961
962 def __init__(self, config):
963 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800964 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
965 'manifests')
966 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +0800967 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800968 if not os.path.exists(self.historical_manifest_git_dir):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800969 raise errors.InternalError('Manifest snapshots should be cloned into %s' %
970 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800971
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800972 def lookup_build_timestamp(self, rev):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800973 assert is_cros_full_version(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800974
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800975 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800976 path = os.path.join('buildspecs', milestone, short_version + '.xml')
977 try:
978 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
979 'refs/heads/master', path)
980 except ValueError:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800981 raise errors.InternalError(
Kuang-che Wu74768d32018-09-07 12:03:24 +0800982 '%s does not have %s' % (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800983 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800984
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800985 def collect_float_spec(self, old, new):
986 old_timestamp = self.lookup_build_timestamp(old)
987 new_timestamp = self.lookup_build_timestamp(new)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800988
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800989 path = os.path.join(self.manifest_dir, 'default.xml')
990 if not os.path.islink(path) or os.readlink(path) != 'full.xml':
Kuang-che Wue121fae2018-11-09 16:18:39 +0800991 raise errors.InternalError(
992 'default.xml not symlink to full.xml is not supported')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800993
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800994 result = []
995 path = 'full.xml'
996 parser = repo_util.ManifestParser(self.manifest_dir)
997 for timestamp, git_rev in parser.enumerate_manifest_commits(
998 old_timestamp, new_timestamp, path):
999 result.append(
1000 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
1001 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001002
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001003 def collect_fixed_spec(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001004 assert is_cros_full_version(old)
1005 assert is_cros_full_version(new)
1006 old_milestone, old_short_version = version_split(old)
1007 new_milestone, new_short_version = version_split(new)
1008
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001009 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001010 for milestone in git_util.list_dir_from_revision(
1011 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
1012 if not milestone.isdigit():
1013 continue
1014 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
1015 continue
1016
Kuang-che Wu74768d32018-09-07 12:03:24 +08001017 files = git_util.list_dir_from_revision(
1018 self.historical_manifest_git_dir, 'refs/heads/master',
1019 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001020
1021 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001022 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001023 short_version, ext = os.path.splitext(fn)
1024 if ext != '.xml':
1025 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001026 if (util.is_version_lesseq(old_short_version, short_version) and
1027 util.is_version_lesseq(short_version, new_short_version) and
1028 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001029 rev = make_cros_full_version(milestone, short_version)
1030 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
1031 'refs/heads/master', path)
1032 result.append(
1033 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001034
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001035 def version_key_func(spec):
1036 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001037 return util.version_key_func(short_version)
1038
1039 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001040 assert result[0].name == old
1041 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +08001042 return result
1043
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001044 def get_manifest(self, rev):
1045 assert is_cros_full_version(rev)
1046 milestone, short_version = version_split(rev)
1047 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
1048 manifest = git_util.get_file_from_revision(self.historical_manifest_git_dir,
1049 'refs/heads/master', path)
1050
1051 manifest_name = 'manifest_%s.xml' % rev
1052 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1053 with open(manifest_path, 'w') as f:
1054 f.write(manifest)
1055
1056 return manifest_name
1057
1058 def parse_spec(self, spec):
1059 parser = repo_util.ManifestParser(self.manifest_dir)
1060 if spec.spec_type == codechange.SPEC_FIXED:
1061 manifest_name = self.get_manifest(spec.name)
1062 manifest_path = os.path.join(self.manifest_dir, manifest_name)
1063 content = open(manifest_path).read()
1064 root = parser.parse_single_xml(content, allow_include=False)
1065 else:
1066 root = parser.parse_xml_recursive(spec.name, spec.path)
1067
1068 spec.entries = parser.process_parsed_result(root)
1069 if spec.spec_type == codechange.SPEC_FIXED:
1070 assert spec.is_static()
1071
1072 def sync_disk_state(self, rev):
1073 manifest_name = self.get_manifest(rev)
1074
1075 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
1076 # manifest. 'repo sync -m' is not enough
1077 repo_util.init(
1078 self.config['chromeos_root'],
1079 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
1080 manifest_name=manifest_name,
1081 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +08001082 reference=self.config['chromeos_mirror'],
Kuang-che Wue4bae0b2018-07-19 12:10:14 +08001083 )
1084
1085 # Note, don't sync with current_branch=True for chromeos. One of its
1086 # build steps (inside mark_as_stable) executes "git describe" which
1087 # needs git tag information.
1088 repo_util.sync(self.config['chromeos_root'])