xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 1 | # Copyright (c) 2016 The Chromium OS Authors. All rights reserved. |
| 2 | # 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 | |
| 7 | The reason to create this file is to let devserver to trigger a background |
| 8 | process for CrOS auto-update. Therefore, when devserver service is restarted |
| 9 | sometimes, the CrOS auto-update process is still running and the corresponding |
| 10 | provision task won't claim failure. |
| 11 | |
| 12 | It 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 | |
| 24 | from __future__ import print_function |
| 25 | |
| 26 | import argparse |
| 27 | import cros_update_logging |
| 28 | import cros_update_progress |
| 29 | import logging |
| 30 | import os |
| 31 | import sys |
| 32 | |
xixuan | cf58dd3 | 2016-08-24 13:57:06 -0700 | [diff] [blame] | 33 | # only import setup_chromite before chromite import. |
| 34 | import setup_chromite # pylint: disable=unused-import |
xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 35 | try: |
| 36 | from chromite.lib import auto_updater |
| 37 | from chromite.lib import remote_access |
| 38 | from chromite.lib import timeout_util |
| 39 | except ImportError as e: |
| 40 | logging.debug('chromite cannot be imported: %r', e) |
| 41 | auto_updater = None |
| 42 | remote_access = None |
xixuan | cf58dd3 | 2016-08-24 13:57:06 -0700 | [diff] [blame] | 43 | timeout_util = None |
xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 44 | |
| 45 | # Timeout for CrOS auto-update process. |
| 46 | CROS_UPDATE_TIMEOUT_MIN = 30 |
| 47 | |
| 48 | # The preserved path in remote device, won't be deleted after rebooting. |
| 49 | CROS_PRESERVED_PATH = ('/mnt/stateful_partition/unencrypted/' |
| 50 | 'preserve/cros-update') |
| 51 | |
| 52 | # Standard error tmeplate to be written into status tracking log. |
| 53 | CROS_ERROR_TEMPLATE = cros_update_progress.ERROR_TAG + ' %r' |
| 54 | |
| 55 | |
| 56 | class CrOSAUParser(object): |
| 57 | """Custom command-line options parser for cros-update.""" |
| 58 | def __init__(self): |
| 59 | self.args = sys.argv[1:] |
| 60 | self.parser = argparse.ArgumentParser( |
| 61 | usage='%(prog)s [options] [control-file]') |
| 62 | self.SetupOptions() |
| 63 | self.removed_args = [] |
| 64 | |
| 65 | # parse an empty list of arguments in order to set self.options |
| 66 | # to default values. |
| 67 | self.options = self.parser.parse_args(args=[]) |
| 68 | |
| 69 | def SetupOptions(self): |
| 70 | """Setup options to call cros-update command.""" |
| 71 | self.parser.add_argument('-d', action='store', type=str, |
| 72 | dest='host_name', |
| 73 | help='host_name of a DUT') |
| 74 | self.parser.add_argument('-b', action='store', type=str, |
| 75 | dest='build_name', |
| 76 | help='build name to be auto-updated') |
| 77 | self.parser.add_argument('--static_dir', action='store', type=str, |
| 78 | dest='static_dir', |
| 79 | help='static directory of the devserver') |
| 80 | self.parser.add_argument('--force_update', action='store_true', |
| 81 | dest='force_update', default=False, |
| 82 | help=('force an update even if the version ' |
| 83 | 'installed is the same')) |
| 84 | self.parser.add_argument('--full_update', action='store_true', |
| 85 | dest='full_update', default=False, |
| 86 | help=('force a rootfs update, skip stateful ' |
| 87 | 'update')) |
| 88 | |
| 89 | def ParseArgs(self): |
| 90 | """Parse and process command line arguments.""" |
| 91 | # Positional arguments from the end of the command line will be included |
| 92 | # in the list of unknown_args. |
| 93 | self.options, unknown_args = self.parser.parse_known_args() |
| 94 | # Filter out none-positional arguments |
| 95 | while unknown_args and unknown_args[0][0] == '-': |
| 96 | self.removed_args.append(unknown_args.pop(0)) |
| 97 | # Always assume the argument has a value. |
| 98 | if unknown_args: |
| 99 | self.removed_args.append(unknown_args.pop(0)) |
| 100 | if self.removed_args: |
| 101 | logging.warn('Unknown arguments are removed from the options: %s', |
| 102 | self.removed_args) |
| 103 | |
| 104 | |
| 105 | class CrOSUpdateTrigger(object): |
| 106 | """The class for CrOS auto-updater trigger. |
| 107 | |
| 108 | This class is used for running all CrOS auto-update trigger logic. |
| 109 | """ |
| 110 | def __init__(self, host_name, build_name, static_dir, progress_tracker=None, |
| 111 | log_file=None, force_update=False, full_update=False): |
| 112 | self.host_name = host_name |
| 113 | self.build_name = build_name |
| 114 | self.static_dir = static_dir |
| 115 | self.progress_tracker = progress_tracker |
| 116 | self.log_file = log_file |
| 117 | self.force_update = force_update |
| 118 | self.full_update = full_update |
| 119 | |
| 120 | def _WriteAUStatus(self, content): |
| 121 | if self.progress_tracker: |
| 122 | self.progress_tracker.WriteStatus(content) |
| 123 | |
| 124 | def _StatefulUpdate(self, cros_updater): |
| 125 | """The detailed process in stateful update. |
| 126 | |
| 127 | Args: |
| 128 | cros_updater: The CrOS auto updater for auto-update. |
| 129 | """ |
| 130 | self._WriteAUStatus('pre-setup stateful update') |
| 131 | cros_updater.PreSetupStatefulUpdate() |
| 132 | self._WriteAUStatus('perform stateful update') |
| 133 | cros_updater.UpdateStateful() |
| 134 | self._WriteAUStatus('post-check stateful update') |
| 135 | cros_updater.PostCheckStatefulUpdate() |
| 136 | |
| 137 | def _RootfsUpdate(self, cros_updater): |
| 138 | """The detailed process in rootfs update. |
| 139 | |
| 140 | Args: |
| 141 | cros_updater: The CrOS auto updater for auto-update. |
| 142 | """ |
| 143 | self._WriteAUStatus('transfer rootfs update package') |
| 144 | cros_updater.TransferRootfsUpdate() |
| 145 | self._WriteAUStatus('pre-setup rootfs update') |
| 146 | cros_updater.PreSetupRootfsUpdate() |
| 147 | self._WriteAUStatus('rootfs update') |
| 148 | cros_updater.UpdateRootfs() |
| 149 | self._WriteAUStatus('post-check rootfs update') |
| 150 | cros_updater.PostCheckRootfsUpdate() |
| 151 | |
| 152 | def TriggerAU(self): |
| 153 | """Execute auto update for cros_host. |
| 154 | |
| 155 | The auto update includes 4 steps: |
| 156 | 1. if devserver cannot run, restore the stateful partition. |
xixuan | 2aca0ac | 2016-07-29 12:02:06 -0700 | [diff] [blame] | 157 | 2. if possible, do stateful update first, but never raise errors, except |
| 158 | for timeout_util.TimeoutError caused by system.signal. |
xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 159 | 3. If required or stateful_update fails, first do rootfs update, then do |
| 160 | stateful_update. |
| 161 | 4. Post-check for the whole update. |
| 162 | """ |
| 163 | try: |
| 164 | with remote_access.ChromiumOSDeviceHandler( |
| 165 | self.host_name, port=None, |
| 166 | base_dir=CROS_PRESERVED_PATH, |
| 167 | ping=True) as device: |
| 168 | |
| 169 | logging.debug('Remote device %s is connected', self.host_name) |
| 170 | payload_dir = os.path.join(self.static_dir, self.build_name) |
| 171 | chromeos_AU = auto_updater.ChromiumOSUpdater( |
xixuan | 2a0970a | 2016-08-10 12:12:44 -0700 | [diff] [blame] | 172 | device, self.build_name, payload_dir, |
| 173 | dev_dir=os.path.abspath(os.path.dirname(__file__)), |
| 174 | log_file=self.log_file, |
xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 175 | yes=True) |
| 176 | chromeos_AU.CheckPayloads() |
| 177 | |
| 178 | self._WriteAUStatus('Transfer Devserver/Stateful Update Package') |
| 179 | chromeos_AU.TransferDevServerPackage() |
| 180 | chromeos_AU.TransferStatefulUpdate() |
| 181 | |
| 182 | restore_stateful = chromeos_AU.CheckRestoreStateful() |
| 183 | do_stateful_update = (not self.full_update) and ( |
| 184 | chromeos_AU.PreSetupCrOSUpdate() and self.force_update) |
| 185 | stateful_update_complete = False |
| 186 | logging.debug('Start CrOS update process...') |
| 187 | try: |
| 188 | if restore_stateful: |
| 189 | self._WriteAUStatus('Restore Stateful Partition') |
| 190 | chromeos_AU.RestoreStateful() |
| 191 | stateful_update_complete = True |
| 192 | else: |
| 193 | # Whether to execute stateful update depends on: |
| 194 | # a. full_update=False: No full reimage is required. |
| 195 | # b. The update version is matched to the current version, And |
| 196 | # force_update=True: Update is forced even if the version |
| 197 | # installed is the same. |
| 198 | if do_stateful_update: |
| 199 | self._StatefulUpdate(chromeos_AU) |
| 200 | stateful_update_complete = True |
| 201 | |
xixuan | 2aca0ac | 2016-07-29 12:02:06 -0700 | [diff] [blame] | 202 | except timeout_util.TimeoutError: |
| 203 | raise |
xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 204 | except Exception as e: |
| 205 | logging.debug('Error happens in stateful update: %r', e) |
| 206 | |
| 207 | # Whether to execute rootfs update depends on: |
| 208 | # a. stateful update is not completed, or completed by |
| 209 | # update action 'restore_stateful'. |
| 210 | # b. force_update=True: Update is forced no matter what the current |
| 211 | # version is. Or, the update version is not matched to the current |
| 212 | # version. |
| 213 | require_rootfs_update = self.force_update or ( |
| 214 | not chromeos_AU.CheckVersion()) |
| 215 | if (not (do_stateful_update and stateful_update_complete) |
| 216 | and require_rootfs_update): |
| 217 | self._RootfsUpdate(chromeos_AU) |
| 218 | self._StatefulUpdate(chromeos_AU) |
| 219 | |
| 220 | self._WriteAUStatus('post-check for CrOS auto-update') |
| 221 | chromeos_AU.PostCheckCrOSUpdate() |
| 222 | self._WriteAUStatus(cros_update_progress.FINISHED) |
| 223 | except Exception as e: |
| 224 | logging.debug('Error happens in CrOS auto-update: %r', e) |
| 225 | self._WriteAUStatus(CROS_ERROR_TEMPLATE % e) |
| 226 | raise |
| 227 | |
| 228 | |
| 229 | def main(): |
| 230 | # Setting logging level |
| 231 | logConfig = cros_update_logging.loggingConfig() |
| 232 | logConfig.ConfigureLogging() |
| 233 | |
| 234 | # Create one cros_update_parser instance for parsing CrOS auto-update cmd. |
| 235 | AU_parser = CrOSAUParser() |
| 236 | try: |
| 237 | AU_parser.ParseArgs() |
| 238 | except Exception as e: |
| 239 | logging.error('Error in Parsing Args: %r', e) |
| 240 | raise |
| 241 | |
| 242 | if len(sys.argv) == 1: |
| 243 | AU_parser.parser.print_help() |
| 244 | sys.exit(1) |
| 245 | |
| 246 | host_name = AU_parser.options.host_name |
| 247 | build_name = AU_parser.options.build_name |
| 248 | static_dir = AU_parser.options.static_dir |
| 249 | force_update = AU_parser.options.force_update |
| 250 | full_update = AU_parser.options.full_update |
| 251 | |
xixuan | 2a0970a | 2016-08-10 12:12:44 -0700 | [diff] [blame] | 252 | # Use process group id as the unique id in track and log files, since |
| 253 | # os.setsid is executed before the current process is run. |
xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 254 | pid = os.getpid() |
xixuan | 2a0970a | 2016-08-10 12:12:44 -0700 | [diff] [blame] | 255 | pgid = os.getpgid(pid) |
xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 256 | |
| 257 | # Setting log files for CrOS auto-update process. |
| 258 | # Log file: file to record every details of CrOS auto-update process. |
xixuan | 2a0970a | 2016-08-10 12:12:44 -0700 | [diff] [blame] | 259 | log_file = cros_update_progress.GetExecuteLogFile(host_name, pgid) |
xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 260 | logging.info('Writing executing logs into file: %s', log_file) |
| 261 | logConfig.SetFileHandler(log_file) |
| 262 | |
| 263 | # Create a progress_tracker for tracking CrOS auto-update progress. |
xixuan | 2a0970a | 2016-08-10 12:12:44 -0700 | [diff] [blame] | 264 | progress_tracker = cros_update_progress.AUProgress(host_name, pgid) |
xixuan | 52c2fba | 2016-05-20 17:02:48 -0700 | [diff] [blame] | 265 | |
| 266 | # Create cros_update instance to run CrOS auto-update. |
| 267 | cros_updater_trigger = CrOSUpdateTrigger(host_name, build_name, static_dir, |
| 268 | progress_tracker=progress_tracker, |
| 269 | log_file=log_file, |
| 270 | force_update=force_update, |
| 271 | full_update=full_update) |
| 272 | |
| 273 | # Set timeout the cros-update process. |
| 274 | try: |
| 275 | with timeout_util.Timeout(CROS_UPDATE_TIMEOUT_MIN*60): |
| 276 | cros_updater_trigger.TriggerAU() |
| 277 | except timeout_util.TimeoutError as e: |
| 278 | error_msg = ('%s. The CrOS auto-update process is timed out, thus will be ' |
| 279 | 'terminated' % str(e)) |
| 280 | progress_tracker.WriteStatus(CROS_ERROR_TEMPLATE % error_msg) |
| 281 | |
| 282 | |
| 283 | if __name__ == '__main__': |
| 284 | main() |