mirror of
https://github.com/nix-community/disko.git
synced 2026-11-30 21:13: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
Vendored
+10
@@ -26,6 +26,16 @@
|
||||
"--flake",
|
||||
".#testmachine"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "disko2 generate",
|
||||
"type": "debugpy",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/disko2",
|
||||
"console": "integratedTerminal",
|
||||
"args": [
|
||||
"generate",
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -8,6 +8,7 @@ from typing import Any, Literal
|
||||
from lib.eval_config import eval_disko_file, eval_flake
|
||||
from lib.logging import LOGGER, debug, info
|
||||
from lib.result import DiskoError, DiskoSuccess, DiskoResult, exit_on_error
|
||||
from lib.types.disk import generate_config
|
||||
|
||||
Mode = Literal[
|
||||
"destroy", "format", "mount", "destroy,format,mount", "format,mount", "generate"
|
||||
@@ -48,8 +49,8 @@ def run_apply(
|
||||
return DiskoError.single_message("ERR_TOO_MANY_ARGUMENTS", {}, "validate args")
|
||||
|
||||
|
||||
def run_generate() -> DiskoResult[Literal["generate"]]:
|
||||
return DiskoSuccess("generate", "generate config")
|
||||
def run_generate() -> DiskoResult[dict[str, Any]]:
|
||||
return generate_config()
|
||||
|
||||
|
||||
def run(
|
||||
|
||||
+42
-2
@@ -1,5 +1,6 @@
|
||||
# Logging functionality and global logging configuration
|
||||
from dataclasses import dataclass, field
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import Any, Literal, assert_never
|
||||
@@ -12,6 +13,8 @@ LOGGER = logging.getLogger("disko_logger")
|
||||
|
||||
# Color definitions. Note: Sort them alphabetically when adding new ones!
|
||||
COMMAND = Colors.CYAN_ITALIC # Commands that were run or can be run
|
||||
EM = Colors.WHITE_ITALIC # Emphasized text
|
||||
EM_WARN = Colors.YELLOW_ITALIC # Emphasized text that is a warning
|
||||
FILE = Colors.BLUE # File paths
|
||||
FLAG = Colors.GREEN # Command line flags (like --version or -f)
|
||||
INVALID = Colors.RED # Invalid values
|
||||
@@ -38,6 +41,8 @@ MessageCode = Literal[
|
||||
"ERR_MISSING_ARGUMENTS",
|
||||
"ERR_MISSING_MODE",
|
||||
"ERR_TOO_MANY_ARGUMENTS",
|
||||
"ERR_UNSUPPORTED_PTTYPE",
|
||||
"WARN_GENERATE_PARTIAL_FAILURE",
|
||||
]
|
||||
|
||||
|
||||
@@ -141,6 +146,41 @@ def to_readable(message: DiskoMessage) -> list[ReadableMessage]:
|
||||
ReadableMessage("error", "Missing mode!"),
|
||||
ReadableMessage("help", "Allowed modes are:\n" + modes_list),
|
||||
]
|
||||
case "ERR_UNSUPPORTED_PTTYPE":
|
||||
return [
|
||||
ReadableMessage(
|
||||
"error",
|
||||
f"Device {FILE}{message.details['device']}{RESET} has unsupported partition type {INVALID}{message.details['pttype']}{RESET}!",
|
||||
),
|
||||
]
|
||||
case "WARN_GENERATE_PARTIAL_FAILURE":
|
||||
return [
|
||||
ReadableMessage(
|
||||
"info",
|
||||
f"""
|
||||
Successfully generated config for {EM}some{RESET} devices.
|
||||
Errors are printed above. The generated partial config is:
|
||||
{json.dumps(message.details["partial_config"], indent=2)}
|
||||
""",
|
||||
),
|
||||
ReadableMessage(
|
||||
"warning",
|
||||
f"""
|
||||
Successfully generated config for {EM}some{RESET} devices, {EM_WARN}but not all{RESET}!
|
||||
Failed devices: {", ".join(f"{INVALID}{d}{RESET}" for d in message.details["failed_devices"])}
|
||||
Successful devices: {", ".join(f"{VALUE}{d}{RESET}" for d in message.details["successful_devices"])}
|
||||
""",
|
||||
),
|
||||
ReadableMessage(
|
||||
"help",
|
||||
f"""
|
||||
The {INVALID}ERROR{RESET} messages are printed {EM}above the generated config{RESET}.
|
||||
Take a look at them and see if you can fix or safely ignore them.
|
||||
If you can't, but you need a solution now, you can try to use the generated config,
|
||||
but there is {EM_WARN}no guarantee{RESET} that it will work!
|
||||
""",
|
||||
),
|
||||
]
|
||||
|
||||
# We could also remove these two lines, but assert_never emits a better error message
|
||||
case _ as c:
|
||||
@@ -159,7 +199,7 @@ def dedent_start_lines(lines: list[str]) -> list[str]:
|
||||
if dedent_width == 0:
|
||||
return lines
|
||||
|
||||
match_indent_regex = re.compile(f"^ {{1,{dedent_width}}}")
|
||||
match_indent_regex = re.compile(f"^ {{{dedent_width}}}")
|
||||
|
||||
dedented_lines = []
|
||||
stop_dedenting = False
|
||||
@@ -214,7 +254,7 @@ def render_message(message: ReadableMessage) -> None:
|
||||
"debug": LOGGER.debug,
|
||||
}[message.type]
|
||||
|
||||
msg_lines = message.msg.strip("\n").splitlines()
|
||||
msg_lines = message.msg.strip("\n").rstrip(" \n").splitlines()
|
||||
|
||||
# "WARNING:" is 8 characters long, center in 10 for space on each side
|
||||
title = f"{bg_color}{title_raw + ":":^10}{RESET}"
|
||||
|
||||
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