clan-cli: Use machine object everywhere instead of name + flake

This commit is contained in:
Qubasa
2025-05-09 13:13:14 +02:00
parent 9867b6a894
commit 2682581c09
20 changed files with 128 additions and 124 deletions

View File

@@ -110,7 +110,7 @@ def create_machine(opts: CreateOptions, commit: bool = True) -> None:
new_machine["deploy"] = {"targetHost": target_host}
patch_inventory_with(
Flake(str(clan_dir)), f"machines.{machine_name}", dataclass_to_dict(new_machine)
opts.clan_dir, f"machines.{machine_name}", dataclass_to_dict(new_machine)
)
# Commit at the end in that order to avoid committing halve-baked machines

View File

@@ -5,9 +5,10 @@ from pathlib import Path
from clan_lib.api import API
from clan_cli import Flake, inventory
from clan_cli import inventory
from clan_cli.completions import add_dynamic_completer, complete_machines
from clan_cli.dirs import specific_machine_dir
from clan_cli.machines.machines import Machine
from clan_cli.secrets.folders import sops_secrets_folder
from clan_cli.secrets.machines import has_machine as secrets_has_machine
from clan_cli.secrets.machines import remove_machine as secrets_machine_remove
@@ -15,49 +16,46 @@ from clan_cli.secrets.secrets import (
list_secrets,
)
from .machines import Machine
log = logging.getLogger(__name__)
@API.register
def delete_machine(flake: Flake, name: str) -> None:
def delete_machine(machine: Machine) -> None:
try:
inventory.delete(flake, {f"machines.{name}"})
inventory.delete(machine.flake, {f"machines.{machine.name}"})
except KeyError as exc:
# louis@(2025-03-09): test infrastructure does not seem to set the
# inventory properly, but more importantly only one machine in my
# personal clan ended up in the inventory for some reason, so I think
# it makes sense to eat the exception here.
log.warning(
f"{name} was missing or already deleted from the machines inventory: {exc}"
f"{machine.name} was missing or already deleted from the machines inventory: {exc}"
)
changed_paths: list[Path] = []
folder = specific_machine_dir(flake, name)
folder = specific_machine_dir(machine)
if folder.exists():
changed_paths.append(folder)
shutil.rmtree(folder)
# louis@(2025-02-04): clean-up legacy (pre-vars) secrets:
sops_folder = sops_secrets_folder(flake.path)
filter_fn = lambda secret_name: secret_name.startswith(f"{name}-")
for secret_name in list_secrets(flake.path, filter_fn):
sops_folder = sops_secrets_folder(machine.flake.path)
filter_fn = lambda secret_name: secret_name.startswith(f"{machine.name}-")
for secret_name in list_secrets(machine.flake.path, filter_fn):
secret_path = sops_folder / secret_name
changed_paths.append(secret_path)
shutil.rmtree(secret_path)
machine = Machine(name, flake)
changed_paths.extend(machine.public_vars_store.delete_store())
changed_paths.extend(machine.secret_vars_store.delete_store())
# Remove the machine's key, and update secrets & vars that referenced it:
if secrets_has_machine(flake.path, name):
secrets_machine_remove(flake.path, name)
if secrets_has_machine(machine.flake.path, machine.name):
secrets_machine_remove(machine.flake.path, machine.name)
def delete_command(args: argparse.Namespace) -> None:
delete_machine(args.flake, args.name)
delete_machine(Machine(flake=args.flake, name=args.name))
def register_delete_parser(parser: argparse.ArgumentParser) -> None:

View File

@@ -7,11 +7,10 @@ from pathlib import Path
from clan_lib.api import API
from clan_cli.cmd import RunOpts, run_no_stdout
from clan_cli.cmd import RunOpts, run
from clan_cli.completions import add_dynamic_completer, complete_machines
from clan_cli.dirs import specific_machine_dir
from clan_cli.errors import ClanCmdError, ClanError
from clan_cli.flake import Flake
from clan_cli.git import commit_file
from clan_cli.machines.machines import Machine
from clan_cli.nix import nix_config, nix_eval
@@ -26,39 +25,35 @@ class HardwareConfig(Enum):
NIXOS_GENERATE_CONFIG = "nixos-generate-config"
NONE = "none"
def config_path(self, flake: Flake, machine_name: str) -> Path:
machine_dir = specific_machine_dir(flake, machine_name)
def config_path(self, machine: Machine) -> Path:
machine_dir = specific_machine_dir(machine)
if self == HardwareConfig.NIXOS_FACTER:
return machine_dir / "facter.json"
return machine_dir / "hardware-configuration.nix"
@classmethod
def detect_type(
cls: type["HardwareConfig"], flake: Flake, machine_name: str
) -> "HardwareConfig":
hardware_config = HardwareConfig.NIXOS_GENERATE_CONFIG.config_path(
flake, machine_name
)
def detect_type(cls: type["HardwareConfig"], machine: Machine) -> "HardwareConfig":
hardware_config = HardwareConfig.NIXOS_GENERATE_CONFIG.config_path(machine)
if hardware_config.exists() and "throw" not in hardware_config.read_text():
return HardwareConfig.NIXOS_GENERATE_CONFIG
if HardwareConfig.NIXOS_FACTER.config_path(flake, machine_name).exists():
if HardwareConfig.NIXOS_FACTER.config_path(machine).exists():
return HardwareConfig.NIXOS_FACTER
return HardwareConfig.NONE
@API.register
def show_machine_hardware_config(flake: Flake, machine_name: str) -> HardwareConfig:
def show_machine_hardware_config(machine: Machine) -> HardwareConfig:
"""
Show hardware information for a machine returns None if none exist.
"""
return HardwareConfig.detect_type(flake, machine_name)
return HardwareConfig.detect_type(machine)
@API.register
def show_machine_hardware_platform(flake: Flake, machine_name: str) -> str | None:
def show_machine_hardware_platform(machine: Machine) -> str | None:
"""
Show hardware information for a machine returns None if none exist.
"""
@@ -66,13 +61,13 @@ def show_machine_hardware_platform(flake: Flake, machine_name: str) -> str | Non
system = config["system"]
cmd = nix_eval(
[
f"{flake}#clanInternals.machines.{system}.{machine_name}",
f"{machine.flake}#clanInternals.machines.{system}.{machine.name}",
"--apply",
"machine: { inherit (machine.pkgs) system; }",
"--json",
]
)
proc = run_no_stdout(cmd, RunOpts(prefix=machine_name))
proc = run(cmd, RunOpts(prefix=machine.name))
res = proc.stdout.strip()
host_platform = json.loads(res)
@@ -81,11 +76,8 @@ def show_machine_hardware_platform(flake: Flake, machine_name: str) -> str | Non
@dataclass
class HardwareGenerateOptions:
flake: Flake
machine: str
machine: Machine
backend: HardwareConfig
target_host: str | None = None
keyfile: str | None = None
password: str | None = None
@@ -96,14 +88,9 @@ def generate_machine_hardware_info(opts: HardwareGenerateOptions) -> HardwareCon
and place the resulting *.nix file in the machine's directory.
"""
machine = Machine(
opts.machine,
flake=opts.flake,
private_key=Path(opts.keyfile) if opts.keyfile else None,
override_target_host=opts.target_host,
)
machine = opts.machine
hw_file = opts.backend.config_path(opts.flake, opts.machine)
hw_file = opts.backend.config_path(opts.machine)
hw_file.parent.mkdir(parents=True, exist_ok=True)
if opts.backend == HardwareConfig.NIXOS_FACTER:
@@ -148,11 +135,11 @@ def generate_machine_hardware_info(opts: HardwareGenerateOptions) -> HardwareCon
commit_file(
hw_file,
opts.flake.path,
opts.machine.flake.path,
f"machines/{opts.machine}/{hw_file.name}: update hardware configuration",
)
try:
show_machine_hardware_platform(opts.flake, opts.machine)
show_machine_hardware_platform(opts.machine)
if backup_file:
backup_file.unlink(missing_ok=True)
except ClanCmdError as e:
@@ -173,10 +160,13 @@ def generate_machine_hardware_info(opts: HardwareGenerateOptions) -> HardwareCon
def update_hardware_config_command(args: argparse.Namespace) -> None:
opts = HardwareGenerateOptions(
machine = Machine(
flake=args.flake,
machine=args.machine,
target_host=args.target_host,
name=args.machine,
override_target_host=args.target_host,
)
opts = HardwareGenerateOptions(
machine=machine,
password=args.password,
backend=HardwareConfig(args.backend),
)

View File

@@ -111,11 +111,7 @@ def install_machine(opts: InstallOptions) -> None:
[
"--generate-hardware-config",
str(opts.update_hardware_config.value),
str(
opts.update_hardware_config.config_path(
machine.flake, machine.name
)
),
str(opts.update_hardware_config.config_path(machine)),
]
)

View File

@@ -67,9 +67,9 @@ def get_machine_details(machine: Machine) -> MachineDetails:
msg = f"Machine {machine.name} not found in inventory"
raise ClanError(msg)
hw_config = HardwareConfig.detect_type(machine.flake, machine.name)
hw_config = HardwareConfig.detect_type(machine)
machine_dir = specific_machine_dir(machine.flake, machine.name)
machine_dir = specific_machine_dir(machine)
disk_schema: MachineDiskMatter | None = None
disk_path = machine_dir / "disko.nix"
if disk_path.exists():

View File

@@ -141,7 +141,7 @@ def deploy_machine(machine: Machine) -> None:
generate_facts([machine], service=None, regenerate=False)
generate_vars([machine], generator_name=None, regenerate=False)
upload_secrets(machine, target_host)
upload_secrets(machine)
upload_secret_vars(machine, target_host)
path = upload_sources(machine, host)