blob: 1db94f6c3d2af03e7472a97a9256884038b3c75c [file] [log] [blame]
Mike Frysingerf1ba7ad2022-09-12 05:42:57 -04001# Copyright 2021 The ChromiumOS Authors
Amin Hassani92f6c4a2021-02-20 17:36:09 -08002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Library containing functions to install an image on a Chromium OS device."""
6
Amin Hassanid4b3ff82021-02-20 23:05:14 -08007import abc
Amin Hassani92f6c4a2021-02-20 17:36:09 -08008import enum
Daichi Hironoc1a8fd32022-01-07 22:17:51 +09009from io import BytesIO
Chris McDonald14ac61d2021-07-21 11:49:56 -060010import logging
Amin Hassani92f6c4a2021-02-20 17:36:09 -080011import os
12import re
Amin Hassanid4b3ff82021-02-20 23:05:14 -080013import tempfile
14import threading
Amin Hassani55970562021-02-22 20:49:13 -080015import time
Daichi Hironoc1a8fd32022-01-07 22:17:51 +090016from typing import Dict, List, Tuple, Union
Amin Hassani92f6c4a2021-02-20 17:36:09 -080017
Amin Hassani55970562021-02-22 20:49:13 -080018from chromite.cli import command
Amin Hassanicf8f0042021-03-12 10:42:13 -080019from chromite.cli import flash
Jae Hoon Kimcc723e02021-08-16 21:03:21 +000020from chromite.lib import cgpt
Amin Hassanid4b3ff82021-02-20 23:05:14 -080021from chromite.lib import constants
Amin Hassani92f6c4a2021-02-20 17:36:09 -080022from chromite.lib import cros_build_lib
Amin Hassani92f6c4a2021-02-20 17:36:09 -080023from chromite.lib import gs
Amin Hassanid4b3ff82021-02-20 23:05:14 -080024from chromite.lib import image_lib
Amin Hassani55970562021-02-22 20:49:13 -080025from chromite.lib import operation
Amin Hassanid4b3ff82021-02-20 23:05:14 -080026from chromite.lib import osutils
Amin Hassani92f6c4a2021-02-20 17:36:09 -080027from chromite.lib import parallel
28from chromite.lib import remote_access
29from chromite.lib import retry_util
Amin Hassani74403082021-02-22 11:40:09 -080030from chromite.lib import stateful_updater
Amin Hassani75c5f942021-02-20 23:56:53 -080031from chromite.lib.paygen import partition_lib
Amin Hassani74403082021-02-22 11:40:09 -080032from chromite.lib.paygen import paygen_stateful_payload_lib
Amin Hassani92f6c4a2021-02-20 17:36:09 -080033from chromite.lib.xbuddy import devserver_constants
34from chromite.lib.xbuddy import xbuddy
Alex Klein18ef1212021-10-14 12:49:02 -060035from chromite.utils import timer
Amin Hassani92f6c4a2021-02-20 17:36:09 -080036
37
Amin Hassani92f6c4a2021-02-20 17:36:09 -080038class Error(Exception):
Alex Klein1699fab2022-09-08 08:46:06 -060039 """Thrown when there is a general Chromium OS-specific flash error."""
Amin Hassani92f6c4a2021-02-20 17:36:09 -080040
41
42class ImageType(enum.Enum):
Alex Klein1699fab2022-09-08 08:46:06 -060043 """Type of the image that is used for flashing the device."""
Amin Hassani92f6c4a2021-02-20 17:36:09 -080044
Alex Klein1699fab2022-09-08 08:46:06 -060045 # The full image on disk (e.g. chromiumos_test_image.bin).
46 FULL = 0
47 # The remote directory path
48 # (e.g gs://chromeos-image-archive/eve-release/R90-x.x.x)
49 REMOTE_DIRECTORY = 1
Amin Hassani92f6c4a2021-02-20 17:36:09 -080050
51
52class Partition(enum.Enum):
Alex Klein1699fab2022-09-08 08:46:06 -060053 """An enum for partition types like kernel and rootfs."""
54
55 KERNEL = 0
56 ROOTFS = 1
57 MINIOS = 2
Amin Hassani92f6c4a2021-02-20 17:36:09 -080058
59
60class DeviceImager(object):
Alex Klein1699fab2022-09-08 08:46:06 -060061 """A class to flash a Chromium OS device.
Amin Hassani92f6c4a2021-02-20 17:36:09 -080062
Alex Klein1699fab2022-09-08 08:46:06 -060063 This utility uses parallelism as much as possible to achieve its goal as fast
64 as possible. For example, it uses parallel compressors, parallel transfers,
65 and simultaneous pipes.
Amin Hassani92f6c4a2021-02-20 17:36:09 -080066 """
67
Alex Klein1699fab2022-09-08 08:46:06 -060068 # The parameters of the kernel and rootfs's two main partitions.
69 A = {Partition.KERNEL: 2, Partition.ROOTFS: 3}
70 B = {Partition.KERNEL: 4, Partition.ROOTFS: 5}
Amin Hassani92f6c4a2021-02-20 17:36:09 -080071
Alex Klein1699fab2022-09-08 08:46:06 -060072 MINIOS_A = {Partition.MINIOS: 9}
73 MINIOS_B = {Partition.MINIOS: 10}
Amin Hassani92f6c4a2021-02-20 17:36:09 -080074
Alex Klein1699fab2022-09-08 08:46:06 -060075 def __init__(
76 self,
77 device,
78 image: str,
79 board: str = None,
80 version: str = None,
81 no_rootfs_update: bool = False,
82 no_stateful_update: bool = False,
83 no_minios_update: bool = False,
84 no_reboot: bool = False,
85 disable_verification: bool = False,
86 clobber_stateful: bool = False,
87 clear_tpm_owner: bool = False,
88 delta: bool = False,
89 ):
90 """Initialize DeviceImager for flashing a Chromium OS device.
Amin Hassani92f6c4a2021-02-20 17:36:09 -080091
Alex Klein1699fab2022-09-08 08:46:06 -060092 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -060093 device: The ChromiumOSDevice to be updated.
94 image: The target image path (can be xBuddy path).
95 board: Board to use.
96 version: Image version to use.
97 no_rootfs_update: Whether to do rootfs partition update.
98 no_stateful_update: Whether to do stateful partition update.
99 no_minios_update: Whether to do minios partition update.
100 no_reboot: Whether to reboot device after update, default True.
101 disable_verification: Whether to disable rootfs verification on the
102 device.
103 clobber_stateful: Whether to do a clean stateful partition.
104 clear_tpm_owner: If true, it will clear the TPM owner on reboot.
105 delta: Whether to use delta compression when transferring image
106 bytes.
Alex Klein1699fab2022-09-08 08:46:06 -0600107 """
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800108
Alex Klein1699fab2022-09-08 08:46:06 -0600109 self._device = device
110 self._image = image
111 self._board = board
112 self._version = version
113 self._no_rootfs_update = no_rootfs_update
114 self._no_stateful_update = no_stateful_update
115 self._no_minios_update = no_minios_update
116 self._no_reboot = no_reboot
117 self._disable_verification = disable_verification
118 self._clobber_stateful = clobber_stateful
119 self._clear_tpm_owner = clear_tpm_owner
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800120
Alex Klein1699fab2022-09-08 08:46:06 -0600121 self._image_type = None
122 self._inactive_state = None
123 self._delta = delta
Daichi Hirono28831b3b2022-04-07 12:41:11 +0900124
Alex Klein1699fab2022-09-08 08:46:06 -0600125 def Run(self):
126 """Update the device with image of specific version."""
127 self._LocateImage()
128 logging.notice(
129 "Preparing to update the remote device %s with image %s",
130 self._device.hostname,
131 self._image,
132 )
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800133
Alex Klein1699fab2022-09-08 08:46:06 -0600134 try:
135 if command.UseProgressBar():
136 op = DeviceImagerOperation()
137 op.Run(self._Run)
138 else:
139 self._Run()
140 except Exception as e:
141 raise Error(f"DeviceImager Failed with error: {e}")
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800142
Alex Klein1699fab2022-09-08 08:46:06 -0600143 # DeviceImagerOperation will look for this log.
144 logging.info("DeviceImager completed.")
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800145
Alex Klein1699fab2022-09-08 08:46:06 -0600146 def _Run(self):
147 """Runs the various operations to install the image on device."""
148 # TODO(b/228389041): Switch to delta compression if self._delta is True
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800149
Alex Klein1699fab2022-09-08 08:46:06 -0600150 self._InstallPartitions()
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800151
Alex Klein1699fab2022-09-08 08:46:06 -0600152 if self._clear_tpm_owner:
153 self._device.ClearTpmOwner()
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800154
Alex Klein1699fab2022-09-08 08:46:06 -0600155 if not self._no_reboot:
156 self._Reboot()
157 self._VerifyBootExpectations()
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800158
Alex Klein1699fab2022-09-08 08:46:06 -0600159 if self._disable_verification:
160 self._device.DisableRootfsVerification()
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800161
Alex Klein1699fab2022-09-08 08:46:06 -0600162 def _LocateImage(self):
163 """Locates the path to the final image(s) that need to be installed.
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800164
Alex Klein1699fab2022-09-08 08:46:06 -0600165 If the paths is local, the image should be the Chromium OS GPT image
166 (e.g. chromiumos_test_image.bin). If the path is remote, it should be the
167 remote directory where we can find the quick-provision and stateful update
168 files (e.g. gs://chromeos-image-archive/eve-release/R90-x.x.x).
Amin Hassanicf8f0042021-03-12 10:42:13 -0800169
Alex Klein1699fab2022-09-08 08:46:06 -0600170 NOTE: At this point there is no caching involved. Hence we always download
171 the partition payloads or extract them from the Chromium OS image.
172 """
173 if os.path.isfile(self._image):
174 self._image_type = ImageType.FULL
175 return
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800176
Alex Klein1699fab2022-09-08 08:46:06 -0600177 # TODO(b/172212406): We could potentially also allow this by searching
178 # through the directory to see whether we have quick-provision and stateful
179 # payloads. This only makes sense when a user has their workstation at home
180 # and doesn't want to incur the bandwidth cost of downloading the same
181 # image multiple times. For that, they can simply download the GPT image
182 # image first and flash that instead.
183 if os.path.isdir(self._image):
184 raise ValueError(
185 f"{self._image}: input must be a disk image, not a directory."
186 )
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800187
Alex Klein1699fab2022-09-08 08:46:06 -0600188 if gs.PathIsGs(self._image):
189 # TODO(b/172212406): Check whether it is a directory. If it wasn't a
190 # directory download the image into some temp location and use it instead.
191 self._image_type = ImageType.REMOTE_DIRECTORY
192 return
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800193
Alex Klein1699fab2022-09-08 08:46:06 -0600194 # Assuming it is an xBuddy path.
195 board = cros_build_lib.GetBoard(
196 device_board=self._device.board or flash.GetDefaultBoard(),
197 override_board=self._board,
198 force=True,
199 )
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800200
Alex Klein1699fab2022-09-08 08:46:06 -0600201 xb = xbuddy.XBuddy(board=board, version=self._version)
202 build_id, local_file = xb.Translate([self._image])
203 if build_id is None:
204 raise Error(f"{self._image}: unable to find matching xBuddy path.")
205 logging.info("XBuddy path translated to build ID %s", build_id)
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800206
Alex Klein1699fab2022-09-08 08:46:06 -0600207 if local_file:
208 self._image = local_file
209 self._image_type = ImageType.FULL
210 return
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800211
Alex Klein1699fab2022-09-08 08:46:06 -0600212 self._image = f"{devserver_constants.GS_IMAGE_DIR}/{build_id}"
213 self._image_type = ImageType.REMOTE_DIRECTORY
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800214
Alex Klein1699fab2022-09-08 08:46:06 -0600215 def _SplitDevPath(self, path: str) -> Tuple[str, int]:
216 """Splits the given /dev/x path into prefix and the dev number.
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800217
Alex Klein1699fab2022-09-08 08:46:06 -0600218 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600219 path: The path to a block dev device.
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800220
Alex Klein1699fab2022-09-08 08:46:06 -0600221 Returns:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600222 A tuple of representing the prefix and the index of the dev path.
223 e.g.: '/dev/mmcblk0p1' -> ['/dev/mmcblk0p', 1]
Alex Klein1699fab2022-09-08 08:46:06 -0600224 """
225 match = re.search(r"(.*)([0-9]+)$", path)
226 if match is None:
227 raise Error(f"{path}: Could not parse root dev path.")
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000228
Alex Klein1699fab2022-09-08 08:46:06 -0600229 return match.group(1), int(match.group(2))
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000230
Alex Klein1699fab2022-09-08 08:46:06 -0600231 def _GetKernelState(self, root_num: int) -> Tuple[Dict, Dict]:
232 """Returns the kernel state.
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800233
Alex Klein1699fab2022-09-08 08:46:06 -0600234 Returns:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600235 A tuple of two dictionaries: The current active kernel state and the
236 inactive kernel state. (Look at A and B constants in this class.)
Alex Klein1699fab2022-09-08 08:46:06 -0600237 """
238 if root_num == self.A[Partition.ROOTFS]:
239 return self.A, self.B
240 elif root_num == self.B[Partition.ROOTFS]:
241 return self.B, self.A
242 else:
243 raise Error(f"Invalid root partition number {root_num}")
Amin Hassanid684e982021-02-26 11:10:58 -0800244
Alex Klein1699fab2022-09-08 08:46:06 -0600245 def _GetMiniOSState(self, minios_num: int) -> Tuple[Dict, Dict]:
246 """Returns the miniOS state.
Amin Hassani75c5f942021-02-20 23:56:53 -0800247
Alex Klein1699fab2022-09-08 08:46:06 -0600248 Returns:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600249 A tuple of dictionaries: The current active miniOS state and the
250 inactive miniOS state.
Alex Klein1699fab2022-09-08 08:46:06 -0600251 """
252 if minios_num == self.MINIOS_A[Partition.MINIOS]:
253 return self.MINIOS_A, self.MINIOS_B
254 elif minios_num == self.MINIOS_B[Partition.MINIOS]:
255 return self.MINIOS_B, self.MINIOS_A
256 else:
257 raise Error(f"Invalid minios partition number {minios_num}")
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800258
Alex Klein1699fab2022-09-08 08:46:06 -0600259 def _InstallPartitions(self):
260 """The main method that installs the partitions of a Chrome OS device.
Amin Hassani74403082021-02-22 11:40:09 -0800261
Alex Klein1699fab2022-09-08 08:46:06 -0600262 It uses parallelism to install the partitions as fast as possible.
263 """
264 prefix, root_num = self._SplitDevPath(self._device.root_dev)
265 active_state, self._inactive_state = self._GetKernelState(root_num)
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000266
Alex Klein1699fab2022-09-08 08:46:06 -0600267 updaters = []
268 if not self._no_rootfs_update:
269 current_root = prefix + str(active_state[Partition.ROOTFS])
270 target_root = prefix + str(self._inactive_state[Partition.ROOTFS])
271 updaters.append(
272 RootfsUpdater(
273 current_root,
274 self._device,
275 self._image,
276 self._image_type,
277 target_root,
278 )
279 )
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800280
Alex Klein1699fab2022-09-08 08:46:06 -0600281 target_kernel = prefix + str(self._inactive_state[Partition.KERNEL])
282 updaters.append(
283 KernelUpdater(
284 self._device, self._image, self._image_type, target_kernel
285 )
286 )
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800287
Alex Klein1699fab2022-09-08 08:46:06 -0600288 if not self._no_stateful_update:
289 updaters.append(
290 StatefulUpdater(
291 self._clobber_stateful,
292 self._device,
293 self._image,
294 self._image_type,
295 None,
296 )
297 )
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800298
Alex Klein1699fab2022-09-08 08:46:06 -0600299 if not self._no_minios_update:
300 minios_priority = self._device.run(
301 ["crossystem", constants.MINIOS_PRIORITY]
302 ).stdout
303 if minios_priority not in ["A", "B"]:
304 logging.warning(
305 "Skipping miniOS flash due to missing priority."
306 )
307 else:
308 # Reference disk_layout_v3 for partition numbering.
309 _, inactive_minios_state = self._GetMiniOSState(
310 9 if minios_priority == "A" else 10
311 )
312 target_minios = prefix + str(
313 inactive_minios_state[Partition.MINIOS]
314 )
315 minios_updater = MiniOSUpdater(
316 self._device, self._image, self._image_type, target_minios
317 )
318 updaters.append(minios_updater)
Amin Hassani92f6c4a2021-02-20 17:36:09 -0800319
Alex Klein1699fab2022-09-08 08:46:06 -0600320 # Retry the partitions updates that failed, in case a transient error (like
321 # SSH drop, etc) caused the error.
322 num_retries = 1
323 try:
324 retry_util.RetryException(
325 Error,
326 num_retries,
327 parallel.RunParallelSteps,
328 (x.Run for x in updaters if not x.IsFinished()),
329 halt_on_error=True,
330 )
331 except Exception:
332 # If one of the partitions failed to be installed, revert all partitions.
333 parallel.RunParallelSteps(x.Revert for x in updaters)
334 raise
335
336 def _Reboot(self):
337 """Reboots the device."""
338 try:
339 self._device.Reboot(timeout_sec=300)
340 except remote_access.RebootError:
341 raise Error(
342 "Could not recover from reboot. Once example reason"
343 " could be the image provided was a non-test image"
344 " or the system failed to boot after the update."
345 )
346 except Exception as e:
347 raise Error(f"Failed to reboot to the device with error: {e}")
348
349 def _VerifyBootExpectations(self):
350 """Verify that we fully booted into the expected kernel state."""
351 # Discover the newly active kernel.
352 _, root_num = self._SplitDevPath(self._device.root_dev)
353 active_state, _ = self._GetKernelState(root_num)
354
355 # If this happens, we should rollback.
356 if active_state != self._inactive_state:
357 raise Error("The expected kernel state after update is invalid.")
358
359 logging.info("Verified boot expectations.")
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800360
361
362class ReaderBase(threading.Thread):
Alex Klein1699fab2022-09-08 08:46:06 -0600363 """The base class for reading different inputs and writing into output.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800364
Alex Klein1699fab2022-09-08 08:46:06 -0600365 This class extends threading.Thread, so it will be run on its own thread. Also
366 it can be used as a context manager. Internally, it opens necessary files for
367 writing to and reading from. This class cannot be instantiated, it needs to be
368 sub-classed first to provide necessary function implementations.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800369 """
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800370
Alex Klein1699fab2022-09-08 08:46:06 -0600371 def __init__(self, use_named_pipes: bool = False):
372 """Initializes the class.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800373
Alex Klein1699fab2022-09-08 08:46:06 -0600374 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600375 use_named_pipes: Whether to use a named pipe or anonymous file
Alex Klein1699fab2022-09-08 08:46:06 -0600376 descriptors.
377 """
378 super().__init__()
379 self._use_named_pipes = use_named_pipes
380 self._pipe_target = None
381 self._pipe_source = None
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800382
Alex Klein1699fab2022-09-08 08:46:06 -0600383 def __del__(self):
384 """Destructor.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800385
Alex Klein1699fab2022-09-08 08:46:06 -0600386 Make sure to clean up any named pipes we might have created.
387 """
388 if self._use_named_pipes:
389 osutils.SafeUnlink(self._pipe_target)
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800390
Alex Klein1699fab2022-09-08 08:46:06 -0600391 def __enter__(self):
392 """Enters the context manager"""
393 if self._use_named_pipes:
394 # There is no need for the temp file, we only need its path. So the named
395 # pipe is created after this temp file is deleted.
396 with tempfile.NamedTemporaryFile(
397 prefix="chromite-device-imager"
398 ) as fp:
399 self._pipe_target = self._pipe_source = fp.name
400 os.mkfifo(self._pipe_target)
401 else:
402 self._pipe_target, self._pipe_source = os.pipe()
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800403
Alex Klein1699fab2022-09-08 08:46:06 -0600404 self.start()
405 return self
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800406
Alex Klein1699fab2022-09-08 08:46:06 -0600407 def __exit__(self, *args, **kwargs):
408 """Exits the context manager."""
409 self.join()
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800410
Alex Klein1699fab2022-09-08 08:46:06 -0600411 def _Source(self):
412 """Returns the source pipe to write data into.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800413
Alex Klein1699fab2022-09-08 08:46:06 -0600414 Sub-classes can use this function to determine where to write their data
415 into.
416 """
417 return self._pipe_source
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800418
Alex Klein1699fab2022-09-08 08:46:06 -0600419 def _CloseSource(self):
420 """Closes the source pipe.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800421
Alex Klein1699fab2022-09-08 08:46:06 -0600422 Sub-classes should use this function to close the pipe after they are done
423 writing into it. Failure to do so may result reader of the data to hang
424 indefinitely.
425 """
426 if not self._use_named_pipes:
427 os.close(self._pipe_source)
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800428
Alex Klein1699fab2022-09-08 08:46:06 -0600429 def Target(self):
430 """Returns the target pipe to read data from.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800431
Alex Klein1699fab2022-09-08 08:46:06 -0600432 Users of this class can use this path to read data from.
433 """
434 return self._pipe_target
435
436 def CloseTarget(self):
437 """Closes the target pipe.
438
439 Users of this class should use this function to close the pipe after they
440 are done reading from it.
441 """
442 if self._use_named_pipes:
443 os.remove(self._pipe_target)
444 else:
445 os.close(self._pipe_target)
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800446
447
448class PartialFileReader(ReaderBase):
Alex Klein1699fab2022-09-08 08:46:06 -0600449 """A class to read specific offset and length from a file and compress it.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800450
Alex Klein1699fab2022-09-08 08:46:06 -0600451 This class can be used to read from specific location and length in a file
452 (e.g. A partition in a GPT image). Then it compresses the input and writes it
453 out (to a pipe). Look at the base class for more information.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800454 """
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800455
Alex Klein1699fab2022-09-08 08:46:06 -0600456 # The offset of different partitions in a Chromium OS image does not always
457 # align to larger values like 4096. It seems that 512 is the maximum value to
458 # be divisible by partition offsets. This size should not be increased just
459 # for 'performance reasons'. Since we are doing everything in parallel, in
460 # practice there is not much difference between this and larger block sizes as
461 # parallelism hides the possible extra latency provided by smaller block
462 # sizes.
463 _BLOCK_SIZE = 512
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800464
Alex Klein1699fab2022-09-08 08:46:06 -0600465 def __init__(
466 self,
467 image: str,
468 offset: int,
469 length: int,
470 compression_command: List[str],
471 ):
472 """Initializes the class.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800473
Alex Klein1699fab2022-09-08 08:46:06 -0600474 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600475 image: The path to an image (local or remote directory).
476 offset: The offset (in bytes) to read from the image.
477 length: The length (in bytes) to read from the image.
478 compression_command: The command to compress transferred bytes.
Alex Klein1699fab2022-09-08 08:46:06 -0600479 """
480 super().__init__()
481
482 self._image = image
483 self._offset = offset
484 self._length = length
485 self._compression_command = compression_command
486
487 def run(self):
488 """Runs the reading and compression."""
489 cmd = [
490 "dd",
491 "status=none",
492 f"if={self._image}",
493 f"ibs={self._BLOCK_SIZE}",
494 f"skip={int(self._offset/self._BLOCK_SIZE)}",
495 f"count={int(self._length/self._BLOCK_SIZE)}",
496 "|",
497 *self._compression_command,
498 ]
499
500 try:
501 cros_build_lib.run(" ".join(cmd), stdout=self._Source(), shell=True)
502 finally:
503 self._CloseSource()
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800504
505
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800506class GsFileCopier(ReaderBase):
Alex Klein1699fab2022-09-08 08:46:06 -0600507 """A class for downloading gzip compressed file from GS bucket into a pipe."""
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800508
Alex Klein1699fab2022-09-08 08:46:06 -0600509 def __init__(self, image: str):
510 """Initializes the class.
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800511
Alex Klein1699fab2022-09-08 08:46:06 -0600512 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600513 image: The path to an image (local or remote directory).
Alex Klein1699fab2022-09-08 08:46:06 -0600514 """
515 super().__init__(use_named_pipes=True)
516 self._image = image
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800517
Alex Klein1699fab2022-09-08 08:46:06 -0600518 def run(self):
519 """Runs the download and write into the output pipe."""
520 try:
521 gs.GSContext().Copy(self._image, self._Source())
522 finally:
523 self._CloseSource()
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800524
525
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800526class PartitionUpdaterBase(object):
Alex Klein1699fab2022-09-08 08:46:06 -0600527 """A base abstract class to use for installing an image into a partition.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800528
Alex Klein1699fab2022-09-08 08:46:06 -0600529 Sub-classes should implement the abstract methods to provide the core
530 functionality.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800531 """
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800532
Alex Klein1699fab2022-09-08 08:46:06 -0600533 def __init__(self, device, image: str, image_type, target: str):
534 """Initializes this base class with values that most sub-classes will need.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800535
Alex Klein1699fab2022-09-08 08:46:06 -0600536 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600537 device: The ChromiumOSDevice to be updated.
538 image: The target image path for the partition update.
539 image_type: The type of the image (ImageType).
540 target: The target path (e.g. block dev) to install the update.
Alex Klein1699fab2022-09-08 08:46:06 -0600541 """
542 self._device = device
543 self._image = image
544 self._image_type = image_type
545 self._target = target
546 self._finished = False
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800547
Alex Klein1699fab2022-09-08 08:46:06 -0600548 def Run(self):
549 """The main function that does the partition update job."""
550 with timer.Timer() as t:
551 try:
552 self._Run()
553 finally:
554 self._finished = True
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800555
Alex Klein1699fab2022-09-08 08:46:06 -0600556 logging.debug("Completed %s in %s", self.__class__.__name__, t)
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800557
Alex Klein1699fab2022-09-08 08:46:06 -0600558 @abc.abstractmethod
559 def _Run(self):
560 """The method that need to be implemented by sub-classes."""
561 raise NotImplementedError("Sub-classes need to implement this.")
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800562
Alex Klein1699fab2022-09-08 08:46:06 -0600563 def IsFinished(self):
564 """Returns whether the partition update has been successful."""
565 return self._finished
566
567 @abc.abstractmethod
568 def Revert(self):
569 """Reverts the partition update.
570
571 Sub-classes need to implement this function to provide revert capability.
572 """
573 raise NotImplementedError("Sub-classes need to implement this.")
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800574
575
576class RawPartitionUpdater(PartitionUpdaterBase):
Alex Klein1699fab2022-09-08 08:46:06 -0600577 """A class to update a raw partition on a Chromium OS device."""
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800578
Alex Klein1699fab2022-09-08 08:46:06 -0600579 def _Run(self):
580 """The function that does the job of kernel partition update."""
581 if self._image_type == ImageType.FULL:
582 self._CopyPartitionFromImage(self._GetPartitionName())
583 elif self._image_type == ImageType.REMOTE_DIRECTORY:
584 self._RedirectPartition(self._GetRemotePartitionName())
585 else:
586 raise ValueError(f"Invalid image type {self._image_type}")
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800587
Alex Klein1699fab2022-09-08 08:46:06 -0600588 def _GetPartitionName(self):
589 """Returns the name of the partition in a Chromium OS GPT layout.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800590
Alex Klein1699fab2022-09-08 08:46:06 -0600591 Subclasses should override this function to return correct name.
592 """
593 raise NotImplementedError("Subclasses need to implement this.")
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800594
Alex Klein1699fab2022-09-08 08:46:06 -0600595 def _CopyPartitionFromImage(self, part_name: str):
596 """Updates the device's partition from a local Chromium OS image.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800597
Alex Klein1699fab2022-09-08 08:46:06 -0600598 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600599 part_name: The name of the partition in the source image that needs
600 to be extracted.
Alex Klein1699fab2022-09-08 08:46:06 -0600601 """
602 offset, length = self._GetPartLocation(part_name)
603 offset, length = self._OptimizePartLocation(offset, length)
604 compressor, decompressor = self._GetCompressionAndDecompression()
Daichi Hironoc1a8fd32022-01-07 22:17:51 +0900605
Alex Klein1699fab2022-09-08 08:46:06 -0600606 with PartialFileReader(
607 self._image, offset, length, compressor
608 ) as generator:
609 try:
610 self._WriteToTarget(generator.Target(), decompressor)
611 finally:
612 generator.CloseTarget()
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800613
Alex Klein1699fab2022-09-08 08:46:06 -0600614 def _GetCompressionAndDecompression(self) -> Tuple[List[str], List[str]]:
615 """Returns compression / decompression commands."""
Daichi Hironoc1a8fd32022-01-07 22:17:51 +0900616
Alex Klein1699fab2022-09-08 08:46:06 -0600617 return (
Mike Frysinger66306012022-04-22 15:23:13 -0400618 [
619 cros_build_lib.FindCompressor(
620 cros_build_lib.CompressionType.GZIP
621 )
622 ],
623 self._device.GetDecompressor(cros_build_lib.CompressionType.GZIP),
Alex Klein1699fab2022-09-08 08:46:06 -0600624 )
Daichi Hironoc1a8fd32022-01-07 22:17:51 +0900625
Alex Klein1699fab2022-09-08 08:46:06 -0600626 def _WriteToTarget(
627 self, source: Union[int, BytesIO], decompress_command: List[str]
628 ) -> None:
629 """Writes bytes source to the target device on DUT.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800630
Alex Klein1699fab2022-09-08 08:46:06 -0600631 Returns:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600632 A string command to run on a device to read data from stdin,
633 uncompress it and write it to the target partition.
Alex Klein1699fab2022-09-08 08:46:06 -0600634 """
635 # Using oflag=direct to tell the OS not to cache the writes (faster).
636 cmd = " ".join(
637 [
638 *decompress_command,
639 "|",
640 "dd",
641 "bs=1M",
642 "oflag=direct",
643 f"of={self._target}",
644 ]
645 )
646 self._device.run(cmd, input=source, shell=True)
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800647
Alex Klein1699fab2022-09-08 08:46:06 -0600648 def _GetPartLocation(self, part_name: str):
649 """Extracts the location and size of the raw partition from the image.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800650
Alex Klein1699fab2022-09-08 08:46:06 -0600651 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600652 part_name: The name of the partition in the source image that needs
653 to be extracted.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800654
Alex Klein1699fab2022-09-08 08:46:06 -0600655 Returns:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600656 A tuple of offset and length (in bytes) from the image.
Alex Klein1699fab2022-09-08 08:46:06 -0600657 """
658 try:
659 parts = image_lib.GetImageDiskPartitionInfo(self._image)
660 part_info = [p for p in parts if p.name == part_name][0]
661 except IndexError:
662 raise Error(f"No partition named {part_name} found.")
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800663
Alex Klein1699fab2022-09-08 08:46:06 -0600664 return int(part_info.start), int(part_info.size)
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800665
Alex Klein1699fab2022-09-08 08:46:06 -0600666 def _GetRemotePartitionName(self):
667 """Returns the name of the quick-provision partition file.
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800668
Alex Klein1699fab2022-09-08 08:46:06 -0600669 Subclasses should override this function to return correct name.
670 """
671 raise NotImplementedError("Subclasses need to implement this.")
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800672
Alex Klein1699fab2022-09-08 08:46:06 -0600673 def _OptimizePartLocation(self, offset: int, length: int):
674 """Optimizes the offset and length of the partition.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800675
Alex Klein1699fab2022-09-08 08:46:06 -0600676 Subclasses can override this to provide better offset/length than what is
677 defined in the PGT partition layout.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800678
Alex Klein1699fab2022-09-08 08:46:06 -0600679 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600680 offset: The offset (in bytes) of the partition in the image.
681 length: The length (in bytes) of the partition.
Amin Hassanid4b3ff82021-02-20 23:05:14 -0800682
Alex Klein1699fab2022-09-08 08:46:06 -0600683 Returns:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600684 A tuple of offset and length (in bytes) from the image.
Alex Klein1699fab2022-09-08 08:46:06 -0600685 """
686 return offset, length
Amin Hassanid684e982021-02-26 11:10:58 -0800687
Alex Klein1699fab2022-09-08 08:46:06 -0600688 def _RedirectPartition(self, file_name: str):
689 """Downloads the partition from a remote path and writes it into target.
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800690
Alex Klein1699fab2022-09-08 08:46:06 -0600691 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600692 file_name: The file name in the remote directory self._image.
Alex Klein1699fab2022-09-08 08:46:06 -0600693 """
694 image_path = os.path.join(self._image, file_name)
695 with GsFileCopier(image_path) as generator:
696 try:
697 with open(generator.Target(), "rb") as fp:
698 # Always use GZIP as remote quick provision images are gzip
699 # compressed only.
700 self._WriteToTarget(
701 fp,
Mike Frysinger66306012022-04-22 15:23:13 -0400702 self._device.GetDecompressor(
703 cros_build_lib.CompressionType.GZIP
704 ),
Alex Klein1699fab2022-09-08 08:46:06 -0600705 )
706 finally:
707 generator.CloseTarget()
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800708
Amin Hassanid684e982021-02-26 11:10:58 -0800709
710class KernelUpdater(RawPartitionUpdater):
Alex Klein1699fab2022-09-08 08:46:06 -0600711 """A class to update the kernel partition on a Chromium OS device."""
Amin Hassanid684e982021-02-26 11:10:58 -0800712
Alex Klein1699fab2022-09-08 08:46:06 -0600713 def _GetPartitionName(self):
714 """See RawPartitionUpdater._GetPartitionName()."""
715 return constants.PART_KERN_B
Amin Hassanid684e982021-02-26 11:10:58 -0800716
Alex Klein1699fab2022-09-08 08:46:06 -0600717 def _GetRemotePartitionName(self):
718 """See RawPartitionUpdater._GetRemotePartitionName()."""
719 return constants.QUICK_PROVISION_PAYLOAD_KERNEL
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800720
Alex Klein1699fab2022-09-08 08:46:06 -0600721 def Revert(self):
722 """Reverts the kernel partition update."""
723 # There is nothing to do for reverting kernel partition.
Amin Hassani75c5f942021-02-20 23:56:53 -0800724
725
726class RootfsUpdater(RawPartitionUpdater):
Alex Klein1699fab2022-09-08 08:46:06 -0600727 """A class to update the root partition on a Chromium OS device."""
Amin Hassani75c5f942021-02-20 23:56:53 -0800728
Alex Klein1699fab2022-09-08 08:46:06 -0600729 def __init__(self, current_root: str, *args):
730 """Initializes the class.
Amin Hassani75c5f942021-02-20 23:56:53 -0800731
Alex Klein1699fab2022-09-08 08:46:06 -0600732 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600733 current_root: The current root device path.
734 *args: See PartitionUpdaterBase
Alex Klein1699fab2022-09-08 08:46:06 -0600735 """
736 super().__init__(*args)
Amin Hassani75c5f942021-02-20 23:56:53 -0800737
Alex Klein1699fab2022-09-08 08:46:06 -0600738 self._current_root = current_root
739 self._ran_postinst = False
Amin Hassani75c5f942021-02-20 23:56:53 -0800740
Alex Klein1699fab2022-09-08 08:46:06 -0600741 def _GetPartitionName(self):
742 """See RawPartitionUpdater._GetPartitionName()."""
743 return constants.PART_ROOT_A
Amin Hassani75c5f942021-02-20 23:56:53 -0800744
Alex Klein1699fab2022-09-08 08:46:06 -0600745 def _GetRemotePartitionName(self):
746 """See RawPartitionUpdater._GetRemotePartitionName()."""
747 return constants.QUICK_PROVISION_PAYLOAD_ROOTFS
Amin Hassani0fe49ae2021-02-21 23:41:58 -0800748
Alex Klein1699fab2022-09-08 08:46:06 -0600749 def _Run(self):
750 """The function that does the job of rootfs partition update."""
751 with ProgressWatcher(self._device, self._target):
752 super()._Run()
Amin Hassani75c5f942021-02-20 23:56:53 -0800753
Alex Klein1699fab2022-09-08 08:46:06 -0600754 self._RunPostInst()
Amin Hassani75c5f942021-02-20 23:56:53 -0800755
Alex Klein1699fab2022-09-08 08:46:06 -0600756 def _OptimizePartLocation(self, offset: int, length: int):
757 """Optimizes the size of the root partition of the image.
Amin Hassani75c5f942021-02-20 23:56:53 -0800758
Alex Klein1699fab2022-09-08 08:46:06 -0600759 Normally the file system does not occupy the entire partition. Furthermore
760 we don't need the verity hash tree at the end of the root file system
761 because postinst will recreate it. This function reads the (approximate)
762 superblock of the ext4 partition and extracts the actual file system size in
763 the root partition.
764 """
765 superblock_size = 4096 * 2
766 with open(self._image, "rb") as r:
767 r.seek(offset)
768 with tempfile.NamedTemporaryFile(delete=False) as fp:
769 fp.write(r.read(superblock_size))
770 fp.close()
771 return offset, partition_lib.Ext2FileSystemSize(fp.name)
Amin Hassani75c5f942021-02-20 23:56:53 -0800772
Alex Klein1699fab2022-09-08 08:46:06 -0600773 def _RunPostInst(self, on_target: bool = True):
774 """Runs the postinst process in the root partition.
Amin Hassani75c5f942021-02-20 23:56:53 -0800775
Alex Klein1699fab2022-09-08 08:46:06 -0600776 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600777 on_target: If true the postinst is run on the target (inactive)
778 partition. This is used when doing normal updates. If false, the
779 postinst is run on the current (active) partition. This is used
780 when reverting an update.
Alex Klein1699fab2022-09-08 08:46:06 -0600781 """
782 try:
783 postinst_dir = "/"
784 partition = self._current_root
785 if on_target:
786 postinst_dir = self._device.run(
787 ["mktemp", "-d", "-p", self._device.work_dir],
788 capture_output=True,
789 ).stdout.strip()
790 self._device.run(
791 ["mount", "-o", "ro", self._target, postinst_dir]
792 )
793 partition = self._target
Amin Hassani75c5f942021-02-20 23:56:53 -0800794
Alex Klein1699fab2022-09-08 08:46:06 -0600795 self._ran_postinst = True
796 postinst = os.path.join(postinst_dir, "postinst")
797 result = self._device.run(
798 [postinst, partition], capture_output=True
799 )
Amin Hassani75c5f942021-02-20 23:56:53 -0800800
Alex Klein1699fab2022-09-08 08:46:06 -0600801 logging.debug(
802 "Postinst result on %s: \n%s", postinst, result.stdout
803 )
804 # DeviceImagerOperation will look for this log.
805 logging.info("Postinstall completed.")
806 finally:
807 if on_target:
808 self._device.run(["umount", postinst_dir])
Amin Hassani75c5f942021-02-20 23:56:53 -0800809
Alex Klein1699fab2022-09-08 08:46:06 -0600810 def Revert(self):
811 """Reverts the root update install."""
812 logging.info("Reverting the rootfs partition update.")
813 if self._ran_postinst:
814 # We don't have to do anything for revert if we haven't changed the kernel
815 # priorities yet.
816 self._RunPostInst(on_target=False)
Amin Hassani74403082021-02-22 11:40:09 -0800817
818
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000819class MiniOSUpdater(RawPartitionUpdater):
Alex Klein1699fab2022-09-08 08:46:06 -0600820 """A class to update the miniOS partition on a Chromium OS device."""
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000821
Alex Klein1699fab2022-09-08 08:46:06 -0600822 def __init__(self, *args):
823 """Initializes the class.
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000824
Alex Klein1699fab2022-09-08 08:46:06 -0600825 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600826 *args: See PartitionUpdaterBase
Alex Klein1699fab2022-09-08 08:46:06 -0600827 """
828 super().__init__(*args)
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000829
Alex Klein1699fab2022-09-08 08:46:06 -0600830 self._ran_postinst = False
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000831
Alex Klein1699fab2022-09-08 08:46:06 -0600832 def _GetPartitionName(self):
833 """See RawPartitionUpdater._GetPartitionName()."""
834 return constants.PART_MINIOS_A
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000835
Alex Klein1699fab2022-09-08 08:46:06 -0600836 def _GetRemotePartitionName(self):
837 """See RawPartitionUpdater._GetRemotePartitionName()."""
838 return constants.QUICK_PROVISION_PAYLOAD_MINIOS
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000839
Alex Klein1699fab2022-09-08 08:46:06 -0600840 def _Run(self):
841 """The function that does the job of rootfs partition update."""
842 if self._image_type == ImageType.FULL:
843 if self._MiniOSPartitionsExistInImage():
844 logging.info("Updating miniOS partition from local.")
845 super()._Run()
846 else:
847 logging.warning(
848 "Not updating miniOS partition as it does not exist."
849 )
850 return
851 elif self._image_type == ImageType.REMOTE_DIRECTORY:
852 if not gs.GSContext().Exists(
853 os.path.join(
854 self._image, constants.QUICK_PROVISION_PAYLOAD_MINIOS
855 )
856 ):
857 logging.warning("Not updating miniOS, missing remote files.")
858 return
859 elif not self._MiniOSPartitionsExist():
860 logging.warning("Not updating miniOS, missing partitions.")
861 return
862 else:
863 logging.info("Updating miniOS partition from remote.")
864 super()._Run()
865 else:
866 # Let super() handle this error.
867 super()._Run()
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000868
Alex Klein1699fab2022-09-08 08:46:06 -0600869 self._RunPostInstall()
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000870
Alex Klein1699fab2022-09-08 08:46:06 -0600871 def _RunPostInstall(self):
872 """The function will change the priority of the miniOS partitions."""
873 self._FlipMiniOSPriority()
874 self._ran_postinst = True
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000875
Alex Klein1699fab2022-09-08 08:46:06 -0600876 def Revert(self):
877 """Reverts the miniOS partition update."""
878 if self._ran_postinst:
879 self._FlipMiniOSPriority()
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000880
Alex Klein1699fab2022-09-08 08:46:06 -0600881 def _GetMiniOSPriority(self):
882 return self._device.run(
883 ["crossystem", constants.MINIOS_PRIORITY]
884 ).stdout
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000885
Alex Klein1699fab2022-09-08 08:46:06 -0600886 def _SetMiniOSPriority(self, priority: str):
887 self._device.run(
888 ["crossystem", f"{constants.MINIOS_PRIORITY}={priority}"]
889 )
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000890
Alex Klein1699fab2022-09-08 08:46:06 -0600891 def _FlipMiniOSPriority(self):
892 inactive_minios_priority = (
893 "B" if self._GetMiniOSPriority() == "A" else "A"
894 )
895 logging.info("Setting miniOS priority to %s", inactive_minios_priority)
896 self._SetMiniOSPriority(inactive_minios_priority)
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000897
Alex Klein1699fab2022-09-08 08:46:06 -0600898 def _MiniOSPartitionsExistInImage(self):
899 """Checks if miniOS partition exists in the image."""
900 d = cgpt.Disk.FromImage(self._image)
901 try:
902 d.GetPartitionByTypeGuid(cgpt.MINIOS_TYPE_GUID)
903 return True
904 except KeyError:
905 return False
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000906
Alex Klein1699fab2022-09-08 08:46:06 -0600907 def _MiniOSPartitionsExist(self):
908 """Checks if the device has miniOS partitions."""
909 run = lambda x: self._device.run(x).stdout.strip()
910 device_drive = run(["rootdev", "-s", "-d"])
911 cmd = ["cgpt", "show", "-t", device_drive, "-i"]
912 return all(
913 (run(cmd + [p]) == cgpt.MINIOS_TYPE_GUID) for p in ("9", "10")
914 )
Jae Hoon Kimb88b7962021-10-18 11:08:38 -0700915
Jae Hoon Kimcc723e02021-08-16 21:03:21 +0000916
Amin Hassani74403082021-02-22 11:40:09 -0800917class StatefulPayloadGenerator(ReaderBase):
Alex Klein1699fab2022-09-08 08:46:06 -0600918 """A class for generating a stateful update payload in a separate thread."""
Amin Hassani74403082021-02-22 11:40:09 -0800919
Alex Klein1699fab2022-09-08 08:46:06 -0600920 def __init__(self, image: str):
921 """Initializes that class.
Amin Hassani74403082021-02-22 11:40:09 -0800922
Alex Klein1699fab2022-09-08 08:46:06 -0600923 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600924 image: The path to a local Chromium OS image.
Alex Klein1699fab2022-09-08 08:46:06 -0600925 """
926 super().__init__()
927 self._image = image
928
929 def run(self):
930 """Generates the stateful update and writes it into the output pipe."""
931 try:
932 paygen_stateful_payload_lib.GenerateStatefulPayload(
933 self._image, self._Source()
934 )
935 finally:
936 self._CloseSource()
Amin Hassani74403082021-02-22 11:40:09 -0800937
938
939class StatefulUpdater(PartitionUpdaterBase):
Alex Klein1699fab2022-09-08 08:46:06 -0600940 """A class to update the stateful partition on a device."""
Amin Hassani74403082021-02-22 11:40:09 -0800941
Alex Klein1699fab2022-09-08 08:46:06 -0600942 def __init__(self, clobber_stateful: bool, *args):
943 """Initializes the class
Amin Hassani74403082021-02-22 11:40:09 -0800944
Alex Klein1699fab2022-09-08 08:46:06 -0600945 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600946 clobber_stateful: Whether to clobber the stateful or not.
947 *args: Look at PartitionUpdaterBase.
Alex Klein1699fab2022-09-08 08:46:06 -0600948 """
949 super().__init__(*args)
950 self._clobber_stateful = clobber_stateful
Amin Hassani74403082021-02-22 11:40:09 -0800951
Alex Klein1699fab2022-09-08 08:46:06 -0600952 def _Run(self):
953 """Reads/Downloads the stateful updates and writes it into the device."""
954 if self._image_type == ImageType.FULL:
955 generator_cls = StatefulPayloadGenerator
956 elif self._image_type == ImageType.REMOTE_DIRECTORY:
957 generator_cls = GsFileCopier
958 self._image = os.path.join(
959 self._image, paygen_stateful_payload_lib.STATEFUL_FILE
960 )
961 else:
962 raise ValueError(f"Invalid image type {self._image_type}")
Amin Hassani74403082021-02-22 11:40:09 -0800963
Alex Klein1699fab2022-09-08 08:46:06 -0600964 with generator_cls(self._image) as generator:
965 try:
966 updater = stateful_updater.StatefulUpdater(self._device)
967 updater.Update(
968 generator.Target(),
969 is_payload_on_device=False,
970 update_type=(
971 stateful_updater.StatefulUpdater.UPDATE_TYPE_CLOBBER
972 if self._clobber_stateful
973 else None
974 ),
975 )
976 finally:
977 generator.CloseTarget()
978
979 def Revert(self):
980 """Reverts the stateful partition update."""
981 logging.info("Reverting the stateful update.")
982 stateful_updater.StatefulUpdater(self._device).Reset()
Amin Hassani55970562021-02-22 20:49:13 -0800983
984
985class ProgressWatcher(threading.Thread):
Alex Klein1699fab2022-09-08 08:46:06 -0600986 """A class used for watching the progress of rootfs update."""
Amin Hassani55970562021-02-22 20:49:13 -0800987
Alex Klein1699fab2022-09-08 08:46:06 -0600988 def __init__(self, device, target_root: str):
989 """Initializes the class.
Amin Hassani55970562021-02-22 20:49:13 -0800990
Alex Klein1699fab2022-09-08 08:46:06 -0600991 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -0600992 device: The ChromiumOSDevice to be updated.
993 target_root: The target root partition to monitor the progress of.
Alex Klein1699fab2022-09-08 08:46:06 -0600994 """
995 super().__init__()
Amin Hassani55970562021-02-22 20:49:13 -0800996
Alex Klein1699fab2022-09-08 08:46:06 -0600997 self._device = device
998 self._target_root = target_root
999 self._exit = False
Amin Hassani55970562021-02-22 20:49:13 -08001000
Alex Klein1699fab2022-09-08 08:46:06 -06001001 def __enter__(self):
1002 """Starts the thread."""
1003 self.start()
1004 return self
Amin Hassani55970562021-02-22 20:49:13 -08001005
Alex Klein1699fab2022-09-08 08:46:06 -06001006 def __exit__(self, *args, **kwargs):
1007 """Exists the thread."""
1008 self._exit = True
1009 self.join()
Amin Hassani55970562021-02-22 20:49:13 -08001010
Alex Klein1699fab2022-09-08 08:46:06 -06001011 def _ShouldExit(self):
1012 return self._exit
Amin Hassani55970562021-02-22 20:49:13 -08001013
Alex Klein1699fab2022-09-08 08:46:06 -06001014 def run(self):
1015 """Monitors the progress of the target root partitions' update.
Amin Hassani55970562021-02-22 20:49:13 -08001016
Alex Klein1699fab2022-09-08 08:46:06 -06001017 This is done by periodically, reading the fd position of the process that is
1018 writing into the target partition and reporting it back. Then the position
1019 is divided by the size of the block device to report an approximate
1020 progress.
1021 """
1022 cmd = ["blockdev", "--getsize64", self._target_root]
Amin Hassani55970562021-02-22 20:49:13 -08001023 output = self._device.run(cmd, capture_output=True).stdout.strip()
Alex Klein1699fab2022-09-08 08:46:06 -06001024 if output is None:
1025 raise Error(f"Cannot get the block device size from {output}.")
1026 dev_size = int(output)
1027
1028 # Using lsof to find out which process is writing to the target rootfs.
1029 cmd = ["lsof", "-t", self._target_root]
1030 while not self._ShouldExit():
1031 try:
1032 pid = self._device.run(cmd, capture_output=True).stdout.strip()
1033 if pid:
1034 break
1035 except cros_build_lib.RunCommandError:
1036 continue
1037 finally:
1038 time.sleep(1)
1039
1040 # Now that we know which process is writing to it, we can look the fdinfo of
1041 # stdout of that process to get its offset. We're assuming there will be no
1042 # seek, which is correct.
1043 cmd = ["cat", f"/proc/{pid}/fdinfo/1"]
1044 while not self._ShouldExit():
1045 try:
1046 output = self._device.run(
1047 cmd, capture_output=True
1048 ).stdout.strip()
1049 m = re.search(r"^pos:\s*(\d+)$", output, flags=re.M)
1050 if m:
1051 offset = int(m.group(1))
1052 # DeviceImagerOperation will look for this log.
1053 logging.info("RootFS progress: %f", offset / dev_size)
1054 except cros_build_lib.RunCommandError:
1055 continue
1056 finally:
1057 time.sleep(1)
Amin Hassani55970562021-02-22 20:49:13 -08001058
1059
1060class DeviceImagerOperation(operation.ProgressBarOperation):
Alex Klein1699fab2022-09-08 08:46:06 -06001061 """A class to provide a progress bar for DeviceImager operation."""
Amin Hassani55970562021-02-22 20:49:13 -08001062
Alex Klein1699fab2022-09-08 08:46:06 -06001063 def __init__(self):
1064 """Initializes the class."""
1065 super().__init__()
Amin Hassani55970562021-02-22 20:49:13 -08001066
Alex Klein1699fab2022-09-08 08:46:06 -06001067 self._progress = 0.0
Amin Hassani55970562021-02-22 20:49:13 -08001068
Alex Klein1699fab2022-09-08 08:46:06 -06001069 def ParseOutput(self, output=None):
1070 """Override function to parse the output and provide progress.
Amin Hassani55970562021-02-22 20:49:13 -08001071
Alex Klein1699fab2022-09-08 08:46:06 -06001072 Args:
Alex Klein53cc3bf2022-10-13 08:50:01 -06001073 output: The stderr or stdout.
Alex Klein1699fab2022-09-08 08:46:06 -06001074 """
1075 output = self._stdout.read()
1076 match = re.findall(r"RootFS progress: (\d+(?:\.\d+)?)", output)
1077 if match:
1078 progress = float(match[0])
1079 self._progress = max(self._progress, progress)
Amin Hassani55970562021-02-22 20:49:13 -08001080
Alex Klein1699fab2022-09-08 08:46:06 -06001081 # If postinstall completes, move half of the remaining progress.
1082 if re.findall(r"Postinstall completed", output):
1083 self._progress += (1.0 - self._progress) / 2
Amin Hassani55970562021-02-22 20:49:13 -08001084
Alex Klein1699fab2022-09-08 08:46:06 -06001085 # While waiting for reboot, each time, move half of the remaining progress.
1086 if re.findall(r"Unable to get new boot_id", output):
1087 self._progress += (1.0 - self._progress) / 2
Amin Hassani55970562021-02-22 20:49:13 -08001088
Alex Klein1699fab2022-09-08 08:46:06 -06001089 if re.findall(r"DeviceImager completed.", output):
1090 self._progress = 1.0
Amin Hassani55970562021-02-22 20:49:13 -08001091
Alex Klein1699fab2022-09-08 08:46:06 -06001092 self.ProgressBar(self._progress)