File: _target.py

package info (click to toggle)
depthcharge-tools 0.6.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 732 kB
  • sloc: python: 6,280; sh: 650; makefile: 12
file content (266 lines) | stat: -rw-r--r-- 8,322 bytes parent folder | download | duplicates (2)
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
#! /usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later

# depthcharge-tools depthchargectl target 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 subprocess
import sys
import types

from depthcharge_tools import __version__
from depthcharge_tools.utils.argparse import (
    Command,
    Argument,
    Group,
    CommandExit,
)
from depthcharge_tools.utils.os import (
    Disk,
    CrosPartition,
    Partition,
)
from depthcharge_tools.utils.string import (
    parse_bytesize,
)

from depthcharge_tools.depthchargectl import depthchargectl


class NotABlockDeviceError(CommandExit):
    def __init__(self, device):
        message = (
            "Target '{}' is not a valid block device."
            .format(device)
        )

        self.device = device
        super().__init__(message=message, returncode=2)


class NotCrosPartitionError(CommandExit):
    def __init__(self, partition):
        message = (
            "Partition '{}' is not of type Chrome OS Kernel."
            .format(partition)
        )

        self.partition = partition
        super().__init__(message=message, returncode=5)


class BootedPartitionError(CommandExit):
    def __init__(self, partition):
        message = (
            "Partition '{}' is the currently booted parttiion."
            .format(partition)
        )

        self.partition = partition
        super().__init__(message=message, returncode=6)


class PartitionSizeTooSmallError(CommandExit):
    def __init__(self, partition, part_size, min_size):
        message = (
            "Partition '{}' ('{}' bytes) is smaller than '{}' bytes."
            .format(partition, part_size, min_size)
        )

        self.partition = partition
        self.part_size = part_size
        self.min_size = min_size
        super().__init__(message=message, returncode=7)


class NoUsableCrosPartition(CommandExit):
    def __init__(self):
        message = (
            "No usable Chrome OS Kernel partition found "
            "for given input arguments."
        )

        super().__init__(message=message, output=None)


@depthchargectl.subcommand("target")
class depthchargectl_target(
    depthchargectl,
    prog="depthchargectl target",
    usage="%(prog)s [options] [PARTITION | DISK ...]",
    add_help=False,
):
    """Choose or validate a ChromeOS Kernel partition to use."""

    _logger = depthchargectl._logger.getChild("target")
    config_section = "depthchargectl/target"

    @depthchargectl.board.copy()
    def board(self, codename=""):
        """Assume we're running on the specified board"""
        # We can target partitions without knowing the board.
        try:
            return super().board
        except Exception as err:
            self.logger.warning(err)
            return None

    @Group
    def positionals(self):
        """Positional arguments"""

        disks = list(self.disks)
        partitions = list(self.partitions)

        # The inputs can be a mixed list of partitions and disks,
        # separate the two.
        for d in list(disks):
            try:
                partitions.append(Partition(d))
                self.logger.info("Using target '{}' as a partition.".format(d))
                disks.remove(d)
            except:
                pass

        self.disks = disks
        self.partitions = partitions

    @positionals.add
    @Argument(metavar="PARTITION", nargs=0)
    def partitions(self, *partitions):
        """Chrome OS kernel partition to validate."""
        return partitions

    @positionals.add
    @Argument(metavar="DISK")
    def disks(self, *disks):
        """Disks to search for an appropriate Chrome OS kernel partition."""
        return disks

    @Group
    def options(self):
        """Options"""

    @options.add
    @Argument("-s", "--min-size", nargs=1)
    def min_size(self, bytes_=None):
        """Target partitions larger than this size."""
        if bytes_ is None:
            return 0x10000

        return parse_bytesize(bytes_)

    @options.add
    @Argument("--allow-current", allow=True)
    def allow_current(self, allow=False):
        """Allow targeting the currently booted partition."""
        return allow

    @options.add
    @Argument("-a", "--all-disks", all_disks=True)
    def all_disks(self, all_disks=False):
        """Target partitions on all disks."""
        return all_disks

    def __call__(self):
        disks = list(self.disks)
        partitions = list(self.partitions)

        # We will need to check partitions against this if allow_current
        # is false.
        current = self.diskinfo.by_kern_guid()

        # Given a single partition, check if the partition is valid.
        if len(partitions) == 1 and len(disks) == 0:
            part = partitions[0]

            self.logger.info("Checking if target partition is writable.")
            if part.path is not None and not part.path.is_block_device():
                raise NotABlockDeviceError(part.path)

            self.logger.info("Checking if targeted partition's disk is writable.")
            if not part.disk.path.is_block_device():
                raise NotABlockDeviceError(part.disk.path)

            self.logger.info(
                "Checking if targeted partition's type is Chrome OS Kernel."
            )
            if part not in part.disk.cros_partitions():
                raise NotCrosPartitionError(part)

            self.logger.info(
                "Checking if targeted partition is currently booted one."
            )
            if current is not None and not self.allow_current:
                if part.path == current.path:
                    raise BootedPartitionError(part)

            self.logger.info(
                "Checking if targeted partition is bigger than given "
                "minimum size."
            )
            if self.min_size is not None and part.size < self.min_size:
                raise PartitionSizeTooSmallError(
                    part,
                    part.size,
                    self.min_size,
                )

        # For arguments which are disks, search all their partitions.
        # If no disks or partitions were given, search bootable disks.
        # Search all disks if explicitly asked.
        if disks or not partitions or self.all_disks:
            partitions += depthchargectl.list(
                disks=disks,
                all_disks=self.all_disks,
                root=self.root,
                root_mountpoint=self.root_mountpoint,
                boot_mountpoint=self.boot_mountpoint,
                config=self.config,
                board=self.board,
                tmpdir=self.tmpdir / "list",
                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,
            )

        good_partitions = []
        for p in partitions:
            if self.min_size is not None and p.size < self.min_size:
                self.logger.warning(
                    "Skipping partition '{}' as too small."
                    .format(p)
                )
                continue

            if current is not None and not self.allow_current:
                if p.path == current.path:
                    self.logger.info(
                        "Skipping currently booted partition '{}'."
                        .format(p)
                    )
                    continue

            self.logger.info("Partition '{}' is usable.".format(p))
            good_partitions.append(
                CrosPartition(p.disk.path, partno=p.partno),
            )

        # Get the least-successful, least-priority, least-tries-left
        # partition in that order of preference.
        if good_partitions:
            return min(good_partitions)
        else:
            return NoUsableCrosPartition()

    global_options = depthchargectl.global_options
    config_options = depthchargectl.config_options