disko2: Add rudimentary plan generation

This commit is contained in:
Felix Uhl committed 2024-11-27 23:18:54 +01:00
1 parent 6651792c28
commit cfcc518b70
28 files changed
+1191 -609

No files matched your search

+63 -48
View File
@@ -1,50 +1,65 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "disko2 mount disko_file",
"type": "debugpy",
"request": "launch",
"module": "disko",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"console": "integratedTerminal",
"args": [
"mount",
"example/simple-efi.nix"
]
},
{
"name": "disko2 mount flake",
"type": "debugpy",
"request": "launch",
"module": "disko",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"console": "integratedTerminal",
"args": [
"mount",
"--flake",
".#testmachine"
]
},
{
"name": "disko2 generate",
"type": "debugpy",
"request": "launch",
"module": "disko",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"console": "integratedTerminal",
"args": [
"generate",
]
}
]
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "disko2 mount disko_file",
"type": "debugpy",
"request": "launch",
"module": "disko",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"console": "integratedTerminal",
"args": [
"mount",
"example/simple-efi.nix"
]
},
{
"name": "disko2 mount flake",
"type": "debugpy",
"request": "launch",
"module": "disko",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"console": "integratedTerminal",
"args": [
"mount",
"--flake",
".#testmachine"
]
},
{
"name": "disko2 generate",
"type": "debugpy",
"request": "launch",
"module": "disko",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"console": "integratedTerminal",
"args": [
"generate"
]
},
{
"name": "disko2 destroy,format,mount dry-run",
"type": "debugpy",
"request": "launch",
"module": "disko",
"env": {
"PYTHONPATH": "${workspaceFolder}/src"
},
"console": "integratedTerminal",
"args": [
"destroy,format,mount",
"--dry-run",
"disko-config.nix"
]
}
]
}
+6 -1
View File
@@ -18,5 +18,10 @@
"python.analysis.extraPaths": [
"./src"
],
"mypy-type-checker.importStrategy": "fromEnvironment"
"mypy-type-checker.importStrategy": "fromEnvironment",
"python.testing.pytestArgs": [
"tests"
],
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true
}
+9 -1
View File
@@ -181,7 +181,15 @@ def generate_class(name: str, fields: dict[str, Any]) -> tuple[str, io.StringIO
if type_code:
contained_classes_buffer.write(type_code.getvalue())
buffer.write(f" {field_name}: {type_name}\n")
# Fields starting with _ are swallowed, see https://github.com/pydantic/pydantic/issues/2105
if field_name.startswith("_"):
field_definition = (
f'{field_name.lstrip("_")}: {type_name} = Field(alias="{field_name}")'
)
else:
field_definition = f"{field_name}: {type_name}"
buffer.write(f" {field_definition}\n")
if contained_classes_buffer.tell() == 0:
return buffer.getvalue(), None
+86 -14
View File
@@ -1,27 +1,49 @@
#!/usr/bin/env python3
import argparse
import dataclasses
import json
from typing import Any, Literal, cast
from disko.mode_dev import run_dev
from disko.mode_generate import run_generate
from disko_lib.action import Action
from disko_lib.config_type import DiskoConfig
from disko_lib.eval_config import eval_and_validate_config
from disko_lib.eval_config import (
eval_config_dict_as_json,
eval_config_file_as_json,
validate_config,
)
from disko_lib.generate_config import generate_config
from disko_lib.generate_plan import generate_plan
from disko_lib.logging import LOGGER, debug, info
from disko_lib.messages.msgs import err_missing_mode
from disko_lib.result import DiskoError, DiskoResult, exit_on_error
from disko_lib.result import (
DiskoError,
DiskoPartialSuccess,
DiskoResult,
DiskoSuccess,
exit_on_error,
)
from disko_lib.json_types import JsonDict
Mode = Literal[
"destroy",
"format",
"mount",
"destroy,format,mount",
"format,mount",
"generate",
"dev",
]
Mode = (
Action
| Literal[
"destroy,format,mount",
"format,mount",
"generate",
"dev",
]
)
MODE_TO_ACTIONS: dict[Mode, set[Action]] = {
"destroy": {"destroy"},
"format": {"format"},
"mount": {"mount"},
"destroy,format,mount": {"destroy", "format", "mount"},
"format,mount": {"format", "mount"},
}
# Modes to apply an existing configuration
@@ -46,9 +68,52 @@ MODE_DESCRIPTION: dict[Mode, str] = {
def run_apply(
*, mode: str, disko_file: str | None, flake: str | None, **_kwargs: dict[str, Any]
) -> DiskoResult[DiskoConfig]:
return eval_and_validate_config(disko_file=disko_file, flake=flake)
*,
mode: Mode,
disko_file: str | None,
flake: str | None,
dry_run: bool,
**_kwargs: dict[str, Any],
) -> DiskoResult[JsonDict]:
assert mode in APPLY_MODES
target_config_json = eval_config_file_as_json(disko_file=disko_file, flake=flake)
if isinstance(target_config_json, DiskoError):
return target_config_json
target_config = validate_config(target_config_json.value)
if isinstance(target_config, DiskoError):
return target_config.with_context("validate evaluated config")
current_status_dict = generate_config()
if isinstance(current_status_dict, DiskoError) and not isinstance(
current_status_dict, DiskoPartialSuccess
):
return current_status_dict.with_context("generate current status")
current_status_evaluated = eval_config_dict_as_json(current_status_dict.value)
if isinstance(current_status_evaluated, DiskoError):
return current_status_evaluated.with_context("eval current status")
current_status = validate_config(current_status_evaluated.value)
if isinstance(current_status, DiskoError):
return current_status.with_context("validate current status")
actions = MODE_TO_ACTIONS[mode]
plan = generate_plan(actions, current_status.value, target_config.value)
if isinstance(plan, DiskoError):
return plan
plan_as_dict: JsonDict = dataclasses.asdict(plan.value)
steps = {"steps": plan_as_dict.get("steps", [])}
if dry_run:
return DiskoSuccess(steps, "generate plan")
info("Plan execution is not implemented yet!")
return DiskoSuccess(steps, "generate plan")
def run(
@@ -106,6 +171,13 @@ def parse_args() -> argparse.Namespace:
"-f",
help="Flake to fetch the disko configuration from",
)
parser.add_argument(
"--dry-run",
"-n",
action="store_true",
default=False,
help="Print the plan without executing it",
)
# Commands to apply an existing configuration
apply_parsers = [create_apply_parser(mode) for mode in APPLY_MODES]
+11 -6
View File
@@ -3,7 +3,7 @@ import json
from typing import Any, cast
from disko_lib.ansi import Colors
from disko_lib.eval_config import eval_and_validate_config, eval_config_as_json
from disko_lib.eval_config import eval_config_file_as_json, validate_config
from disko_lib.messages.msgs import err_missing_mode
from disko_lib.result import DiskoError, DiskoSuccess, DiskoResult
from disko_lib.types.device import run_lsblk
@@ -31,7 +31,7 @@ def run_dev_ansi() -> DiskoResult[None]:
def run_dev_eval(
*, disko_file: str | None, flake: str | None, **_: Any
) -> DiskoResult[None]:
result = eval_config_as_json(disko_file=disko_file, flake=flake)
result = eval_config_file_as_json(disko_file=disko_file, flake=flake)
if isinstance(result, DiskoError):
return result
@@ -43,12 +43,17 @@ def run_dev_eval(
def run_dev_validate(
*, disko_file: str | None, flake: str | None, **_: Any
) -> DiskoResult[None]:
result = eval_and_validate_config(disko_file=disko_file, flake=flake)
eval_result = eval_config_file_as_json(disko_file=disko_file, flake=flake)
if isinstance(eval_result, DiskoError):
return eval_result
if isinstance(result, DiskoError):
return result
validate_result = validate_config(eval_result.value)
if isinstance(validate_result, DiskoError):
return validate_result
print(result.value.model_dump_json(indent=2))
print(
validate_result.value.model_dump_json(indent=2, by_alias=True, warnings="error")
)
return DiskoSuccess(None, "run disko dev validate")
+25 -19
View File
@@ -1,9 +1,9 @@
import json
import re
from disko_lib.eval_config import eval_config_dict_as_json
from disko_lib.logging import info
from disko_lib.messages.msgs import warn_generate_partial_failure
from disko_lib.result import DiskoResult, DiskoError
from disko_lib.types.disk import generate_config
from disko_lib.result import DiskoPartialSuccess, DiskoResult, DiskoError
from disko_lib.generate_config import generate_config
from disko_lib.run_cmd import run
from disko_lib.json_types import JsonDict
@@ -25,29 +25,35 @@ PARTIAL_FAILURE_COMMENT = """
"""
def filter_internal_keys(d: JsonDict) -> JsonDict:
return {
k: (v if not isinstance(v, dict) else filter_internal_keys(v))
for k, v in d.items()
if not k.startswith("_")
}
def run_generate() -> DiskoResult[JsonDict]:
generated_config_result = generate_config()
generated_config = None
generate_result = generate_config()
if isinstance(generated_config_result, DiskoError):
partial_failure_warning = generated_config_result.find_message(
warn_generate_partial_failure
)
if not partial_failure_warning:
return generated_config_result
if isinstance(generate_result, DiskoError) and not isinstance(
generate_result, DiskoPartialSuccess
):
return generate_result
generated_config = partial_failure_warning.details["partial_config"]
else:
generated_config = generated_config_result.value
config_to_write = filter_internal_keys(generate_result.value)
evaluate_result = eval_config_dict_as_json(config_to_write)
if isinstance(evaluate_result, DiskoError):
# TODO: Add --no-validate flag and explanatory text
return evaluate_result
config_as_nix = run(
[
"nix",
"eval",
"--expr",
"{ disko.devices = ("
f"builtins.fromJSON(''{json.dumps(generated_config)}'')"
"); }",
f"builtins.fromJSON(''{json.dumps(config_to_write)}'')",
]
)
if isinstance(config_as_nix, DiskoError):
@@ -59,11 +65,11 @@ def run_generate() -> DiskoResult[JsonDict]:
with open(DEFAULT_CONFIG_FILE, "w") as f:
f.write(HEADER_COMMENT)
if isinstance(generated_config_result, DiskoError):
if isinstance(generate_result, DiskoError):
f.write(PARTIAL_FAILURE_COMMENT)
f.write(nix_code)
info(f"Wrote generated config to {DEFAULT_CONFIG_FILE}")
run(["nixfmt", DEFAULT_CONFIG_FILE])
return generated_config_result
return generate_result
+44
View File
@@ -0,0 +1,44 @@
from dataclasses import dataclass, field
from typing import Literal
Action = Literal["destroy", "format", "mount"]
EMPTY_DESCRIPTION = "__empty__"
@dataclass
class Step:
action: Action # Which action the step belongs to
commands: list[list[str]] # List of commands to execute
description: str # Explanatory message to display to the user
@classmethod
def empty(cls, action: Action) -> "Step":
return cls(action, [], EMPTY_DESCRIPTION)
def is_empty(self) -> bool:
return self.commands == [] and self.description == EMPTY_DESCRIPTION
@dataclass
class Plan:
actions: set[Action]
steps: list[Step] = field(default_factory=list)
skipped_steps: list[Step] = field(default_factory=list)
def extend(self, other: "Plan") -> None:
# For now I don't see a usecase for merging plans with action sets.
assert self.actions == other.actions
self.steps.extend(other.steps)
self.skipped_steps.extend(other.skipped_steps)
def append(self, step: Step) -> None:
if step.is_empty():
return
if step.action in self.actions:
self.steps.append(step)
else:
self.skipped_steps.append(step)
+2 -2
View File
@@ -72,7 +72,7 @@ class gpt_partitions_hybrid(BaseModel):
class gpt_partitions(BaseModel):
_index: int
index: int = Field(alias="_index")
alignment: int
content: "partitionType" = Field(..., discriminator="type")
device: str
@@ -172,7 +172,7 @@ class swap(BaseModel):
class table_partitions(BaseModel):
_index: int
index: int = Field(alias="_index")
bootable: bool
content: "partitionType" = Field(..., discriminator="type")
end: str
-53
View File
@@ -1,53 +0,0 @@
from .json_types import JsonDict
def dict_diff(left: JsonDict, right: JsonDict) -> JsonDict:
"""Return a dict that only contains the keys and values of `right`
that are different from those in `left`.
>>> dict_diff({"a": 1, "b": 2}, {"a": 1, "b": 3})
{'b': 3}
Keys that are in `left` but not in `right` get the value `None`.
>>> dict_diff({"a": 1, "b": 2}, {"a": 1})
{'b': None}
Dicts are compared recursively.
>>> dict_diff({"a": {"b": 2}}, {"a": {"b": 3}})
{'a': {'b': 3}}
If a dict is missing in `left`, it gets the special key "_new" set
to True to differentiate it from a dict that was present but changed.
>>> dict_diff({"a": {"b": 1}}, {"a": {"b": 3}, "c": {"d": 4}})
{'a': {'b': 3}, 'c': {'d': 4, '_new': True}}
"""
new_dict: JsonDict = {}
for k, right_val in right.items():
left_val = left.get(k)
if left_val == right_val:
continue
if not isinstance(right_val, dict):
new_dict[k] = right_val
continue
if not isinstance(left_val, dict):
left_val = {}
diffed_right_val = dict_diff(left_val, right_val)
if not left_val:
diffed_right_val["_new"] = True
new_dict[k] = diffed_right_val
for k, left_val in left.items():
if k not in right:
# Do not recurse, even if left_val is a dict!
# Recursion is already done in the first loop.
new_dict[k] = None
return new_dict
+6 -1
View File
@@ -3,6 +3,7 @@
, flake ? null
, flakeAttr ? null
, diskoFile ? null
, configJsonStr ? null
, rootMountPoint ? "/mnt"
, ...
}@args:
@@ -18,6 +19,8 @@ let
hasFlakeDiskoConfig = lib.hasAttrByPath [ "diskoConfigurations" flakeAttr ] flake';
hasConfigStr = configJsonStr != null;
hasFlakeDiskoModule =
lib.hasAttrByPath [ "nixosConfigurations" flakeAttr "config" "disko" "devices" ] flake';
@@ -26,6 +29,8 @@ let
diskoConfig =
if hasDiskoFile then
import diskoFile
else if hasConfigStr then
(builtins.fromJSON configJsonStr)
else
flake'.diskoConfigurations.${flakeAttr};
in
@@ -35,7 +40,7 @@ let
diskoConfig;
evaluatedConfig =
if hasDiskoFile || hasFlakeDiskoConfig then
if hasDiskoFile || hasConfigStr || hasFlakeDiskoConfig then
disko.eval-disko diskFormat
else if (lib.traceValSeq hasFlakeDiskoModule) then
flake'.nixosConfigurations.${flakeAttr}
+6 -9
View File
@@ -95,7 +95,7 @@ def _eval_flake(flake_uri: str) -> DiskoResult[JsonDict]:
return _eval_config({"flake": flake, "flakeAttr": flake_attr})
def eval_config_as_json(
def eval_config_file_as_json(
*, disko_file: str | None, flake: str | None
) -> DiskoResult[JsonDict]:
# match would be nicer, but mypy doesn't understand type narrowing in tuples
@@ -109,22 +109,19 @@ def eval_config_as_json(
return DiskoError.single_message(err_too_many_arguments, "validate args")
def eval_and_validate_config(
*, disko_file: str | None, flake: str | None
) -> DiskoResult[DiskoConfig]:
json_config = eval_config_as_json(disko_file=disko_file, flake=flake)
def eval_config_dict_as_json(config: JsonDict) -> DiskoResult[JsonDict]:
return _eval_config({"configJsonStr": json.dumps(config)})
if isinstance(json_config, DiskoError):
return json_config
def validate_config(json_config: JsonDict) -> DiskoResult[DiskoConfig]:
try:
result = DiskoConfig(**cast(dict[str, Any], json_config.value)) # type: ignore[misc]
result = DiskoConfig(**cast(dict[str, Any], json_config)) # type: ignore[misc]
except ValidationError as e:
return DiskoError.single_message(
bug_validate_config_failed,
"validate disko config",
error=e,
config=json_config.value,
config=json_config,
)
return DiskoSuccess(result, "validate disko config")
+58
View File
@@ -0,0 +1,58 @@
from disko_lib.logging import DiskoMessage
from disko_lib.messages.msgs import (
help_generate_partial_failure,
)
from disko_lib.result import DiskoError, DiskoPartialSuccess, DiskoResult, DiskoSuccess
from disko_lib.types.device import BlockDevice
from disko_lib.json_types import JsonDict
import disko_lib.types.disk as disk
def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[JsonDict]:
error = DiskoError([], "generate disko config")
config: dict[str, JsonDict] = {
"disk": {},
"lvm_vg": {},
"mdadm": {},
"nodev": {},
"zpool": {},
}
successful_sections = []
failed_sections = []
disk_config = disk.generate_config(devices)
if isinstance(disk_config, DiskoSuccess):
config["disk"] = disk_config.value
successful_sections.append("disk")
else:
error.extend(disk_config)
failed_sections.append("disk")
if isinstance(disk_config, DiskoPartialSuccess):
config["disk"] = disk_config.value
successful_sections.append("disk")
# TODO: Add generation for ZFS, MDADM, LVM, etc.
successful_sections.append("lvm_vg")
successful_sections.append("mdadm")
successful_sections.append("nodev")
successful_sections.append("zpool")
final_config: JsonDict = {"disko": {"devices": config}} # type: ignore[dict-item]
if not failed_sections:
return DiskoSuccess(final_config, "generate disko config")
if not successful_sections:
return error
error.append(
DiskoMessage(
help_generate_partial_failure,
partial_config=final_config,
successful=successful_sections,
failed=failed_sections,
)
)
return error.to_partial_success(final_config)
+11
View File
@@ -0,0 +1,11 @@
from disko_lib.action import Action, Plan
from disko_lib.config_type import DiskoConfig
from disko_lib.result import DiskoResult
import disko_lib.types.disk as disk
def generate_plan(
actions: set[Action], current_status: DiskoConfig, target_config: DiskoConfig
) -> DiskoResult[Plan]:
# TODO: Add generation for ZFS, MDADM, LVM, etc.
return disk.generate_plan(actions, current_status, target_config)
+32 -2
View File
@@ -1,7 +1,7 @@
import json
import pydantic
from disko_lib.logging import ReadableMessage
from disko_lib.messages.colors import INVALID, RESET, VALUE
from disko_lib.messages.colors import FILE, INVALID, RESET, VALUE
from ..json_types import JsonDict
@@ -55,10 +55,40 @@ def bug_validate_config_failed(
ReadableMessage(
"bug",
f"""
Configuration was evaluated successfully, but failed validation!
Configuration validation failed!
Most likely, the types in python are out-of-sync with those in nix.
The {INVALID}validation errors{RESET} and the {VALUE}evaluated configuration{RESET} are printed above.
""",
),
__bug_help_message("bug_validate_config_failed"),
]
def bug_unsupported_device_content_type(
*, name: str, device: str, type: str
) -> list[ReadableMessage]:
return [
ReadableMessage(
"bug",
f"""
Configuration for device {FILE}{device}{RESET} (name={VALUE}{name}{RESET}) specifies unsupported
device content type {INVALID}{type}{RESET}, which was not implemented yet!
""",
),
__bug_help_message("err_unsupported_device_content_type"),
]
def bug_unsupported_partition_content_type(
*, name: str, device: str, type: str
) -> list[ReadableMessage]:
return [
ReadableMessage(
"bug",
f"""
Configuration for partition {FILE}{device}{RESET} (name={VALUE}{name}{RESET}) specifies unsupported
partition content type {INVALID}{type}{RESET}, which was not implemented yet!
""",
),
__bug_help_message("bug_unsupported_partition_content_type"),
]
+96 -10
View File
@@ -19,6 +19,54 @@ def err_command_failed(*, command: str, exit_code: int, stderr: str) -> Readable
)
def err_disk_type_changed_no_destroy(
*, disk: str, device: str, old_type: str, new_type: str
) -> list[ReadableMessage]:
return [
ReadableMessage(
"error",
f"""
Disk {VALUE}{disk}{RESET} ({FILE}{device}{RESET}) changed type from {INVALID}{old_type}{RESET} to {INVALID}{new_type}{RESET}.
Need to destroy and recreate the disk, but the current mode does not allow it!
""",
),
ReadableMessage(
"help",
f"""
Run `{COMMAND}disko{RESET} {VALUE}destroy,format,mount{RESET}` to allow destructive changes,
or change {VALUE}{disk}{RESET}'s type back to {INVALID}{old_type}{RESET} to keep the data.
""",
),
]
def err_disk_not_found(*, disk: str, device: str) -> ReadableMessage:
return ReadableMessage(
"error",
f"Device path {FILE}{device}{RESET} (for disk {VALUE}{disk}{RESET}) was not found!",
)
def err_duplicated_disk_devices(
*, devices: list[str], duplicates: set[str]
) -> list[ReadableMessage]:
return [
ReadableMessage(
"error",
f"""
Your config sets the same device path for multiple disks!
Devices: {", ".join(f"{VALUE}{d}{RESET}" for d in sorted(devices))}
""",
),
ReadableMessage(
"help",
f"""The duplicates are:
{", ".join(f"{INVALID}{d}{RESET}" for d in duplicates)}
""",
),
]
def err_eval_config_failed(*, args: dict[str, str], stderr: str) -> ReadableMessage:
return ReadableMessage(
"error",
@@ -33,6 +81,27 @@ def err_file_not_found(*, path: Path) -> ReadableMessage:
return ReadableMessage("error", f"File not found: {FILE}{path}{RESET}")
def err_filesystem_changed_no_destroy(
*, device: str, old_format: str, new_format: str
) -> list[ReadableMessage]:
return [
ReadableMessage(
"error",
f"""
Filesystem on device {FILE}{device}{RESET} changed from {INVALID}{old_format}{RESET} to {INVALID}{new_format}{RESET}.
Need to destroy and recreate the filesystem, but the current mode does not allow it!
""",
),
ReadableMessage(
"help",
f"""
Run `{COMMAND}disko{RESET} {VALUE}destroy,format,mount{RESET}` to allow destructive changes,
or change the filesystem back to {INVALID}{old_format}{RESET} to keep the data.
""",
),
]
def err_flake_uri_no_attr(*, flake_uri: str) -> list[ReadableMessage]:
return [
ReadableMessage(
@@ -82,10 +151,30 @@ def err_unsupported_pttype(*, device: Path, pttype: str) -> ReadableMessage:
def warn_generate_partial_failure(
*,
kind: str,
failed: list[str],
successful: list[str],
) -> ReadableMessage:
partially_successful = [x for x in successful if x in failed]
failed = [x for x in failed if x not in partially_successful]
successful = [x for x in successful if x not in partially_successful]
return ReadableMessage(
"warning",
f"""
Successfully generated config for {EM}some{RESET} {kind}s of your setup, {EM_WARN}but not all{RESET}!
Failed {kind}s: {", ".join(f"{INVALID}{d}{RESET}" for d in failed)}
Successful {kind}s: {", ".join(f"{VALUE}{d}{RESET}" for d in successful)}
Partially successful {kind}s: {", ".join(f"{EM_WARN}{d}{RESET}" for d in partially_successful)}
""",
)
def help_generate_partial_failure(
*,
partial_config: JsonDict,
failed_devices: list[str],
successful_devices: list[str],
failed: list[str],
successful: list[str],
) -> list[ReadableMessage]:
return [
ReadableMessage(
@@ -94,16 +183,13 @@ def warn_generate_partial_failure(
Successfully generated config for {EM}some{RESET} devices.
Errors are printed above. The generated partial config is:
{json.dumps(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 failed_devices)}
Successful devices: {", ".join(f"{VALUE}{d}{RESET}" for d in successful_devices)}
""",
),
warn_generate_partial_failure(
kind="section",
failed=failed,
successful=successful,
),
ReadableMessage(
"help",
f"""
+26 -5
View File
@@ -1,11 +1,18 @@
from dataclasses import dataclass
from typing import Any, Generic, Literal, ParamSpec, TypeVar, cast
from typing import Any, Generic, ParamSpec, TypeVar, cast
from disko_lib.messages.bugs import bug_success_without_context
from .logging import DiskoMessage, debug, MessageFactory
from .logging import (
DiskoMessage,
ReadableMessage,
debug,
MessageFactory,
render_message,
)
T = TypeVar("T", covariant=True)
S = TypeVar("S")
P = ParamSpec("P")
@@ -13,14 +20,15 @@ P = ParamSpec("P")
class DiskoSuccess(Generic[T]):
value: T
context: None | str = None
success: Literal[True] = True
@dataclass
class DiskoError:
messages: list[DiskoMessage[object]]
context: str
success: Literal[False] = False
def __len__(self) -> int:
return len(self.messages)
@classmethod
def single_message(
@@ -43,8 +51,19 @@ class DiskoError:
def extend(self, other_error: "DiskoError") -> None:
self.messages.extend(other_error.messages)
def with_context(self, context: str) -> "DiskoError":
return DiskoError(self.messages, context)
DiskoResult = DiskoSuccess[T] | DiskoError # type: ignore[misc, unused-ignore]
def to_partial_success(self, value: S) -> "DiskoPartialSuccess[S]":
return DiskoPartialSuccess(self.messages, self.context, value)
@dataclass
class DiskoPartialSuccess(Generic[T], DiskoError):
value: T
DiskoResult = DiskoSuccess[T] | DiskoPartialSuccess[T] | DiskoError # type: ignore[misc, unused-ignore]
def exit_on_error(result: DiskoResult[T]) -> T:
@@ -56,6 +75,8 @@ def exit_on_error(result: DiskoResult[T]) -> T:
debug(f"Returned value: {result.value}")
return result.value
render_message(ReadableMessage("error", f"Failed to {result.context}!"))
for message in result.messages:
message.print()
+15 -4
View File
@@ -62,7 +62,7 @@ class BlockDevice:
serial: str
size: str
start: str
mountpoint: str
mountpoint: str | None
mountpoints: list[str]
type: str
uuid: str
@@ -104,9 +104,9 @@ class BlockDevice:
pttype=cast(str, json_dict["pttype"]),
rev=cast(str, json_dict["rev"]) or "",
serial=cast(str, json_dict["serial"]) or "",
size=cast(str, json_dict["size"]),
size=str(cast(int, json_dict["size"])),
start=cast(str, json_dict["start"]) or "",
mountpoint=cast(str, json_dict["mountpoint"]) or "",
mountpoint=cast(str, json_dict["mountpoint"]) or None,
mountpoints=mountpoints,
type=cast(str, json_dict["type"]),
uuid=cast(str, json_dict["uuid"]) or "",
@@ -114,7 +114,18 @@ class BlockDevice:
def run_lsblk() -> DiskoResult[str]:
return run(["lsblk", "--json", "--tree", "--output", ",".join(LSBLK_OUTPUT_FIELDS)])
return run(
[
"lsblk",
"--json", # JSON output
"--tree", # Tree structure with `children` field
# Show sizes in bytes. The human readable abbreviation can be less precise and harder to parse
"--bytes",
# Determine and output only the fields we are interested in
"--output",
",".join(LSBLK_OUTPUT_FIELDS),
]
)
def list_block_devices(lsblk_output: str = "") -> DiskoResult[list[BlockDevice]]:
+147 -16
View File
@@ -1,23 +1,31 @@
from typing import cast
from disko_lib.action import Action, Plan, Step
from disko_lib.config_type import DiskoConfig, disk, gpt, deviceType
from disko_lib.messages.msgs import (
err_disk_not_found,
err_duplicated_disk_devices,
err_unsupported_pttype,
warn_generate_partial_failure,
)
from disko_lib.messages.bugs import bug_unsupported_device_content_type
from disko_lib.utils import find_by_predicate, find_duplicates
import disko_lib.types.gpt
from ..logging import DiskoMessage, debug
from ..result import DiskoError, DiskoResult, DiskoSuccess
from ..types.device import BlockDevice, list_block_devices
from ..json_types import JsonDict
from . import gpt
def _generate_content(device: BlockDevice) -> DiskoResult[JsonDict]:
def _generate_config_content(device: BlockDevice) -> DiskoResult[JsonDict]:
match device.pttype:
case "gpt":
return gpt.generate_config(device)
return disko_lib.types.gpt.generate_config(device)
case _:
return DiskoError.single_message(
err_unsupported_pttype,
"generate disk content",
"generate disk config",
device=device.path,
pttype=device.pttype,
)
@@ -41,7 +49,7 @@ def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[JsonDict]:
successful_devices = []
for device in block_devices:
content = _generate_content(device)
content = _generate_config_content(device)
if isinstance(content, DiskoError):
error.extend(content)
@@ -49,25 +57,148 @@ def generate_config(devices: list[BlockDevice] = []) -> DiskoResult[JsonDict]:
continue
disks[f"MODEL:{device.model},SN:{device.serial}"] = {
"device": device.kname,
"device": f"/dev/{device.kname}",
"type": device.type,
"content": content.value,
}
successful_devices.append(device.path)
config: JsonDict = {"disks": disks}
if not failed_devices:
return DiskoSuccess(config, "generate disk config")
return DiskoSuccess(disks, "generate disk config")
if successful_devices:
if not successful_devices:
return error
error.append(
DiskoMessage(
warn_generate_partial_failure,
kind="disk",
failed=failed_devices,
successful=successful_devices,
)
)
return error.to_partial_success(disks)
def _generate_plan_content(
actions: set[Action],
name: str,
device: str,
current_content: deviceType,
target_content: deviceType,
) -> DiskoResult[Plan]:
if target_content is None:
debug(f"Element '{name}': No target content")
return DiskoSuccess(Plan(actions, []), f"generate '{name}' content plan")
target_type = target_content.type
if current_content is not None:
assert (
current_content.type == target_type
), "BUG! Device content type mismatch, should've been resolved earlier!"
match target_type:
case "gpt":
return disko_lib.types.gpt.generate_plan(
actions, cast(gpt | None, current_content), cast(gpt, target_content)
)
case _:
return DiskoError.single_message(
bug_unsupported_device_content_type,
"generate disk plan",
name=name,
device=device,
type=target_type,
)
def generate_plan(
actions: set[Action], current_status: DiskoConfig, target_config: DiskoConfig
) -> DiskoResult[Plan]:
debug("Generating plan for disko config")
error = DiskoError([], "generate disk plan")
plan = Plan(actions)
current_disks = current_status.disk
target_disks = target_config.disk
target_devices = [d.device for d in target_disks.values()]
if duplicate_devices := find_duplicates(target_devices):
error.append(
DiskoMessage(
warn_generate_partial_failure,
partial_config=config,
failed_devices=failed_devices,
successful_devices=successful_devices,
),
err_duplicated_disk_devices,
devices=target_devices,
duplicates=duplicate_devices,
)
)
return error
current_disks_by_target_name: dict[str, disk] = {}
# Create plan for this disk
for name, target_disk_config in target_disks.items():
device = target_disk_config.device
_, current_disk_config = find_by_predicate(
current_disks, lambda k, v: v.device == device
)
disk_exists = current_disk_config is not None
current_type = current_disk_config.type if current_disk_config else None
target_type = target_disk_config.type
disk_has_same_type = current_type == target_type
debug(
f"Disk '{name}': {device=}, {disk_exists=}, {disk_has_same_type=}, {current_type=}, {target_type=}"
)
# Can't use disk_exists here, mypy doesn't understand that it
# narrows the type of current_disk_config
if current_disk_config is None:
error.append(
DiskoMessage(
err_disk_not_found,
disk=name,
device=device,
)
)
continue
current_disks_by_target_name[name] = current_disk_config
if disk_has_same_type:
continue
plan.append(
Step(
"destroy",
[[f"disk-deactivate {device}"]],
f"destroy partition table on `{name}`, at {device}",
)
)
# Create content plan
for name, target_disk_config in target_disks.items():
current_content = None
current_disk_config = current_disks_by_target_name.get(name)
if current_disk_config is not None:
current_content = current_disk_config.content
result = _generate_plan_content(
actions,
name,
target_disk_config.device,
current_content,
target_disk_config.content,
)
if isinstance(result, DiskoError):
error.extend(result)
continue
plan.extend(result.value)
if error:
return error
return DiskoSuccess(plan, "generate disk plan")
+59
View File
@@ -1,3 +1,6 @@
from disko_lib.action import Action, Plan, Step
from disko_lib.config_type import filesystem
from disko_lib.logging import debug
from .device import BlockDevice
from ..result import DiskoResult, DiskoSuccess
from ..json_types import JsonDict
@@ -15,3 +18,59 @@ def generate_config(device: BlockDevice) -> DiskoResult[JsonDict]:
"mountpoint": device.mountpoint,
}
)
def _generate_mount_step(target_config: filesystem) -> Step:
if target_config.mountpoint is None:
return Step.empty("mount")
return Step(
"mount",
[
# TODO: Only try to mount if the device is not already mounted
# This will probably require us to change the way we specify steps,
# as they currently don't allow for conditional execution
[
"mount",
target_config.device,
target_config.mountpoint,
"-t",
target_config.format,
]
+ target_config.mountOptions
+ ["-o", "X-mount.mkdir"]
],
"mount filesystem",
)
def generate_plan(
actions: set[Action], current_config: filesystem | None, target_config: filesystem
) -> DiskoResult[Plan]:
debug("Generating plan for filesystem")
plan = Plan(actions, [])
current_format = current_config.format if current_config is not None else None
target_format = target_config.format
device = target_config.device
need_to_destroy_current = (
current_config is not None and current_format != target_format
)
debug(
f"Filesystem {device}: {current_format=}, {target_format=}, {need_to_destroy_current=}"
)
if need_to_destroy_current:
plan.append(
Step(
"destroy",
[[f"mkfs.{target_format}"] + target_config.extraArgs + [device]],
"destroy current filesystem and create new one",
)
)
plan.append(_generate_mount_step(target_config))
return DiskoSuccess(plan, "generate filesystem plan")
+192 -7
View File
@@ -1,5 +1,10 @@
from typing import cast
from disko_lib.action import Action, Plan, Step
from disko_lib.config_type import gpt, gpt_partitions, partitionType, filesystem
from disko_lib.messages.bugs import bug_unsupported_partition_content_type
from disko_lib.utils import find_by_predicate
import disko_lib.types.filesystem
from ..logging import debug
from . import filesystem
from .device import BlockDevice
from ..result import DiskoError, DiskoResult, DiskoSuccess
from ..json_types import JsonDict
@@ -24,11 +29,11 @@ def _generate_name(device: BlockDevice) -> str:
return f"PARTUUID:{device.partuuid}"
def _generate_content(device: BlockDevice) -> DiskoResult[JsonDict]:
def _generate_config_content(device: BlockDevice) -> DiskoResult[JsonDict]:
match device.fstype:
# TODO: Add filesystems that are not supported by `mkfs` here
case _:
return filesystem.generate_config(device)
return disko_lib.types.filesystem.generate_config(device)
def generate_config(device: BlockDevice) -> DiskoResult[JsonDict]:
@@ -43,8 +48,8 @@ def generate_config(device: BlockDevice) -> DiskoResult[JsonDict]:
failed_partitions = []
successful_partitions = []
for partition in device.children:
content = _generate_content(partition)
for index, partition in enumerate(device.children):
content = _generate_config_content(partition)
if isinstance(content, DiskoError):
error.extend(content)
@@ -52,11 +57,191 @@ def generate_config(device: BlockDevice) -> DiskoResult[JsonDict]:
continue
partitions[_generate_name(partition)] = _add_type_if_required(
partition, {"size": partition.size, "content": content.value}
partition,
{"_index": index + 1, "size": partition.size, "content": content.value},
)
successful_partitions.append(partition.path)
if not failed_partitions:
return DiskoSuccess({"partitions": partitions}, "generate gpt config")
return DiskoSuccess(
{"type": "gpt", "partitions": partitions}, "generate gpt config"
)
return error
def _generate_plan_content(
actions: set[Action],
name: str,
device: str,
current_content: partitionType,
target_content: partitionType,
) -> DiskoResult[Plan]:
if target_content is None:
return DiskoSuccess(Plan(actions, []), f"generate '{name}' content plan")
target_type = target_content.type
if current_content is not None:
assert (
current_content.type == target_type
), "BUG! Partition content type mismatch, should've been resolved earlier!"
match target_type:
case "filesystem":
return disko_lib.types.filesystem.generate_plan(
actions,
cast(filesystem | None, current_content),
cast(filesystem, target_content),
)
case _:
return DiskoError.single_message(
bug_unsupported_partition_content_type,
"generate partition plan",
name=name,
device=device,
type=target_type,
)
def _step_clear_partition_table(device: str) -> Step:
return Step(
"format", [["sgdisk", "--clear", device]], f"Clear partition table on {device}"
)
def _partprobe_settle(device: str) -> list[list[str]]:
# ensure /dev/disk/by-path/..-partN exists before continuing
return [
["partprobe", device],
["udevadm", "trigger", "--subsystem-match=block"],
["udevadm", "settle"],
]
def _sgdisk_create_args(partition_config: gpt_partitions) -> list[str]:
alignment = partition_config.alignment
index = partition_config.index
start = partition_config.start
end = partition_config.end
alignment_args = [] if alignment == 0 else [f"--set-alignment={alignment}"]
return [
"--align-end",
*alignment_args,
f"--new={index}:{start}:{end}",
]
def _sgdisk_modify_args(partition_config: gpt_partitions) -> list[str]:
index = partition_config.index
label = partition_config.label
type = partition_config.type
return [
f'--change-name="{index}:{label}"',
f"--typecode=${index}:{type}",
]
def _step_modify_partition(device: str, partition_config: gpt_partitions) -> Step:
return Step(
"format",
[
[
"sgdisk",
*_sgdisk_modify_args(partition_config),
device,
]
]
+ _partprobe_settle(device),
"Create partition {}",
)
def _step_create_partition(device: str, partition_config: gpt_partitions) -> Step:
return Step(
"format",
[
[
"sgdisk",
*_sgdisk_create_args(partition_config),
*_sgdisk_modify_args(partition_config),
device,
]
]
+ _partprobe_settle(device),
"Create partition {}",
)
def generate_plan(
actions: set[Action], current_gpt_config: gpt | None, target_gpt_config: gpt
) -> DiskoResult[Plan]:
device = target_gpt_config.device
debug(f"Generating GPT plan for disk {device}")
if current_gpt_config is None:
current_partitions = {}
else:
current_partitions = current_gpt_config.partitions
target_partitions = target_gpt_config.partitions
error_messages = []
plan = Plan(actions)
if current_gpt_config is None:
plan.append(_step_clear_partition_table(device))
current_partitions_by_target_name: dict[str, gpt_partitions] = {}
# Create or modify all partitions first
for name, target_partition in target_partitions.items():
_, current_partition = find_by_predicate(
current_partitions, lambda k, v: v.index == target_partition.index
)
if not current_partition:
plan.append(_step_create_partition(device, target_partition))
continue
current_partitions_by_target_name[name] = current_partition
if (
current_partition.type == target_partition.type
and current_partition.label == target_partition.label
):
debug(f"Partition {name} has no changes we could apply")
continue
# TODO: Determine if something else about the disk changed. Add a warning message if that change
# can't be applied by disko automatically, (plus a help message that explains how to target just
# a single disk in case the user wants to make the change destructively) or add the
# necessary steps to apply the changes
if "format" not in actions:
continue
plan.append(_step_modify_partition(device, target_partition))
# Then dispatch to all the filesystems
for name, target_partition in target_partitions.items():
current_content = None
current_partition_config = current_partitions_by_target_name.get(name)
if current_partition_config is not None:
current_content = current_partition_config.content
content_plan_result = _generate_plan_content(
actions,
name,
target_partition.device,
current_content,
target_partition.content,
)
if isinstance(content_plan_result, DiskoError):
error_messages.append(content_plan_result.messages)
continue
plan.extend(content_plan_result.value)
return DiskoSuccess(plan, "generate gpt plan")
+23
View File
@@ -0,0 +1,23 @@
from typing import Iterable, TypeVar, Callable
T = TypeVar("T")
def find_by_predicate(
dct: dict[str, T], predicate: Callable[[str, T], bool]
) -> tuple[str, T] | tuple[None, None]:
for k, v in dct.items():
if predicate(k, v):
return k, v
return None, None
def find_duplicates(it: Iterable[T]) -> set[T]:
seen = set()
duplicates = set()
for item in it:
if item in seen:
duplicates.add(item)
else:
seen.add(item)
return duplicates
@@ -6,6 +6,7 @@
"efiGptPartitionFirst": true,
"partitions": {
"ESP": {
"_index": 1,
"alignment": 0,
"content": {
"device": "/dev/disk/by-partlabel/disk-main-ESP",
@@ -28,6 +29,7 @@
"type": "EF00"
},
"root": {
"_index": 2,
"alignment": 0,
"content": {
"device": "/dev/disk/by-partlabel/disk-main-root",
@@ -63,4 +65,4 @@
"mdadm": {},
"nodev": {},
"zpool": {}
}
}
@@ -6,6 +6,7 @@
"efiGptPartitionFirst": true,
"partitions": {
"ESP": {
"_index": 2,
"alignment": 0,
"content": {
"device": "/dev/disk/by-partlabel/disk-main-ESP",
@@ -28,6 +29,7 @@
"type": "EF00"
},
"boot": {
"_index": 1,
"alignment": 0,
"content": null,
"device": "/dev/disk/by-partlabel/disk-main-boot",
@@ -41,6 +43,7 @@
"type": "EF02"
},
"root": {
"_index": 3,
"alignment": 0,
"content": {
"device": "/dev/disk/by-partlabel/disk-main-root",
@@ -76,4 +79,4 @@
"mdadm": {},
"nodev": {},
"zpool": {}
}
}
+17 -12
View File
@@ -1,9 +1,8 @@
import json
from pathlib import Path
import readline
from typing import cast
from disko_lib.eval_config import eval_config_as_json, eval_and_validate_config
from disko_lib.eval_config import eval_config_file_as_json, validate_config
from disko_lib.messages.msgs import err_missing_arguments, err_too_many_arguments
from disko_lib.result import DiskoError, DiskoSuccess
from disko_lib.json_types import JsonDict
@@ -14,14 +13,14 @@ assert (ROOT_DIR / "flake.nix").exists()
def test_eval_config_missing_arguments() -> None:
result = eval_config_as_json(disko_file=None, flake=None)
result = eval_config_file_as_json(disko_file=None, flake=None)
assert isinstance(result, DiskoError)
assert result.messages[0].is_message(err_missing_arguments)
assert result.context == "validate args"
def test_eval_config_too_many_arguments() -> None:
result = eval_config_as_json(disko_file="foo", flake="bar")
result = eval_config_file_as_json(disko_file="foo", flake="bar")
assert isinstance(result, DiskoError)
assert result.messages[0].is_message(err_too_many_arguments)
assert result.context == "validate args"
@@ -29,7 +28,7 @@ def test_eval_config_too_many_arguments() -> None:
def test_eval_config_disko_file() -> None:
disko_file_path = ROOT_DIR / "example" / "simple-efi.nix"
result = eval_config_as_json(disko_file=str(disko_file_path), flake=None)
result = eval_config_file_as_json(disko_file=str(disko_file_path), flake=None)
assert isinstance(result, DiskoSuccess)
with open(CURRENT_DIR / "file-simple-efi-eval-result.json") as f:
expected_result = cast(JsonDict, json.load(f))
@@ -37,7 +36,7 @@ def test_eval_config_disko_file() -> None:
def test_eval_config_flake_testmachine() -> None:
result = eval_config_as_json(disko_file=None, flake=f"{ROOT_DIR}#testmachine")
result = eval_config_file_as_json(disko_file=None, flake=f"{ROOT_DIR}#testmachine")
assert isinstance(result, DiskoSuccess)
with open(CURRENT_DIR / "flake-testmachine-eval-result.json") as f:
expected_result = cast(JsonDict, json.load(f))
@@ -46,16 +45,22 @@ def test_eval_config_flake_testmachine() -> None:
def test_eval_and_validate_config_disko_file() -> None:
disko_file_path = ROOT_DIR / "example" / "simple-efi.nix"
result = eval_and_validate_config(disko_file=str(disko_file_path), flake=None)
assert isinstance(result, DiskoSuccess)
eval_result = eval_config_file_as_json(disko_file=str(disko_file_path), flake=None)
assert isinstance(eval_result, DiskoSuccess)
validate_result = validate_config(eval_result.value)
assert isinstance(validate_result, DiskoSuccess)
with open(CURRENT_DIR / "file-simple-efi-validate-result.json") as f:
expected_result = f.read()
assert json.loads(result.value.model_dump_json()) == json.loads(expected_result) # type: ignore[misc]
assert json.loads(validate_result.value.model_dump_json(by_alias=True)) == json.loads(expected_result) # type: ignore[misc]
def test_eval_and_validate_flake_testmachine() -> None:
result = eval_and_validate_config(disko_file=None, flake=f"{ROOT_DIR}#testmachine")
assert isinstance(result, DiskoSuccess)
eval_result = eval_config_file_as_json(
disko_file=None, flake=f"{ROOT_DIR}#testmachine"
)
assert isinstance(eval_result, DiskoSuccess)
validate_result = validate_config(eval_result.value)
assert isinstance(validate_result, DiskoSuccess)
with open(CURRENT_DIR / "flake-testmachine-validate-result.json") as f:
expected_result = f.read()
assert json.loads(result.value.model_dump_json()) == json.loads(expected_result) # type: ignore[misc]
assert json.loads(validate_result.value.model_dump_json(by_alias=True)) == json.loads(expected_result) # type: ignore[misc]
-168
View File
@@ -1,168 +0,0 @@
from disko_lib.dict_diff import dict_diff
from disko_lib.json_types import JsonDict
def test_dict_diff_basic() -> None:
left: JsonDict = {
"a": 1,
"b": 2,
"c": 3,
"d": 4,
}
right: JsonDict = {
"a": 1,
"b": 3,
"c": 4,
"e": 5,
}
assert dict_diff(left, right) == {
"b": 3,
"c": 4,
"d": None,
"e": 5,
}
assert dict_diff(right, left) == {
"b": 2,
"c": 3,
"d": 4,
"e": None,
}
assert dict_diff(left, left) == {}
assert dict_diff(right, right) == {}
assert dict_diff({}, {}) == {}
assert dict_diff(left, {}) == {
"a": None,
"b": None,
"c": None,
"d": None,
}
assert dict_diff({}, right) == right
def test_dict_diff_arrays() -> None:
left: JsonDict = {
"a": [1, 2, 3],
"b": [4, 5, 6],
"c": [7, 8, 9],
}
right: JsonDict = {
"a": [1, 2, 3],
"b": [4, 5, 7],
"c": [7, 8, 9],
"d": [10, 11, 12],
}
assert dict_diff(left, right) == {
"b": [4, 5, 7],
"d": [10, 11, 12],
}
assert dict_diff(right, left) == {
"b": [4, 5, 6],
"d": None,
}
assert dict_diff(left, left) == {}
assert dict_diff(right, right) == {}
assert dict_diff(left, {}) == {
"a": None,
"b": None,
"c": None,
}
assert dict_diff({}, right) == right
def test_dict_diff_nested() -> None:
left: JsonDict = {
"a": {
"b": {
"c": 1,
"d": 2,
},
"e": 3,
"f": 4,
},
"g": {
"h": 4,
},
"k": {
"l": {
"m": 5,
},
},
}
right: JsonDict = {
"a": {
"b": {
"c": 1,
"d": 3,
},
"e": 3,
},
"g": {
"h": 4,
"i": 5,
},
"o": {
"p": 6,
},
}
assert dict_diff(left, right) == {
"a": {
"b": {
"d": 3,
},
"f": None,
},
"g": {
"i": 5,
},
"k": None,
"o": {
"p": 6,
"_new": True,
},
}
assert dict_diff(right, left) == {
"a": {
"b": {
"d": 2,
},
"f": 4,
},
"g": {
"i": None,
},
"k": {
"l": {
"m": 5,
"_new": True,
},
"_new": True,
},
"o": None,
}
assert dict_diff(left, left) == {}
assert dict_diff(right, right) == {}
assert dict_diff(left, {}) == {
"a": None,
"g": None,
"k": None,
}
assert dict_diff({}, right) == {
"a": {
"b": {
"c": 1,
"d": 3,
"_new": True,
},
"e": 3,
"_new": True,
},
"g": {
"h": 4,
"i": 5,
"_new": True,
},
"o": {
"p": 6,
"_new": True,
},
}
@@ -1,110 +1,131 @@
{
"disks": {
"MODEL:ST2000LM003 HN-M201RAD,SN:S321J9GFC01497": {
"device": "sda",
"type": "disk",
"content": {
"partitions": {
"PARTUUID:c090741b-68e2-4867-96df-2ec00765f2c0": {
"size": "128M",
"content": {
"type": "filesystem",
"format": "",
"mountpoint": ""
}
},
"UUID:7CA41E5EA41E1B6A": {
"size": "1.8T",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": "/mnt/g"
}
}
}
}
},
"disko": {
"devices": {
"disk": {
"MODEL:SanDisk SD8TB8U256G1001,SN:171887425854": {
"device": "sdb",
"type": "disk",
"content": {
"partitions": {
"UUID:01D60069CEED69C0": {
"size": "499.5M",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": ""
}
},
"UUID:01D6006B90875FE0": {
"size": "236.8G",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": ""
}
},
"UUID:708B-C192": {
"size": "100M",
"content": {
"type": "filesystem",
"format": "vfat",
"mountpoint": ""
},
"type": "EF00"
},
"UUID:90B6FB81B6FB65DE": {
"size": "544M",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": ""
}
}
"device": "/dev/sdb",
"type": "disk",
"content": {
"type": "gpt",
"partitions": {
"UUID:01D60069CEED69C0": {
"_index": 1,
"size": "523730944",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": null
}
},
"UUID:01D6006B90875FE0": {
"_index": 2,
"size": "254301093376",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": null
}
},
"UUID:708B-C192": {
"_index": 3,
"size": "104857600",
"content": {
"type": "filesystem",
"format": "vfat",
"mountpoint": null
},
"type": "EF00"
},
"UUID:90B6FB81B6FB65DE": {
"_index": 4,
"size": "570425344",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": null
}
}
}
}
},
"MODEL:CT2000MX500SSD1,SN:2105E4F0DE85": {
"device": "sdd",
"type": "disk",
"content": {
"partitions": {
"UUID:2740-1628": {
"size": "1000M",
"content": {
"type": "filesystem",
"format": "vfat",
"mountpoint": "/boot"
},
"type": "EF00"
},
"UUID:ca548f68-4e51-4364-b366-690ecc27590f": {
"size": "588.4G",
"content": {
"type": "filesystem",
"format": "ext4",
"mountpoint": "/"
}
},
"UUID:879299db-4147-4fac-9f34-5e8e92073efc": {
"size": "588.4G",
"content": {
"type": "filesystem",
"format": "crypto_LUKS",
"mountpoint": ""
}
},
"UUID:9A48E8C248E89E6F": {
"size": "685.2G",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": "/mnt/s"
}
}
"device": "/dev/sdc",
"type": "disk",
"content": {
"type": "gpt",
"partitions": {
"UUID:2740-1628": {
"_index": 1,
"size": "1048576000",
"content": {
"type": "filesystem",
"format": "vfat",
"mountpoint": "/boot"
},
"type": "EF00"
},
"UUID:ca548f68-4e51-4364-b366-690ecc27590f": {
"_index": 2,
"size": "631794302976",
"content": {
"type": "filesystem",
"format": "ext4",
"mountpoint": "/"
}
},
"UUID:879299db-4147-4fac-9f34-5e8e92073efc": {
"_index": 3,
"size": "631810031616",
"content": {
"type": "filesystem",
"format": "crypto_LUKS",
"mountpoint": null
}
},
"UUID:9A48E8C248E89E6F": {
"_index": 4,
"size": "735743836160",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": "/mnt/s"
}
}
}
}
},
"MODEL:ST2000LM003 HN-M201RAD,SN:S321J9GFC01497": {
"device": "/dev/sdd",
"type": "disk",
"content": {
"type": "gpt",
"partitions": {
"PARTUUID:c090741b-68e2-4867-96df-2ec00765f2c0": {
"_index": 1,
"size": "134217728",
"content": {
"type": "filesystem",
"format": "",
"mountpoint": null
}
},
"UUID:7CA41E5EA41E1B6A": {
"_index": 2,
"size": "2000263577600",
"content": {
"type": "filesystem",
"format": "ntfs",
"mountpoint": "/mnt/g"
}
}
}
}
}
},
"lvm_vg": {},
"mdadm": {},
"nodev": {},
"zpool": {}
}
}
}
@@ -1,13 +1,13 @@
{
"blockdevices": [
{
"id-link": "wwn-0x50004cf20ecb1679",
"id-link": "wwn-0x5002538043584d30",
"fstype": null,
"fssize": null,
"fsuse%": null,
"kname": "sda",
"label": null,
"model": "ST2000LM003 HN-M201RAD",
"model": "SAMSUNG SSD PM830 mSATA 256GB",
"partflags": null,
"partlabel": null,
"partn": null,
@@ -15,75 +15,18 @@
"parttypename": null,
"partuuid": null,
"path": "/dev/sda",
"phy-sec": 4096,
"pttype": "gpt",
"rev": "2BC10001",
"serial": "S321J9GFC01497",
"size": "1.8T",
"phy-sec": 512,
"pttype": "dos",
"rev": "CXM13D1Q",
"serial": "S0XPNYAD407619",
"size": 256060514304,
"start": null,
"mountpoint": null,
"mountpoints": [
null
],
"type": "disk",
"uuid": null,
"children": [
{
"id-link": "wwn-0x50004cf20ecb1679-part1",
"fstype": null,
"fssize": null,
"fsuse%": null,
"kname": "sda1",
"label": null,
"model": null,
"partflags": null,
"partlabel": "Microsoft reserved partition",
"partn": 1,
"parttype": "e3c9e316-0b5c-4db8-817d-f92df00215ae",
"parttypename": "Microsoft reserved",
"partuuid": "c090741b-68e2-4867-96df-2ec00765f2c0",
"path": "/dev/sda1",
"phy-sec": 4096,
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "128M",
"start": 34,
"mountpoint": null,
"mountpoints": [
null
],
"type": "part",
"uuid": null
},{
"id-link": "wwn-0x50004cf20ecb1679-part2",
"fstype": "ntfs",
"fssize": "1.8T",
"fsuse%": "51%",
"kname": "sda2",
"label": "Groß",
"model": null,
"partflags": null,
"partlabel": "Basic data partition",
"partn": 2,
"parttype": "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7",
"parttypename": "Microsoft basic data",
"partuuid": "425b6415-db2b-4684-b619-994bdd0f9b71",
"path": "/dev/sda2",
"phy-sec": 4096,
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "1.8T",
"start": 264192,
"mountpoint": "/mnt/g",
"mountpoints": [
"/mnt/g"
],
"type": "part",
"uuid": "7CA41E5EA41E1B6A"
}
]
"uuid": null
},{
"id-link": "wwn-0x5001b444a63292c3",
"fstype": null,
@@ -103,7 +46,7 @@
"pttype": "gpt",
"rev": "X4133101",
"serial": "171887425854",
"size": "238.5G",
"size": 256060514304,
"start": null,
"mountpoint": null,
"mountpoints": [
@@ -131,7 +74,7 @@
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "499.5M",
"size": 523730944,
"start": 64,
"mountpoint": null,
"mountpoints": [
@@ -158,7 +101,7 @@
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "236.8G",
"size": 254301093376,
"start": 1022976,
"mountpoint": null,
"mountpoints": [
@@ -185,7 +128,7 @@
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "100M",
"size": 104857600,
"start": 497704960,
"mountpoint": null,
"mountpoints": [
@@ -212,7 +155,7 @@
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "544M",
"size": 570425344,
"start": 497909760,
"mountpoint": null,
"mountpoints": [
@@ -222,39 +165,12 @@
"uuid": "90B6FB81B6FB65DE"
}
]
},{
"id-link": "wwn-0x5002538043584d30",
"fstype": null,
"fssize": null,
"fsuse%": null,
"kname": "sdc",
"label": null,
"model": "SAMSUNG SSD PM830 mSATA 256GB",
"partflags": null,
"partlabel": null,
"partn": null,
"parttype": null,
"parttypename": null,
"partuuid": null,
"path": "/dev/sdc",
"phy-sec": 512,
"pttype": "dos",
"rev": "CXM13D1Q",
"serial": "S0XPNYAD407619",
"size": "238.5G",
"start": null,
"mountpoint": null,
"mountpoints": [
null
],
"type": "disk",
"uuid": null
},{
"id-link": "wwn-0x500a0751e4f0de85",
"fstype": null,
"fssize": null,
"fsuse%": null,
"kname": "sdd",
"kname": "sdc",
"label": null,
"model": "CT2000MX500SSD1",
"partflags": null,
@@ -263,12 +179,12 @@
"parttype": null,
"parttypename": null,
"partuuid": null,
"path": "/dev/sdd",
"path": "/dev/sdc",
"phy-sec": 4096,
"pttype": "gpt",
"rev": "M3CR033",
"serial": "2105E4F0DE85",
"size": "1.8T",
"size": 2000398934016,
"start": null,
"mountpoint": null,
"mountpoints": [
@@ -280,9 +196,9 @@
{
"id-link": "wwn-0x500a0751e4f0de85-part1",
"fstype": "vfat",
"fssize": "998M",
"fsuse%": "6%",
"kname": "sdd1",
"fssize": 1046478848,
"fsuse%": "9%",
"kname": "sdc1",
"label": "boot",
"model": null,
"partflags": null,
@@ -291,12 +207,12 @@
"parttype": "c12a7328-f81f-11d2-ba4b-00a0c93ec93b",
"parttypename": "EFI System",
"partuuid": "7f623bea-5891-49ee-9980-6534716f0f50",
"path": "/dev/sdd1",
"path": "/dev/sdc1",
"phy-sec": 4096,
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "1000M",
"size": 1048576000,
"start": 2048,
"mountpoint": "/boot",
"mountpoints": [
@@ -307,9 +223,9 @@
},{
"id-link": "wwn-0x500a0751e4f0de85-part2",
"fstype": "ext4",
"fssize": "578.1G",
"fsuse%": "10%",
"kname": "sdd2",
"fssize": 620727574528,
"fsuse%": "13%",
"kname": "sdc2",
"label": "root",
"model": null,
"partflags": null,
@@ -318,12 +234,12 @@
"parttype": "0fc63daf-8483-4772-8e79-3d69d8477de4",
"parttypename": "Linux filesystem",
"partuuid": "d562416c-1632-40c6-88ed-5095fb921698",
"path": "/dev/sdd2",
"path": "/dev/sdc2",
"phy-sec": 4096,
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "588.4G",
"size": 631794302976,
"start": 2050048,
"mountpoint": "/",
"mountpoints": [
@@ -336,7 +252,7 @@
"fstype": "crypto_LUKS",
"fssize": null,
"fsuse%": null,
"kname": "sdd3",
"kname": "sdc3",
"label": "home",
"model": null,
"partflags": null,
@@ -345,12 +261,12 @@
"parttype": "0fc63daf-8483-4772-8e79-3d69d8477de4",
"parttypename": "Linux filesystem",
"partuuid": "0ca34f17-5c80-4f2d-97b5-2a5f559b55b5",
"path": "/dev/sdd3",
"path": "/dev/sdc3",
"phy-sec": 4096,
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "588.4G",
"size": 631810031616,
"start": 1236023296,
"mountpoint": null,
"mountpoints": [
@@ -362,8 +278,8 @@
{
"id-link": "dm-name-crypt-home",
"fstype": "btrfs",
"fssize": "588.4G",
"fsuse%": "49%",
"fssize": 631793254400,
"fsuse%": "47%",
"kname": "dm-0",
"label": null,
"model": null,
@@ -378,7 +294,7 @@
"pttype": null,
"rev": null,
"serial": null,
"size": "588.4G",
"size": 631793254400,
"start": null,
"mountpoint": "/home",
"mountpoints": [
@@ -391,9 +307,9 @@
},{
"id-link": "wwn-0x500a0751e4f0de85-part4",
"fstype": "ntfs",
"fssize": "685.2G",
"fsuse%": "90%",
"kname": "sdd4",
"fssize": 735743832064,
"fsuse%": "92%",
"kname": "sdc4",
"label": "Schnell",
"model": null,
"partflags": null,
@@ -402,12 +318,12 @@
"parttype": "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7",
"parttypename": "Microsoft basic data",
"partuuid": "1d55f1cf-5a42-4fa1-a0ba-573fbd0d152c",
"path": "/dev/sdd4",
"path": "/dev/sdc4",
"phy-sec": 4096,
"pttype": "gpt",
"rev": null,
"serial": null,
"size": "685.2G",
"size": 735743836160,
"start": 2470027264,
"mountpoint": "/mnt/s",
"mountpoints": [
@@ -417,6 +333,90 @@
"uuid": "9A48E8C248E89E6F"
}
]
},{
"id-link": "wwn-0x50004cf20ecb1679",
"fstype": null,
"fssize": null,
"fsuse%": null,
"kname": "sdd",
"label": null,
"model": "ST2000LM003 HN-M201RAD",
"partflags": null,
"partlabel": null,
"partn": null,
"parttype": null,
"parttypename": null,
"partuuid": null,
"path": "/dev/sdd",
"phy-sec": 4096,
"pttype": "gpt",
"rev": "2BC10001",
"serial": "S321J9GFC01497",
"size": 2000398934016,
"start": null,
"mountpoint": null,
"mountpoints": [
null
],
"type": "disk",
"uuid": null,
"children": [
{
"id-link": "wwn-0x50004cf20ecb1679-part1",
"fstype": null,
"fssize": null,
"fsuse%": null,
"kname": "sdd1",
"label": null,
"model": null,
"partflags": null,
"partlabel": "Microsoft reserved partition",
"partn": 1,
"parttype": "e3c9e316-0b5c-4db8-817d-f92df00215ae",
"parttypename": "Microsoft reserved",
"partuuid": "c090741b-68e2-4867-96df-2ec00765f2c0",
"path": "/dev/sdd1",
"phy-sec": 4096,
"pttype": "gpt",
"rev": null,
"serial": null,
"size": 134217728,
"start": 34,
"mountpoint": null,
"mountpoints": [
null
],
"type": "part",
"uuid": null
},{
"id-link": "wwn-0x50004cf20ecb1679-part2",
"fstype": "ntfs",
"fssize": 2000263573504,
"fsuse%": "51%",
"kname": "sdd2",
"label": "Groß",
"model": null,
"partflags": null,
"partlabel": "Basic data partition",
"partn": 2,
"parttype": "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7",
"parttypename": "Microsoft basic data",
"partuuid": "425b6415-db2b-4684-b619-994bdd0f9b71",
"path": "/dev/sdd2",
"phy-sec": 4096,
"pttype": "gpt",
"rev": null,
"serial": null,
"size": 2000263577600,
"start": 264192,
"mountpoint": "/mnt/g",
"mountpoints": [
"/mnt/g"
],
"type": "part",
"uuid": "7CA41E5EA41E1B6A"
}
]
}
]
}
@@ -2,8 +2,8 @@ import json
from pathlib import Path, PosixPath
from disko_lib.messages import err_unsupported_pttype, warn_generate_partial_failure
from disko_lib.result import DiskoError, DiskoSuccess
from disko_lib.types import disk
from disko_lib.result import DiskoPartialSuccess, DiskoSuccess
from disko_lib.generate_config import generate_config
from disko_lib.types import device
CURRENT_DIR = Path(__file__).parent
@@ -15,22 +15,22 @@ def test_generate_config_partial_failure_dos_table() -> None:
assert isinstance(lsblk_result, DiskoSuccess)
result = disk.generate_config(lsblk_result.value)
result = generate_config(lsblk_result.value)
assert isinstance(result, DiskoError)
assert isinstance(result, DiskoPartialSuccess)
assert result.messages[0].is_message(err_unsupported_pttype)
assert result.messages[0].details == {
"pttype": "dos",
"device": PosixPath("/dev/sdc"),
"device": PosixPath("/dev/sda"),
}
assert result.messages[1].is_message(warn_generate_partial_failure)
with open(CURRENT_DIR / "partial_failure_dos_table-generate-result.json") as f:
assert result.messages[1].details["partial_config"] == json.load(f) # type: ignore[misc]
assert result.messages[1].details["failed_devices"] == [PosixPath("/dev/sdc")]
assert result.messages[1].details["successful_devices"] == [
PosixPath("/dev/sda"),
assert result.value == json.load(f) # type: ignore[misc]
assert result.messages[1].details["failed"] == [PosixPath("/dev/sda")]
assert result.messages[1].details["successful"] == [
PosixPath("/dev/sdb"),
PosixPath("/dev/sdc"),
PosixPath("/dev/sdd"),
]