blob: 29acbeaa48591a72be80666d48a9b8f4fc03cce7 [file] [log] [blame]
Chris Sosa5e4246b2012-05-22 18:05:22 -07001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Sean O'Connor5346e4e2010-08-12 18:49:24 +02002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Don Garrett56b1cc82013-12-06 17:49:20 -08005import glob
Sean O'Connor5346e4e2010-08-12 18:49:24 +02006import logging
Dale Curtis5c32c722011-05-04 19:24:23 -07007import os
Sean O'Connor5346e4e2010-08-12 18:49:24 +02008import re
Prashanth B32baa9b2014-03-13 13:23:01 -07009import urllib2
Richard Barnette0beb14b2018-05-15 18:07:52 +000010import urlparse
Sean O'Connor5346e4e2010-08-12 18:49:24 +020011
Chris Sosa65425082013-10-16 13:26:22 -070012from autotest_lib.client.bin import utils
Dale Curtis5c32c722011-05-04 19:24:23 -070013from autotest_lib.client.common_lib import error, global_config
Prashanth B32baa9b2014-03-13 13:23:01 -070014from autotest_lib.client.common_lib.cros import dev_server
Richard Barnette0beb14b2018-05-15 18:07:52 +000015from autotest_lib.server import autotest
Shelley Chen61d28982016-10-28 09:40:20 -070016from autotest_lib.server import utils as server_utils
Richard Barnette0beb14b2018-05-15 18:07:52 +000017from autotest_lib.server.cros.dynamic_suite import constants as ds_constants
18from autotest_lib.server.cros.dynamic_suite import tools
Luigi Semenzatoe76d9f82016-11-21 11:15:10 -080019from chromite.lib import retry_util
Dan Shif3a35f72016-01-25 11:18:14 -080020
Shelley Chen16b8df32016-10-27 16:24:21 -070021try:
22 from chromite.lib import metrics
Dan Shi5e2efb72017-02-07 11:40:23 -080023except ImportError:
24 metrics = utils.metrics_mock
Sean O'Connor5346e4e2010-08-12 18:49:24 +020025
Gwendal Grignou3e96cc22017-06-07 16:22:51 -070026
Richard Barnette621a8e42018-06-25 17:34:11 -070027def _metric_name(base_name):
28 return 'chromeos/autotest/provision/' + base_name
29
30
Dale Curtis5c32c722011-05-04 19:24:23 -070031# Local stateful update path is relative to the CrOS source directory.
Sean O'Connor5346e4e2010-08-12 18:49:24 +020032UPDATER_IDLE = 'UPDATE_STATUS_IDLE'
Sean Oc053dfe2010-08-23 18:22:26 +020033UPDATER_NEED_REBOOT = 'UPDATE_STATUS_UPDATED_NEED_REBOOT'
beeps5e8c45a2013-12-17 22:05:11 -080034# A list of update engine client states that occur after an update is triggered.
35UPDATER_PROCESSING_UPDATE = ['UPDATE_STATUS_CHECKING_FORUPDATE',
36 'UPDATE_STATUS_UPDATE_AVAILABLE',
37 'UPDATE_STATUS_DOWNLOADING',
38 'UPDATE_STATUS_FINALIZING']
Sean O'Connor5346e4e2010-08-12 18:49:24 +020039
Richard Barnette0beb14b2018-05-15 18:07:52 +000040
Richard Barnette3e8b2282018-05-15 20:42:20 +000041_STATEFUL_UPDATE_SCRIPT = 'stateful_update'
Richard Barnettee86b1ce2018-06-07 10:37:23 -070042_QUICK_PROVISION_SCRIPT = 'quick-provision'
Richard Barnette3e8b2282018-05-15 20:42:20 +000043
44_UPDATER_BIN = '/usr/bin/update_engine_client'
45_UPDATER_LOGS = ['/var/log/messages', '/var/log/update_engine']
46
47_KERNEL_A = {'name': 'KERN-A', 'kernel': 2, 'root': 3}
48_KERNEL_B = {'name': 'KERN-B', 'kernel': 4, 'root': 5}
49
50# Time to wait for new kernel to be marked successful after
51# auto update.
52_KERNEL_UPDATE_TIMEOUT = 120
53
54
Richard Barnette0beb14b2018-05-15 18:07:52 +000055# PROVISION_FAILED - A flag file to indicate provision failures. The
56# file is created at the start of any AU procedure (see
Richard Barnette9d43e562018-06-05 17:20:10 +000057# `ChromiumOSUpdater._prepare_host()`). The file's location in
Richard Barnette0beb14b2018-05-15 18:07:52 +000058# stateful means that on successul update it will be removed. Thus, if
59# this file exists, it indicates that we've tried and failed in a
60# previous attempt to update.
61PROVISION_FAILED = '/var/tmp/provision_failed'
62
63
Richard Barnette3e8b2282018-05-15 20:42:20 +000064# A flag file used to enable special handling in lab DUTs. Some
65# parts of the system in Chromium OS test images will behave in ways
66# convenient to the test lab when this file is present. Generally,
67# we create this immediately after any update completes.
68_LAB_MACHINE_FILE = '/mnt/stateful_partition/.labmachine'
69
70
Richard Barnette3ef29a82018-06-28 13:52:54 -070071# _TARGET_VERSION - A file containing the new version to which we plan
72# to update. This file is used by the CrOS shutdown code to detect and
73# handle certain version downgrade cases. Specifically: Downgrading
74# may trigger an unwanted powerwash in the target build when the
75# following conditions are met:
76# * Source build is a v4.4 kernel with R69-10756.0.0 or later.
77# * Target build predates the R69-10756.0.0 cutoff.
78# When this file is present and indicates a downgrade, the OS shutdown
79# code on the DUT knows how to prevent the powerwash.
80_TARGET_VERSION = '/run/update_target_version'
81
82
Richard Barnette5adb6d42018-06-28 15:52:32 -070083# _REBOOT_FAILURE_MESSAGE - This is the standard message text returned
84# when the Host.reboot() method fails. The source of this text comes
85# from `wait_for_restart()` in client/common_lib/hosts/base_classes.py.
86
87_REBOOT_FAILURE_MESSAGE = 'Host did not return from reboot'
88
89
Richard Barnette9d43e562018-06-05 17:20:10 +000090class RootFSUpdateError(error.TestFail):
Chris Sosa77556d82012-04-05 15:23:14 -070091 """Raised when the RootFS fails to update."""
Chris Sosa77556d82012-04-05 15:23:14 -070092
93
Richard Barnette9d43e562018-06-05 17:20:10 +000094class StatefulUpdateError(error.TestFail):
Chris Sosa77556d82012-04-05 15:23:14 -070095 """Raised when the stateful partition fails to update."""
Chris Sosa77556d82012-04-05 15:23:14 -070096
97
Richard Barnette9d43e562018-06-05 17:20:10 +000098class _AttributedUpdateError(error.TestFail):
99 """Update failure with an attributed cause."""
100
101 def __init__(self, attribution, msg):
102 super(_AttributedUpdateError, self).__init__(
103 '%s: %s' % (attribution, msg))
Richard Barnette5adb6d42018-06-28 15:52:32 -0700104 self._message = msg
105
106 def _classify(self):
107 for err_pattern, classification in self._CLASSIFIERS:
108 if re.match(err_pattern, self._message):
109 return classification
110 return None
111
112 @property
113 def failure_summary(self):
114 """Summarize this error for metrics reporting."""
115 classification = self._classify()
116 if classification:
117 return '%s: %s' % (self._SUMMARY, classification)
118 else:
119 return self._SUMMARY
Richard Barnette9d43e562018-06-05 17:20:10 +0000120
121
122class HostUpdateError(_AttributedUpdateError):
123 """Failure updating a DUT attributable to the DUT.
124
125 This class of exception should be raised when the most likely cause
126 of failure was a condition existing on the DUT prior to the update,
127 such as a hardware problem, or a bug in the software on the DUT.
128 """
129
Richard Barnette5adb6d42018-06-28 15:52:32 -0700130 DUT_DOWN = 'No answer to ssh'
131
132 _SUMMARY = 'DUT failed prior to update'
133 _CLASSIFIERS = [
134 (DUT_DOWN, DUT_DOWN),
135 (_REBOOT_FAILURE_MESSAGE, 'Reboot failed'),
136 ]
137
Richard Barnette9d43e562018-06-05 17:20:10 +0000138 def __init__(self, hostname, msg):
139 super(HostUpdateError, self).__init__(
140 'Error on %s prior to update' % hostname, msg)
141
142
143class DevServerError(_AttributedUpdateError):
144 """Failure updating a DUT attributable to the devserver.
145
146 This class of exception should be raised when the most likely cause
147 of failure was the devserver serving the target image for update.
148 """
149
Richard Barnette5adb6d42018-06-28 15:52:32 -0700150 _SUMMARY = 'Devserver failed prior to update'
151 _CLASSIFIERS = []
152
Richard Barnette9d43e562018-06-05 17:20:10 +0000153 def __init__(self, devserver, msg):
154 super(DevServerError, self).__init__(
155 'Devserver error on %s' % devserver, msg)
156
157
158class ImageInstallError(_AttributedUpdateError):
159 """Failure updating a DUT when installing from the devserver.
160
161 This class of exception should be raised when the target DUT fails
162 to download and install the target image from the devserver, and
163 either the devserver or the DUT might be at fault.
164 """
165
Richard Barnette5adb6d42018-06-28 15:52:32 -0700166 _SUMMARY = 'Image failed to download and install'
167 _CLASSIFIERS = []
168
Richard Barnette9d43e562018-06-05 17:20:10 +0000169 def __init__(self, hostname, devserver, msg):
170 super(ImageInstallError, self).__init__(
171 'Download and install failed from %s onto %s'
172 % (devserver, hostname), msg)
173
174
175class NewBuildUpdateError(_AttributedUpdateError):
176 """Failure updating a DUT attributable to the target build.
177
178 This class of exception should be raised when updating to a new
179 build fails, and the most likely cause of the failure is a bug in
180 the newly installed target build.
181 """
182
Richard Barnette5adb6d42018-06-28 15:52:32 -0700183 CHROME_FAILURE = 'Chrome failed to reach login screen'
184 UPDATE_ENGINE_FAILURE = ('update-engine failed to call '
185 'chromeos-setgoodkernel')
186 ROLLBACK_FAILURE = 'System rolled back to previous build'
187
188 _SUMMARY = 'New build failed'
189 _CLASSIFIERS = [
190 (CHROME_FAILURE, 'Chrome did not start'),
191 (UPDATE_ENGINE_FAILURE, 'update-engine did not start'),
192 (ROLLBACK_FAILURE, ROLLBACK_FAILURE),
193 ]
194
Richard Barnette9d43e562018-06-05 17:20:10 +0000195 def __init__(self, update_version, msg):
196 super(NewBuildUpdateError, self).__init__(
197 'Failure in build %s' % update_version, msg)
198
Richard Barnette621a8e42018-06-25 17:34:11 -0700199 @property
200 def failure_summary(self):
201 #pylint: disable=missing-docstring
202 return 'Build failed to work after installing'
203
Richard Barnette9d43e562018-06-05 17:20:10 +0000204
Richard Barnette3e8b2282018-05-15 20:42:20 +0000205def _url_to_version(update_url):
Dan Shi0f466e82013-02-22 15:44:58 -0800206 """Return the version based on update_url.
207
208 @param update_url: url to the image to update to.
209
210 """
Dale Curtisddfdb942011-07-14 13:59:24 -0700211 # The Chrome OS version is generally the last element in the URL. The only
212 # exception is delta update URLs, which are rooted under the version; e.g.,
213 # http://.../update/.../0.14.755.0/au/0.14.754.0. In this case we want to
214 # strip off the au section of the path before reading the version.
Dan Shi5002cfc2013-04-29 10:45:05 -0700215 return re.sub('/au/.*', '',
216 urlparse.urlparse(update_url).path).split('/')[-1].strip()
Sean O'Connor5346e4e2010-08-12 18:49:24 +0200217
218
Scott Zawalskieadbf702013-03-14 09:23:06 -0400219def url_to_image_name(update_url):
220 """Return the image name based on update_url.
221
222 From a URL like:
223 http://172.22.50.205:8082/update/lumpy-release/R27-3837.0.0
224 return lumpy-release/R27-3837.0.0
225
226 @param update_url: url to the image to update to.
227 @returns a string representing the image name in the update_url.
228
229 """
230 return '/'.join(urlparse.urlparse(update_url).path.split('/')[-2:])
231
232
Richard Barnette4c81b972018-07-18 12:35:16 -0700233def get_update_failure_reason(exception):
234 """Convert an exception into a failure reason for metrics.
235
236 The passed in `exception` should be one raised by failure of
237 `ChromiumOSUpdater.run_update`. The returned string will describe
238 the failure. If the input exception value is not a truish value
239 the return value will be `None`.
240
241 The number of possible return strings is restricted to a limited
242 enumeration of values so that the string may be safely used in
243 Monarch metrics without worrying about cardinality of the range of
244 string values.
245
246 @param exception Exception to be converted to a failure reason.
247
248 @return A string suitable for use in Monarch metrics, or `None`.
249 """
250 if exception:
251 if isinstance(exception, _AttributedUpdateError):
252 return exception.failure_summary
253 else:
254 return 'Unknown Error: %s' % type(exception).__name__
255 return None
256
257
Prashanth B32baa9b2014-03-13 13:23:01 -0700258def _get_devserver_build_from_update_url(update_url):
259 """Get the devserver and build from the update url.
260
261 @param update_url: The url for update.
262 Eg: http://devserver:port/update/build.
263
264 @return: A tuple of (devserver url, build) or None if the update_url
265 doesn't match the expected pattern.
266
267 @raises ValueError: If the update_url doesn't match the expected pattern.
268 @raises ValueError: If no global_config was found, or it doesn't contain an
269 image_url_pattern.
270 """
271 pattern = global_config.global_config.get_config_value(
272 'CROS', 'image_url_pattern', type=str, default='')
273 if not pattern:
274 raise ValueError('Cannot parse update_url, the global config needs '
275 'an image_url_pattern.')
276 re_pattern = pattern.replace('%s', '(\S+)')
277 parts = re.search(re_pattern, update_url)
278 if not parts or len(parts.groups()) < 2:
279 raise ValueError('%s is not an update url' % update_url)
280 return parts.groups()
281
282
Richard Barnette3e8b2282018-05-15 20:42:20 +0000283def _list_image_dir_contents(update_url):
Prashanth B32baa9b2014-03-13 13:23:01 -0700284 """Lists the contents of the devserver for a given build/update_url.
285
286 @param update_url: An update url. Eg: http://devserver:port/update/build.
287 """
288 if not update_url:
289 logging.warning('Need update_url to list contents of the devserver.')
290 return
291 error_msg = 'Cannot check contents of devserver, update url %s' % update_url
292 try:
293 devserver_url, build = _get_devserver_build_from_update_url(update_url)
294 except ValueError as e:
295 logging.warning('%s: %s', error_msg, e)
296 return
297 devserver = dev_server.ImageServer(devserver_url)
298 try:
299 devserver.list_image_dir(build)
300 # The devserver will retry on URLError to avoid flaky connections, but will
301 # eventually raise the URLError if it persists. All HTTPErrors get
302 # converted to DevServerExceptions.
303 except (dev_server.DevServerException, urllib2.URLError) as e:
304 logging.warning('%s: %s', error_msg, e)
305
306
Richard Barnette621a8e42018-06-25 17:34:11 -0700307def _get_metric_fields(update_url):
308 """Return a dict of metric fields.
309
310 This is used for sending autoupdate metrics for the given update URL.
311
312 @param update_url Metrics fields will be calculated from this URL.
313 """
314 build_name = url_to_image_name(update_url)
315 try:
316 board, build_type, milestone, _ = server_utils.ParseBuildName(
317 build_name)
318 except server_utils.ParseBuildNameException:
319 logging.warning('Unable to parse build name %s for metrics. '
320 'Continuing anyway.', build_name)
321 board, build_type, milestone = ('', '', '')
322 return {
323 'dev_server': dev_server.get_resolved_hostname(update_url),
324 'board': board,
325 'build_type': build_type,
326 'milestone': milestone,
327 }
328
329
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700330# TODO(garnold) This implements shared updater functionality needed for
331# supporting the autoupdate_EndToEnd server-side test. We should probably
332# migrate more of the existing ChromiumOSUpdater functionality to it as we
333# expand non-CrOS support in other tests.
Richard Barnette3e8b2282018-05-15 20:42:20 +0000334class ChromiumOSUpdater(object):
335 """Chromium OS specific DUT update functionality."""
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700336
Richard Barnette3e8b2282018-05-15 20:42:20 +0000337 def __init__(self, update_url, host=None, interactive=True):
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700338 """Initializes the object.
339
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700340 @param update_url: The URL we want the update to use.
341 @param host: A client.common_lib.hosts.Host implementation.
David Haddock76a4c882017-12-13 18:50:09 -0800342 @param interactive: Bool whether we are doing an interactive update.
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700343 """
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700344 self.update_url = update_url
345 self.host = host
David Haddock76a4c882017-12-13 18:50:09 -0800346 self.interactive = interactive
Richard Barnette3e8b2282018-05-15 20:42:20 +0000347 self.update_version = _url_to_version(update_url)
348
349
350 def _run(self, cmd, *args, **kwargs):
351 """Abbreviated form of self.host.run(...)"""
352 return self.host.run(cmd, *args, **kwargs)
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700353
354
355 def check_update_status(self):
356 """Returns the current update engine state.
357
358 We use the `update_engine_client -status' command and parse the line
359 indicating the update state, e.g. "CURRENT_OP=UPDATE_STATUS_IDLE".
360 """
Luigi Semenzatof15c8fc2017-03-03 14:12:40 -0800361 update_status = self.host.run(command='%s -status | grep CURRENT_OP' %
Richard Barnette3e8b2282018-05-15 20:42:20 +0000362 _UPDATER_BIN)
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700363 return update_status.stdout.strip().split('=')[-1]
364
365
Richard Barnette55d1af82018-05-22 23:40:14 +0000366 def _rootdev(self, options=''):
367 """Returns the stripped output of rootdev <options>.
368
369 @param options: options to run rootdev.
370
371 """
372 return self._run('rootdev %s' % options).stdout.strip()
373
374
375 def get_kernel_state(self):
Richard Barnette9d43e562018-06-05 17:20:10 +0000376 """Returns the (<active>, <inactive>) kernel state as a pair.
377
378 @raise RootFSUpdateError if the DUT reports a root partition
379 number that isn't one of the known valid values.
380 """
Richard Barnette55d1af82018-05-22 23:40:14 +0000381 active_root = int(re.findall('\d+\Z', self._rootdev('-s'))[0])
382 if active_root == _KERNEL_A['root']:
383 return _KERNEL_A, _KERNEL_B
384 elif active_root == _KERNEL_B['root']:
385 return _KERNEL_B, _KERNEL_A
386 else:
Richard Barnette9d43e562018-06-05 17:20:10 +0000387 raise RootFSUpdateError(
388 'Encountered unknown root partition: %s' % active_root)
Richard Barnette55d1af82018-05-22 23:40:14 +0000389
390
Richard Barnette18fd5842018-05-25 18:21:14 +0000391 def _cgpt(self, flag, kernel):
392 """Return numeric cgpt value for the specified flag, kernel, device."""
393 return int(self._run('cgpt show -n -i %d %s $(rootdev -s -d)' % (
394 kernel['kernel'], flag)).stdout.strip())
Richard Barnette55d1af82018-05-22 23:40:14 +0000395
396
397 def _get_next_kernel(self):
398 """Return the kernel that has priority for the next boot."""
399 priority_a = self._cgpt('-P', _KERNEL_A)
400 priority_b = self._cgpt('-P', _KERNEL_B)
401 if priority_a > priority_b:
402 return _KERNEL_A
403 else:
404 return _KERNEL_B
405
406
407 def _get_kernel_success(self, kernel):
408 """Return boolean success flag for the specified kernel.
409
410 @param kernel: information of the given kernel, either _KERNEL_A
411 or _KERNEL_B.
412 """
413 return self._cgpt('-S', kernel) != 0
414
415
416 def _get_kernel_tries(self, kernel):
417 """Return tries count for the specified kernel.
418
419 @param kernel: information of the given kernel, either _KERNEL_A
420 or _KERNEL_B.
421 """
422 return self._cgpt('-T', kernel)
423
424
Richard Barnette3e8b2282018-05-15 20:42:20 +0000425 def _get_last_update_error(self):
Shuqian Zhaod9992722016-02-29 12:26:38 -0800426 """Get the last autoupdate error code."""
Richard Barnette3e8b2282018-05-15 20:42:20 +0000427 command_result = self._run(
428 '%s --last_attempt_error' % _UPDATER_BIN)
429 return command_result.stdout.strip().replace('\n', ', ')
Shuqian Zhaod9992722016-02-29 12:26:38 -0800430
431
Luigi Semenzatoe76d9f82016-11-21 11:15:10 -0800432 def _base_update_handler_no_retry(self, run_args):
Shuqian Zhaod9992722016-02-29 12:26:38 -0800433 """Base function to handle a remote update ssh call.
434
435 @param run_args: Dictionary of args passed to ssh_host.run function.
Shuqian Zhaod9992722016-02-29 12:26:38 -0800436
Luigi Semenzatoe76d9f82016-11-21 11:15:10 -0800437 @throws: intercepts and re-throws all exceptions
Shuqian Zhaod9992722016-02-29 12:26:38 -0800438 """
Shuqian Zhaod9992722016-02-29 12:26:38 -0800439 try:
440 self.host.run(**run_args)
Shuqian Zhaod9992722016-02-29 12:26:38 -0800441 except Exception as e:
Luigi Semenzatoe76d9f82016-11-21 11:15:10 -0800442 logging.debug('exception in update handler: %s', e)
443 raise e
Shuqian Zhaod9992722016-02-29 12:26:38 -0800444
Luigi Semenzatoe76d9f82016-11-21 11:15:10 -0800445
446 def _base_update_handler(self, run_args, err_msg_prefix=None):
447 """Handle a remote update ssh call, possibly with retries.
448
449 @param run_args: Dictionary of args passed to ssh_host.run function.
450 @param err_msg_prefix: Prefix of the exception error message.
451 """
452 def exception_handler(e):
453 """Examines exceptions and returns True if the update handler
454 should be retried.
455
456 @param e: the exception intercepted by the retry util.
457 """
458 return (isinstance(e, error.AutoservSSHTimeout) or
459 (isinstance(e, error.GenericHostRunError) and
460 hasattr(e, 'description') and
461 (re.search('ERROR_CODE=37', e.description) or
462 re.search('generic error .255.', e.description))))
463
464 try:
465 # Try the update twice (arg 2 is max_retry, not including the first
466 # call). Some exceptions may be caught by the retry handler.
467 retry_util.GenericRetry(exception_handler, 1,
468 self._base_update_handler_no_retry,
469 run_args)
470 except Exception as e:
471 message = err_msg_prefix + ': ' + str(e)
472 raise RootFSUpdateError(message)
Shuqian Zhaod9992722016-02-29 12:26:38 -0800473
474
Luigi Semenzatof15c8fc2017-03-03 14:12:40 -0800475 def _wait_for_update_service(self):
476 """Ensure that the update engine daemon is running, possibly
477 by waiting for it a bit in case the DUT just rebooted and the
478 service hasn't started yet.
479 """
480 def handler(e):
481 """Retry exception handler.
482
483 Assumes that the error is due to the update service not having
484 started yet.
485
486 @param e: the exception intercepted by the retry util.
487 """
488 if isinstance(e, error.AutoservRunError):
489 logging.debug('update service check exception: %s\n'
490 'retrying...', e)
491 return True
492 else:
493 return False
494
495 # Retry at most three times, every 5s.
496 status = retry_util.GenericRetry(handler, 3,
497 self.check_update_status,
498 sleep=5)
499
500 # Expect the update engine to be idle.
501 if status != UPDATER_IDLE:
Richard Barnette9d43e562018-06-05 17:20:10 +0000502 raise RootFSUpdateError(
503 'Update engine status is %s (%s was expected).'
504 % (status, UPDATER_IDLE))
Luigi Semenzatof15c8fc2017-03-03 14:12:40 -0800505
506
Richard Barnette55d1af82018-05-22 23:40:14 +0000507 def _reset_update_engine(self):
508 """Resets the host to prepare for a clean update regardless of state."""
509 self._run('stop ui || true')
510 self._run('stop update-engine || true')
511 self._run('start update-engine')
Luigi Semenzatof15c8fc2017-03-03 14:12:40 -0800512 self._wait_for_update_service()
513
Richard Barnette55d1af82018-05-22 23:40:14 +0000514
515 def _reset_stateful_partition(self):
516 """Clear any pending stateful update request."""
Richard Barnette18fd5842018-05-25 18:21:14 +0000517 self._run('%s --stateful_change=reset 2>&1'
Richard Barnettef00a2ee2018-06-08 11:51:38 -0700518 % self._get_stateful_update_script())
Richard Barnette3ef29a82018-06-28 13:52:54 -0700519 self._run('rm -f %s' % _TARGET_VERSION)
520
521
522 def _set_target_version(self):
523 """Set the "target version" for the update."""
524 version_number = self.update_version.split('-')[1]
525 self._run('echo %s > %s' % (version_number, _TARGET_VERSION))
Richard Barnette55d1af82018-05-22 23:40:14 +0000526
527
528 def _revert_boot_partition(self):
529 """Revert the boot partition."""
530 part = self._rootdev('-s')
531 logging.warning('Reverting update; Boot partition will be %s', part)
532 return self._run('/postinst %s 2>&1' % part)
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700533
534
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700535 def _verify_kernel_state(self):
536 """Verify that the next kernel to boot is correct for update.
537
538 This tests that the kernel state is correct for a successfully
539 downloaded and installed update. That is, the next kernel to
540 boot must be the currently inactive kernel.
541
542 @raise RootFSUpdateError if the DUT next kernel isn't the
543 expected next kernel.
544 """
545 inactive_kernel = self.get_kernel_state()[1]
546 next_kernel = self._get_next_kernel()
547 if next_kernel != inactive_kernel:
548 raise RootFSUpdateError(
549 'Update failed. The kernel for next boot is %s, '
550 'but %s was expected.'
551 % (next_kernel['name'], inactive_kernel['name']))
552 return inactive_kernel
553
554
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700555 def _verify_update_completed(self):
556 """Verifies that an update has completed.
557
Richard Barnette9d43e562018-06-05 17:20:10 +0000558 @raise RootFSUpdateError if the DUT doesn't indicate that
559 download is complete and the DUT is ready for reboot.
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700560 """
561 status = self.check_update_status()
562 if status != UPDATER_NEED_REBOOT:
Shuqian Zhaod9992722016-02-29 12:26:38 -0800563 error_msg = ''
564 if status == UPDATER_IDLE:
Richard Barnette3e8b2282018-05-15 20:42:20 +0000565 error_msg = 'Update error: %s' % self._get_last_update_error()
Richard Barnette9d43e562018-06-05 17:20:10 +0000566 raise RootFSUpdateError(
567 'Update engine status is %s (%s was expected). %s'
568 % (status, UPDATER_NEED_REBOOT, error_msg))
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700569 return self._verify_kernel_state()
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700570
571
Richard Barnette55d1af82018-05-22 23:40:14 +0000572 def trigger_update(self):
Richard Barnette9d43e562018-06-05 17:20:10 +0000573 """Triggers a background update."""
574 # If this function is called immediately after reboot (which it
575 # can be), there is no guarantee that the update engine is up
576 # and running yet, so wait for it.
Richard Barnette55d1af82018-05-22 23:40:14 +0000577 self._wait_for_update_service()
578
579 autoupdate_cmd = ('%s --check_for_update --omaha_url=%s' %
580 (_UPDATER_BIN, self.update_url))
581 run_args = {'command': autoupdate_cmd}
582 err_prefix = 'Failed to trigger an update on %s. ' % self.host.hostname
583 logging.info('Triggering update via: %s', autoupdate_cmd)
584 metric_fields = {'success': False}
585 try:
586 self._base_update_handler(run_args, err_prefix)
587 metric_fields['success'] = True
588 finally:
589 c = metrics.Counter('chromeos/autotest/autoupdater/trigger')
Richard Barnette621a8e42018-06-25 17:34:11 -0700590 metric_fields.update(_get_metric_fields(self.update_url))
Richard Barnette55d1af82018-05-22 23:40:14 +0000591 c.increment(fields=metric_fields)
592
593
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700594 def update_image(self):
Richard Barnette18fd5842018-05-25 18:21:14 +0000595 """Updates the device root FS and kernel and verifies success."""
Shuqian Zhaofe4d62e2016-06-23 14:46:45 -0700596 autoupdate_cmd = ('%s --update --omaha_url=%s' %
Richard Barnette3e8b2282018-05-15 20:42:20 +0000597 (_UPDATER_BIN, self.update_url))
David Haddock76a4c882017-12-13 18:50:09 -0800598 if not self.interactive:
599 autoupdate_cmd = '%s --interactive=false' % autoupdate_cmd
Shuqian Zhaod9992722016-02-29 12:26:38 -0800600 run_args = {'command': autoupdate_cmd, 'timeout': 3600}
601 err_prefix = ('Failed to install device image using payload at %s '
602 'on %s. ' % (self.update_url, self.host.hostname))
603 logging.info('Updating image via: %s', autoupdate_cmd)
Allen Li1a5cc0a2017-06-20 14:08:59 -0700604 metric_fields = {'success': False}
Luigi Semenzatoe76d9f82016-11-21 11:15:10 -0800605 try:
Luigi Semenzatoe76d9f82016-11-21 11:15:10 -0800606 self._base_update_handler(run_args, err_prefix)
Allen Li1a5cc0a2017-06-20 14:08:59 -0700607 metric_fields['success'] = True
608 finally:
Allen Li1a5cc0a2017-06-20 14:08:59 -0700609 c = metrics.Counter('chromeos/autotest/autoupdater/update')
Richard Barnette621a8e42018-06-25 17:34:11 -0700610 metric_fields.update(_get_metric_fields(self.update_url))
Allen Li1a5cc0a2017-06-20 14:08:59 -0700611 c.increment(fields=metric_fields)
Richard Barnette4d211c92018-05-24 18:56:08 +0000612 return self._verify_update_completed()
Gilad Arnoldd6adeb82015-09-21 07:10:03 -0700613
614
Richard Barnettef00a2ee2018-06-08 11:51:38 -0700615 def _get_remote_script(self, script_name):
616 """Ensure that `script_name` is present on the DUT.
Chris Sosa5e4246b2012-05-22 18:05:22 -0700617
Richard Barnettef00a2ee2018-06-08 11:51:38 -0700618 The given script (e.g. `stateful_update`) may be present in the
619 stateful partition under /usr/local/bin, or we may have to
620 download it from the devserver.
Chris Sosaa3ac2152012-05-23 22:23:13 -0700621
Richard Barnettef00a2ee2018-06-08 11:51:38 -0700622 Determine whether the script is present or must be downloaded
623 and download if necessary. Then, return a command fragment
624 sufficient to run the script from whereever it now lives on the
625 DUT.
Richard Barnette9d43e562018-06-05 17:20:10 +0000626
Richard Barnettef00a2ee2018-06-08 11:51:38 -0700627 @param script_name The name of the script as expected in
628 /usr/local/bin and on the devserver.
629 @return A string with the command (minus arguments) that will
630 run the target script.
Gwendal Grignou3e96cc22017-06-07 16:22:51 -0700631 """
Richard Barnettef00a2ee2018-06-08 11:51:38 -0700632 remote_script = '/usr/local/bin/%s' % script_name
633 if self.host.path_exists(remote_script):
634 return remote_script
635 remote_tmp_script = '/tmp/%s' % script_name
636 server_name = urlparse.urlparse(self.update_url)[1]
637 script_url = 'http://%s/static/%s' % (server_name, script_name)
638 fetch_script = (
639 'curl -o %s %s && head -1 %s | grep "^#!" | sed "s/#!//"') % (
640 remote_tmp_script, script_url, remote_tmp_script)
641 script_interpreter = self._run(fetch_script,
642 ignore_status=True).stdout.strip()
643 if not script_interpreter:
644 return None
645 return '%s %s' % (script_interpreter, remote_tmp_script)
Chris Sosa5e4246b2012-05-22 18:05:22 -0700646
Richard Barnettef00a2ee2018-06-08 11:51:38 -0700647
648 def _get_stateful_update_script(self):
649 """Returns a command to run the stateful update script.
650
651 Find `stateful_update` on the target or install it, as
652 necessary. If installation fails, raise an exception.
653
654 @raise StatefulUpdateError if the script can't be found or
655 installed.
656 @return A string that can be joined with arguments to run the
657 `stateful_update` command on the DUT.
658 """
659 script_command = self._get_remote_script(_STATEFUL_UPDATE_SCRIPT)
660 if not script_command:
661 raise StatefulUpdateError('Could not install %s on DUT'
Richard Barnette9d43e562018-06-05 17:20:10 +0000662 % _STATEFUL_UPDATE_SCRIPT)
Richard Barnettef00a2ee2018-06-08 11:51:38 -0700663 return script_command
Chris Sosa5e4246b2012-05-22 18:05:22 -0700664
665
Chris Sosac1932172013-10-16 13:28:53 -0700666 def rollback_rootfs(self, powerwash):
667 """Triggers rollback and waits for it to complete.
668
669 @param powerwash: If true, powerwash as part of rollback.
670
671 @raise RootFSUpdateError if anything went wrong.
Chris Sosac1932172013-10-16 13:28:53 -0700672 """
Dan Shi549fb822015-03-24 18:01:11 -0700673 version = self.host.get_release_version()
Chris Sosac8617522014-06-09 23:22:26 +0000674 # Introduced can_rollback in M36 (build 5772). # etc/lsb-release matches
675 # X.Y.Z. This version split just pulls the first part out.
676 try:
677 build_number = int(version.split('.')[0])
678 except ValueError:
679 logging.error('Could not parse build number.')
680 build_number = 0
681
682 if build_number >= 5772:
Richard Barnette3e8b2282018-05-15 20:42:20 +0000683 can_rollback_cmd = '%s --can_rollback' % _UPDATER_BIN
Chris Sosac8617522014-06-09 23:22:26 +0000684 logging.info('Checking for rollback.')
685 try:
686 self._run(can_rollback_cmd)
687 except error.AutoservRunError as e:
688 raise RootFSUpdateError("Rollback isn't possible on %s: %s" %
689 (self.host.hostname, str(e)))
690
Richard Barnette3e8b2282018-05-15 20:42:20 +0000691 rollback_cmd = '%s --rollback --follow' % _UPDATER_BIN
Chris Sosac1932172013-10-16 13:28:53 -0700692 if not powerwash:
Dan Shif3a35f72016-01-25 11:18:14 -0800693 rollback_cmd += ' --nopowerwash'
Chris Sosac1932172013-10-16 13:28:53 -0700694
Chris Sosac8617522014-06-09 23:22:26 +0000695 logging.info('Performing rollback.')
Chris Sosac1932172013-10-16 13:28:53 -0700696 try:
697 self._run(rollback_cmd)
Chris Sosac1932172013-10-16 13:28:53 -0700698 except error.AutoservRunError as e:
699 raise RootFSUpdateError('Rollback failed on %s: %s' %
700 (self.host.hostname, str(e)))
701
702 self._verify_update_completed()
703
Gilad Arnold0ed760c2012-11-05 23:42:53 -0800704
Chris Sosa72312602013-04-16 15:01:56 -0700705 def update_stateful(self, clobber=True):
706 """Updates the stateful partition.
707
708 @param clobber: If True, a clean stateful installation.
Richard Barnette9d43e562018-06-05 17:20:10 +0000709
710 @raise StatefulUpdateError if the update script fails to
711 complete successfully.
Chris Sosa72312602013-04-16 15:01:56 -0700712 """
Chris Sosa77556d82012-04-05 15:23:14 -0700713 logging.info('Updating stateful partition...')
Richard Barnette18fd5842018-05-25 18:21:14 +0000714 statefuldev_url = self.update_url.replace('update', 'static')
Chris Sosaa3ac2152012-05-23 22:23:13 -0700715
Dale Curtis5c32c722011-05-04 19:24:23 -0700716 # Attempt stateful partition update; this must succeed so that the newly
717 # installed host is testable after update.
Richard Barnettef00a2ee2018-06-08 11:51:38 -0700718 statefuldev_cmd = [self._get_stateful_update_script(), statefuldev_url]
Chris Sosa72312602013-04-16 15:01:56 -0700719 if clobber:
720 statefuldev_cmd.append('--stateful_change=clean')
721
722 statefuldev_cmd.append('2>&1')
Dale Curtis5c32c722011-05-04 19:24:23 -0700723 try:
Dan Shi205b8732016-01-25 10:56:22 -0800724 self._run(' '.join(statefuldev_cmd), timeout=1200)
Dale Curtis5c32c722011-05-04 19:24:23 -0700725 except error.AutoservRunError:
Richard Barnette18fd5842018-05-25 18:21:14 +0000726 raise StatefulUpdateError(
Gilad Arnold62cf3a42015-10-01 09:15:25 -0700727 'Failed to perform stateful update on %s' %
728 self.host.hostname)
Dale Curtis5c32c722011-05-04 19:24:23 -0700729
Chris Sosaa3ac2152012-05-23 22:23:13 -0700730
Richard Barnette54d14f52018-05-18 16:39:49 +0000731 def verify_boot_expectations(self, expected_kernel, rollback_message):
Richard Barnette55d1af82018-05-22 23:40:14 +0000732 """Verifies that we fully booted given expected kernel state.
733
734 This method both verifies that we booted using the correct kernel
735 state and that the OS has marked the kernel as good.
736
Richard Barnette54d14f52018-05-18 16:39:49 +0000737 @param expected_kernel: kernel that we are verifying with,
Richard Barnette55d1af82018-05-22 23:40:14 +0000738 i.e. I expect to be booted onto partition 4 etc. See output of
739 get_kernel_state.
Richard Barnette9d43e562018-06-05 17:20:10 +0000740 @param rollback_message: string include in except message text
Richard Barnette55d1af82018-05-22 23:40:14 +0000741 if we booted with the wrong partition.
742
Richard Barnette9d43e562018-06-05 17:20:10 +0000743 @raise NewBuildUpdateError if any of the various checks fail.
Richard Barnette55d1af82018-05-22 23:40:14 +0000744 """
745 # Figure out the newly active kernel.
Richard Barnette54d14f52018-05-18 16:39:49 +0000746 active_kernel = self.get_kernel_state()[0]
Richard Barnette55d1af82018-05-22 23:40:14 +0000747
748 # Check for rollback due to a bad build.
Richard Barnette54d14f52018-05-18 16:39:49 +0000749 if active_kernel != expected_kernel:
Richard Barnette55d1af82018-05-22 23:40:14 +0000750
751 # Kernel crash reports should be wiped between test runs, but
752 # may persist from earlier parts of the test, or from problems
753 # with provisioning.
754 #
755 # Kernel crash reports will NOT be present if the crash happened
756 # before encrypted stateful is mounted.
757 #
758 # TODO(dgarrett): Integrate with server/crashcollect.py at some
759 # point.
760 kernel_crashes = glob.glob('/var/spool/crash/kernel.*.kcrash')
761 if kernel_crashes:
762 rollback_message += ': kernel_crash'
763 logging.debug('Found %d kernel crash reports:',
764 len(kernel_crashes))
765 # The crash names contain timestamps that may be useful:
766 # kernel.20131207.005945.0.kcrash
767 for crash in kernel_crashes:
768 logging.debug(' %s', os.path.basename(crash))
769
770 # Print out some information to make it easier to debug
771 # the rollback.
772 logging.debug('Dumping partition table.')
773 self._run('cgpt show $(rootdev -s -d)')
774 logging.debug('Dumping crossystem for firmware debugging.')
775 self._run('crossystem --all')
Richard Barnette9d43e562018-06-05 17:20:10 +0000776 raise NewBuildUpdateError(self.update_version, rollback_message)
Richard Barnette55d1af82018-05-22 23:40:14 +0000777
778 # Make sure chromeos-setgoodkernel runs.
779 try:
780 utils.poll_for_condition(
Richard Barnette54d14f52018-05-18 16:39:49 +0000781 lambda: (self._get_kernel_tries(active_kernel) == 0
782 and self._get_kernel_success(active_kernel)),
Richard Barnette9d43e562018-06-05 17:20:10 +0000783 exception=RootFSUpdateError(),
Richard Barnette55d1af82018-05-22 23:40:14 +0000784 timeout=_KERNEL_UPDATE_TIMEOUT, sleep_interval=5)
Richard Barnette9d43e562018-06-05 17:20:10 +0000785 except RootFSUpdateError:
Richard Barnette55d1af82018-05-22 23:40:14 +0000786 services_status = self._run('status system-services').stdout
787 if services_status != 'system-services start/running\n':
Richard Barnette5adb6d42018-06-28 15:52:32 -0700788 event = NewBuildUpdateError.CHROME_FAILURE
Richard Barnette55d1af82018-05-22 23:40:14 +0000789 else:
Richard Barnette5adb6d42018-06-28 15:52:32 -0700790 event = NewBuildUpdateError.UPDATE_ENGINE_FAILURE
Richard Barnette9d43e562018-06-05 17:20:10 +0000791 raise NewBuildUpdateError(self.update_version, event)
Richard Barnette55d1af82018-05-22 23:40:14 +0000792
793
Richard Barnette14ee84c2018-05-18 20:23:42 +0000794 def _prepare_host(self):
795 """Make sure the target DUT is working and ready for update.
796
797 Initially, the target DUT's state is unknown. The DUT is
798 expected to be online, but we strive to be forgiving if Chrome
799 and/or the update engine aren't fully functional.
800 """
801 # Summary of work, and the rationale:
802 # 1. Reboot, because it's a good way to clear out problems.
803 # 2. Touch the PROVISION_FAILED file, to allow repair to detect
804 # failure later.
805 # 3. Run the hook for host class specific preparation.
806 # 4. Stop Chrome, because the system is designed to eventually
807 # reboot if Chrome is stuck in a crash loop.
808 # 5. Force `update-engine` to start, because if Chrome failed
809 # to start properly, the status of the `update-engine` job
810 # will be uncertain.
Richard Barnette5adb6d42018-06-28 15:52:32 -0700811 if not self.host.is_up():
812 raise HostUpdateError(self.host.hostname,
813 HostUpdateError.DUT_DOWN)
Richard Barnette14ee84c2018-05-18 20:23:42 +0000814 self._reset_stateful_partition()
815 self.host.reboot(timeout=self.host.REBOOT_TIMEOUT)
816 self._run('touch %s' % PROVISION_FAILED)
817 self.host.prepare_for_update()
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700818 self._reset_update_engine()
Richard Barnette14ee84c2018-05-18 20:23:42 +0000819 logging.info('Updating from version %s to %s.',
820 self.host.get_release_version(),
821 self.update_version)
822
823
824 def _verify_devserver(self):
Richard Barnette9d43e562018-06-05 17:20:10 +0000825 """Check that our chosen devserver is still working.
826
827 @raise DevServerError if the devserver fails any sanity check.
828 """
Richard Barnette14ee84c2018-05-18 20:23:42 +0000829 server = 'http://%s' % urlparse.urlparse(self.update_url)[1]
830 try:
831 if not dev_server.ImageServer.devserver_healthy(server):
Richard Barnette9d43e562018-06-05 17:20:10 +0000832 raise DevServerError(
833 server, 'Devserver is not healthy')
Richard Barnette14ee84c2018-05-18 20:23:42 +0000834 except Exception as e:
Richard Barnette9d43e562018-06-05 17:20:10 +0000835 raise DevServerError(
836 server, 'Devserver is not up and available')
Richard Barnette14ee84c2018-05-18 20:23:42 +0000837
838
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700839 def _install_via_update_engine(self):
840 """Install an updating using the production AU flow.
841
842 This uses the standard AU flow and the `stateful_update` script
843 to download and install a root FS, kernel and stateful
844 filesystem content.
845
846 @return The kernel expected to be booted next.
847 """
848 logging.info('Installing image using update_engine.')
849 expected_kernel = self.update_image()
850 self.update_stateful()
Richard Barnette3ef29a82018-06-28 13:52:54 -0700851 self._set_target_version()
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700852 return expected_kernel
853
854
855 def _install_via_quick_provision(self):
856 """Install an updating using the `quick-provision` script.
857
858 This uses the `quick-provision` script to download and install
859 a root FS, kernel and stateful filesystem content.
860
861 @return The kernel expected to be booted next.
862 """
863 build_re = global_config.global_config.get_config_value(
864 'CROS', 'quick_provision_build_regex', type=str, default='')
865 image_name = url_to_image_name(self.update_url)
866 if not build_re or re.match(build_re, image_name) is None:
867 logging.info('Not eligible for quick-provision.')
868 return None
869 logging.info('Installing image using quick-provision.')
870 provision_command = self._get_remote_script(_QUICK_PROVISION_SCRIPT)
871 server_name = urlparse.urlparse(self.update_url)[1]
872 static_url = 'http://%s/static' % server_name
873 command = '%s --noreboot %s %s' % (
874 provision_command, image_name, static_url)
875 try:
876 self._run(command)
Richard Barnette3ef29a82018-06-28 13:52:54 -0700877 self._set_target_version()
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700878 return self._verify_kernel_state()
879 except Exception:
880 # N.B. We handle only `Exception` here. Non-Exception
881 # classes (such as KeyboardInterrupt) are handled by our
882 # caller.
883 logging.exception('quick-provision script failed; '
884 'will fall back to update_engine.')
885 self._revert_boot_partition()
886 self._reset_stateful_partition()
887 self._reset_update_engine()
888 return None
889
890
Richard Barnette54d14f52018-05-18 16:39:49 +0000891 def _install_update(self):
Richard Barnette0beb14b2018-05-15 18:07:52 +0000892 """Install the requested image on the DUT, but don't start it.
893
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700894 This downloads and installs a root FS, kernel and stateful
895 filesystem content. This does not reboot the DUT, so the update
896 is merely pending when the method returns.
897
898 @return The kernel expected to be booted next.
Dan Shi0f466e82013-02-22 15:44:58 -0800899 """
Richard Barnette14ee84c2018-05-18 20:23:42 +0000900 logging.info('Installing image at %s onto %s',
901 self.update_url, self.host.hostname)
Sean O'Connor5346e4e2010-08-12 18:49:24 +0200902 try:
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700903 return (self._install_via_quick_provision()
904 or self._install_via_update_engine())
Dale Curtis1e973182011-07-12 18:21:36 -0700905 except:
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700906 # N.B. This handling code includes non-Exception classes such
907 # as KeyboardInterrupt. We need to clean up, but we also must
908 # re-raise.
Richard Barnette14ee84c2018-05-18 20:23:42 +0000909 self._revert_boot_partition()
910 self._reset_stateful_partition()
Richard Barnettee86b1ce2018-06-07 10:37:23 -0700911 self._reset_update_engine()
Dale Curtis1e973182011-07-12 18:21:36 -0700912 # Collect update engine logs in the event of failure.
913 if self.host.job:
Aviv Keshet2610d3e2016-06-01 16:37:01 -0700914 logging.info('Collecting update engine logs due to failure...')
Dale Curtis1e973182011-07-12 18:21:36 -0700915 self.host.get_file(
Richard Barnette3e8b2282018-05-15 20:42:20 +0000916 _UPDATER_LOGS, self.host.job.sysinfo.sysinfodir,
Gilad Arnold0c0df732015-09-21 06:37:59 -0700917 preserve_perm=False)
Richard Barnette3e8b2282018-05-15 20:42:20 +0000918 _list_image_dir_contents(self.update_url)
Dale Curtis1e973182011-07-12 18:21:36 -0700919 raise
Sean O'Connor5346e4e2010-08-12 18:49:24 +0200920
921
Richard Barnette14ee84c2018-05-18 20:23:42 +0000922 def _complete_update(self, expected_kernel):
923 """Finish the update, and confirm that it succeeded.
Richard Barnette0beb14b2018-05-15 18:07:52 +0000924
Richard Barnette14ee84c2018-05-18 20:23:42 +0000925 Initial condition is that the target build has been downloaded
926 and installed on the DUT, but has not yet been booted. This
927 function is responsible for rebooting the DUT, and checking that
928 the new build is running successfully.
Richard Barnette0beb14b2018-05-15 18:07:52 +0000929
Richard Barnette14ee84c2018-05-18 20:23:42 +0000930 @param expected_kernel: kernel expected to be active after reboot.
Richard Barnette0beb14b2018-05-15 18:07:52 +0000931 """
Richard Barnette14ee84c2018-05-18 20:23:42 +0000932 # Regarding the 'crossystem' command below: In some cases,
933 # the update flow puts the TPM into a state such that it
934 # fails verification. We don't know why. However, this
935 # call papers over the problem by clearing the TPM during
936 # the reboot.
937 #
938 # We ignore failures from 'crossystem'. Although failure
939 # here is unexpected, and could signal a bug, the point of
940 # the exercise is to paper over problems; allowing this to
941 # fail would defeat the purpose.
942 self._run('crossystem clear_tpm_owner_request=1',
943 ignore_status=True)
944 self.host.reboot(timeout=self.host.REBOOT_TIMEOUT)
945
Richard Barnette0beb14b2018-05-15 18:07:52 +0000946 # Touch the lab machine file to leave a marker that
947 # distinguishes this image from other test images.
948 # Afterwards, we must re-run the autoreboot script because
949 # it depends on the _LAB_MACHINE_FILE.
950 autoreboot_cmd = ('FILE="%s" ; [ -f "$FILE" ] || '
951 '( touch "$FILE" ; start autoreboot )')
Richard Barnette3e8b2282018-05-15 20:42:20 +0000952 self._run(autoreboot_cmd % _LAB_MACHINE_FILE)
Richard Barnette0beb14b2018-05-15 18:07:52 +0000953 self.verify_boot_expectations(
Richard Barnette5adb6d42018-06-28 15:52:32 -0700954 expected_kernel, NewBuildUpdateError.ROLLBACK_FAILURE)
Richard Barnette0beb14b2018-05-15 18:07:52 +0000955
956 logging.debug('Cleaning up old autotest directories.')
957 try:
958 installed_autodir = autotest.Autotest.get_installed_autodir(
959 self.host)
960 self._run('rm -rf ' + installed_autodir)
961 except autotest.AutodirNotFoundError:
962 logging.debug('No autotest installed directory found.')
963
964
Richard Barnette4c81b972018-07-18 12:35:16 -0700965 def run_update(self):
966 """Perform a full update of a DUT in the test lab.
Richard Barnette0beb14b2018-05-15 18:07:52 +0000967
Richard Barnette4c81b972018-07-18 12:35:16 -0700968 This downloads and installs the root FS and stateful partition
969 content needed for the update specified in `self.host` and
970 `self.update_url`. The update is performed according to the
971 requirements for provisioning a DUT for testing the requested
972 build.
Richard Barnette0beb14b2018-05-15 18:07:52 +0000973
Richard Barnette4c81b972018-07-18 12:35:16 -0700974 At the end of the procedure, metrics are reported describing the
975 outcome of the operation.
976
977 @returns A tuple of the form `(image_name, attributes)`, where
978 `image_name` is the name of the image installed, and
979 `attributes` is new attributes to be applied to the DUT.
Richard Barnette0beb14b2018-05-15 18:07:52 +0000980 """
Richard Barnette4c81b972018-07-18 12:35:16 -0700981 server_name = dev_server.get_resolved_hostname(self.update_url)
982 metrics.Counter(_metric_name('install')).increment(
983 fields={'devserver': server_name})
984
Richard Barnette14ee84c2018-05-18 20:23:42 +0000985 self._verify_devserver()
Richard Barnette9d43e562018-06-05 17:20:10 +0000986
987 try:
988 self._prepare_host()
989 except _AttributedUpdateError:
990 raise
991 except Exception as e:
992 logging.exception('Failure preparing host prior to update.')
993 raise HostUpdateError(self.host.hostname, str(e))
994
995 try:
996 expected_kernel = self._install_update()
997 except _AttributedUpdateError:
998 raise
999 except Exception as e:
1000 logging.exception('Failure during download and install.')
Richard Barnette621a8e42018-06-25 17:34:11 -07001001 server_name = dev_server.get_resolved_hostname(self.update_url)
Richard Barnette9d43e562018-06-05 17:20:10 +00001002 raise ImageInstallError(self.host.hostname, server_name, str(e))
1003
1004 try:
1005 self._complete_update(expected_kernel)
1006 except _AttributedUpdateError:
1007 raise
1008 except Exception as e:
1009 logging.exception('Failure from build after update.')
1010 raise NewBuildUpdateError(self.update_version, str(e))
Richard Barnette0beb14b2018-05-15 18:07:52 +00001011
Richard Barnette0beb14b2018-05-15 18:07:52 +00001012 image_name = url_to_image_name(self.update_url)
1013 # update_url is different from devserver url needed to stage autotest
1014 # packages, therefore, resolve a new devserver url here.
1015 devserver_url = dev_server.ImageServer.resolve(
1016 image_name, self.host.hostname).url()
1017 repo_url = tools.get_package_url(devserver_url, image_name)
1018 return image_name, {ds_constants.JOB_REPO_URL: repo_url}