blob: 479f82d6722d08a7c77fcdcb81695197516f45cc [file] [log] [blame]
Amin Hassani86583432019-10-03 10:45:45 -07001# -*- coding: utf-8 -*-
xixuana4f4e712017-05-08 15:17:54 -07002# Copyright 2016 The Chromium OS Authors. All rights reserved.
xixuan52c2fba2016-05-20 17:02:48 -07003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""An executable function cros-update for auto-update of a CrOS host.
7
8The reason to create this file is to let devserver to trigger a background
9process for CrOS auto-update. Therefore, when devserver service is restarted
10sometimes, the CrOS auto-update process is still running and the corresponding
11provision task won't claim failure.
12
13It includes two classes:
14 a. CrOSUpdateTrigger:
15 1. Includes all logics which identify which types of update need to be
16 performed in the current DUT.
17 2. Responsible for write current status of CrOS auto-update process into
18 progress_tracker.
19
20 b. CrOSAUParser:
21 1. Pre-setup the required args for CrOS auto-update.
22 2. Parse the input parameters for cmd that runs 'cros_update.py'.
23"""
24
25from __future__ import print_function
26
27import argparse
xixuan52c2fba2016-05-20 17:02:48 -070028import os
David Rileyef7aad12017-11-24 22:03:21 -080029import re
xixuan52c2fba2016-05-20 17:02:48 -070030import sys
David Riley63820672017-11-02 10:46:42 -070031import time
xixuan28d99072016-10-06 12:24:16 -070032import traceback
Amin Hassani86583432019-10-03 10:45:45 -070033import logging # pylint: disable=cros-logging-import
34
35import cros_update_logging
36import cros_update_progress
xixuan52c2fba2016-05-20 17:02:48 -070037
xixuancf58dd32016-08-24 13:57:06 -070038# only import setup_chromite before chromite import.
Amin Hassani86583432019-10-03 10:45:45 -070039import setup_chromite # pylint: disable=unused-import
xixuan52c2fba2016-05-20 17:02:48 -070040try:
41 from chromite.lib import auto_updater
David Riley63820672017-11-02 10:46:42 -070042 from chromite.lib import cros_build_lib
xixuan52c2fba2016-05-20 17:02:48 -070043 from chromite.lib import remote_access
44 from chromite.lib import timeout_util
45except ImportError as e:
46 logging.debug('chromite cannot be imported: %r', e)
47 auto_updater = None
48 remote_access = None
xixuancf58dd32016-08-24 13:57:06 -070049 timeout_util = None
xixuan52c2fba2016-05-20 17:02:48 -070050
xixuanac89ce82016-11-30 16:48:20 -080051# The build channel for recovering host's stateful partition
52STABLE_BUILD_CHANNEL = 'stable-channel'
53
xixuan52c2fba2016-05-20 17:02:48 -070054# Timeout for CrOS auto-update process.
55CROS_UPDATE_TIMEOUT_MIN = 30
56
57# The preserved path in remote device, won't be deleted after rebooting.
58CROS_PRESERVED_PATH = ('/mnt/stateful_partition/unencrypted/'
59 'preserve/cros-update')
60
61# Standard error tmeplate to be written into status tracking log.
xixuan28d99072016-10-06 12:24:16 -070062CROS_ERROR_TEMPLATE = cros_update_progress.ERROR_TAG + ' %s'
xixuan52c2fba2016-05-20 17:02:48 -070063
David Riley63820672017-11-02 10:46:42 -070064# How long after a quick provision fails to wait before falling back to the
65# standard provisioning flow.
66QUICK_PROVISION_FAILURE_DELAY_SEC = 45
67
xixuan27d50442017-08-09 10:38:25 -070068# Setting logging level
69logConfig = cros_update_logging.loggingConfig()
70logConfig.ConfigureLogging()
xixuan52c2fba2016-05-20 17:02:48 -070071
72class CrOSAUParser(object):
73 """Custom command-line options parser for cros-update."""
74 def __init__(self):
75 self.args = sys.argv[1:]
76 self.parser = argparse.ArgumentParser(
77 usage='%(prog)s [options] [control-file]')
78 self.SetupOptions()
79 self.removed_args = []
80
81 # parse an empty list of arguments in order to set self.options
82 # to default values.
83 self.options = self.parser.parse_args(args=[])
84
85 def SetupOptions(self):
86 """Setup options to call cros-update command."""
87 self.parser.add_argument('-d', action='store', type=str,
88 dest='host_name',
89 help='host_name of a DUT')
90 self.parser.add_argument('-b', action='store', type=str,
91 dest='build_name',
92 help='build name to be auto-updated')
93 self.parser.add_argument('--static_dir', action='store', type=str,
xixuan52c2fba2016-05-20 17:02:48 -070094 help='static directory of the devserver')
95 self.parser.add_argument('--force_update', action='store_true',
David Riley63820672017-11-02 10:46:42 -070096 default=False,
xixuan52c2fba2016-05-20 17:02:48 -070097 help=('force an update even if the version '
98 'installed is the same'))
99 self.parser.add_argument('--full_update', action='store_true',
David Riley63820672017-11-02 10:46:42 -0700100 default=False,
101 help='force a rootfs update, skip stateful update')
xixuanac89ce82016-11-30 16:48:20 -0800102 self.parser.add_argument('--original_build', action='store', type=str,
David Riley63820672017-11-02 10:46:42 -0700103 default='',
xixuanac89ce82016-11-30 16:48:20 -0800104 help=('force stateful update with the same '
105 'version of previous rootfs partition'))
David Haddock90e49442017-04-07 19:14:09 -0700106 self.parser.add_argument('--payload_filename', action='store', type=str,
David Riley63820672017-11-02 10:46:42 -0700107 default=None, help='A custom payload filename')
David Haddock20559612017-06-28 22:15:08 -0700108 self.parser.add_argument('--clobber_stateful', action='store_true',
David Riley63820672017-11-02 10:46:42 -0700109 default=False, help='Whether to clobber stateful')
110 self.parser.add_argument('--quick_provision', action='store_true',
111 default=False,
112 help='Whether to attempt quick provisioning path')
113 self.parser.add_argument('--devserver_url', action='store', type=str,
114 default=None, help='Devserver URL base for RPCs')
115 self.parser.add_argument('--static_url', action='store', type=str,
116 default=None,
117 help='Devserver URL base for static files')
xixuan52c2fba2016-05-20 17:02:48 -0700118
119 def ParseArgs(self):
120 """Parse and process command line arguments."""
121 # Positional arguments from the end of the command line will be included
122 # in the list of unknown_args.
123 self.options, unknown_args = self.parser.parse_known_args()
124 # Filter out none-positional arguments
125 while unknown_args and unknown_args[0][0] == '-':
126 self.removed_args.append(unknown_args.pop(0))
127 # Always assume the argument has a value.
128 if unknown_args:
129 self.removed_args.append(unknown_args.pop(0))
130 if self.removed_args:
131 logging.warn('Unknown arguments are removed from the options: %s',
132 self.removed_args)
133
134
135class CrOSUpdateTrigger(object):
136 """The class for CrOS auto-updater trigger.
137
138 This class is used for running all CrOS auto-update trigger logic.
139 """
140 def __init__(self, host_name, build_name, static_dir, progress_tracker=None,
xixuan3bc974e2016-10-18 17:21:43 -0700141 log_file=None, au_tempdir=None, force_update=False,
David Haddock20559612017-06-28 22:15:08 -0700142 full_update=False, original_build=None, payload_filename=None,
David Riley63820672017-11-02 10:46:42 -0700143 clobber_stateful=True, quick_provision=False,
144 devserver_url=None, static_url=None):
xixuan52c2fba2016-05-20 17:02:48 -0700145 self.host_name = host_name
146 self.build_name = build_name
147 self.static_dir = static_dir
148 self.progress_tracker = progress_tracker
149 self.log_file = log_file
xixuan3bc974e2016-10-18 17:21:43 -0700150 self.au_tempdir = au_tempdir
xixuan52c2fba2016-05-20 17:02:48 -0700151 self.force_update = force_update
152 self.full_update = full_update
xixuanac89ce82016-11-30 16:48:20 -0800153 self.original_build = original_build
David Haddock90e49442017-04-07 19:14:09 -0700154 self.payload_filename = payload_filename
David Haddock20559612017-06-28 22:15:08 -0700155 self.clobber_stateful = clobber_stateful
David Riley63820672017-11-02 10:46:42 -0700156 self.quick_provision = quick_provision
157 self.devserver_url = devserver_url
158 self.static_url = static_url
xixuan52c2fba2016-05-20 17:02:48 -0700159
160 def _WriteAUStatus(self, content):
161 if self.progress_tracker:
162 self.progress_tracker.WriteStatus(content)
163
164 def _StatefulUpdate(self, cros_updater):
165 """The detailed process in stateful update.
166
167 Args:
168 cros_updater: The CrOS auto updater for auto-update.
169 """
170 self._WriteAUStatus('pre-setup stateful update')
171 cros_updater.PreSetupStatefulUpdate()
172 self._WriteAUStatus('perform stateful update')
173 cros_updater.UpdateStateful()
174 self._WriteAUStatus('post-check stateful update')
175 cros_updater.PostCheckStatefulUpdate()
176
177 def _RootfsUpdate(self, cros_updater):
178 """The detailed process in rootfs update.
179
180 Args:
181 cros_updater: The CrOS auto updater for auto-update.
182 """
xixuana4f4e712017-05-08 15:17:54 -0700183 self._WriteAUStatus('Check whether devserver can run before rootfs update')
184 cros_updater.CheckDevserverRun()
xixuan52c2fba2016-05-20 17:02:48 -0700185 self._WriteAUStatus('transfer rootfs update package')
186 cros_updater.TransferRootfsUpdate()
187 self._WriteAUStatus('pre-setup rootfs update')
188 cros_updater.PreSetupRootfsUpdate()
189 self._WriteAUStatus('rootfs update')
190 cros_updater.UpdateRootfs()
191 self._WriteAUStatus('post-check rootfs update')
192 cros_updater.PostCheckRootfsUpdate()
193
xixuanac89ce82016-11-30 16:48:20 -0800194 def _GetOriginalPayloadDir(self):
195 """Get the directory of original payload.
196
197 Returns:
198 The directory of original payload, whose format is like:
199 'static/stable-channel/link/3428.210.0'
200 """
201 if self.original_build:
202 return os.path.join(self.static_dir, '%s/%s' % (STABLE_BUILD_CHANNEL,
203 self.original_build))
204 else:
205 return None
206
David Riley63820672017-11-02 10:46:42 -0700207 def _MakeStatusUrl(self, devserver_url, host_name, pid):
208 """Generates a URL to post auto update status to.
209
210 Args:
211 devserver_url: URL base for devserver RPCs.
212 host_name: Host to post status for.
213 pid: pid of the update process.
214
215 Returns:
216 An unescaped URL.
217 """
218 return '%s/post_au_status?host_name=%s&pid=%d' % (devserver_url, host_name,
219 pid)
220
221 def _QuickProvision(self, device):
222 """Performs a quick provision of device.
223
224 Returns:
David Rileyef7aad12017-11-24 22:03:21 -0800225 A dictionary of extracted key-value pairs returned from the script
226 execution.
227
228 Raises:
229 cros_build_lib.RunCommandError: error executing command or script
230 remote_access.SSHConnectionError: SSH connection error
David Riley63820672017-11-02 10:46:42 -0700231 """
232 pid = os.getpid()
233 pgid = os.getpgid(pid)
234 if self.progress_tracker is None:
235 self.progress_tracker = cros_update_progress.AUProgress(self.host_name,
236 pgid)
237
238 dut_script = '/tmp/quick-provision'
239 status_url = self._MakeStatusUrl(self.devserver_url, self.host_name, pgid)
240 cmd = ('curl -o %s %s && bash '
241 '%s --status_url %s %s %s') % (
242 dut_script, os.path.join(self.static_url, 'quick-provision'),
243 dut_script, cros_build_lib.ShellQuote(status_url),
244 self.build_name, self.static_url
245 )
David Rileyf5941192018-03-01 14:30:38 -0800246 # Quick provision script issues a reboot and might result in the SSH
247 # connection being terminated so set ssh_error_ok so that output can
248 # still be captured.
249 results = device.RunCommand(cmd, log_output=True, capture_output=True,
250 ssh_error_ok=True)
David Rileyef7aad12017-11-24 22:03:21 -0800251 key_re = re.compile(r'^KEYVAL: ([^\d\W]\w*)=(.*)$')
252 matches = [key_re.match(l) for l in results.output.splitlines()]
253 keyvals = {m.group(1): m.group(2) for m in matches if m}
Amin Hassani86583432019-10-03 10:45:45 -0700254 logging.info('DUT returned keyvals: %s', keyvals)
David Rileyf5941192018-03-01 14:30:38 -0800255
256 # If there was an SSH error, check the keyvals to see if it actually
257 # completed and suppress the error if so.
258 if results.returncode == remote_access.SSH_ERROR_CODE:
259 if 'COMPLETED' in keyvals:
260 logging.warning('Quick provision completed with ssh error, ignoring...')
261 else:
262 logging.error('Incomplete quick provision failed with ssh error')
263 raise remote_access.SSHConnectionError(results.error)
264
David Rileyef7aad12017-11-24 22:03:21 -0800265 return keyvals
David Riley63820672017-11-02 10:46:42 -0700266
xixuan52c2fba2016-05-20 17:02:48 -0700267 def TriggerAU(self):
268 """Execute auto update for cros_host.
269
270 The auto update includes 4 steps:
271 1. if devserver cannot run, restore the stateful partition.
xixuan2aca0ac2016-07-29 12:02:06 -0700272 2. if possible, do stateful update first, but never raise errors, except
273 for timeout_util.TimeoutError caused by system.signal.
xixuan52c2fba2016-05-20 17:02:48 -0700274 3. If required or stateful_update fails, first do rootfs update, then do
275 stateful_update.
276 4. Post-check for the whole update.
277 """
278 try:
279 with remote_access.ChromiumOSDeviceHandler(
280 self.host_name, port=None,
281 base_dir=CROS_PRESERVED_PATH,
Luigi Semenzato8db8b3c2017-01-26 18:02:19 -0800282 ping=False) as device:
xixuan52c2fba2016-05-20 17:02:48 -0700283
284 logging.debug('Remote device %s is connected', self.host_name)
285 payload_dir = os.path.join(self.static_dir, self.build_name)
xixuanac89ce82016-11-30 16:48:20 -0800286 original_payload_dir = self._GetOriginalPayloadDir()
287
xixuan52c2fba2016-05-20 17:02:48 -0700288 chromeos_AU = auto_updater.ChromiumOSUpdater(
xixuan2a0970a2016-08-10 12:12:44 -0700289 device, self.build_name, payload_dir,
290 dev_dir=os.path.abspath(os.path.dirname(__file__)),
xixuan3bc974e2016-10-18 17:21:43 -0700291 tempdir=self.au_tempdir,
xixuan2a0970a2016-08-10 12:12:44 -0700292 log_file=self.log_file,
xixuanac89ce82016-11-30 16:48:20 -0800293 original_payload_dir=original_payload_dir,
David Haddock90e49442017-04-07 19:14:09 -0700294 yes=True,
David Haddock20559612017-06-28 22:15:08 -0700295 payload_filename=self.payload_filename,
296 clobber_stateful=self.clobber_stateful)
xixuan52c2fba2016-05-20 17:02:48 -0700297
David Riley63820672017-11-02 10:46:42 -0700298 # Allow fall back if the quick provision does not succeed.
299 invoke_autoupdate = True
xixuan52c2fba2016-05-20 17:02:48 -0700300
David Riley6c467252017-11-30 16:39:11 -0800301 if (self.quick_provision and self.clobber_stateful and
302 not self.full_update):
David Riley63820672017-11-02 10:46:42 -0700303 try:
304 logging.debug('Start CrOS quick provision process...')
305 self._WriteAUStatus('Start Quick Provision')
David Riley6c467252017-11-30 16:39:11 -0800306 keyvals = self._QuickProvision(device)
David Riley63820672017-11-02 10:46:42 -0700307 logging.debug('Start CrOS check process...')
David Riley8a7ed5c2018-02-22 11:16:47 -0800308 self._WriteAUStatus('Finish Quick Provision, reboot')
309 chromeos_AU.AwaitReboot(keyvals.get('BOOT_ID'))
David Riley63820672017-11-02 10:46:42 -0700310 self._WriteAUStatus('Finish Quick Provision, post-check')
David Riley8a7ed5c2018-02-22 11:16:47 -0800311 chromeos_AU.PostCheckCrOSUpdate()
David Riley63820672017-11-02 10:46:42 -0700312 self._WriteAUStatus(cros_update_progress.FINISHED)
313 invoke_autoupdate = False
314 except (cros_build_lib.RunCommandError,
David Riley8a7ed5c2018-02-22 11:16:47 -0800315 remote_access.SSHConnectionError,
316 auto_updater.RebootVerificationError) as e:
David Rileyf5941192018-03-01 14:30:38 -0800317 logging.warning(
318 'Error during quick provision, falling back to legacy: %s: %s',
319 type(e).__name__, e)
David Riley63820672017-11-02 10:46:42 -0700320 time.sleep(QUICK_PROVISION_FAILURE_DELAY_SEC)
321
322 if invoke_autoupdate:
323 chromeos_AU.CheckPayloads()
324
325 version_match = chromeos_AU.PreSetupCrOSUpdate()
326 self._WriteAUStatus('Transfer Devserver/Stateful Update Package')
327 chromeos_AU.TransferDevServerPackage()
328 chromeos_AU.TransferStatefulUpdate()
329
330 restore_stateful = chromeos_AU.CheckRestoreStateful()
331 do_stateful_update = (not self.full_update) and (
332 version_match and self.force_update)
333 stateful_update_complete = False
334 logging.debug('Start CrOS update process...')
335 try:
336 if restore_stateful:
337 self._WriteAUStatus('Restore Stateful Partition')
338 chromeos_AU.RestoreStateful()
xixuan52c2fba2016-05-20 17:02:48 -0700339 stateful_update_complete = True
David Riley63820672017-11-02 10:46:42 -0700340 else:
341 # Whether to execute stateful update depends on:
342 # a. full_update=False: No full reimage is required.
343 # b. The update version is matched to the current version, And
344 # force_update=True: Update is forced even if the version
345 # installed is the same.
346 if do_stateful_update:
347 self._StatefulUpdate(chromeos_AU)
348 stateful_update_complete = True
xixuan52c2fba2016-05-20 17:02:48 -0700349
David Riley63820672017-11-02 10:46:42 -0700350 except timeout_util.TimeoutError:
351 raise
352 except Exception as e:
353 logging.debug('Error happens in stateful update: %r', e)
xixuan52c2fba2016-05-20 17:02:48 -0700354
David Riley63820672017-11-02 10:46:42 -0700355 # Whether to execute rootfs update depends on:
356 # a. stateful update is not completed, or completed by
357 # update action 'restore_stateful'.
358 # b. force_update=True: Update is forced no matter what the current
359 # version is. Or, the update version is not matched to the current
360 # version.
361 require_rootfs_update = self.force_update or (
362 not chromeos_AU.CheckVersion())
363 if (not (do_stateful_update and stateful_update_complete)
364 and require_rootfs_update):
365 self._RootfsUpdate(chromeos_AU)
366 self._StatefulUpdate(chromeos_AU)
xixuan52c2fba2016-05-20 17:02:48 -0700367
David Riley63820672017-11-02 10:46:42 -0700368 self._WriteAUStatus('post-check for CrOS auto-update')
369 chromeos_AU.PostCheckCrOSUpdate()
370 self._WriteAUStatus(cros_update_progress.FINISHED)
David Rileyf5941192018-03-01 14:30:38 -0800371
372 logging.debug('Provision successfully completed (%s)',
373 'legacy' if invoke_autoupdate else 'quick provision')
xixuan52c2fba2016-05-20 17:02:48 -0700374 except Exception as e:
375 logging.debug('Error happens in CrOS auto-update: %r', e)
xixuan28d99072016-10-06 12:24:16 -0700376 self._WriteAUStatus(CROS_ERROR_TEMPLATE % str(traceback.format_exc()))
xixuan52c2fba2016-05-20 17:02:48 -0700377 raise
378
379
380def main():
xixuan52c2fba2016-05-20 17:02:48 -0700381 # Create one cros_update_parser instance for parsing CrOS auto-update cmd.
382 AU_parser = CrOSAUParser()
383 try:
384 AU_parser.ParseArgs()
385 except Exception as e:
386 logging.error('Error in Parsing Args: %r', e)
387 raise
388
389 if len(sys.argv) == 1:
390 AU_parser.parser.print_help()
391 sys.exit(1)
392
xixuanac89ce82016-11-30 16:48:20 -0800393 options = AU_parser.options
xixuan52c2fba2016-05-20 17:02:48 -0700394
xixuan2a0970a2016-08-10 12:12:44 -0700395 # Use process group id as the unique id in track and log files, since
396 # os.setsid is executed before the current process is run.
xixuan52c2fba2016-05-20 17:02:48 -0700397 pid = os.getpid()
xixuan2a0970a2016-08-10 12:12:44 -0700398 pgid = os.getpgid(pid)
xixuan52c2fba2016-05-20 17:02:48 -0700399
400 # Setting log files for CrOS auto-update process.
401 # Log file: file to record every details of CrOS auto-update process.
xixuanac89ce82016-11-30 16:48:20 -0800402 log_file = cros_update_progress.GetExecuteLogFile(options.host_name, pgid)
xixuan52c2fba2016-05-20 17:02:48 -0700403 logging.info('Writing executing logs into file: %s', log_file)
404 logConfig.SetFileHandler(log_file)
405
406 # Create a progress_tracker for tracking CrOS auto-update progress.
xixuanac89ce82016-11-30 16:48:20 -0800407 progress_tracker = cros_update_progress.AUProgress(options.host_name, pgid)
xixuan52c2fba2016-05-20 17:02:48 -0700408
xixuan3bc974e2016-10-18 17:21:43 -0700409 # Create a dir for temporarily storing devserver codes and logs.
xixuanac89ce82016-11-30 16:48:20 -0800410 au_tempdir = cros_update_progress.GetAUTempDirectory(options.host_name, pgid)
xixuan3bc974e2016-10-18 17:21:43 -0700411
xixuan52c2fba2016-05-20 17:02:48 -0700412 # Create cros_update instance to run CrOS auto-update.
xixuanac89ce82016-11-30 16:48:20 -0800413 cros_updater_trigger = CrOSUpdateTrigger(
414 options.host_name, options.build_name, options.static_dir,
415 progress_tracker=progress_tracker,
416 log_file=log_file,
417 au_tempdir=au_tempdir,
418 force_update=options.force_update,
419 full_update=options.full_update,
David Haddock90e49442017-04-07 19:14:09 -0700420 original_build=options.original_build,
David Haddock20559612017-06-28 22:15:08 -0700421 payload_filename=options.payload_filename,
David Riley63820672017-11-02 10:46:42 -0700422 clobber_stateful=options.clobber_stateful,
423 quick_provision=options.quick_provision,
424 devserver_url=options.devserver_url,
425 static_url=options.static_url)
xixuan52c2fba2016-05-20 17:02:48 -0700426
427 # Set timeout the cros-update process.
428 try:
429 with timeout_util.Timeout(CROS_UPDATE_TIMEOUT_MIN*60):
430 cros_updater_trigger.TriggerAU()
431 except timeout_util.TimeoutError as e:
432 error_msg = ('%s. The CrOS auto-update process is timed out, thus will be '
433 'terminated' % str(e))
434 progress_tracker.WriteStatus(CROS_ERROR_TEMPLATE % error_msg)
435
436
437if __name__ == '__main__':
438 main()