#!/usr/bin/env python3 """Retire the accidental local K3s cluster and deploy the declared native host.""" import argparse from contextlib import ExitStack import fcntl import importlib.util import json import os from pathlib import Path import shutil import subprocess import sys import time from types import SimpleNamespace 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): path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) temporary = path.with_suffix(".tmp") temporary.write_text(json.dumps(value, indent=2) + "\n") temporary.chmod(0o600) os.replace(temporary, path) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("k3s-to-native",)) parser.add_argument("--yes", action="store_true") parser.add_argument("--source-kubeconfig", default=str(Path.home() / ".kube/k3s-config")) args = parser.parse_args() inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text()) profiles = inventory["cluster"]["profiles"] control = profiles["k3s"]["control_plane"] laptop = inventory["hosts"]["debian"] if profiles["k3s"].get("runtime") != "k3s" or control["lan_ip"] != inventory["hosts"]["opi5_pimox"]["lan_ip"]: raise RuntimeError("The K3s profile must target the declared Orange Pi host") local_ips = set(subprocess.check_output(["hostname", "-I"], text=True).split()) if laptop["lan_ip"] not in local_ips or control["lan_ip"] in local_ips: raise RuntimeError("Run this transition on the Debian deployment laptop, not on the native target") state = Path(os.environ.get("HOMELAB_STATE_DIR", Path.home() / ".local/share/homelab")) if not state.is_absolute(): raise RuntimeError("State directory must be absolute") root = state / "clusters/k3s" journal_path = state / "transitions/k3s-to-native.json" registry = module("registry_transition", "registry-storage-reconcile.py") context = module("context_transition", "cluster-context.py") remote = lambda command, **kw: registry.run(registry.ssh(control["lan_ip"], control["user"], control["ssh_key_path"], command), **kw) required_mount = profiles["k3s"].get("storage", {}).get("required_mount", "") registry.require_remote_data_mount(remote, required_mount) architecture = remote("uname -m") if architecture not in ("aarch64", "arm64"): raise RuntimeError("Native target is not ARM64; refusing to deploy on another laptop") remote("set -eu; sudo -n qm list >/dev/null; " "if sudo -n test -s /etc/kubernetes/admin.conf || sudo -n test -s /etc/kubernetes/manifests/kube-apiserver.yaml; " "then echo 'Native target contains a kubeadm control plane' >&2; exit 1; fi") old_endpoint = "https://" + laptop["lan_ip"] + ":6443" journal = json.loads(journal_path.read_text()) if journal_path.exists() else None if journal and journal["target"] != control: raise RuntimeError("Recorded transition belongs to a different target inventory") if journal and journal.get("phase") not in ("verified", "backed-up", "archived", "prepared", "enrolled", "platform-ready", "complete"): raise RuntimeError("Unknown transition phase; refusing to infer completed work") if journal is None: existing = remote("if sudo -n test -d /var/lib/rancher/k3s/server/db; then echo existing; else echo fresh; fi") if existing != "fresh": raise RuntimeError("Orange Pi already contains a K3s datastore; review its ownership before replacing the laptop profile") plan = {"source": old_endpoint, "destination": control["lan_ip"], "node": control["node_name"], "actions": ["verify and stop laptop K3s", "back up server data and archive scoped state", "stop Pimox VMs gracefully", "verify/copy registry before native K3s starts", "bootstrap native cluster", "verify/enroll its new identity", "apply platform and apps"], "preserved": ["laptop data directories and kubeconfig", "old scoped state", "Pimox VM disks"], "application_data": "Only registry data is copied. Other existing laptop PVC data remains on the laptop."} print(json.dumps(plan, indent=2), flush=True) if not args.yes: print("Review, then repeat with --yes. No changes made.") return with ExitStack() as locks: (state / "clusters").mkdir(parents=True, exist_ok=True, mode=0o700) lock = locks.enter_context((state / "clusters/.runtime-pipeline.lock").open("a")) fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) os.set_inheritable(lock.fileno(), True) # Also exclude direct guarded Tofu mutations during state archival. if root.exists() and (journal is None or journal["phase"] in ("verified", "backed-up")): 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) if journal is None: binding = json.loads((root / "identity.json").read_text()) if binding.get("profile") != "k3s" or binding.get("endpoint") != old_endpoint: raise RuntimeError("Expected the old laptop K3s identity; refusing to archive another cluster") source_config = str(Path(args.source_kubeconfig).resolve()) kubectl = [context.binary("kubectl"), "--kubeconfig", source_config] config = json.loads(context.capture(kubectl + ["config", "view", "--raw", "--minify", "--flatten", "-o", "json"])) cluster = config["clusters"][0]["cluster"] import base64 ca = context.ca_fingerprint(base64.b64decode(cluster["certificate-authority-data"], validate=True).decode()) if cluster.get("insecure-skip-tls-verify") or cluster.get("proxy-url") or cluster.get("tls-server-name"): raise RuntimeError("Unexpected source TLS configuration") if context.endpoint(cluster["server"]) != old_endpoint or ca != binding["ca_sha256"]: raise RuntimeError("Source kubeconfig does not match the pinned laptop identity") uid = context.capture(kubectl + ["--request-timeout=15s", "get", "namespace", "kube-system", "-o", "jsonpath={.metadata.uid}"]) if uid.strip() != binding["kube_system_uid"]: raise RuntimeError("Source namespace UID does not match the pinned laptop identity") timestamp = str(time.time_ns()) journal = {"target": control, "source_identity": binding, "source_kubeconfig": source_config, "archive": str(state / "retired-clusters" / ("k3s-laptop-" + timestamp)), "backup": "/var/backups/jeannie-k3s-laptop-" + timestamp, "phase": "verified"} save(journal_path, journal) if journal["phase"] == "verified": # Re-verify CA directly on the host before stopping its service, # including resumed runs where the API may already be stopped. host_ca = registry.run(["sudo", "-n", "cat", "/var/lib/rancher/k3s/server/tls/server-ca.crt"]) if context.ca_fingerprint(host_ca) != journal["source_identity"]["ca_sha256"]: raise RuntimeError("Local K3s server CA changed since transition review") print("Stopping and disabling only the accidental laptop K3s service...", flush=True) subprocess.run(["bash", str(REPO / "scripts/k3s-stop.sh"), "--disable"], check=True, timeout=1800) backup = journal["backup"] registry.run(["sudo", "-n", "install", "-d", "-m", "0700", backup]) registry.run(["sudo", "-n", "tar", "-C", "/", "-cpf", backup + "/server.tar", "etc/rancher/k3s", "var/lib/rancher/k3s/server"], timeout=1800) registry.run(["sudo", "-n", "tar", "-tf", backup + "/server.tar"], timeout=120) journal["server_backup_sha256"] = registry.run(["sudo", "-n", "sha256sum", backup + "/server.tar"]).split()[0] journal["phase"] = "backed-up" save(journal_path, journal) archive = Path(journal["archive"]) if journal["phase"] == "backed-up": archive.parent.mkdir(parents=True, exist_ok=True, mode=0o700) if not archive.exists(): os.rename(root, archive) elif root.exists(): raise RuntimeError("Both active and archived state exist; refusing an ambiguous transition") archive.chmod(0o700) shutil.copy2(journal["source_kubeconfig"], archive / "laptop-kubeconfig") (archive / "laptop-kubeconfig").chmod(0o600) journal["phase"] = "archived" save(journal_path, journal) if journal["phase"] == "archived": if remote("systemctl is-active k3s 2>/dev/null || true") not in ("inactive", "failed", "unknown"): raise RuntimeError("Native K3s is already active; stop it before offline registry preparation") for line in remote("sudo -n qm list").splitlines(): fields = line.split() if fields and fields[0].isdigit() and fields[2] != "stopped": print(f"Gracefully stopping Pimox VM {fields[0]}...", flush=True) remote(f"sudo -n qm shutdown {int(fields[0])} --timeout 90", timeout=110) source = profiles["pimox"]["pimox"]["worker_static_ips"].split()[0] cache = state / "transitions/k3s-registry-cache" options = SimpleNamespace(state_dir=str(cache), source_host=source, source_user=control["user"], source_key=control["ssh_key_path"], source_node=inventory["pimox"]["worker_name_prefix"] + "-01", source_vmid=str(inventory["pimox"]["worker_base_vmid"]), source_path="/data/openebs/local/registry", hypervisor_host=control["lan_ip"], hypervisor_user=control["user"], hypervisor_key=control["ssh_key_path"], transfer_cipher="aes256-gcm@openssh.com", registry_endpoint=profiles["k3s"]["registry"]["endpoint"]) options.required_data_mount = required_mount registry.require_no_local_writer("/data/openebs/local/registry") registry.prepare_local(options, "/data/openebs/local/registry", False) root.mkdir(parents=True, exist_ok=True, mode=0o700) registry.publish_remote(options, "/data/openebs/local/registry", control, root / "registry-migration.json") registry.retire_legacy_forwarding() journal["phase"] = "prepared" save(journal_path, journal) environment = {key: value for key, value in os.environ.items() if not key.startswith(("TF_VAR_", "LAB_CLUSTER_")) and key not in ("KUBECONFIG_PATH", "LAB_CALICO_OPERATOR_NODE_NAME", "LAB_K3S_ALLOW_HYPERVISOR_HOST")} environment.update(LAB_CLUSTER_PROFILE="k3s", LAB_CLUSTER_RUNTIME="k3s", TF_VAR_cluster_runtime="k3s", KUBECONFIG=control["kubeconfig"], LAB_KUBECONFIG_PATH=control["kubeconfig"], KUBECONFIG_PATH=control["kubeconfig"], TF_VAR_kubeconfig_path=control["kubeconfig"], JEANNIE_RUNTIME_PIPELINE_LOCK="k3s", JEANNIE_RUNTIME_PIPELINE_LOCK_FD=str(lock.fileno())) def deploy(*arguments): subprocess.run([str(REPO / "jeannie"), *arguments], env=environment, pass_fds=(lock.fileno(),), check=True) if journal["phase"] == "prepared": deploy("cluster") # Enroll only after comparing both API-observed identity fields # against reads performed directly on the intended SSH host. observed = context.Context("k3s", control["kubeconfig"]).observed() host_ca = remote("sudo -n cat /var/lib/rancher/k3s/server/tls/server-ca.crt") host_uid = remote("sudo -n k3s kubectl get namespace kube-system -o jsonpath='{.metadata.uid}'") if observed["ca_sha256"] != context.ca_fingerprint(host_ca) or observed["kube_system_uid"] != host_uid: raise RuntimeError("Native API identity differs from the intended SSH host; refusing enrollment") deploy("cluster-context", "enroll", "--yes") journal["phase"] = "enrolled" save(journal_path, journal) if journal["phase"] == "enrolled": deploy("platform", "all") journal["phase"] = "platform-ready" save(journal_path, journal) if journal["phase"] == "platform-ready": deploy("apps") journal["phase"] = "complete" save(journal_path, journal) print(f"Native K3s transition complete. Old state: {archive}; server backup: {journal['backup']}", flush=True) if __name__ == "__main__": try: main() except (OSError, RuntimeError, ValueError, KeyError, subprocess.SubprocessError) as error: print(f"Cluster transition stopped: {error}. Original data and transition journal are retained.", file=sys.stderr) sys.exit(1)