blob: 2025e4c49154e0d0bf1eba6b50b8f576acda8ec0 [file] [log] [blame]
xixuana4f4e712017-05-08 15:17:54 -07001# Copyright 2016 The Chromium OS Authors. All rights reserved.
xixuan52c2fba2016-05-20 17:02:48 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""An executable function cros-update for auto-update of a CrOS host.
6
7The reason to create this file is to let devserver to trigger a background
8process for CrOS auto-update. Therefore, when devserver service is restarted
9sometimes, the CrOS auto-update process is still running and the corresponding
10provision task won't claim failure.
11
12It includes two classes:
13 a. CrOSUpdateTrigger:
14 1. Includes all logics which identify which types of update need to be
15 performed in the current DUT.
16 2. Responsible for write current status of CrOS auto-update process into
17 progress_tracker.
18
19 b. CrOSAUParser:
20 1. Pre-setup the required args for CrOS auto-update.
21 2. Parse the input parameters for cmd that runs 'cros_update.py'.
22"""
23
24from __future__ import print_function
25
26import argparse
27import cros_update_logging
28import cros_update_progress
David Riley63820672017-11-02 10:46:42 -070029import logging # pylint: disable=cros-logging-import
xixuan52c2fba2016-05-20 17:02:48 -070030import os
David Rileyef7aad12017-11-24 22:03:21 -080031import re
xixuan52c2fba2016-05-20 17:02:48 -070032import sys
David Riley63820672017-11-02 10:46:42 -070033import time
xixuan28d99072016-10-06 12:24:16 -070034import traceback
xixuan52c2fba2016-05-20 17:02:48 -070035
xixuancf58dd32016-08-24 13:57:06 -070036# only import setup_chromite before chromite import.
37import setup_chromite # pylint: disable=unused-import
xixuan52c2fba2016-05-20 17:02:48 -070038try:
39 from chromite.lib import auto_updater
David Riley63820672017-11-02 10:46:42 -070040 from chromite.lib import cros_build_lib
xixuan52c2fba2016-05-20 17:02:48 -070041 from chromite.lib import remote_access
42 from chromite.lib import timeout_util
43except ImportError as e:
44 logging.debug('chromite cannot be imported: %r', e)
45 auto_updater = None
46 remote_access = None
xixuancf58dd32016-08-24 13:57:06 -070047 timeout_util = None
xixuan52c2fba2016-05-20 17:02:48 -070048
xixuanac89ce82016-11-30 16:48:20 -080049# The build channel for recovering host's stateful partition
50STABLE_BUILD_CHANNEL = 'stable-channel'
51
xixuan52c2fba2016-05-20 17:02:48 -070052# Timeout for CrOS auto-update process.
53CROS_UPDATE_TIMEOUT_MIN = 30
54
55# The preserved path in remote device, won't be deleted after rebooting.
56CROS_PRESERVED_PATH = ('/mnt/stateful_partition/unencrypted/'
57 'preserve/cros-update')
58
59# Standard error tmeplate to be written into status tracking log.
xixuan28d99072016-10-06 12:24:16 -070060CROS_ERROR_TEMPLATE = cros_update_progress.ERROR_TAG + ' %s'
xixuan52c2fba2016-05-20 17:02:48 -070061
David Riley63820672017-11-02 10:46:42 -070062# How long after a quick provision fails to wait before falling back to the
63# standard provisioning flow.
64QUICK_PROVISION_FAILURE_DELAY_SEC = 45
65
xixuan27d50442017-08-09 10:38:25 -070066# Setting logging level
67logConfig = cros_update_logging.loggingConfig()
68logConfig.ConfigureLogging()
xixuan52c2fba2016-05-20 17:02:48 -070069
70class CrOSAUParser(object):
71 """Custom command-line options parser for cros-update."""
72 def __init__(self):
73 self.args = sys.argv[1:]
74 self.parser = argparse.ArgumentParser(
75 usage='%(prog)s [options] [control-file]')
76 self.SetupOptions()
77 self.removed_args = []
78
79 # parse an empty list of arguments in order to set self.options
80 # to default values.
81 self.options = self.parser.parse_args(args=[])
82
83 def SetupOptions(self):
84 """Setup options to call cros-update command."""
85 self.parser.add_argument('-d', action='store', type=str,
86 dest='host_name',
87 help='host_name of a DUT')
88 self.parser.add_argument('-b', action='store', type=str,
89 dest='build_name',
90 help='build name to be auto-updated')
91 self.parser.add_argument('--static_dir', action='store', type=str,
xixuan52c2fba2016-05-20 17:02:48 -070092 help='static directory of the devserver')
93 self.parser.add_argument('--force_update', action='store_true',
David Riley63820672017-11-02 10:46:42 -070094 default=False,
xixuan52c2fba2016-05-20 17:02:48 -070095 help=('force an update even if the version '
96 'installed is the same'))
97 self.parser.add_argument('--full_update', action='store_true',
David Riley63820672017-11-02 10:46:42 -070098 default=False,
99 help='force a rootfs update, skip stateful update')
xixuanac89ce82016-11-30 16:48:20 -0800100 self.parser.add_argument('--original_build', action='store', type=str,
David Riley63820672017-11-02 10:46:42 -0700101 default='',
xixuanac89ce82016-11-30 16:48:20 -0800102 help=('force stateful update with the same '
103 'version of previous rootfs partition'))
David Haddock90e49442017-04-07 19:14:09 -0700104 self.parser.add_argument('--payload_filename', action='store', type=str,
David Riley63820672017-11-02 10:46:42 -0700105 default=None, help='A custom payload filename')
David Haddock20559612017-06-28 22:15:08 -0700106 self.parser.add_argument('--clobber_stateful', action='store_true',
David Riley63820672017-11-02 10:46:42 -0700107 default=False, help='Whether to clobber stateful')
108 self.parser.add_argument('--quick_provision', action='store_true',
109 default=False,
110 help='Whether to attempt quick provisioning path')
111 self.parser.add_argument('--devserver_url', action='store', type=str,
112 default=None, help='Devserver URL base for RPCs')
113 self.parser.add_argument('--static_url', action='store', type=str,
114 default=None,
115 help='Devserver URL base for static files')
xixuan52c2fba2016-05-20 17:02:48 -0700116
117 def ParseArgs(self):
118 """Parse and process command line arguments."""
119 # Positional arguments from the end of the command line will be included
120 # in the list of unknown_args.
121 self.options, unknown_args = self.parser.parse_known_args()
122 # Filter out none-positional arguments
123 while unknown_args and unknown_args[0][0] == '-':
124 self.removed_args.append(unknown_args.pop(0))
125 # Always assume the argument has a value.
126 if unknown_args:
127 self.removed_args.append(unknown_args.pop(0))
128 if self.removed_args:
129 logging.warn('Unknown arguments are removed from the options: %s',
130 self.removed_args)
131
132
133class CrOSUpdateTrigger(object):
134 """The class for CrOS auto-updater trigger.
135
136 This class is used for running all CrOS auto-update trigger logic.
137 """
138 def __init__(self, host_name, build_name, static_dir, progress_tracker=None,
xixuan3bc974e2016-10-18 17:21:43 -0700139 log_file=None, au_tempdir=None, force_update=False,
David Haddock20559612017-06-28 22:15:08 -0700140 full_update=False, original_build=None, payload_filename=None,
David Riley63820672017-11-02 10:46:42 -0700141 clobber_stateful=True, quick_provision=False,
142 devserver_url=None, static_url=None):
xixuan52c2fba2016-05-20 17:02:48 -0700143 self.host_name = host_name
144 self.build_name = build_name
145 self.static_dir = static_dir
146 self.progress_tracker = progress_tracker
147 self.log_file = log_file
xixuan3bc974e2016-10-18 17:21:43 -0700148 self.au_tempdir = au_tempdir
xixuan52c2fba2016-05-20 17:02:48 -0700149 self.force_update = force_update
150 self.full_update = full_update
xixuanac89ce82016-11-30 16:48:20 -0800151 self.original_build = original_build
David Haddock90e49442017-04-07 19:14:09 -0700152 self.payload_filename = payload_filename
David Haddock20559612017-06-28 22:15:08 -0700153 self.clobber_stateful = clobber_stateful
David Riley63820672017-11-02 10:46:42 -0700154 self.quick_provision = quick_provision
155 self.devserver_url = devserver_url
156 self.static_url = static_url
xixuan52c2fba2016-05-20 17:02:48 -0700157
158 def _WriteAUStatus(self, content):
159 if self.progress_tracker:
160 self.progress_tracker.WriteStatus(content)
161
162 def _StatefulUpdate(self, cros_updater):
163 """The detailed process in stateful update.
164
165 Args:
166 cros_updater: The CrOS auto updater for auto-update.
167 """
168 self._WriteAUStatus('pre-setup stateful update')
169 cros_updater.PreSetupStatefulUpdate()
170 self._WriteAUStatus('perform stateful update')
171 cros_updater.UpdateStateful()
172 self._WriteAUStatus('post-check stateful update')
173 cros_updater.PostCheckStatefulUpdate()
174
175 def _RootfsUpdate(self, cros_updater):
176 """The detailed process in rootfs update.
177
178 Args:
179 cros_updater: The CrOS auto updater for auto-update.
180 """
xixuana4f4e712017-05-08 15:17:54 -0700181 self._WriteAUStatus('Check whether devserver can run before rootfs update')
182 cros_updater.CheckDevserverRun()
xixuan52c2fba2016-05-20 17:02:48 -0700183 self._WriteAUStatus('transfer rootfs update package')
184 cros_updater.TransferRootfsUpdate()
185 self._WriteAUStatus('pre-setup rootfs update')
186 cros_updater.PreSetupRootfsUpdate()
187 self._WriteAUStatus('rootfs update')
188 cros_updater.UpdateRootfs()
189 self._WriteAUStatus('post-check rootfs update')
190 cros_updater.PostCheckRootfsUpdate()
191
xixuanac89ce82016-11-30 16:48:20 -0800192 def _GetOriginalPayloadDir(self):
193 """Get the directory of original payload.
194
195 Returns:
196 The directory of original payload, whose format is like:
197 'static/stable-channel/link/3428.210.0'
198 """
199 if self.original_build:
200 return os.path.join(self.static_dir, '%s/%s' % (STABLE_BUILD_CHANNEL,
201 self.original_build))
202 else:
203 return None
204
David Riley63820672017-11-02 10:46:42 -0700205 def _MakeStatusUrl(self, devserver_url, host_name, pid):
206 """Generates a URL to post auto update status to.
207
208 Args:
209 devserver_url: URL base for devserver RPCs.
210 host_name: Host to post status for.
211 pid: pid of the update process.
212
213 Returns:
214 An unescaped URL.
215 """
216 return '%s/post_au_status?host_name=%s&pid=%d' % (devserver_url, host_name,
217 pid)
218
219 def _QuickProvision(self, device):
220 """Performs a quick provision of device.
221
222 Returns:
David Rileyef7aad12017-11-24 22:03:21 -0800223 A dictionary of extracted key-value pairs returned from the script
224 execution.
225
226 Raises:
227 cros_build_lib.RunCommandError: error executing command or script
228 remote_access.SSHConnectionError: SSH connection error
David Riley63820672017-11-02 10:46:42 -0700229 """
230 pid = os.getpid()
231 pgid = os.getpgid(pid)
232 if self.progress_tracker is None:
233 self.progress_tracker = cros_update_progress.AUProgress(self.host_name,
234 pgid)
235
236 dut_script = '/tmp/quick-provision'
237 status_url = self._MakeStatusUrl(self.devserver_url, self.host_name, pgid)
238 cmd = ('curl -o %s %s && bash '
239 '%s --status_url %s %s %s') % (
240 dut_script, os.path.join(self.static_url, 'quick-provision'),
241 dut_script, cros_build_lib.ShellQuote(status_url),
242 self.build_name, self.static_url
243 )
David Rileyf5941192018-03-01 14:30:38 -0800244 # Quick provision script issues a reboot and might result in the SSH
245 # connection being terminated so set ssh_error_ok so that output can
246 # still be captured.
247 results = device.RunCommand(cmd, log_output=True, capture_output=True,
248 ssh_error_ok=True)
David Rileyef7aad12017-11-24 22:03:21 -0800249 key_re = re.compile(r'^KEYVAL: ([^\d\W]\w*)=(.*)$')
250 matches = [key_re.match(l) for l in results.output.splitlines()]
251 keyvals = {m.group(1): m.group(2) for m in matches if m}
David Riley6c467252017-11-30 16:39:11 -0800252 logging.info("DUT returned keyvals: %s", keyvals)
David Rileyf5941192018-03-01 14:30:38 -0800253
254 # If there was an SSH error, check the keyvals to see if it actually
255 # completed and suppress the error if so.
256 if results.returncode == remote_access.SSH_ERROR_CODE:
257 if 'COMPLETED' in keyvals:
258 logging.warning('Quick provision completed with ssh error, ignoring...')
259 else:
260 logging.error('Incomplete quick provision failed with ssh error')
261 raise remote_access.SSHConnectionError(results.error)
262
David Rileyef7aad12017-11-24 22:03:21 -0800263 return keyvals
David Riley63820672017-11-02 10:46:42 -0700264
xixuan52c2fba2016-05-20 17:02:48 -0700265 def TriggerAU(self):
266 """Execute auto update for cros_host.
267
268 The auto update includes 4 steps:
269 1. if devserver cannot run, restore the stateful partition.
xixuan2aca0ac2016-07-29 12:02:06 -0700270 2. if possible, do stateful update first, but never raise errors, except
271 for timeout_util.TimeoutError caused by system.signal.
xixuan52c2fba2016-05-20 17:02:48 -0700272 3. If required or stateful_update fails, first do rootfs update, then do
273 stateful_update.
274 4. Post-check for the whole update.
275 """
276 try:
277 with remote_access.ChromiumOSDeviceHandler(
278 self.host_name, port=None,
279 base_dir=CROS_PRESERVED_PATH,
Luigi Semenzato8db8b3c2017-01-26 18:02:19 -0800280 ping=False) as device:
xixuan52c2fba2016-05-20 17:02:48 -0700281
282 logging.debug('Remote device %s is connected', self.host_name)
283 payload_dir = os.path.join(self.static_dir, self.build_name)
xixuanac89ce82016-11-30 16:48:20 -0800284 original_payload_dir = self._GetOriginalPayloadDir()
285
xixuan52c2fba2016-05-20 17:02:48 -0700286 chromeos_AU = auto_updater.ChromiumOSUpdater(
xixuan2a0970a2016-08-10 12:12:44 -0700287 device, self.build_name, payload_dir,
288 dev_dir=os.path.abspath(os.path.dirname(__file__)),
xixuan3bc974e2016-10-18 17:21:43 -0700289 tempdir=self.au_tempdir,
xixuan2a0970a2016-08-10 12:12:44 -0700290 log_file=self.log_file,
xixuanac89ce82016-11-30 16:48:20 -0800291 original_payload_dir=original_payload_dir,
David Haddock90e49442017-04-07 19:14:09 -0700292 yes=True,
David Haddock20559612017-06-28 22:15:08 -0700293 payload_filename=self.payload_filename,
294 clobber_stateful=self.clobber_stateful)
xixuan52c2fba2016-05-20 17:02:48 -0700295
David Riley63820672017-11-02 10:46:42 -0700296 # Allow fall back if the quick provision does not succeed.
297 invoke_autoupdate = True
xixuan52c2fba2016-05-20 17:02:48 -0700298
David Riley6c467252017-11-30 16:39:11 -0800299 if (self.quick_provision and self.clobber_stateful and
300 not self.full_update):
David Riley63820672017-11-02 10:46:42 -0700301 try:
302 logging.debug('Start CrOS quick provision process...')
303 self._WriteAUStatus('Start Quick Provision')
David Riley6c467252017-11-30 16:39:11 -0800304 keyvals = self._QuickProvision(device)
David Riley63820672017-11-02 10:46:42 -0700305 logging.debug('Start CrOS check process...')
David Riley8a7ed5c2018-02-22 11:16:47 -0800306 self._WriteAUStatus('Finish Quick Provision, reboot')
307 chromeos_AU.AwaitReboot(keyvals.get('BOOT_ID'))
David Riley63820672017-11-02 10:46:42 -0700308 self._WriteAUStatus('Finish Quick Provision, post-check')
David Riley8a7ed5c2018-02-22 11:16:47 -0800309 chromeos_AU.PostCheckCrOSUpdate()
David Riley63820672017-11-02 10:46:42 -0700310 self._WriteAUStatus(cros_update_progress.FINISHED)
311 invoke_autoupdate = False
312 except (cros_build_lib.RunCommandError,
David Riley8a7ed5c2018-02-22 11:16:47 -0800313 remote_access.SSHConnectionError,
314 auto_updater.RebootVerificationError) as e:
David Rileyf5941192018-03-01 14:30:38 -0800315 logging.warning(
316 'Error during quick provision, falling back to legacy: %s: %s',
317 type(e).__name__, e)
David Riley63820672017-11-02 10:46:42 -0700318 time.sleep(QUICK_PROVISION_FAILURE_DELAY_SEC)
319
320 if invoke_autoupdate:
321 chromeos_AU.CheckPayloads()
322
323 version_match = chromeos_AU.PreSetupCrOSUpdate()
324 self._WriteAUStatus('Transfer Devserver/Stateful Update Package')
325 chromeos_AU.TransferDevServerPackage()
326 chromeos_AU.TransferStatefulUpdate()
327
328 restore_stateful = chromeos_AU.CheckRestoreStateful()
329 do_stateful_update = (not self.full_update) and (
330 version_match and self.force_update)
331 stateful_update_complete = False
332 logging.debug('Start CrOS update process...')
333 try:
334 if restore_stateful:
335 self._WriteAUStatus('Restore Stateful Partition')
336 chromeos_AU.RestoreStateful()
xixuan52c2fba2016-05-20 17:02:48 -0700337 stateful_update_complete = True
David Riley63820672017-11-02 10:46:42 -0700338 else:
339 # Whether to execute stateful update depends on:
340 # a. full_update=False: No full reimage is required.
341 # b. The update version is matched to the current version, And
342 # force_update=True: Update is forced even if the version
343 # installed is the same.
344 if do_stateful_update:
345 self._StatefulUpdate(chromeos_AU)
346 stateful_update_complete = True
xixuan52c2fba2016-05-20 17:02:48 -0700347
David Riley63820672017-11-02 10:46:42 -0700348 except timeout_util.TimeoutError:
349 raise
350 except Exception as e:
351 logging.debug('Error happens in stateful update: %r', e)
xixuan52c2fba2016-05-20 17:02:48 -0700352
David Riley63820672017-11-02 10:46:42 -0700353 # Whether to execute rootfs update depends on:
354 # a. stateful update is not completed, or completed by
355 # update action 'restore_stateful'.
356 # b. force_update=True: Update is forced no matter what the current
357 # version is. Or, the update version is not matched to the current
358 # version.
359 require_rootfs_update = self.force_update or (
360 not chromeos_AU.CheckVersion())
361 if (not (do_stateful_update and stateful_update_complete)
362 and require_rootfs_update):
363 self._RootfsUpdate(chromeos_AU)
364 self._StatefulUpdate(chromeos_AU)
xixuan52c2fba2016-05-20 17:02:48 -0700365
David Riley63820672017-11-02 10:46:42 -0700366 self._WriteAUStatus('post-check for CrOS auto-update')
367 chromeos_AU.PostCheckCrOSUpdate()
368 self._WriteAUStatus(cros_update_progress.FINISHED)
David Rileyf5941192018-03-01 14:30:38 -0800369
370 logging.debug('Provision successfully completed (%s)',
371 'legacy' if invoke_autoupdate else 'quick provision')
xixuan52c2fba2016-05-20 17:02:48 -0700372 except Exception as e:
373 logging.debug('Error happens in CrOS auto-update: %r', e)
xixuan28d99072016-10-06 12:24:16 -0700374 self._WriteAUStatus(CROS_ERROR_TEMPLATE % str(traceback.format_exc()))
xixuan52c2fba2016-05-20 17:02:48 -0700375 raise
376
377
378def main():
xixuan52c2fba2016-05-20 17:02:48 -0700379 # Create one cros_update_parser instance for parsing CrOS auto-update cmd.
380 AU_parser = CrOSAUParser()
381 try:
382 AU_parser.ParseArgs()
383 except Exception as e:
384 logging.error('Error in Parsing Args: %r', e)
385 raise
386
387 if len(sys.argv) == 1:
388 AU_parser.parser.print_help()
389 sys.exit(1)
390
xixuanac89ce82016-11-30 16:48:20 -0800391 options = AU_parser.options
xixuan52c2fba2016-05-20 17:02:48 -0700392
xixuan2a0970a2016-08-10 12:12:44 -0700393 # Use process group id as the unique id in track and log files, since
394 # os.setsid is executed before the current process is run.
xixuan52c2fba2016-05-20 17:02:48 -0700395 pid = os.getpid()
xixuan2a0970a2016-08-10 12:12:44 -0700396 pgid = os.getpgid(pid)
xixuan52c2fba2016-05-20 17:02:48 -0700397
398 # Setting log files for CrOS auto-update process.
399 # Log file: file to record every details of CrOS auto-update process.
xixuanac89ce82016-11-30 16:48:20 -0800400 log_file = cros_update_progress.GetExecuteLogFile(options.host_name, pgid)
xixuan52c2fba2016-05-20 17:02:48 -0700401 logging.info('Writing executing logs into file: %s', log_file)
402 logConfig.SetFileHandler(log_file)
403
404 # Create a progress_tracker for tracking CrOS auto-update progress.
xixuanac89ce82016-11-30 16:48:20 -0800405 progress_tracker = cros_update_progress.AUProgress(options.host_name, pgid)
xixuan52c2fba2016-05-20 17:02:48 -0700406
xixuan3bc974e2016-10-18 17:21:43 -0700407 # Create a dir for temporarily storing devserver codes and logs.
xixuanac89ce82016-11-30 16:48:20 -0800408 au_tempdir = cros_update_progress.GetAUTempDirectory(options.host_name, pgid)
xixuan3bc974e2016-10-18 17:21:43 -0700409
xixuan52c2fba2016-05-20 17:02:48 -0700410 # Create cros_update instance to run CrOS auto-update.
xixuanac89ce82016-11-30 16:48:20 -0800411 cros_updater_trigger = CrOSUpdateTrigger(
412 options.host_name, options.build_name, options.static_dir,
413 progress_tracker=progress_tracker,
414 log_file=log_file,
415 au_tempdir=au_tempdir,
416 force_update=options.force_update,
417 full_update=options.full_update,
David Haddock90e49442017-04-07 19:14:09 -0700418 original_build=options.original_build,
David Haddock20559612017-06-28 22:15:08 -0700419 payload_filename=options.payload_filename,
David Riley63820672017-11-02 10:46:42 -0700420 clobber_stateful=options.clobber_stateful,
421 quick_provision=options.quick_provision,
422 devserver_url=options.devserver_url,
423 static_url=options.static_url)
xixuan52c2fba2016-05-20 17:02:48 -0700424
425 # Set timeout the cros-update process.
426 try:
427 with timeout_util.Timeout(CROS_UPDATE_TIMEOUT_MIN*60):
428 cros_updater_trigger.TriggerAU()
429 except timeout_util.TimeoutError as e:
430 error_msg = ('%s. The CrOS auto-update process is timed out, thus will be '
431 'terminated' % str(e))
432 progress_tracker.WriteStatus(CROS_ERROR_TEMPLATE % error_msg)
433
434
435if __name__ == '__main__':
436 main()