my-homelab-configs/scripts/doctor-k3s-storage.py

99 lines
5.3 KiB
Python

#!/usr/bin/env python3
"""Diagnose and recover a stale USB-backed K3s runtime on its selected host."""
from contextlib import ExitStack
import fcntl
import importlib.util
import json
import os
from pathlib import Path
import shlex
import subprocess
import sys
import time
REPO = Path(__file__).resolve().parents[1]
def load(name, filename):
spec = importlib.util.spec_from_file_location(name, REPO / "scripts" / filename)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main(action):
runtime = load("doctor_storage_runtime", "cluster_runtime_context.py").resolve()
if runtime["profile"] != "k3s" or runtime["runtime"] != "k3s":
raise RuntimeError("Selected profile is not native K3s")
data = Path(runtime["required_mount"])
target = Path(runtime["runtime_path"])
if not data.is_absolute() or not target.is_absolute() or ".." in data.parts or ".." in target.parts or data == Path("/") or data == target or not target.is_relative_to(data):
raise RuntimeError("K3s runtime storage paths are invalid")
context = load("doctor_storage_context", "cluster-context.py")
registry = load("doctor_storage_ssh", "registry-storage-reconcile.py")
ctx = context.Context("k3s", runtime["kubeconfig"])
binding = json.loads(ctx.binding.read_text()) if ctx.binding.exists() else {}
ca = binding.get("ca_sha256", "")
if action == "repair" and (not isinstance(ca, str) or len(ca) != 64 or any(c not in "0123456789abcdef" for c in ca)):
raise RuntimeError("Pinned K3s CA fingerprint is unavailable")
code = ("EXPECTED_CA = " + repr(ca) + "\nDATA_MOUNT = " + repr(str(data)) + "\nRUNTIME_PATH = " + repr(str(target)) +
"\nSTOP_SCRIPT = " + repr((REPO / "scripts/k3s-stop.sh").read_text()) + "\n" +
(REPO / "scripts/doctor-k3s-storage-host.py").read_text())
def remote(*args):
command = "sudo -n python3 - " + shlex.join(args)
result = subprocess.run(registry.ssh(runtime["host"], runtime["user"], runtime["key"], command),
input=code, text=True, capture_output=True, timeout=900)
if result.returncode:
raise RuntimeError((result.stderr or "Remote storage check failed").strip()[-1200:])
return result.stdout.strip()
if action == "inspect":
evidence = json.loads(remote("inspect"))
print(json.dumps(evidence, sort_keys=True))
return
if action != "repair":
raise RuntimeError("Unknown K3s storage doctor action")
root = ctx.root
root.mkdir(parents=True, exist_ok=True, mode=0o700)
with ExitStack() as locks:
for path in [root.parent / ".runtime-pipeline.lock", *(root / f".{name}.operation.lock" for name in ("cluster", "platform", "apps"))]:
lock = locks.enter_context(path.open("a"))
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
transition = root / "runtime-storage-transition.json"
if transition.exists() and json.loads(transition.read_text()).get("phase") != "complete":
raise RuntimeError("An unfinished K3s storage transition exists; recovery is refused")
ctx.observed(startup=True)
load("doctor_storage_guard", "cluster-runtime-guard.py").check("k3s", require_storage=False)
evidence = json.loads(remote("inspect"))
candidates = evidence.get("reappeared_usb_ext4") or []
if not evidence.get("stale_readonly_mount") or evidence.get("service") not in ("failed", "inactive") or len(candidates) != 1:
raise RuntimeError("Recovery requires failed or inactive K3s, a stale read-only mount, and exactly one unmounted USB ext4 partition")
print("Verified evidence:", json.dumps(evidence, sort_keys=True), flush=True)
print("Recovering the stale K3s mount after checking the SSD against the pinned CA; busy mounts are not forced.", flush=True)
print(remote("repair", candidates[0]["uuid"]), flush=True)
deadline = time.monotonic() + 300
while True:
try:
identity = ctx.check()
node = json.loads(context.capture(ctx.client() + ["--request-timeout=10s", "get", "node", ctx.expected_node, "-o", "json"]))
if not any(condition.get("type") == "Ready" and condition.get("status") == "True" for condition in (node.get("status", {}).get("conditions") or [])):
raise RuntimeError("K3s node is not Ready")
print("Pinned cluster identity verified:", json.dumps(identity, sort_keys=True), flush=True)
print(f"K3s node {ctx.expected_node} is Ready.", flush=True)
break
except (context.Refused, RuntimeError, subprocess.SubprocessError):
if time.monotonic() >= deadline:
raise RuntimeError("K3s started, but the pinned live cluster identity was not verified")
time.sleep(5)
if __name__ == "__main__":
try:
if len(sys.argv) != 2 or sys.argv[1] not in ("inspect", "repair"):
raise RuntimeError("Usage: doctor-k3s-storage.py inspect|repair")
main(sys.argv[1])
except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError, BlockingIOError) as exc:
print(f"K3s storage doctor: {exc}", file=sys.stderr)
sys.exit(1)