blob: 59de98ba97906975ea49b97ea6b0c8effecbe571 [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 Wu3eb6b502018-06-06 16:15:18 +080025from bisect_kit import cr_util
Kuang-che Wue121fae2018-11-09 16:18:39 +080026from bisect_kit import errors
Kuang-che Wubfc4a642018-04-19 11:54:08 +080027from bisect_kit import git_util
Kuang-che Wufb553102018-10-02 18:14:29 +080028from bisect_kit import locking
Kuang-che Wubfc4a642018-04-19 11:54:08 +080029from bisect_kit import repo_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080030from bisect_kit import util
31
32logger = logging.getLogger(__name__)
33
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080034re_chromeos_full_version = r'^R\d+-\d+\.\d+\.\d+$'
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080035re_chromeos_localbuild_version = r'^\d+\.\d+\.\d{4}_\d\d_\d\d_\d{4}$'
36re_chromeos_short_version = r'^\d+\.\d+\.\d+$'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080037
38gs_archive_path = 'gs://chromeos-image-archive/{board}-release'
39gs_release_path = (
40 'gs://chromeos-releases/{channel}-channel/{board}/{short_version}')
41
42# Assume gsutil is in PATH.
43gsutil_bin = 'gsutil'
44
Kuang-che Wub9705bd2018-06-28 17:59:18 +080045chromeos_root_inside_chroot = '/mnt/host/source'
46# relative to chromeos_root
47prebuilt_autotest_dir = 'tmp/autotest-prebuilt'
48
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080049VERSION_KEY_CROS_SHORT_VERSION = 'cros_short_version'
50VERSION_KEY_CROS_FULL_VERSION = 'cros_full_version'
51VERSION_KEY_MILESTONE = 'milestone'
52VERSION_KEY_CR_VERSION = 'cr_version'
Kuang-che Wu708310b2018-03-28 17:24:34 +080053VERSION_KEY_ANDROID_BUILD_ID = 'android_build_id'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080054VERSION_KEY_ANDROID_BRANCH = 'android_branch'
55
56
Kuang-che Wu9890ce82018-07-07 15:14:10 +080057class NeedRecreateChrootException(Exception):
58 """Failed to build ChromeOS because of chroot mismatch or corruption"""
59
60
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080061def is_cros_short_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080062 """Determines if `s` is chromeos short version.
63
64 This function doesn't accept version number of local build.
65 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080066 return bool(re.match(re_chromeos_short_version, s))
67
68
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080069def is_cros_localbuild_version(s):
70 """Determines if `s` is chromeos local build version."""
71 return bool(re.match(re_chromeos_localbuild_version, s))
72
73
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080074def is_cros_full_version(s):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080075 """Determines if `s` is chromeos full 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_full_version, s))
80
81
82def is_cros_version(s):
83 """Determines if `s` is chromeos version (either short or full)"""
84 return is_cros_short_version(s) or is_cros_full_version(s)
85
86
87def make_cros_full_version(milestone, short_version):
88 """Makes full_version from milestone and short_version"""
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080089 assert milestone
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080090 return 'R%s-%s' % (milestone, short_version)
91
92
93def version_split(full_version):
94 """Splits full_version into milestone and short_version"""
95 assert is_cros_full_version(full_version)
96 milestone, short_version = full_version.split('-')
97 return milestone[1:], short_version
98
99
100def argtype_cros_version(s):
101 if not is_cros_version(s):
102 msg = 'invalid cros version'
103 raise cli.ArgTypeError(msg, '9876.0.0 or R62-9876.0.0')
104 return s
105
106
107def query_dut_lsb_release(host):
108 """Query /etc/lsb-release of given DUT
109
110 Args:
111 host: the DUT address
112
113 Returns:
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800114 dict for keys and values of /etc/lsb-release.
115
116 Raises:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800117 errors.ExecutionFatalError: cannot connect to host or lsb-release file
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800118 doesn't exist
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800119 """
120 try:
121 output = util.check_output('ssh', host, 'cat', '/etc/lsb-release')
122 except subprocess.CalledProcessError:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800123 raise errors.ExternalError('cannot connect to DUT or not a DUT')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800124 return dict(re.findall(r'^(\w+)=(.*)$', output, re.M))
125
126
127def is_dut(host):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800128 """Determines whether a host is a chromeos device.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800129
130 Args:
131 host: the DUT address
132
133 Returns:
134 True if the host is a chromeos device.
135 """
136 return query_dut_lsb_release(host).get('DEVICETYPE') in [
137 'CHROMEBASE',
138 'CHROMEBIT',
139 'CHROMEBOOK',
140 'CHROMEBOX',
141 'REFERENCE',
142 ]
143
144
145def query_dut_board(host):
146 """Query board name of a given DUT"""
147 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_BOARD')
148
149
150def query_dut_short_version(host):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800151 """Query short version of a given DUT.
152
153 This function may return version of local build, which
154 is_cros_short_version() is false.
155 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800156 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_VERSION')
157
158
159def query_dut_boot_id(host, connect_timeout=None):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800160 """Query boot id.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800161
162 Args:
163 host: DUT address
164 connect_timeout: connection timeout
165
166 Returns:
167 boot uuid
168 """
169 cmd = ['ssh']
170 if connect_timeout:
171 cmd += ['-oConnectTimeout=%d' % connect_timeout]
172 cmd += [host, 'cat', '/proc/sys/kernel/random/boot_id']
173 return util.check_output(*cmd).strip()
174
175
176def reboot(host):
177 """Reboot a DUT and verify"""
178 logger.debug('reboot %s', host)
179 boot_id = query_dut_boot_id(host)
180
181 # Depends on timing, ssh may return failure due to broken pipe,
182 # so don't check ssh return code.
183 util.call('ssh', host, 'reboot')
Kuang-che Wu708310b2018-03-28 17:24:34 +0800184 wait_reboot_done(host, boot_id)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800185
Kuang-che Wu708310b2018-03-28 17:24:34 +0800186
187def wait_reboot_done(host, boot_id):
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800188 # For dev-mode test image, the reboot time is roughly at least 16 seconds
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800189 # (dev screen short delay) or more (long delay).
190 time.sleep(15)
191 for _ in range(100):
192 try:
193 # During boot, DUT does not response and thus ssh may hang a while. So
194 # set a connect timeout. 3 seconds are enough and 2 are not. It's okay to
195 # set tight limit because it's inside retry loop.
196 assert boot_id != query_dut_boot_id(host, connect_timeout=3)
197 return
198 except subprocess.CalledProcessError:
199 logger.debug('reboot not ready? sleep wait 1 sec')
200 time.sleep(1)
201
Kuang-che Wue121fae2018-11-09 16:18:39 +0800202 raise errors.ExternalError('reboot failed?')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800203
204
205def gsutil(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800206 """gsutil command line wrapper.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800207
208 Args:
209 args: command line arguments passed to gsutil
210 kwargs:
211 ignore_errors: if true, return '' for failures, for example 'gsutil ls'
212 but the path not found.
213
214 Returns:
215 stdout of gsutil
216
217 Raises:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800218 errors.InternalError: gsutil failed to run
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800219 subprocess.CalledProcessError: command failed
220 """
221 stderr_lines = []
222 try:
223 return util.check_output(
224 gsutil_bin, *args, stderr_callback=stderr_lines.append)
225 except subprocess.CalledProcessError as e:
226 stderr = ''.join(stderr_lines)
227 if re.search(r'ServiceException:.* does not have .*access', stderr):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800228 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800229 'gsutil failed due to permission. ' +
230 'Run "%s config" and follow its instruction. ' % gsutil_bin +
231 'Fill any string if it asks for project-id')
232 if kwargs.get('ignore_errors'):
233 return ''
234 raise
235 except OSError as e:
236 if e.errno == errno.ENOENT:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800237 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800238 'Unable to run %s. gsutil is not installed or not in PATH?' %
239 gsutil_bin)
240 raise
241
242
243def gsutil_ls(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800244 """gsutil ls.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800245
246 Args:
247 args: arguments passed to 'gsutil ls'
248 kwargs: extra parameters, where
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800249 ignore_errors: if true, return empty list instead of raising
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800250 exception, ex. path not found.
251
252 Returns:
253 list of 'gsutil ls' result. One element for one line of gsutil output.
254
255 Raises:
256 subprocess.CalledProcessError: gsutil failed, usually means path not found
257 """
258 return gsutil('ls', *args, **kwargs).splitlines()
259
260
261def query_milestone_by_version(board, short_version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800262 """Query milestone by ChromeOS version number.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800263
264 Args:
265 board: ChromeOS board name
266 short_version: ChromeOS version number in short format, ex. 9300.0.0
267
268 Returns:
269 ChromeOS milestone number (string). For example, '58' for '9300.0.0'.
270 None if failed.
271 """
272 path = gs_archive_path.format(board=board) + '/R*-' + short_version
273 for line in gsutil_ls('-d', path, ignore_errors=True):
274 m = re.search(r'/R(\d+)-', line)
275 if not m:
276 continue
277 return m.group(1)
278
279 for channel in ['canary', 'dev', 'beta', 'stable']:
280 path = gs_release_path.format(
281 channel=channel, board=board, short_version=short_version)
282 for line in gsutil_ls(path, ignore_errors=True):
283 m = re.search(r'\bR(\d+)-' + short_version, line)
284 if not m:
285 continue
286 return m.group(1)
287
288 logger.error('unable to query milestone of %s for %s', short_version, board)
289 return None
290
291
292def recognize_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800293 """Recognize ChromeOS version.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800294
295 Args:
296 board: ChromeOS board name
297 version: ChromeOS version number in short or full format
298
299 Returns:
300 (milestone, version in short format)
301 """
302 if is_cros_short_version(version):
303 milestone = query_milestone_by_version(board, version)
304 short_version = version
305 else:
306 milestone, short_version = version_split(version)
307 return milestone, short_version
308
309
310def version_to_short(version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800311 """Convert ChromeOS version number to short format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800312
313 Args:
314 version: ChromeOS version number in short or full format
315
316 Returns:
317 version number in short format
318 """
319 if is_cros_short_version(version):
320 return version
321 _, short_version = version_split(version)
322 return short_version
323
324
325def version_to_full(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800326 """Convert ChromeOS version number to full format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800327
328 Args:
329 board: ChromeOS board name
330 version: ChromeOS version number in short or full format
331
332 Returns:
333 version number in full format
334 """
335 if is_cros_full_version(version):
336 return version
337 milestone = query_milestone_by_version(board, version)
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800338 assert milestone
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800339 return make_cros_full_version(milestone, version)
340
341
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800342def prepare_prebuilt_image(board, version):
343 """Prepare chromeos prebuilt image.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800344
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800345 It searches for xbuddy image which "cros flash" can use, or fetch image to
346 local disk.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800347
348 Args:
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800349 board: ChromeOS board name
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800350 version: ChromeOS version number in short or full format
351
352 Returns:
353 xbuddy path or file path (outside chroot)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800354 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800355 assert is_cros_version(version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800356 full_version = version_to_full(board, version)
357 short_version = version_to_short(full_version)
358
359 image_path = None
360 gs_path = gs_archive_path.format(board=board) + '/' + full_version
361 if gsutil_ls('-d', gs_path, ignore_errors=True):
362 image_path = 'xbuddy://remote/{board}/{full_version}/test'.format(
363 board=board, full_version=full_version)
364 else:
365 tmp_dir = 'tmp/ChromeOS-test-%s-%s' % (full_version, board)
366 if not os.path.exists(tmp_dir):
367 os.makedirs(tmp_dir)
368 # gs://chromeos-releases may have more old images than
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800369 # gs://chromeos-image-archive, but 'cros flash' doesn't support it. We have
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800370 # to fetch the image by ourselves
371 for channel in ['canary', 'dev', 'beta', 'stable']:
372 fn = 'ChromeOS-test-{full_version}-{board}.tar.xz'.format(
373 full_version=full_version, board=board)
374 gs_path = gs_release_path.format(
375 channel=channel, board=board, short_version=short_version)
376 gs_path += '/' + fn
377 if gsutil_ls(gs_path, ignore_errors=True):
378 # TODO(kcwu): delete tmp
379 gsutil('cp', gs_path, tmp_dir)
380 util.check_call('tar', 'Jxvf', fn, cwd=tmp_dir)
381 image_path = os.path.abspath(
382 os.path.join(tmp_dir, 'chromiumos_test_image.bin'))
383 break
384
385 assert image_path
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800386 return image_path
387
388
389def cros_flash(chromeos_root,
390 host,
391 board,
392 image_path,
393 version=None,
394 clobber_stateful=False,
395 disable_rootfs_verification=True,
396 run_inside_chroot=False):
397 """Flash a DUT with given ChromeOS image.
398
399 This is implemented by 'cros flash' command line.
400
401 Args:
402 chromeos_root: use 'cros flash' of which chromeos tree
403 host: DUT address
404 board: ChromeOS board name
405 image_path: chromeos image xbuddy path or file path. If
406 run_inside_chroot is True, the file path is relative to src/scrips.
407 Otherwise, the file path is relative to chromeos_root.
408 version: ChromeOS version in short or full format
409 clobber_stateful: Clobber stateful partition when performing update
410 disable_rootfs_verification: Disable rootfs verification after update
411 is completed
412 run_inside_chroot: if True, run 'cros flash' command inside the chroot
413 """
414 logger.info('cros_flash %s %s %s %s', host, board, version, image_path)
415
416 # Reboot is necessary because sometimes previous 'cros flash' failed and
417 # entered a bad state.
418 reboot(host)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800419
Kuang-che Wu73e60172018-09-06 14:35:38 +0800420 args = ['--no-ping', '--send-payload-in-parallel', host, image_path]
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800421 if clobber_stateful:
422 args.append('--clobber-stateful')
423 if disable_rootfs_verification:
424 args.append('--disable-rootfs-verification')
425
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800426 if run_inside_chroot:
427 cros_sdk(chromeos_root, 'cros', 'flash', *args)
428 else:
429 util.check_call('chromite/bin/cros', 'flash', *args, cwd=chromeos_root)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800430
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800431 if version:
432 # In the past, cros flash may fail with returncode=0
433 # So let's have an extra check.
434 short_version = version_to_short(version)
435 dut_version = query_dut_short_version(host)
436 assert dut_version == short_version
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800437
438
439def version_info(board, version):
440 """Query subcomponents version info of given version of ChromeOS
441
442 Args:
443 board: ChromeOS board name
444 version: ChromeOS version number in short or full format
445
446 Returns:
447 dict of component and version info, including (if available):
448 cros_short_version: ChromeOS version
449 cros_full_version: ChromeOS version
450 milestone: milestone of ChromeOS
451 cr_version: Chrome version
Kuang-che Wu708310b2018-03-28 17:24:34 +0800452 android_build_id: Android build id
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800453 android_branch: Android branch, in format like 'git_nyc-mr1-arc'
454 """
455 info = {}
456 full_version = version_to_full(board, version)
457
458 # Some boards may have only partial-metadata.json but no metadata.json.
459 # e.g. caroline R60-9462.0.0
460 # Let's try both.
461 metadata = None
462 for metadata_filename in ['metadata.json', 'partial-metadata.json']:
463 path = gs_archive_path.format(board=board) + '/%s/%s' % (full_version,
464 metadata_filename)
465 metadata = gsutil('cat', path, ignore_errors=True)
466 if metadata:
467 o = json.loads(metadata)
468 v = o['version']
469 board_metadata = o['board-metadata'][board]
470 info.update({
471 VERSION_KEY_CROS_SHORT_VERSION: v['platform'],
472 VERSION_KEY_CROS_FULL_VERSION: v['full'],
473 VERSION_KEY_MILESTONE: v['milestone'],
474 VERSION_KEY_CR_VERSION: v['chrome'],
475 })
476
477 if 'android' in v:
Kuang-che Wu708310b2018-03-28 17:24:34 +0800478 info[VERSION_KEY_ANDROID_BUILD_ID] = v['android']
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800479 if 'android-branch' in v: # this appears since R58-9317.0.0
480 info[VERSION_KEY_ANDROID_BRANCH] = v['android-branch']
481 elif 'android-container-branch' in board_metadata:
482 info[VERSION_KEY_ANDROID_BRANCH] = v['android-container-branch']
483 break
484 else:
485 logger.error('Failed to read metadata from gs://chromeos-image-archive')
486 logger.error(
487 'Note, so far no quick way to look up version info for too old builds')
488
489 return info
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800490
491
492def query_chrome_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800493 """Queries chrome version of chromeos build.
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800494
495 Args:
496 board: ChromeOS board name
497 version: ChromeOS version number in short or full format
498
499 Returns:
500 Chrome version number
501 """
502 info = version_info(board, version)
503 return info['cr_version']
Kuang-che Wu708310b2018-03-28 17:24:34 +0800504
505
506def query_android_build_id(board, rev):
507 info = version_info(board, rev)
508 rev = info['android_build_id']
509 return rev
510
511
512def query_android_branch(board, rev):
513 info = version_info(board, rev)
514 rev = info['android_branch']
515 return rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800516
517
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800518def guess_chrome_version(board, rev):
519 """Guess chrome version number.
520
521 Args:
522 board: chromeos board name
523 rev: chrome or chromeos version
524
525 Returns:
526 chrome version number
527 """
528 if is_cros_version(rev):
529 assert board, 'need to specify BOARD for cros version'
530 rev = query_chrome_version(board, rev)
531 assert cr_util.is_chrome_version(rev)
532
533 return rev
534
535
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800536def is_inside_chroot():
537 """Returns True if we are inside chroot."""
538 return os.path.exists('/etc/cros_chroot_version')
539
540
541def cros_sdk(chromeos_root, *args, **kwargs):
542 """Run commands inside chromeos chroot.
543
544 Args:
545 chromeos_root: chromeos tree root
546 *args: command to run
547 **kwargs:
548 env: (dict) environment variables for the command
549 stdin: standard input file handle for the command
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800550 stderr_callback: Callback function for stderr. Called once per line.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800551 """
552 envs = []
553 for k, v in kwargs.get('env', {}).items():
554 assert re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', k)
555 envs.append('%s=%s' % (k, v))
556
557 # Use --no-ns-pid to prevent cros_sdk change our pgid, otherwise subsequent
558 # commands would be considered as background process.
559 cmd = ['chromite/bin/cros_sdk', '--no-ns-pid'] + envs + ['--'] + list(args)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800560 return util.check_output(
561 *cmd,
562 cwd=chromeos_root,
563 stdin=kwargs.get('stdin'),
564 stderr_callback=kwargs.get('stderr_callback'))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800565
566
567def copy_into_chroot(chromeos_root, src, dst):
568 """Copies file into chromeos chroot.
569
570 Args:
571 chromeos_root: chromeos tree root
572 src: path outside chroot
573 dst: path inside chroot
574 """
575 # chroot may be an image, so we cannot copy to corresponding path
576 # directly.
577 cros_sdk(chromeos_root, 'sh', '-c', 'cat > %s' % dst, stdin=open(src))
578
579
580def exists_in_chroot(chromeos_root, path):
581 """Determine whether a path exists in the chroot.
582
583 Args:
584 chromeos_root: chromeos tree root
585 path: path inside chroot, relative to src/scripts
586
587 Returns:
588 True if a path exists
589 """
590 try:
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800591 cros_sdk(chromeos_root, 'test', '-e', path)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800592 except subprocess.CalledProcessError:
593 return False
594 return True
595
596
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800597def check_if_need_recreate_chroot(stdout, stderr):
598 """Analyze build log and determine if chroot should be recreated.
599
600 Args:
601 stdout: stdout output of build
602 stderr: stderr output of build
603
604 Returns:
605 the reason if chroot needs recreated; None otherwise
606 """
Kuang-che Wu74768d32018-09-07 12:03:24 +0800607 if re.search(
608 r"The current version of portage supports EAPI '\d+'. "
609 "You must upgrade", stderr):
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800610 return 'EAPI version mismatch'
611
Kuang-che Wu5ac81322018-11-26 14:04:06 +0800612 if 'Chroot is too new. Consider running:' in stderr:
613 return 'chroot version is too new'
614
615 # old message before Oct 2018
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800616 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
617 return 'chroot version is too new'
618
Kuang-che Wu6fe987f2018-08-28 15:24:20 +0800619 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
620 if "undefined reference to 'std::__1::basic_string" in stdout:
621 return 'might be due to compiler change'
622
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800623 return None
624
625
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800626def build_image(chromeos_root, board, rev):
627 """Build ChromeOS image.
628
629 Args:
630 chromeos_root: chromeos tree root
631 board: ChromeOS board name
632 rev: the version name to build
633
634 Returns:
635 Image path
636 """
637
638 # If the given version is already built, reuse it.
Kuang-che Wuf41599c2018-08-03 16:11:11 +0800639 image_name = 'bisect-%s' % rev.replace('/', '_')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800640 image_path = os.path.join('../build/images', board, image_name,
641 'chromiumos_test_image.bin')
642 if exists_in_chroot(chromeos_root, image_path):
643 logger.info('"%s" already exists, skip build step', image_path)
644 return image_path
645
646 dirname = os.path.dirname(os.path.abspath(__file__))
647 script_name = 'build_cros_helper.sh'
648 copy_into_chroot(chromeos_root, os.path.join(dirname, '..', script_name),
649 script_name)
650 cros_sdk(chromeos_root, 'chmod', '+x', script_name)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800651
652 stderr_lines = []
653 try:
Kuang-che Wufb553102018-10-02 18:14:29 +0800654 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
655 cros_sdk(
656 chromeos_root,
657 './%s' % script_name,
658 board,
659 image_name,
660 stderr_callback=stderr_lines.append)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800661 except subprocess.CalledProcessError as e:
662 # Detect failures due to incompatibility between chroot and source tree. If
663 # so, notify the caller to recreate chroot and retry.
664 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
665 if reason:
666 raise NeedRecreateChrootException(reason)
667
668 # For other failures, don't know how to handle. Just bail out.
669 raise
670
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800671 return image_path
672
673
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800674class AutotestControlInfo(object):
675 """Parsed content of autotest control file.
676
677 Attributes:
678 name: test name
679 path: control file path
680 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
681 DOC, ATTRIBUTES, DEPENDENCIES, etc.
682 """
683
684 def __init__(self, path, variables):
685 self.name = variables['NAME']
686 self.path = path
687 self.variables = variables
688
689
690def parse_autotest_control_file(path):
691 """Parses autotest control file.
692
693 This only parses simple top-level string assignments.
694
695 Returns:
696 AutotestControlInfo object
697 """
698 variables = {}
699 code = ast.parse(open(path).read())
700 for stmt in code.body:
701 # Skip if not simple "NAME = *" assignment.
702 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
703 isinstance(stmt.targets[0], ast.Name)):
704 continue
705
706 # Only support string value.
707 if isinstance(stmt.value, ast.Str):
708 variables[stmt.targets[0].id] = stmt.value.s
709
710 return AutotestControlInfo(path, variables)
711
712
713def enumerate_autotest_control_files(autotest_dir):
714 """Enumerate autotest control files.
715
716 Args:
717 autotest_dir: autotest folder
718
719 Returns:
720 list of paths to control files
721 """
722 # Where to find control files. Relative to autotest_dir.
723 subpaths = [
724 'server/site_tests',
725 'client/site_tests',
726 'server/tests',
727 'client/tests',
728 ]
729
730 blacklist = ['site-packages', 'venv', 'results', 'logs', 'containers']
731 result = []
732 for subpath in subpaths:
733 path = os.path.join(autotest_dir, subpath)
734 for root, dirs, files in os.walk(path):
735
736 for black in blacklist:
737 if black in dirs:
738 dirs.remove(black)
739
740 for filename in files:
741 if filename == 'control' or filename.startswith('control.'):
742 result.append(os.path.join(root, filename))
743
744 return result
745
746
747def get_autotest_test_info(autotest_dir, test_name):
748 """Get metadata of given test.
749
750 Args:
751 autotest_dir: autotest folder
752 test_name: test name
753
754 Returns:
755 AutotestControlInfo object. None if test not found.
756 """
757 for control_file in enumerate_autotest_control_files(autotest_dir):
758 info = parse_autotest_control_file(control_file)
759 if info.name == test_name:
760 return info
761 return None
762
763
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800764class ChromeOSSpecManager(codechange.SpecManager):
765 """Repo manifest related operations.
766
767 This class enumerates chromeos manifest files, parses them,
768 and sync to disk state according to them.
769 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800770
771 def __init__(self, config):
772 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800773 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
774 'manifests')
775 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +0800776 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800777 if not os.path.exists(self.historical_manifest_git_dir):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800778 raise errors.InternalError('Manifest snapshots should be cloned into %s' %
779 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800780
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800781 def lookup_build_timestamp(self, rev):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800782 assert is_cros_full_version(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800783
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800784 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800785 path = os.path.join('buildspecs', milestone, short_version + '.xml')
786 try:
787 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
788 'refs/heads/master', path)
789 except ValueError:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800790 raise errors.InternalError(
Kuang-che Wu74768d32018-09-07 12:03:24 +0800791 '%s does not have %s' % (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800792 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800793
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800794 def collect_float_spec(self, old, new):
795 old_timestamp = self.lookup_build_timestamp(old)
796 new_timestamp = self.lookup_build_timestamp(new)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800797
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800798 path = os.path.join(self.manifest_dir, 'default.xml')
799 if not os.path.islink(path) or os.readlink(path) != 'full.xml':
Kuang-che Wue121fae2018-11-09 16:18:39 +0800800 raise errors.InternalError(
801 'default.xml not symlink to full.xml is not supported')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800802
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800803 result = []
804 path = 'full.xml'
805 parser = repo_util.ManifestParser(self.manifest_dir)
806 for timestamp, git_rev in parser.enumerate_manifest_commits(
807 old_timestamp, new_timestamp, path):
808 result.append(
809 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
810 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800811
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800812 def collect_fixed_spec(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800813 assert is_cros_full_version(old)
814 assert is_cros_full_version(new)
815 old_milestone, old_short_version = version_split(old)
816 new_milestone, new_short_version = version_split(new)
817
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800818 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800819 for milestone in git_util.list_dir_from_revision(
820 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
821 if not milestone.isdigit():
822 continue
823 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
824 continue
825
Kuang-che Wu74768d32018-09-07 12:03:24 +0800826 files = git_util.list_dir_from_revision(
827 self.historical_manifest_git_dir, 'refs/heads/master',
828 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800829
830 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800831 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800832 short_version, ext = os.path.splitext(fn)
833 if ext != '.xml':
834 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800835 if (util.is_version_lesseq(old_short_version, short_version) and
836 util.is_version_lesseq(short_version, new_short_version) and
837 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800838 rev = make_cros_full_version(milestone, short_version)
839 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
840 'refs/heads/master', path)
841 result.append(
842 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800843
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800844 def version_key_func(spec):
845 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800846 return util.version_key_func(short_version)
847
848 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800849 assert result[0].name == old
850 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800851 return result
852
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800853 def get_manifest(self, rev):
854 assert is_cros_full_version(rev)
855 milestone, short_version = version_split(rev)
856 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
857 manifest = git_util.get_file_from_revision(self.historical_manifest_git_dir,
858 'refs/heads/master', path)
859
860 manifest_name = 'manifest_%s.xml' % rev
861 manifest_path = os.path.join(self.manifest_dir, manifest_name)
862 with open(manifest_path, 'w') as f:
863 f.write(manifest)
864
865 return manifest_name
866
867 def parse_spec(self, spec):
868 parser = repo_util.ManifestParser(self.manifest_dir)
869 if spec.spec_type == codechange.SPEC_FIXED:
870 manifest_name = self.get_manifest(spec.name)
871 manifest_path = os.path.join(self.manifest_dir, manifest_name)
872 content = open(manifest_path).read()
873 root = parser.parse_single_xml(content, allow_include=False)
874 else:
875 root = parser.parse_xml_recursive(spec.name, spec.path)
876
877 spec.entries = parser.process_parsed_result(root)
878 if spec.spec_type == codechange.SPEC_FIXED:
879 assert spec.is_static()
880
881 def sync_disk_state(self, rev):
882 manifest_name = self.get_manifest(rev)
883
884 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
885 # manifest. 'repo sync -m' is not enough
886 repo_util.init(
887 self.config['chromeos_root'],
888 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
889 manifest_name=manifest_name,
890 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +0800891 reference=self.config['chromeos_mirror'],
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800892 )
893
894 # Note, don't sync with current_branch=True for chromeos. One of its
895 # build steps (inside mark_as_stable) executes "git describe" which
896 # needs git tag information.
897 repo_util.sync(self.config['chromeos_root'])