1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
|
#! /usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
# depthcharge-tools depthchargectl write subcommand
# Copyright (C) 2020-2022 Alper Nebi Yasak <alpernebiyasak@gmail.com>
# See COPYRIGHT and LICENSE files for full copyright information.
import argparse
import logging
import os
import subprocess
from pathlib import Path
from depthcharge_tools import (
__version__,
)
from depthcharge_tools.utils.argparse import (
Command,
Argument,
Group,
CommandExit,
)
from depthcharge_tools.utils.platform import (
KernelEntry,
installed_kernels,
)
from depthcharge_tools.depthchargectl import depthchargectl
class ImageBuildError(CommandExit):
def __init__(self, kernel_version=None):
self.kernel_version = kernel_version
if kernel_version is None:
message = "Failed to build depthcharge image."
else:
message = (
"Failed to build depthcharge image for kernel version '{}'."
.format(kernel_version)
)
super().__init__(message=message)
class NotBootableImageError(CommandExit):
def __init__(self, image):
self.image = image
super().__init__(
"Image '{}' is not bootable on this board."
.format(image)
)
class NoUsableCrosPartitionError(CommandExit):
def __init__(self):
super().__init__(
"No usable Chrome OS Kernel partition found."
)
@depthchargectl.subcommand("write")
class depthchargectl_write(
depthchargectl,
prog="depthchargectl write",
usage="%(prog)s [options] [KERNEL-VERSION | IMAGE]",
add_help=False,
):
"""Write an image to a ChromeOS kernel partition."""
_logger = depthchargectl._logger.getChild("write")
config_section = "depthchargectl/write"
@depthchargectl.board.copy()
def board(self, codename=""):
"""Assume we're running on the specified board"""
# We can write images to partitions without knowing the board.
# The image argument will become required if this returns None.
try:
return super().board
except Exception as err:
self.logger.warning(err)
return None
@Group
def positionals(self):
"""Positional arguments"""
if self.image is not None and self.kernel_version is not None:
raise ValueError(
"Image and kernel_version arguments are mutually exclusive"
)
arg = self.image or self.kernel_version
# Turn arg into a relevant KernelEntry if it's a kernel version
# or a Path() if not
if isinstance(arg, str):
arg = max(
(k for k in installed_kernels() if k.release == arg),
default=Path(arg).resolve(),
)
if isinstance(arg, KernelEntry):
self.image = None
self.kernel_version = arg
elif isinstance(arg, Path):
self.image = arg
self.kernel_version = None
if self.board is None and self.image is None:
raise ValueError(
"An image file is required when no board is specified."
)
@positionals.add
@Argument(dest=argparse.SUPPRESS, nargs=0)
def kernel_version(self, kernel_version):
"""Installed kernel version to write to disk."""
return kernel_version
@positionals.add
@Argument
def image(self, image=None):
"""Depthcharge image to write to disk."""
return image
@Group
def options(self):
"""Options"""
@options.add
@Argument("-f", "--force", force=True)
def force(self, force=False):
"""Write image even if it cannot be verified."""
return force
@options.add
@Argument("-t", "--target", metavar="DISK|PART")
def target(self, target):
"""Specify a disk or partition to write to."""
return target
@options.add
@Argument("--no-prioritize", prioritize=False)
def prioritize(self, prioritize=True):
"""Don't set any flags on the partition."""
return prioritize
@options.add
@Argument("--allow-current", allow=True)
def allow_current(self, allow=False):
"""Allow overwriting the currently booted partition."""
return allow
def __call__(self):
if self.board is None:
self.logger.warning(
"Using given image '{}' without board-specific checks."
.format(self.image)
)
image = self.image
elif self.image is not None:
self.logger.info("Using given image '{}'." .format(self.image))
image = self.image
try:
depthchargectl.check(
image=image,
config=self.config,
board=self.board,
tmpdir=self.tmpdir / "check",
images_dir=self.images_dir,
vboot_keyblock=self.vboot_keyblock,
vboot_public_key=self.vboot_public_key,
vboot_private_key=self.vboot_private_key,
kernel_cmdline=self.kernel_cmdline,
ignore_initramfs=self.ignore_initramfs,
verbosity=self.verbosity,
)
except Exception as err:
if self.force:
self.logger.warning(
"Image '{}' is not bootable on this board, "
"continuing due to --force."
.format(image)
)
else:
raise NotBootableImageError(image) from err
else:
# No image given, try creating one.
try:
image = depthchargectl.build_(
kernel_version=self.kernel_version,
root=self.root,
root_mountpoint=self.root_mountpoint,
boot_mountpoint=self.boot_mountpoint,
config=self.config,
board=self.board,
tmpdir=self.tmpdir / "build",
images_dir=self.images_dir,
vboot_keyblock=self.vboot_keyblock,
vboot_public_key=self.vboot_public_key,
vboot_private_key=self.vboot_private_key,
kernel_cmdline=self.kernel_cmdline,
ignore_initramfs=self.ignore_initramfs,
verbosity=self.verbosity,
)
except Exception as err:
raise ImageBuildError(self.kernel_version) from err
# We don't want target to unconditionally avoid the current
# partition since we will also check that here. But whatever we
# choose must be bigger than the image we'll write to it.
self.logger.info("Searching disks for a target partition.")
try:
target = depthchargectl.target(
disks=[self.target] if self.target else [],
min_size=image.stat().st_size,
allow_current=self.allow_current,
root=self.root,
root_mountpoint=self.root_mountpoint,
boot_mountpoint=self.boot_mountpoint,
config=self.config,
board=self.board,
tmpdir=self.tmpdir / "target",
images_dir=self.images_dir,
vboot_keyblock=self.vboot_keyblock,
vboot_public_key=self.vboot_public_key,
vboot_private_key=self.vboot_private_key,
kernel_cmdline=self.kernel_cmdline,
ignore_initramfs=self.ignore_initramfs,
verbosity=self.verbosity,
)
except Exception as err:
raise NoUsableCrosPartitionError() from err
if target is None:
raise NoUsableCrosPartitionError()
self.logger.info("Targeted partition '{}'.".format(target))
# Check and warn if we targeted the currently booted partition,
# as that usually means it's the only partition.
current = self.diskinfo.by_kern_guid()
if current is not None and self.allow_current and target.path == current.path:
self.logger.warning(
"Overwriting the currently booted partition '{}'. "
"This might make your system unbootable."
.format(target)
)
self.logger.info(
"Writing image '{}' to partition '{}'."
.format(image, target)
)
target.write_bytes(image.read_bytes())
self.logger.warning(
"Wrote image '{}' to partition '{}'."
.format(image, target)
)
if self.prioritize:
self.logger.info(
"Setting '{}' as the highest-priority bootable part."
.format(target)
)
try:
depthchargectl.bless(
partition=target,
oneshot=True,
root=self.root,
root_mountpoint=self.root_mountpoint,
boot_mountpoint=self.boot_mountpoint,
config=self.config,
board=self.board,
tmpdir=self.tmpdir / "bless",
images_dir=self.images_dir,
vboot_keyblock=self.vboot_keyblock,
vboot_public_key=self.vboot_public_key,
vboot_private_key=self.vboot_private_key,
kernel_cmdline=self.kernel_cmdline,
ignore_initramfs=self.ignore_initramfs,
verbosity=self.verbosity,
)
except Exception as err:
raise CommandExit(
"Failed to set '{}' as the highest-priority bootable part."
.format(target)
) from err
self.logger.warning(
"Set partition '{}' as next to boot."
.format(target)
)
return target
global_options = depthchargectl.global_options
config_options = depthchargectl.config_options
|