my-homelab-configs/scripts/cluster-runtime-guard.py

135 lines
6.6 KiB
Python

#!/usr/bin/env python3
"""Read-only mutual exclusion checks for the three homelab cluster modes."""
import argparse
import fcntl
import json
import os
from pathlib import Path
import subprocess
import sys
import yaml
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
""")
values = dict(line.split("=", 1) for line in output.splitlines() if "=" in line)
if set(values) != {"k3s", "kubelet", "api"}:
raise RuntimeError(f"Ambiguous runtime probe on {host}")
return values
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 os.environ.get("LAB_CLUSTER_PROFILE") or inventory["cluster"]["active_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}")
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 = {}
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]
if not output.strip() or "VMID" not in output:
raise RuntimeError("Cannot verify Pimox VM inventory")
cp_vmid = int(profiles["pimox"]["pimox"]["control_plane_vmid"])
conflicts = []
if laptop_state["k3s"] == "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 = [str(vmid) for vmid, state in vms.items() if state != "stopped"]
if active_vms:
conflicts.append("Pimox VMs are not stopped: " + ", ".join(active_vms))
else:
if hyper_state["k3s"] == "running" or hyper_state["api"] == "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)