mirror of
https://github.com/nix-community/disko.git
synced 2026-12-01 05:23:28 +01:00
disko2: Implement rudimentary generate mode
Error handling could be done better, but I'm pretty happy with it already. The important part is aggregating all errors instead of failing on the first issue we encounter.
This commit is contained in:
1 parent
8acd24950d
commit
e825c64c8d
8 files changed
+337
-4
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,126 @@
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from lib.result import DiskoError, DiskoResult, DiskoSuccess
|
||||
from lib.run_cmd import run
|
||||
|
||||
# To see what other fields are available in the lsblk output and what
|
||||
# sort of values you can expect from them, run:
|
||||
# lsblk -O | less -S
|
||||
LSBLK_OUTPUT_FIELDS = [
|
||||
"ID-LINK",
|
||||
"FSTYPE",
|
||||
"FSSIZE",
|
||||
"FSUSE%",
|
||||
"KNAME",
|
||||
"LABEL",
|
||||
"MODEL",
|
||||
"PARTFLAGS",
|
||||
"PARTLABEL",
|
||||
"PARTN",
|
||||
"PARTTYPE",
|
||||
"PARTTYPENAME",
|
||||
"PARTUUID", # The UUID used for /dev/disk/by-partuuid
|
||||
"PATH", # The canonical path of the block device
|
||||
"PHY-SEC",
|
||||
"PTTYPE",
|
||||
"REV",
|
||||
"SERIAL",
|
||||
"SIZE",
|
||||
"START",
|
||||
"MOUNTPOINT", # Canonical mountpoint
|
||||
"MOUNTPOINTS", # All mountpoints, including e.g. bind mounts
|
||||
"TYPE",
|
||||
"UUID", # The UUID used for /dev/disk/by-uuid, if available
|
||||
]
|
||||
|
||||
|
||||
# Could think about splitting this into multiple classes based on the type field
|
||||
# Would make access to the fields more type safe
|
||||
@dataclass
|
||||
class BlockDevice:
|
||||
id_link: str
|
||||
fstype: str
|
||||
fssize: str
|
||||
fsuse_pct: str
|
||||
kname: str
|
||||
label: str
|
||||
model: str
|
||||
partflags: str
|
||||
partlabel: str
|
||||
partn: int | None
|
||||
parttype: str
|
||||
parttypename: str
|
||||
partuuid: str
|
||||
path: Path
|
||||
phy_sec: int
|
||||
pttype: str
|
||||
rev: str
|
||||
serial: str
|
||||
size: str
|
||||
start: str
|
||||
mountpoint: str
|
||||
mountpoints: list[str]
|
||||
type: str
|
||||
uuid: str
|
||||
children: list["BlockDevice"]
|
||||
|
||||
@classmethod
|
||||
def from_json_dict(cls, json_dict: dict[str, Any]) -> "BlockDevice":
|
||||
children = [
|
||||
cls.from_json_dict(child_dict)
|
||||
for child_dict in json_dict.get("children", [])
|
||||
]
|
||||
|
||||
# The mountpoints field will be a list containing a single null if there are no mountpoints
|
||||
mountpoints = json_dict["mountpoints"] or []
|
||||
if not any(mountpoints):
|
||||
mountpoints = []
|
||||
|
||||
# When we request the output fields from lsblk, the keys are guaranteed to exists,
|
||||
# but some might be null. Set a default value for the fields we have observed to be optional.
|
||||
return cls(
|
||||
children=children,
|
||||
id_link=json_dict["id-link"],
|
||||
fstype=json_dict["fstype"] or "",
|
||||
fssize=json_dict["fssize"] or "",
|
||||
fsuse_pct=json_dict["fsuse%"] or "",
|
||||
kname=json_dict["kname"],
|
||||
label=json_dict["label"] or "",
|
||||
model=json_dict["model"] or "",
|
||||
partflags=json_dict["partflags"] or "",
|
||||
partlabel=json_dict["partlabel"] or "",
|
||||
partn=json_dict["partn"],
|
||||
parttype=json_dict["parttype"] or "",
|
||||
parttypename=json_dict["parttypename"] or "",
|
||||
partuuid=json_dict["partuuid"] or "",
|
||||
path=Path(json_dict["path"]),
|
||||
phy_sec=json_dict["phy-sec"],
|
||||
pttype=json_dict["pttype"],
|
||||
rev=json_dict["rev"] or "",
|
||||
serial=json_dict["serial"] or "",
|
||||
size=json_dict["size"],
|
||||
start=json_dict["start"] or "",
|
||||
mountpoint=json_dict["mountpoint"] or "",
|
||||
mountpoints=mountpoints,
|
||||
type=json_dict["type"],
|
||||
uuid=json_dict["uuid"] or "",
|
||||
)
|
||||
|
||||
|
||||
def list_block_devices() -> DiskoResult[list[BlockDevice]]:
|
||||
lsblk_result = run(
|
||||
["lsblk", "--json", "--tree", "--output", ",".join(LSBLK_OUTPUT_FIELDS)]
|
||||
)
|
||||
|
||||
if isinstance(lsblk_result, DiskoError):
|
||||
return lsblk_result
|
||||
|
||||
# We trust the output of `lsblk` to be valid JSON
|
||||
lsblk_json: list[dict[str, Any]] = json.loads(lsblk_result.value)["blockdevices"]
|
||||
|
||||
blockdevices = [BlockDevice.from_json_dict(dev) for dev in lsblk_json]
|
||||
|
||||
return DiskoSuccess(blockdevices, "list block devices")
|
||||
@@ -0,0 +1,75 @@
|
||||
from typing import Any
|
||||
|
||||
from lib.logging import DiskoMessage, debug
|
||||
from lib.result import DiskoError, DiskoResult, DiskoSuccess
|
||||
from lib.types.device import BlockDevice, list_block_devices
|
||||
import lib.types.gpt as gpt
|
||||
|
||||
|
||||
def _generate_content(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
||||
match device.pttype:
|
||||
case "gpt":
|
||||
return gpt.generate_config(device)
|
||||
case _:
|
||||
return DiskoError.single_message(
|
||||
"ERR_UNSUPPORTED_PTTYPE",
|
||||
{"device": device.path, "pttype": device.pttype},
|
||||
"generate disk content",
|
||||
)
|
||||
|
||||
|
||||
def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[dict[str, Any]]:
|
||||
block_devices = devices
|
||||
if not block_devices:
|
||||
lsblk_result = list_block_devices()
|
||||
|
||||
if isinstance(lsblk_result, DiskoError):
|
||||
return lsblk_result
|
||||
|
||||
block_devices = lsblk_result.value
|
||||
|
||||
if isinstance(block_devices, DiskoError):
|
||||
return block_devices
|
||||
|
||||
debug(f"Generating config for devices {[d.path for d in block_devices]}")
|
||||
|
||||
disks = {}
|
||||
error_messages = []
|
||||
failed_devices = []
|
||||
successful_devices = []
|
||||
|
||||
for device in block_devices:
|
||||
content = _generate_content(device)
|
||||
|
||||
if isinstance(content, DiskoError):
|
||||
error_messages.extend(content.messages)
|
||||
failed_devices.append(device.path)
|
||||
continue
|
||||
|
||||
disks[f"MODEL:{device.model},SN:{device.serial}"] = {
|
||||
"device": device.kname,
|
||||
"type": device.type,
|
||||
"content": content.value,
|
||||
}
|
||||
successful_devices.append(device.path)
|
||||
|
||||
if not failed_devices:
|
||||
return DiskoSuccess({"disks": disks}, "generate disk config")
|
||||
|
||||
if not successful_devices:
|
||||
return DiskoError(error_messages, "generate disk config")
|
||||
|
||||
return DiskoError(
|
||||
error_messages
|
||||
+ [
|
||||
DiskoMessage(
|
||||
"WARN_GENERATE_PARTIAL_FAILURE",
|
||||
{
|
||||
"partial_config": {"disks": disks},
|
||||
"failed_devices": failed_devices,
|
||||
"successful_devices": successful_devices,
|
||||
},
|
||||
)
|
||||
],
|
||||
"generate disk config",
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
from typing import Any
|
||||
from lib.types.device import BlockDevice
|
||||
from lib.result import DiskoResult, DiskoSuccess
|
||||
|
||||
|
||||
def generate_config(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
||||
assert (
|
||||
device.type == "part"
|
||||
), f"BUG! filesystem.generate_config called with non-partition device {device.path}"
|
||||
|
||||
return DiskoSuccess(
|
||||
{
|
||||
"type": "filesystem",
|
||||
"format": device.fstype,
|
||||
"mountpoint": device.mountpoint,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
from typing import Any
|
||||
from lib.logging import debug
|
||||
from lib.types import filesystem
|
||||
from lib.types.device import BlockDevice
|
||||
from lib.result import DiskoError, DiskoResult, DiskoSuccess
|
||||
|
||||
|
||||
def _add_type_if_required(
|
||||
device: BlockDevice, part_config: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
type = {
|
||||
"c12a7328-f81f-11d2-ba4b-00a0c93ec93b": "EF00", # EFI System
|
||||
"21686148-6449-6e6f-744e-656564454649": "EF02", # BIOS boot
|
||||
}.get(device.parttype)
|
||||
|
||||
if type:
|
||||
part_config["type"] = type
|
||||
|
||||
return part_config
|
||||
|
||||
|
||||
def _generate_name(device: BlockDevice) -> str:
|
||||
if device.uuid:
|
||||
return f"UUID:{device.uuid}"
|
||||
|
||||
return f"PARTUUID:{device.partuuid}"
|
||||
|
||||
|
||||
def _generate_content(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
||||
match device.fstype:
|
||||
# TODO: Add filesystems that are not supported by `mkfs` here
|
||||
case _:
|
||||
return filesystem.generate_config(device)
|
||||
|
||||
|
||||
def generate_config(device: BlockDevice) -> DiskoResult[dict[str, Any]]:
|
||||
assert (
|
||||
device.pttype == "gpt"
|
||||
), f"BUG! gpt.generate_config called with non-gpt device {device.path}"
|
||||
|
||||
debug(f"Generating GPT config for device {device.path}")
|
||||
|
||||
partitions = {}
|
||||
error_messages = []
|
||||
failed_partitions = []
|
||||
successful_partitions = []
|
||||
|
||||
for partition in device.children:
|
||||
content = _generate_content(partition)
|
||||
|
||||
if isinstance(content, DiskoError):
|
||||
error_messages.extend(content.messages)
|
||||
failed_partitions.append(partition.path)
|
||||
continue
|
||||
|
||||
partitions[_generate_name(partition)] = _add_type_if_required(
|
||||
partition, {"size": partition.size, "content": content.value}
|
||||
)
|
||||
successful_partitions.append(partition.path)
|
||||
|
||||
if not failed_partitions:
|
||||
return DiskoSuccess({"partitions": partitions}, "generate gpt config")
|
||||
|
||||
return DiskoError(error_messages, "generate gpt config")
|
||||
Reference in new issue
Block a user