blob: b59236f6dbd1eca60e89b7eef0cfcbc14751f59d [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 Wu44278142019-03-04 11:33:57 +0800117 errors.SshConnectionError: cannot connect to host
118 errors.ExternalError: lsb-release file doesn't exist
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800119 """
120 try:
Kuang-che Wu44278142019-03-04 11:33:57 +0800121 output = util.ssh_cmd(host, 'cat', '/etc/lsb-release')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800122 except subprocess.CalledProcessError:
Kuang-che Wu44278142019-03-04 11:33:57 +0800123 raise errors.ExternalError('unable to read /etc/lsb-release; 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 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800136 try:
137 return query_dut_lsb_release(host).get('DEVICETYPE') in [
138 'CHROMEBASE',
139 'CHROMEBIT',
140 'CHROMEBOOK',
141 'CHROMEBOX',
142 'REFERENCE',
143 ]
144 except (errors.ExternalError, errors.SshConnectionError):
145 return False
146
147
148def is_good_dut(host):
149 if not is_dut(host):
150 return False
151
152 # Sometimes python is broken after 'cros flash'.
153 try:
154 util.ssh_cmd(host, 'python', '-c', '1')
155 return True
156 except (subprocess.CalledProcessError, errors.SshConnectionError):
157 return False
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800158
159
160def query_dut_board(host):
161 """Query board name of a given DUT"""
162 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_BOARD')
163
164
165def query_dut_short_version(host):
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800166 """Query short version of a given DUT.
167
168 This function may return version of local build, which
169 is_cros_short_version() is false.
170 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800171 return query_dut_lsb_release(host).get('CHROMEOS_RELEASE_VERSION')
172
173
174def query_dut_boot_id(host, connect_timeout=None):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800175 """Query boot id.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800176
177 Args:
178 host: DUT address
179 connect_timeout: connection timeout
180
181 Returns:
182 boot uuid
183 """
Kuang-che Wu44278142019-03-04 11:33:57 +0800184 return util.ssh_cmd(
185 host,
186 'cat',
187 '/proc/sys/kernel/random/boot_id',
188 connect_timeout=connect_timeout).strip()
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800189
190
191def reboot(host):
192 """Reboot a DUT and verify"""
193 logger.debug('reboot %s', host)
194 boot_id = query_dut_boot_id(host)
195
196 # Depends on timing, ssh may return failure due to broken pipe,
Kuang-che Wu44278142019-03-04 11:33:57 +0800197 # so ignore any errors.
198 try:
199 util.ssh_cmd(host, 'reboot')
200 except subprocess.CalledProcessError:
201 pass
Kuang-che Wu708310b2018-03-28 17:24:34 +0800202 wait_reboot_done(host, boot_id)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800203
Kuang-che Wu708310b2018-03-28 17:24:34 +0800204
205def wait_reboot_done(host, boot_id):
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800206 # For dev-mode test image, the reboot time is roughly at least 16 seconds
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800207 # (dev screen short delay) or more (long delay).
208 time.sleep(15)
209 for _ in range(100):
210 try:
211 # During boot, DUT does not response and thus ssh may hang a while. So
212 # set a connect timeout. 3 seconds are enough and 2 are not. It's okay to
213 # set tight limit because it's inside retry loop.
214 assert boot_id != query_dut_boot_id(host, connect_timeout=3)
215 return
216 except subprocess.CalledProcessError:
217 logger.debug('reboot not ready? sleep wait 1 sec')
218 time.sleep(1)
219
Kuang-che Wue121fae2018-11-09 16:18:39 +0800220 raise errors.ExternalError('reboot failed?')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800221
222
223def gsutil(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800224 """gsutil command line wrapper.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800225
226 Args:
227 args: command line arguments passed to gsutil
228 kwargs:
229 ignore_errors: if true, return '' for failures, for example 'gsutil ls'
230 but the path not found.
231
232 Returns:
233 stdout of gsutil
234
235 Raises:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800236 errors.InternalError: gsutil failed to run
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800237 subprocess.CalledProcessError: command failed
238 """
239 stderr_lines = []
240 try:
241 return util.check_output(
242 gsutil_bin, *args, stderr_callback=stderr_lines.append)
243 except subprocess.CalledProcessError as e:
244 stderr = ''.join(stderr_lines)
245 if re.search(r'ServiceException:.* does not have .*access', stderr):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800246 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800247 'gsutil failed due to permission. ' +
248 'Run "%s config" and follow its instruction. ' % gsutil_bin +
249 'Fill any string if it asks for project-id')
250 if kwargs.get('ignore_errors'):
251 return ''
252 raise
253 except OSError as e:
254 if e.errno == errno.ENOENT:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800255 raise errors.ExternalError(
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800256 'Unable to run %s. gsutil is not installed or not in PATH?' %
257 gsutil_bin)
258 raise
259
260
261def gsutil_ls(*args, **kwargs):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800262 """gsutil ls.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800263
264 Args:
265 args: arguments passed to 'gsutil ls'
266 kwargs: extra parameters, where
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800267 ignore_errors: if true, return empty list instead of raising
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800268 exception, ex. path not found.
269
270 Returns:
271 list of 'gsutil ls' result. One element for one line of gsutil output.
272
273 Raises:
274 subprocess.CalledProcessError: gsutil failed, usually means path not found
275 """
276 return gsutil('ls', *args, **kwargs).splitlines()
277
278
279def query_milestone_by_version(board, short_version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800280 """Query milestone by ChromeOS version number.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800281
282 Args:
283 board: ChromeOS board name
284 short_version: ChromeOS version number in short format, ex. 9300.0.0
285
286 Returns:
287 ChromeOS milestone number (string). For example, '58' for '9300.0.0'.
288 None if failed.
289 """
290 path = gs_archive_path.format(board=board) + '/R*-' + short_version
291 for line in gsutil_ls('-d', path, ignore_errors=True):
292 m = re.search(r'/R(\d+)-', line)
293 if not m:
294 continue
295 return m.group(1)
296
297 for channel in ['canary', 'dev', 'beta', 'stable']:
298 path = gs_release_path.format(
299 channel=channel, board=board, short_version=short_version)
300 for line in gsutil_ls(path, ignore_errors=True):
301 m = re.search(r'\bR(\d+)-' + short_version, line)
302 if not m:
303 continue
304 return m.group(1)
305
306 logger.error('unable to query milestone of %s for %s', short_version, board)
307 return None
308
309
310def recognize_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800311 """Recognize ChromeOS version.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800312
313 Args:
314 board: ChromeOS board name
315 version: ChromeOS version number in short or full format
316
317 Returns:
318 (milestone, version in short format)
319 """
320 if is_cros_short_version(version):
321 milestone = query_milestone_by_version(board, version)
322 short_version = version
323 else:
324 milestone, short_version = version_split(version)
325 return milestone, short_version
326
327
328def version_to_short(version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800329 """Convert ChromeOS version number to short format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800330
331 Args:
332 version: ChromeOS version number in short or full format
333
334 Returns:
335 version number in short format
336 """
337 if is_cros_short_version(version):
338 return version
339 _, short_version = version_split(version)
340 return short_version
341
342
343def version_to_full(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800344 """Convert ChromeOS version number to full format.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800345
346 Args:
347 board: ChromeOS board name
348 version: ChromeOS version number in short or full format
349
350 Returns:
351 version number in full format
352 """
353 if is_cros_full_version(version):
354 return version
355 milestone = query_milestone_by_version(board, version)
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800356 assert milestone
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800357 return make_cros_full_version(milestone, version)
358
359
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800360def prepare_prebuilt_image(board, version):
361 """Prepare chromeos prebuilt image.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800362
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800363 It searches for xbuddy image which "cros flash" can use, or fetch image to
364 local disk.
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800365
366 Args:
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800367 board: ChromeOS board name
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800368 version: ChromeOS version number in short or full format
369
370 Returns:
371 xbuddy path or file path (outside chroot)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800372 """
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800373 assert is_cros_version(version)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800374 full_version = version_to_full(board, version)
375 short_version = version_to_short(full_version)
376
377 image_path = None
378 gs_path = gs_archive_path.format(board=board) + '/' + full_version
379 if gsutil_ls('-d', gs_path, ignore_errors=True):
380 image_path = 'xbuddy://remote/{board}/{full_version}/test'.format(
381 board=board, full_version=full_version)
382 else:
383 tmp_dir = 'tmp/ChromeOS-test-%s-%s' % (full_version, board)
384 if not os.path.exists(tmp_dir):
385 os.makedirs(tmp_dir)
386 # gs://chromeos-releases may have more old images than
Kuang-che Wu4fe945b2018-03-31 16:46:38 +0800387 # gs://chromeos-image-archive, but 'cros flash' doesn't support it. We have
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800388 # to fetch the image by ourselves
389 for channel in ['canary', 'dev', 'beta', 'stable']:
390 fn = 'ChromeOS-test-{full_version}-{board}.tar.xz'.format(
391 full_version=full_version, board=board)
392 gs_path = gs_release_path.format(
393 channel=channel, board=board, short_version=short_version)
394 gs_path += '/' + fn
395 if gsutil_ls(gs_path, ignore_errors=True):
396 # TODO(kcwu): delete tmp
397 gsutil('cp', gs_path, tmp_dir)
398 util.check_call('tar', 'Jxvf', fn, cwd=tmp_dir)
399 image_path = os.path.abspath(
400 os.path.join(tmp_dir, 'chromiumos_test_image.bin'))
401 break
402
403 assert image_path
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800404 return image_path
405
406
407def cros_flash(chromeos_root,
408 host,
409 board,
410 image_path,
411 version=None,
412 clobber_stateful=False,
Kuang-che Wu155fb6e2018-11-29 16:00:41 +0800413 disable_rootfs_verification=True):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800414 """Flash a DUT with given ChromeOS image.
415
416 This is implemented by 'cros flash' command line.
417
418 Args:
419 chromeos_root: use 'cros flash' of which chromeos tree
420 host: DUT address
421 board: ChromeOS board name
422 image_path: chromeos image xbuddy path or file path. If
423 run_inside_chroot is True, the file path is relative to src/scrips.
424 Otherwise, the file path is relative to chromeos_root.
425 version: ChromeOS version in short or full format
426 clobber_stateful: Clobber stateful partition when performing update
427 disable_rootfs_verification: Disable rootfs verification after update
428 is completed
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800429 """
430 logger.info('cros_flash %s %s %s %s', host, board, version, image_path)
431
432 # Reboot is necessary because sometimes previous 'cros flash' failed and
433 # entered a bad state.
434 reboot(host)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800435
Kuang-che Wu73e60172018-09-06 14:35:38 +0800436 args = ['--no-ping', '--send-payload-in-parallel', host, image_path]
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800437 if clobber_stateful:
438 args.append('--clobber-stateful')
439 if disable_rootfs_verification:
440 args.append('--disable-rootfs-verification')
441
Kuang-che Wu155fb6e2018-11-29 16:00:41 +0800442 cros_sdk(chromeos_root, 'cros', 'flash', *args)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800443
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800444 if version:
445 # In the past, cros flash may fail with returncode=0
446 # So let's have an extra check.
447 short_version = version_to_short(version)
448 dut_version = query_dut_short_version(host)
449 assert dut_version == short_version
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800450
451
452def version_info(board, version):
453 """Query subcomponents version info of given version of ChromeOS
454
455 Args:
456 board: ChromeOS board name
457 version: ChromeOS version number in short or full format
458
459 Returns:
460 dict of component and version info, including (if available):
461 cros_short_version: ChromeOS version
462 cros_full_version: ChromeOS version
463 milestone: milestone of ChromeOS
464 cr_version: Chrome version
Kuang-che Wu708310b2018-03-28 17:24:34 +0800465 android_build_id: Android build id
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800466 android_branch: Android branch, in format like 'git_nyc-mr1-arc'
467 """
468 info = {}
469 full_version = version_to_full(board, version)
470
471 # Some boards may have only partial-metadata.json but no metadata.json.
472 # e.g. caroline R60-9462.0.0
473 # Let's try both.
474 metadata = None
475 for metadata_filename in ['metadata.json', 'partial-metadata.json']:
476 path = gs_archive_path.format(board=board) + '/%s/%s' % (full_version,
477 metadata_filename)
478 metadata = gsutil('cat', path, ignore_errors=True)
479 if metadata:
480 o = json.loads(metadata)
481 v = o['version']
482 board_metadata = o['board-metadata'][board]
483 info.update({
484 VERSION_KEY_CROS_SHORT_VERSION: v['platform'],
485 VERSION_KEY_CROS_FULL_VERSION: v['full'],
486 VERSION_KEY_MILESTONE: v['milestone'],
487 VERSION_KEY_CR_VERSION: v['chrome'],
488 })
489
490 if 'android' in v:
Kuang-che Wu708310b2018-03-28 17:24:34 +0800491 info[VERSION_KEY_ANDROID_BUILD_ID] = v['android']
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800492 if 'android-branch' in v: # this appears since R58-9317.0.0
493 info[VERSION_KEY_ANDROID_BRANCH] = v['android-branch']
494 elif 'android-container-branch' in board_metadata:
495 info[VERSION_KEY_ANDROID_BRANCH] = v['android-container-branch']
496 break
497 else:
498 logger.error('Failed to read metadata from gs://chromeos-image-archive')
499 logger.error(
500 'Note, so far no quick way to look up version info for too old builds')
501
502 return info
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800503
504
505def query_chrome_version(board, version):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800506 """Queries chrome version of chromeos build.
Kuang-che Wu848b1af2018-02-01 20:59:36 +0800507
508 Args:
509 board: ChromeOS board name
510 version: ChromeOS version number in short or full format
511
512 Returns:
513 Chrome version number
514 """
515 info = version_info(board, version)
516 return info['cr_version']
Kuang-che Wu708310b2018-03-28 17:24:34 +0800517
518
519def query_android_build_id(board, rev):
520 info = version_info(board, rev)
521 rev = info['android_build_id']
522 return rev
523
524
525def query_android_branch(board, rev):
526 info = version_info(board, rev)
527 rev = info['android_branch']
528 return rev
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800529
530
Kuang-che Wu3eb6b502018-06-06 16:15:18 +0800531def guess_chrome_version(board, rev):
532 """Guess chrome version number.
533
534 Args:
535 board: chromeos board name
536 rev: chrome or chromeos version
537
538 Returns:
539 chrome version number
540 """
541 if is_cros_version(rev):
542 assert board, 'need to specify BOARD for cros version'
543 rev = query_chrome_version(board, rev)
544 assert cr_util.is_chrome_version(rev)
545
546 return rev
547
548
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800549def is_inside_chroot():
550 """Returns True if we are inside chroot."""
551 return os.path.exists('/etc/cros_chroot_version')
552
553
554def cros_sdk(chromeos_root, *args, **kwargs):
555 """Run commands inside chromeos chroot.
556
557 Args:
558 chromeos_root: chromeos tree root
559 *args: command to run
560 **kwargs:
Kuang-che Wud4603d72018-11-29 17:51:21 +0800561 chrome_root: pass to cros_sdk; mount this path into the SDK chroot
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800562 env: (dict) environment variables for the command
563 stdin: standard input file handle for the command
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800564 stderr_callback: Callback function for stderr. Called once per line.
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800565 """
566 envs = []
567 for k, v in kwargs.get('env', {}).items():
568 assert re.match(r'^[A-Za-z_][A-Za-z0-9_]*$', k)
569 envs.append('%s=%s' % (k, v))
570
571 # Use --no-ns-pid to prevent cros_sdk change our pgid, otherwise subsequent
572 # commands would be considered as background process.
Kuang-che Wud4603d72018-11-29 17:51:21 +0800573 cmd = ['chromite/bin/cros_sdk', '--no-ns-pid']
574
575 if kwargs.get('chrome_root'):
576 cmd += ['--chrome_root', kwargs['chrome_root']]
577
578 cmd += envs + ['--'] + list(args)
579
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800580 return util.check_output(
581 *cmd,
582 cwd=chromeos_root,
583 stdin=kwargs.get('stdin'),
584 stderr_callback=kwargs.get('stderr_callback'))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800585
586
587def copy_into_chroot(chromeos_root, src, dst):
588 """Copies file into chromeos chroot.
589
590 Args:
591 chromeos_root: chromeos tree root
592 src: path outside chroot
593 dst: path inside chroot
594 """
595 # chroot may be an image, so we cannot copy to corresponding path
596 # directly.
597 cros_sdk(chromeos_root, 'sh', '-c', 'cat > %s' % dst, stdin=open(src))
598
599
600def exists_in_chroot(chromeos_root, path):
601 """Determine whether a path exists in the chroot.
602
603 Args:
604 chromeos_root: chromeos tree root
605 path: path inside chroot, relative to src/scripts
606
607 Returns:
608 True if a path exists
609 """
610 try:
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800611 cros_sdk(chromeos_root, 'test', '-e', path)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800612 except subprocess.CalledProcessError:
613 return False
614 return True
615
616
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800617def check_if_need_recreate_chroot(stdout, stderr):
618 """Analyze build log and determine if chroot should be recreated.
619
620 Args:
621 stdout: stdout output of build
622 stderr: stderr output of build
623
624 Returns:
625 the reason if chroot needs recreated; None otherwise
626 """
Kuang-che Wu74768d32018-09-07 12:03:24 +0800627 if re.search(
628 r"The current version of portage supports EAPI '\d+'. "
629 "You must upgrade", stderr):
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800630 return 'EAPI version mismatch'
631
Kuang-che Wu5ac81322018-11-26 14:04:06 +0800632 if 'Chroot is too new. Consider running:' in stderr:
633 return 'chroot version is too new'
634
635 # old message before Oct 2018
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800636 if 'Chroot version is too new. Consider running cros_sdk --replace' in stderr:
637 return 'chroot version is too new'
638
Kuang-che Wu6fe987f2018-08-28 15:24:20 +0800639 # https://groups.google.com/a/chromium.org/forum/#!msg/chromium-os-dev/uzwT5APspB4/NFakFyCIDwAJ
640 if "undefined reference to 'std::__1::basic_string" in stdout:
641 return 'might be due to compiler change'
642
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800643 return None
644
645
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800646def build_image(chromeos_root, board, rev):
647 """Build ChromeOS image.
648
649 Args:
650 chromeos_root: chromeos tree root
651 board: ChromeOS board name
652 rev: the version name to build
653
654 Returns:
655 Image path
656 """
657
658 # If the given version is already built, reuse it.
Kuang-che Wuf41599c2018-08-03 16:11:11 +0800659 image_name = 'bisect-%s' % rev.replace('/', '_')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800660 image_path = os.path.join('../build/images', board, image_name,
661 'chromiumos_test_image.bin')
662 if exists_in_chroot(chromeos_root, image_path):
663 logger.info('"%s" already exists, skip build step', image_path)
664 return image_path
665
666 dirname = os.path.dirname(os.path.abspath(__file__))
667 script_name = 'build_cros_helper.sh'
668 copy_into_chroot(chromeos_root, os.path.join(dirname, '..', script_name),
669 script_name)
670 cros_sdk(chromeos_root, 'chmod', '+x', script_name)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800671
672 stderr_lines = []
673 try:
Kuang-che Wufb553102018-10-02 18:14:29 +0800674 with locking.lock_file(locking.LOCK_FILE_FOR_BUILD):
675 cros_sdk(
676 chromeos_root,
677 './%s' % script_name,
678 board,
679 image_name,
680 stderr_callback=stderr_lines.append)
Kuang-che Wu9890ce82018-07-07 15:14:10 +0800681 except subprocess.CalledProcessError as e:
682 # Detect failures due to incompatibility between chroot and source tree. If
683 # so, notify the caller to recreate chroot and retry.
684 reason = check_if_need_recreate_chroot(e.output, ''.join(stderr_lines))
685 if reason:
686 raise NeedRecreateChrootException(reason)
687
688 # For other failures, don't know how to handle. Just bail out.
689 raise
690
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800691 return image_path
692
693
Kuang-che Wub9705bd2018-06-28 17:59:18 +0800694class AutotestControlInfo(object):
695 """Parsed content of autotest control file.
696
697 Attributes:
698 name: test name
699 path: control file path
700 variables: dict of top-level control variables. Sample keys: NAME, AUTHOR,
701 DOC, ATTRIBUTES, DEPENDENCIES, etc.
702 """
703
704 def __init__(self, path, variables):
705 self.name = variables['NAME']
706 self.path = path
707 self.variables = variables
708
709
710def parse_autotest_control_file(path):
711 """Parses autotest control file.
712
713 This only parses simple top-level string assignments.
714
715 Returns:
716 AutotestControlInfo object
717 """
718 variables = {}
719 code = ast.parse(open(path).read())
720 for stmt in code.body:
721 # Skip if not simple "NAME = *" assignment.
722 if not (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and
723 isinstance(stmt.targets[0], ast.Name)):
724 continue
725
726 # Only support string value.
727 if isinstance(stmt.value, ast.Str):
728 variables[stmt.targets[0].id] = stmt.value.s
729
730 return AutotestControlInfo(path, variables)
731
732
733def enumerate_autotest_control_files(autotest_dir):
734 """Enumerate autotest control files.
735
736 Args:
737 autotest_dir: autotest folder
738
739 Returns:
740 list of paths to control files
741 """
742 # Where to find control files. Relative to autotest_dir.
743 subpaths = [
744 'server/site_tests',
745 'client/site_tests',
746 'server/tests',
747 'client/tests',
748 ]
749
750 blacklist = ['site-packages', 'venv', 'results', 'logs', 'containers']
751 result = []
752 for subpath in subpaths:
753 path = os.path.join(autotest_dir, subpath)
754 for root, dirs, files in os.walk(path):
755
756 for black in blacklist:
757 if black in dirs:
758 dirs.remove(black)
759
760 for filename in files:
761 if filename == 'control' or filename.startswith('control.'):
762 result.append(os.path.join(root, filename))
763
764 return result
765
766
767def get_autotest_test_info(autotest_dir, test_name):
768 """Get metadata of given test.
769
770 Args:
771 autotest_dir: autotest folder
772 test_name: test name
773
774 Returns:
775 AutotestControlInfo object. None if test not found.
776 """
777 for control_file in enumerate_autotest_control_files(autotest_dir):
778 info = parse_autotest_control_file(control_file)
779 if info.name == test_name:
780 return info
781 return None
782
783
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800784class ChromeOSSpecManager(codechange.SpecManager):
785 """Repo manifest related operations.
786
787 This class enumerates chromeos manifest files, parses them,
788 and sync to disk state according to them.
789 """
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800790
791 def __init__(self, config):
792 self.config = config
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800793 self.manifest_dir = os.path.join(self.config['chromeos_root'], '.repo',
794 'manifests')
795 self.historical_manifest_git_dir = os.path.join(
Kuang-che Wud8fc9572018-10-03 21:00:41 +0800796 self.config['chromeos_mirror'], 'chromeos/manifest-versions.git')
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800797 if not os.path.exists(self.historical_manifest_git_dir):
Kuang-che Wue121fae2018-11-09 16:18:39 +0800798 raise errors.InternalError('Manifest snapshots should be cloned into %s' %
799 self.historical_manifest_git_dir)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800800
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800801 def lookup_build_timestamp(self, rev):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800802 assert is_cros_full_version(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800803
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800804 milestone, short_version = version_split(rev)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800805 path = os.path.join('buildspecs', milestone, short_version + '.xml')
806 try:
807 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
808 'refs/heads/master', path)
809 except ValueError:
Kuang-che Wue121fae2018-11-09 16:18:39 +0800810 raise errors.InternalError(
Kuang-che Wu74768d32018-09-07 12:03:24 +0800811 '%s does not have %s' % (self.historical_manifest_git_dir, path))
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800812 return timestamp
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800813
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800814 def collect_float_spec(self, old, new):
815 old_timestamp = self.lookup_build_timestamp(old)
816 new_timestamp = self.lookup_build_timestamp(new)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800817
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800818 path = os.path.join(self.manifest_dir, 'default.xml')
819 if not os.path.islink(path) or os.readlink(path) != 'full.xml':
Kuang-che Wue121fae2018-11-09 16:18:39 +0800820 raise errors.InternalError(
821 'default.xml not symlink to full.xml is not supported')
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800822
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800823 result = []
824 path = 'full.xml'
825 parser = repo_util.ManifestParser(self.manifest_dir)
826 for timestamp, git_rev in parser.enumerate_manifest_commits(
827 old_timestamp, new_timestamp, path):
828 result.append(
829 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
830 return result
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800831
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800832 def collect_fixed_spec(self, old, new):
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800833 assert is_cros_full_version(old)
834 assert is_cros_full_version(new)
835 old_milestone, old_short_version = version_split(old)
836 new_milestone, new_short_version = version_split(new)
837
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800838 result = []
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800839 for milestone in git_util.list_dir_from_revision(
840 self.historical_manifest_git_dir, 'refs/heads/master', 'buildspecs'):
841 if not milestone.isdigit():
842 continue
843 if not int(old_milestone) <= int(milestone) <= int(new_milestone):
844 continue
845
Kuang-che Wu74768d32018-09-07 12:03:24 +0800846 files = git_util.list_dir_from_revision(
847 self.historical_manifest_git_dir, 'refs/heads/master',
848 os.path.join('buildspecs', milestone))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800849
850 for fn in files:
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800851 path = os.path.join('buildspecs', milestone, fn)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800852 short_version, ext = os.path.splitext(fn)
853 if ext != '.xml':
854 continue
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800855 if (util.is_version_lesseq(old_short_version, short_version) and
856 util.is_version_lesseq(short_version, new_short_version) and
857 util.is_direct_relative_version(short_version, new_short_version)):
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800858 rev = make_cros_full_version(milestone, short_version)
859 timestamp = git_util.get_commit_time(self.historical_manifest_git_dir,
860 'refs/heads/master', path)
861 result.append(
862 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800863
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800864 def version_key_func(spec):
865 _milestone, short_version = version_split(spec.name)
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800866 return util.version_key_func(short_version)
867
868 result.sort(key=version_key_func)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800869 assert result[0].name == old
870 assert result[-1].name == new
Kuang-che Wubfc4a642018-04-19 11:54:08 +0800871 return result
872
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800873 def get_manifest(self, rev):
874 assert is_cros_full_version(rev)
875 milestone, short_version = version_split(rev)
876 path = os.path.join('buildspecs', milestone, '%s.xml' % short_version)
877 manifest = git_util.get_file_from_revision(self.historical_manifest_git_dir,
878 'refs/heads/master', path)
879
880 manifest_name = 'manifest_%s.xml' % rev
881 manifest_path = os.path.join(self.manifest_dir, manifest_name)
882 with open(manifest_path, 'w') as f:
883 f.write(manifest)
884
885 return manifest_name
886
887 def parse_spec(self, spec):
888 parser = repo_util.ManifestParser(self.manifest_dir)
889 if spec.spec_type == codechange.SPEC_FIXED:
890 manifest_name = self.get_manifest(spec.name)
891 manifest_path = os.path.join(self.manifest_dir, manifest_name)
892 content = open(manifest_path).read()
893 root = parser.parse_single_xml(content, allow_include=False)
894 else:
895 root = parser.parse_xml_recursive(spec.name, spec.path)
896
897 spec.entries = parser.process_parsed_result(root)
898 if spec.spec_type == codechange.SPEC_FIXED:
899 assert spec.is_static()
900
901 def sync_disk_state(self, rev):
902 manifest_name = self.get_manifest(rev)
903
904 # For ChromeOS, mark_as_stable step requires 'repo init -m', which sticks
905 # manifest. 'repo sync -m' is not enough
906 repo_util.init(
907 self.config['chromeos_root'],
908 'https://chrome-internal.googlesource.com/chromeos/manifest-internal',
909 manifest_name=manifest_name,
910 repo_url='https://chromium.googlesource.com/external/repo.git',
Kuang-che Wud8fc9572018-10-03 21:00:41 +0800911 reference=self.config['chromeos_mirror'],
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800912 )
913
914 # Note, don't sync with current_branch=True for chromeos. One of its
915 # build steps (inside mark_as_stable) executes "git describe" which
916 # needs git tag information.
917 repo_util.sync(self.config['chromeos_root'])