blob: 9cb600d000a5f581a7118e475a94c2097c62153d [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 Wu2ea804f2017-11-28 17:11:41 +080025from bisect_kit import core
Kuang-che Wu3eb6b502018-06-06 16:15:18 +080026from bisect_kit import cr_util
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:
117 core.ExecutionFatalError: cannot connect to host or lsb-release file
118 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 Wu3eb6b502018-06-06 16:15:18 +0800123 raise core.ExecutionFatalError('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
202 raise core.ExecutionFatalError('reboot failed?')
203
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:
218 core.ExecutionFatalError: gsutil failed to run
219 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):
228 raise core.ExecutionFatalError(
229 '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:
237 raise core.ExecutionFatalError(
238 '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
612 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
613 return 'chroot version is too new'
614
Kuang-che Wu6fe987f2018-08-28 15:24:20 +0800615 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
616 if "undefined reference to 'std::__1::basic_string" in stdout:
617 return 'might be due to compiler change'
618
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800619 return None
620
621
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800622def build_image(chromeos_root, board, rev):
623 """Build ChromeOS image.
624
625 Args:
626 chromeos_root: chromeos tree root
627 board: ChromeOS board name
628 rev: the version name to build
629
630 Returns:
631 Image path
632 """
633
634 # If the given version is already built, reuse it.
Kuang-che Wuf41599c2018-08-03 16:11:11 +0800635 image_name = 'bisect-%s' % rev.replace('/', '_')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800636 image_path = os.path.join('../build/images', board, image_name,
637 'chromiumos_test_image.bin')
638 if exists_in_chroot(chromeos_root, image_path):
639 logger.info('"%s" already exists, skip build step', image_path)
640 return image_path
641
642 dirname = os.path.dirname(os.path.abspath(__file__))
643 script_name = 'build_cros_helper.sh'
644 copy_into_chroot(chromeos_root, os.path.join(dirname, '..', script_name),
645 script_name)
646 cros_sdk(chromeos_root, 'chmod', '+x', script_name)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800647
648 stderr_lines = []
649 try:
Kuang-che Wufb553102018-10-02 18:14:29 +0800650 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
651 cros_sdk(
652 chromeos_root,
653 './%s' % script_name,
654 board,
655 image_name,
656 stderr_callback=stderr_lines.append)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800657 except subprocess.CalledProcessError as e:
658 # Detect failures due to incompatibility between chroot and source tree. If
659 # so, notify the caller to recreate chroot and retry.
660 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
661 if reason:
662 raise NeedRecreateChrootException(reason)
663
664 # For other failures, don't know how to handle. Just bail out.
665 raise
666
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800667 return image_path
668
669
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800670class AutotestControlInfo(object):
671 """Parsed content of autotest control file.
672
673 Attributes:
674 name: test name
675 path: control file path
676 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
677 DOC, ATTRIBUTES, DEPENDENCIES, etc.
678 """
679
680 def __init__(self, path, variables):
681 self.name = variables['NAME']
682 self.path = path
683 self.variables = variables
684
685
686def parse_autotest_control_file(path):
687 """Parses autotest control file.
688
689 This only parses simple top-level string assignments.
690
691 Returns:
692 AutotestControlInfo object
693 """
694 variables = {}
695 code = ast.parse(open(path).read())
696 for stmt in code.body:
697 # Skip if not simple "NAME = *" assignment.
698 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
699 isinstance(stmt.targets[0], ast.Name)):
700 continue
701
702 # Only support string value.
703 if isinstance(stmt.value, ast.Str):
704 variables[stmt.targets[0].id] = stmt.value.s
705
706 return AutotestControlInfo(path, variables)
707
708
709def enumerate_autotest_control_files(autotest_dir):
710 """Enumerate autotest control files.
711
712 Args:
713 autotest_dir: autotest folder
714
715 Returns:
716 list of paths to control files
717 """
718 # Where to find control files. Relative to autotest_dir.
719 subpaths = [
720 'server/site_tests',
721 'client/site_tests',
722 'server/tests',
723 'client/tests',
724 ]
725
726 blacklist = ['site-packages', 'venv', 'results', 'logs', 'containers']
727 result = []
728 for subpath in subpaths:
729 path = os.path.join(autotest_dir, subpath)
730 for root, dirs, files in os.walk(path):
731
732 for black in blacklist:
733 if black in dirs:
734 dirs.remove(black)
735
736 for filename in files:
737 if filename == 'control' or filename.startswith('control.'):
738 result.append(os.path.join(root, filename))
739
740 return result
741
742
743def get_autotest_test_info(autotest_dir, test_name):
744 """Get metadata of given test.
745
746 Args:
747 autotest_dir: autotest folder
748 test_name: test name
749
750 Returns:
751 AutotestControlInfo object. None if test not found.
752 """
753 for control_file in enumerate_autotest_control_files(autotest_dir):
754 info = parse_autotest_control_file(control_file)
755 if info.name == test_name:
756 return info
757 return None
758
759
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800760class ChromeOSSpecManager(codechange.SpecManager):
761 """Repo manifest related operations.
762
763 This class enumerates chromeos manifest files, parses them,
764 and sync to disk state according to them.
765 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800766
767 def __init__(self, config):
768 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800769 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
770 'manifests')
771 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +0800772 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800773 if not os.path.exists(self.historical_manifest_git_dir):
774 raise core.ExecutionFatalError(
775 'Manifest snapshots should be cloned into %s' %
776 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800777
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800778 def lookup_build_timestamp(self, rev):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800779 assert is_cros_full_version(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800780
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800781 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800782 path = os.path.join('buildspecs', milestone, short_version + '.xml')
783 try:
784 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
785 'refs/heads/master', path)
786 except ValueError:
Kuang-che Wu74768d32018-09-07 12:03:24 +0800787 raise core.ExecutionFatalError(
788 '%s does not have %s' % (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800789 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800790
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800791 def collect_float_spec(self, old, new):
792 old_timestamp = self.lookup_build_timestamp(old)
793 new_timestamp = self.lookup_build_timestamp(new)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800794
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800795 path = os.path.join(self.manifest_dir, 'default.xml')
796 if not os.path.islink(path) or os.readlink(path) != 'full.xml':
797 raise Exception('default.xml not symlink to full.xml is not supported')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800798
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800799 result = []
800 path = 'full.xml'
801 parser = repo_util.ManifestParser(self.manifest_dir)
802 for timestamp, git_rev in parser.enumerate_manifest_commits(
803 old_timestamp, new_timestamp, path):
804 result.append(
805 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
806 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800807
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800808 def collect_fixed_spec(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800809 assert is_cros_full_version(old)
810 assert is_cros_full_version(new)
811 old_milestone, old_short_version = version_split(old)
812 new_milestone, new_short_version = version_split(new)
813
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800814 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800815 for milestone in git_util.list_dir_from_revision(
816 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
817 if not milestone.isdigit():
818 continue
819 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
820 continue
821
Kuang-che Wu74768d32018-09-07 12:03:24 +0800822 files = git_util.list_dir_from_revision(
823 self.historical_manifest_git_dir, 'refs/heads/master',
824 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800825
826 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800827 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800828 short_version, ext = os.path.splitext(fn)
829 if ext != '.xml':
830 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800831 if (util.is_version_lesseq(old_short_version, short_version) and
832 util.is_version_lesseq(short_version, new_short_version) and
833 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800834 rev = make_cros_full_version(milestone, short_version)
835 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
836 'refs/heads/master', path)
837 result.append(
838 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800839
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800840 def version_key_func(spec):
841 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800842 return util.version_key_func(short_version)
843
844 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800845 assert result[0].name == old
846 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800847 return result
848
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800849 def get_manifest(self, rev):
850 assert is_cros_full_version(rev)
851 milestone, short_version = version_split(rev)
852 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
853 manifest = git_util.get_file_from_revision(self.historical_manifest_git_dir,
854 'refs/heads/master', path)
855
856 manifest_name = 'manifest_%s.xml' % rev
857 manifest_path = os.path.join(self.manifest_dir, manifest_name)
858 with open(manifest_path, 'w') as f:
859 f.write(manifest)
860
861 return manifest_name
862
863 def parse_spec(self, spec):
864 parser = repo_util.ManifestParser(self.manifest_dir)
865 if spec.spec_type == codechange.SPEC_FIXED:
866 manifest_name = self.get_manifest(spec.name)
867 manifest_path = os.path.join(self.manifest_dir, manifest_name)
868 content = open(manifest_path).read()
869 root = parser.parse_single_xml(content, allow_include=False)
870 else:
871 root = parser.parse_xml_recursive(spec.name, spec.path)
872
873 spec.entries = parser.process_parsed_result(root)
874 if spec.spec_type == codechange.SPEC_FIXED:
875 assert spec.is_static()
876
877 def sync_disk_state(self, rev):
878 manifest_name = self.get_manifest(rev)
879
880 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
881 # manifest. 'repo sync -m' is not enough
882 repo_util.init(
883 self.config['chromeos_root'],
884 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
885 manifest_name=manifest_name,
886 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +0800887 reference=self.config['chromeos_mirror'],
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800888 )
889
890 # Note, don't sync with current_branch=True for chromeos. One of its
891 # build steps (inside mark_as_stable) executes "git describe" which
892 # needs git tag information.
893 repo_util.sync(self.config['chromeos_root'])