173 lines
8.5 KiB
Python
173 lines
8.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Read-only mutual exclusion checks for the three homelab cluster modes."""
|
|
|
|
import argparse
|
|
import fcntl
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
|
|
import yaml
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
from cluster_runtime_context import resolve
|
|
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def remote(host, user, key, command):
|
|
result = subprocess.run(["ssh", "-T", "-i", key, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes",
|
|
"-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=accept-new",
|
|
f"{user}@{host}", command], text=True, capture_output=True, timeout=30)
|
|
if result.returncode:
|
|
raise RuntimeError(f"Cannot verify runtime on {host} (SSH exit {result.returncode}); refusing to assume it is stopped")
|
|
return result.stdout
|
|
|
|
|
|
def services(host, user, key):
|
|
output = remote(host, user, key, """set -eu
|
|
for unit in k3s kubelet; do
|
|
status="$(systemctl is-active "$unit" 2>/dev/null || true)"
|
|
case "$status" in
|
|
active|activating|reloading|deactivating) printf '%s=running\\n' "$unit" ;;
|
|
inactive|failed|unknown) printf '%s=stopped\\n' "$unit" ;;
|
|
*) echo "Cannot determine $unit state" >&2; exit 1 ;;
|
|
esac
|
|
done
|
|
listeners="$(ss -lntH 'sport = :6443')" || exit 1
|
|
if [ -n "$listeners" ]; then echo api=running; else echo api=stopped; fi
|
|
if sudo -n pgrep -f '[c]ontainerd-shim.*[/]run/k3s' >/dev/null; then
|
|
echo k3s_workloads=running
|
|
else
|
|
status=$?
|
|
[ "$status" = 1 ] || exit "$status"
|
|
echo k3s_workloads=stopped
|
|
fi
|
|
""")
|
|
values = dict(line.split("=", 1) for line in output.splitlines() if "=" in line)
|
|
if set(values) != {"k3s", "kubelet", "api", "k3s_workloads"}:
|
|
raise RuntimeError(f"Ambiguous runtime probe on {host}")
|
|
return values
|
|
|
|
|
|
def is_competing_cluster_vm(vmid, name, cluster_vmids):
|
|
"""Classify declared cluster VMs without depending on unrelated guests."""
|
|
return vmid in cluster_vmids or name.startswith(('pimox-cp-', 'pimox-worker-'))
|
|
|
|
|
|
def check(profile=None, vm_start=False):
|
|
inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text())
|
|
profiles = inventory["cluster"]["profiles"]
|
|
selected = profile or resolve()["profile"]
|
|
if selected not in ("debian", "pimox", "k3s") or selected not in profiles:
|
|
raise RuntimeError("Select one of the canonical profiles: debian, pimox, k3s")
|
|
runtime = profiles[selected].get("runtime", "kubeadm")
|
|
for variable in ("LAB_CLUSTER_RUNTIME", "TF_VAR_cluster_runtime"):
|
|
if os.environ.get(variable, runtime) != runtime:
|
|
raise RuntimeError(f"{variable} conflicts with profile {selected}; expected {runtime}")
|
|
required_mount = profiles[selected].get("storage", {}).get("required_mount", "")
|
|
if required_mount:
|
|
control = profiles[selected]["control_plane"]
|
|
spec = importlib.util.spec_from_file_location("registry_storage_guard", REPO / "scripts/registry-storage-reconcile.py")
|
|
storage = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(storage)
|
|
storage.require_remote_data_mount(
|
|
lambda command: remote(control["lan_ip"], control["user"], control["ssh_key_path"], command), required_mount)
|
|
laptop = inventory["hosts"]["debian"]
|
|
hypervisor = inventory["hosts"]["opi5_pimox"]
|
|
laptop_key = profiles["debian"]["control_plane"]["ssh_key_path"]
|
|
hyper_key = os.environ.get("LAB_PIMOX_SSH_KEY_PATH") or profiles["k3s"]["control_plane"]["ssh_key_path"]
|
|
laptop_state = services(laptop["lan_ip"], laptop["user"], laptop_key)
|
|
hyper_state = services(hypervisor["lan_ip"], hypervisor["user"], hyper_key)
|
|
output = remote(hypervisor["lan_ip"], hypervisor["user"], hyper_key, "sudo -n qm list")
|
|
vms = {}
|
|
vm_names = {}
|
|
for line in output.splitlines():
|
|
fields = line.split()
|
|
if fields and fields[0].isdigit():
|
|
if len(fields) < 3 or fields[2] not in ("running", "stopped", "paused", "suspended"):
|
|
raise RuntimeError("Cannot determine Pimox VM state")
|
|
vms[int(fields[0])] = fields[2]
|
|
vm_names[int(fields[0])] = fields[1]
|
|
if not output.strip() or "VMID" not in output:
|
|
raise RuntimeError("Cannot verify Pimox VM inventory")
|
|
cp_vmid = int(os.environ.get('LAB_PIMOX_CONTROL_PLANE_VMID') or
|
|
os.environ.get('LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID') or
|
|
profiles["pimox"]["pimox"]["control_plane_vmid"])
|
|
pimox = inventory.get('pimox', {})
|
|
worker_base = int(os.environ.get('LAB_PIMOX_WORKER_BASE_VMID') or pimox.get('worker_base_vmid', 9010))
|
|
worker_count = int(os.environ.get('LAB_PIMOX_WORKER_COUNT') or profiles['pimox']['pimox'].get('worker_count', 0))
|
|
if worker_count < 0 or worker_count > 4096:
|
|
raise RuntimeError('Invalid Pimox worker count')
|
|
cluster_vmids = {cp_vmid} | set(range(worker_base, worker_base + worker_count))
|
|
conflicts = []
|
|
if laptop_state["k3s"] == "running" or laptop_state["k3s_workloads"] == "running":
|
|
conflicts.append("unexpected laptop k3s service is running on " + laptop["lan_ip"])
|
|
if hyper_state["kubelet"] == "running":
|
|
conflicts.append("unexpected host kubeadm kubelet is running on " + hypervisor["lan_ip"])
|
|
if runtime == "k3s":
|
|
if vm_start:
|
|
conflicts.append("VM startup is incompatible with the selected direct-host k3s profile")
|
|
if laptop_state["kubelet"] == "running" or laptop_state["api"] == "running":
|
|
conflicts.append("Debian laptop control plane is running")
|
|
active_vms = []
|
|
for vmid, state in vms.items():
|
|
if state == "stopped":
|
|
continue
|
|
if is_competing_cluster_vm(vmid, vm_names[vmid], cluster_vmids):
|
|
active_vms.append(str(vmid))
|
|
if active_vms:
|
|
conflicts.append("Competing Pimox cluster VMs are not stopped: " + ", ".join(active_vms))
|
|
else:
|
|
if hyper_state["k3s"] == "running" or hyper_state["api"] == "running" or hyper_state["k3s_workloads"] == "running":
|
|
conflicts.append("Orange Pi host K3s/control-plane API is running")
|
|
if selected == "pimox" and (laptop_state["kubelet"] == "running" or laptop_state["api"] == "running"):
|
|
conflicts.append("Debian laptop control plane is running")
|
|
if selected == "debian" and vms.get(cp_vmid, "stopped") != "stopped":
|
|
conflicts.append(f"Pimox control-plane VM {cp_vmid} is not stopped")
|
|
if conflicts:
|
|
raise RuntimeError("; ".join(conflicts) + ". Stop the conflicting runtime before continuing; no runtime was changed.")
|
|
return {"profile": selected, "exclusive": True, "laptop": laptop_state,
|
|
"orange_pi": hyper_state, "vms": vms}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("action", choices=("check", "run"))
|
|
parser.add_argument("--profile")
|
|
parser.add_argument("--vm-start", action="store_true")
|
|
arguments = sys.argv[1:]
|
|
command = []
|
|
if "--" in arguments:
|
|
separator = arguments.index("--")
|
|
command = arguments[separator + 1:]
|
|
arguments = arguments[:separator]
|
|
args = parser.parse_args(arguments)
|
|
try:
|
|
if args.action == "run":
|
|
state = Path(os.environ.get("HOMELAB_STATE_DIR", Path.home() / ".local/share/homelab"))
|
|
root = state / "clusters"
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
lock = (root / ".runtime-pipeline.lock").open("a")
|
|
try:
|
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except BlockingIOError:
|
|
raise RuntimeError("Another cluster pipeline holds the global runtime lock; wait for it to finish")
|
|
selected = check(args.profile, args.vm_start)["profile"]
|
|
if not command:
|
|
raise RuntimeError("Runtime-guarded execution requires a command")
|
|
os.set_inheritable(lock.fileno(), True)
|
|
environment = dict(os.environ, JEANNIE_RUNTIME_PIPELINE_LOCK=selected,
|
|
JEANNIE_RUNTIME_PIPELINE_LOCK_FD=str(lock.fileno()))
|
|
os.execvpe(command[0], command, environment)
|
|
else:
|
|
if command:
|
|
raise RuntimeError("The check action does not accept a command")
|
|
print(json.dumps(check(args.profile, args.vm_start), sort_keys=True))
|
|
except (RuntimeError, OSError, ValueError, KeyError, yaml.YAMLError, subprocess.SubprocessError) as error:
|
|
print(f"Cluster runtime refused: {error}", file=sys.stderr)
|
|
sys.exit(1)
|