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

109 lines
5.3 KiB
Python

#!/usr/bin/env python3
"""Relocate an enrolled K3s runtime without changing its identity or data path."""
from contextlib import ExitStack
import fcntl
import importlib.util
import json
import os
from pathlib import Path
import shlex
import subprocess
import time
import yaml
REPO = Path(__file__).resolve().parents[1]
def module(name, filename):
spec = importlib.util.spec_from_file_location(name, REPO / "scripts" / filename)
value = importlib.util.module_from_spec(spec)
spec.loader.exec_module(value)
return value
def save(path, value):
temporary = path.with_suffix(".tmp")
temporary.write_text(json.dumps(value, indent=2) + "\n")
temporary.chmod(0o600)
os.replace(temporary, path)
def main(yes=False):
inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text())
profile = inventory["cluster"]["profiles"]["k3s"]
control = profile["control_plane"]
storage = profile.get("storage", {})
target, mount = storage.get("runtime_path"), storage.get("required_mount")
if profile.get("runtime") != "k3s" or not target or not mount:
raise RuntimeError("Declare the K3s runtime_path and required_mount before relocating storage")
context = module("runtime_storage_context", "cluster-context.py")
registry = module("runtime_storage_registry", "registry-storage-reconcile.py")
guard = module("runtime_storage_guard", "cluster-runtime-guard.py")
ctx = context.Context("k3s", control["kubeconfig"])
binding = json.loads(ctx.binding.read_text())
expected = {key: binding[key] for key in context.IDENTITY_FIELDS}
root = ctx.root
root.mkdir(parents=True, exist_ok=True, mode=0o700)
journal_path = root / "runtime-storage-transition.json"
record = {"identity": expected, "host": control["lan_ip"], "target": target, "mount": mount}
with ExitStack() as locks:
lock = locks.enter_context((root.parent / ".runtime-pipeline.lock").open("a"))
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
for stack in ("cluster", "platform", "apps"):
operation = locks.enter_context((root / f".{stack}.operation.lock").open("a"))
fcntl.flock(operation, fcntl.LOCK_EX | fcntl.LOCK_NB)
os.environ["LAB_CLUSTER_RUNTIME"] = "k3s"
os.environ["TF_VAR_cluster_runtime"] = "k3s"
guard.check("k3s")
journal = json.loads(journal_path.read_text()) if journal_path.exists() else None
if journal and any(journal.get(key) != value for key, value in record.items()):
raise RuntimeError("Recorded storage transition belongs to a different host, disk path or identity")
if journal is None or journal.get("phase") == "complete":
ctx.check()
else:
# Only a previously verified transition may resume while its API
# is deliberately stopped. Endpoint/CA remain pinned throughout.
ctx.observed(startup=True)
code = ("EXPECTED = " + repr(expected) + "\nSTOP_SCRIPT = "
+ repr((REPO / "scripts/k3s-stop.sh").read_text()) + "\n"
+ (REPO / "scripts/k3s-runtime-storage-host.py").read_text())
def remote(action, capture=False):
command = "sudo -n python3 - " + shlex.join([action, target, mount])
result = subprocess.run(registry.ssh(control["lan_ip"], control["user"], control["ssh_key_path"], command),
input=code, text=True, check=True, timeout=21600,
stdout=subprocess.PIPE if capture else None)
return result.stdout
inspection = json.loads(remote("inspect", capture=True))
print(json.dumps({**record, **inspection,
"actions": ["stop K3s and its private containers", "preserve hidden registry data",
"verify two cold SSD copies", "bind mount the original runtime path",
"verify original live identity and node readiness",
"reclaim verified eMMC duplicate; retain SSD rollback copy"]}, indent=2), flush=True)
if not yes:
print("Review, then repeat with --yes. No runtime or storage changes made.")
return
if journal is None:
save(journal_path, {**record, "phase": "moving"})
remote("move")
print("Waiting up to 600s for the original cluster identity and Ready node...", flush=True)
deadline = time.monotonic() + 600
while True:
try:
ctx.check()
node = json.loads(context.capture(ctx.client() + ["--request-timeout=10s", "get", "node", ctx.expected_node, "-o", "json"]))
if not any(c.get("type") == "Ready" and c.get("status") == "True" for c in node["status"]["conditions"]):
raise RuntimeError("Node is not Ready")
break
except (context.Refused, RuntimeError, subprocess.SubprocessError):
if time.monotonic() >= deadline:
raise RuntimeError("Original identity/readiness was not restored; eMMC and SSD rollback copies retained")
time.sleep(5)
remote("finalize")
save(journal_path, {**record, "phase": "complete"})
print("K3s runtime is on SSD; identity unchanged. Resume the existing apps transition.", flush=True)