#!/usr/bin/env python3 """Prepare retained registry storage before Argo changes placement. Run on the destination control-plane host through Jeannie. Source data is never deleted. An unreachable source is an error, not proof that no registry exists. """ import argparse import fcntl import hashlib import json import os import re from pathlib import Path import shlex import shutil import subprocess import sys import tempfile import time def run(command, **kwargs): return subprocess.run(command, check=True, text=True, capture_output=True, timeout=kwargs.pop("timeout", 60), **kwargs).stdout.strip() def ssh(host, user, key, command): return ["ssh", "-i", key, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=accept-new", f"{user}@{host}", command] def main(): parser = argparse.ArgumentParser(description=__doc__) for name in ("kubeconfig", "destination-node", "destination-path", "source-host", "source-user", "source-key", "source-node", "source-path", "hypervisor-host", "hypervisor-user", "hypervisor-key", "source-vmid", "state-dir", "result"): parser.add_argument("--" + name, required=True) parser.add_argument("--registry-endpoint", required=True) args = parser.parse_args() for path in (args.destination_path, args.source_path): if not path.startswith("/data/") or ".." in Path(path).parts or path.rstrip("/") == "/data": raise RuntimeError("Registry storage must be a specific absolute directory under /data") if not args.source_vmid.isdigit(): raise RuntimeError("Source VMID must be numeric") kubectl = ["kubectl", "--kubeconfig", args.kubeconfig, "--request-timeout=15s"] nodes = json.loads(run(kubectl + ["get", "nodes", "-o", "json"]))["items"] node_names = {node["metadata"]["name"] for node in nodes} raw_pv = run(kubectl + ["get", "pv", "registry-data-pimox-worker-01", "--ignore-not-found", "-o", "json"]) path = args.destination_path target = args.destination_node if raw_pv: pv = json.loads(raw_pv) terms = pv["spec"].get("nodeAffinity", {}).get("required", {}).get("nodeSelectorTerms", []) hosts = {host for term in terms for expr in term.get("matchExpressions", []) if expr.get("key") == "kubernetes.io/hostname" and expr.get("operator") == "In" for host in expr.get("values", [])} if len(hosts) != 1 or not hosts.issubset(node_names): raise RuntimeError("Existing registry PV has unavailable/ambiguous placement; refusing to mutate retained storage") target = next(iter(hosts)) path = pv["spec"].get("local", {}).get("path") if not path: raise RuntimeError("Existing registry PV is not a local registry volume") elif args.source_node in node_names: target, path = args.source_node, args.source_path elif node_names != {args.destination_node}: raise RuntimeError("No existing registry PV and no unique local destination; refusing to guess placement") if target == args.destination_node: local_ips = set(run(["hostname", "-I"]).split()) selected = next(node for node in nodes if node["metadata"]["name"] == target) if not any(a["type"] == "InternalIP" and a["address"] in local_ips for a in selected["status"]["addresses"]): raise RuntimeError("Registry migration must run on the selected destination node") prepare_local(args, path, bool(raw_pv)) retire_legacy_forwarding() configure_local_registry_client(args) else: # Existing Pimox placement remains unchanged; the existing worker # preparation step creates its directory without replacing its data. print(f"Preserving registry placement on {target}:{path}", flush=True) Path(args.result).write_text(json.dumps({"node": target, "path": path}) + "\n") Path(args.result).chmod(0o600) def prepare_local(args, path, existing_pv): state = Path(args.state_dir) state.mkdir(parents=True, exist_ok=True, mode=0o700) with (state / "registry-migration.lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) receipt = state / "registry-migration.json" run(["sudo", "-n", "true"]) if subprocess.run(["sudo", "-n", "test", "-L", path], check=False).returncode == 0: raise RuntimeError("Registry destination must not be a symlink") if existing_pv: run(["sudo", "test", "-d", path]) print(f"Preserving existing registry PV and data at {path}", flush=True) return if receipt.exists(): recorded = json.loads(receipt.read_text()) if recorded.get("destination") != path: raise RuntimeError("Registry migration receipt belongs to another path") run(["sudo", "test", "-d", path]) print(f"Registry migration already completed at {path}; source copy skipped", flush=True) return exists = subprocess.run(["sudo", "test", "-e", path], check=False).returncode == 0 if exists: run(["sudo", "test", "-d", path]) if run(["sudo", "find", path, "-mindepth", "1", "-maxdepth", "1", "-print", "-quit"]): raise RuntimeError("Unrecorded registry data already exists at destination; refusing to overwrite or merge it") source_ssh = lambda command: ssh(args.source_host, args.source_user, args.source_key, command) hyper_ssh = lambda command: ssh(args.hypervisor_host, args.hypervisor_user, args.hypervisor_key, command) started = False stage = None try: try: run(source_ssh("true"), timeout=15) except (subprocess.CalledProcessError, subprocess.TimeoutExpired): status = run(hyper_ssh(f"sudo -n qm status {args.source_vmid}"), timeout=20) if status == "status: stopped": config = run(hyper_ssh(f"sudo -n qm config {args.source_vmid}"), timeout=20) if f"name: {args.source_node}" not in config.splitlines(): raise RuntimeError("Source VMID does not match discovered registry node; refusing to start another VM") print(f"Temporarily starting source VM {args.source_vmid} to inspect registry data", flush=True) run(hyper_ssh(f"sudo -n qm start {args.source_vmid}"), timeout=60) started = True elif status != "status: running": raise RuntimeError("Cannot determine registry source VM state") deadline = time.monotonic() + 180 while True: try: run(source_ssh("true"), timeout=15) break except (subprocess.CalledProcessError, subprocess.TimeoutExpired): if time.monotonic() >= deadline: raise RuntimeError("Source SSH unavailable; refusing to treat it as empty registry storage") time.sleep(5) probe = ( "set -eu; " f"if sudo -n test -L {shlex.quote(args.source_path)}; then exit 42; fi; " f"if sudo -n test -d {shlex.quote(args.source_path)}; then " f"sudo -n find {shlex.quote(args.source_path)} -mindepth 1 -maxdepth 1 -print -quit; " f"elif sudo -n test -e {shlex.quote(args.source_path)}; then exit 43; fi" ) # Verify sudo independently: a permission failure must not look # like a missing source directory. run(source_ssh("sudo -n true"), timeout=15) has_data = bool(run(source_ssh(probe))) parent = str(Path(path).parent) run(["sudo", "mkdir", "-p", parent]) stage = run(["sudo", "mktemp", "-d", parent + "/.registry-migration.XXXXXX"]) digest = None if has_data: source_bytes = int(run(source_ssh("sudo -n du -sb " + shlex.quote(args.source_path))).split()[0]) available = int(run(["df", "-B1", "--output=avail", parent]).splitlines()[-1].strip()) if available < source_bytes + 256 * 1024 * 1024: raise RuntimeError("Insufficient destination disk space for a verified registry copy") manifest_command = "cd " + shlex.quote(args.source_path) + " && find . -type f -print0 | sort -z | xargs -0 -r sha256sum" manifest_ssh = source_ssh("sudo -n bash -o pipefail -c " + shlex.quote(manifest_command)) before = run(manifest_ssh, timeout=1800) special = run(source_ssh("sudo -n find " + shlex.quote(args.source_path) + " -mindepth 1 ! -type f ! -type d -print -quit")) if special: raise RuntimeError("Source registry contains non-regular files; refusing unsafe archive extraction") print(f"Copying registry data from {args.source_host}:{args.source_path} into staging storage", flush=True) with tempfile.TemporaryFile() as errors: source = subprocess.Popen(source_ssh("sudo -n tar -C " + shlex.quote(args.source_path) + " -cpf - ."), stdout=subprocess.PIPE, stderr=errors) try: destination = subprocess.run(["sudo", "tar", "-C", stage, "-xpf", "-", "--no-same-owner"], stdin=source.stdout, stderr=errors, timeout=1800) source.stdout.close() source_status = source.wait(timeout=30) if destination.returncode or source_status: raise RuntimeError("Registry archive transfer failed; source preserved") finally: if source.poll() is None: source.kill() source.wait() after = run(manifest_ssh, timeout=1800) copied = run(["sudo", "bash", "-o", "pipefail", "-c", "cd " + shlex.quote(stage) + " && find . -type f -print0 | sort -z | xargs -0 -r sha256sum"], timeout=1800) if before != after or before != copied: raise RuntimeError("Registry changed during copy or verification failed; staging retained, source preserved") digest = hashlib.sha256(before.encode()).hexdigest() else: print("Source inspection confirmed no registry data; preparing a fresh retained registry directory", flush=True) run(["sudo", "chown", "-R", "1000:1000", stage]) run(["sudo", "chmod", "0750", stage]) # The existing directory, if any, was verified empty above. if exists: run(["sudo", "rmdir", path]) run(["sudo", "mv", "-T", stage, path]) stage = None receipt_tmp = state / "registry-migration.json.tmp" receipt_tmp.write_text(json.dumps({"destination": path, "source_host": args.source_host, "source_path": args.source_path, "copied": has_data, "manifest_sha256": digest}) + "\n") receipt_tmp.chmod(0o600) os.replace(receipt_tmp, receipt) print(f"Registry storage ready at {path}; original source retained", flush=True) finally: if stage: print(f"Unpublished migration staging retained at {stage}", file=sys.stderr) if started: # Restore only a VM that this operation started. Never force # stop or reset source services/data after a failed shutdown. run(hyper_ssh(f"sudo -n qm shutdown {args.source_vmid} --timeout 90"), timeout=110) def retire_legacy_forwarding(): """Remove only Jeannie's explicitly tagged redirects to the old VM.""" unit = "homelab-pimox-registry-forward.service" if run(["systemctl", "show", unit, "-p", "LoadState", "--value"]) != "not-found": run(["sudo", "-n", "systemctl", "disable", "--now", unit]) iptables = shutil.which("iptables") or "/usr/sbin/iptables" if not Path(iptables).exists(): return removed = 0 for table in ("nat", "filter"): lines = run(["sudo", "-n", iptables, "-w", "5", "-t", table, "-S"]) for line in lines.splitlines(): fields = shlex.split(line) if not fields or fields[0] != "-A" or "--comment" not in fields: continue if fields[fields.index("--comment") + 1] != "homelab-pimox-registry-forward": continue run(["sudo", "-n", iptables, "-w", "5", "-t", table, "-D", *fields[1:]]) removed += 1 print(f"Retired {removed} Jeannie registry forwarding rule(s); local NodePort can serve the registry", flush=True) def configure_local_registry_client(args): """Merge the local HTTP registry mirror only when k3s owns the runtime.""" if subprocess.run(["systemctl", "is-active", "--quiet", "k3s"], check=False).returncode: return import yaml endpoint = args.registry_endpoint if not re.fullmatch(r"[A-Za-z0-9.-]+:[0-9]+", endpoint) or not 1 <= int(endpoint.rsplit(":", 1)[1]) <= 65535: raise RuntimeError("Registry endpoint must be a host:port pair") filename = "/etc/rancher/k3s/registries.yaml" exists = subprocess.run(["sudo", "-n", "test", "-e", filename], check=False).returncode == 0 config = yaml.safe_load(run(["sudo", "-n", "cat", filename])) if exists else {} config = config or {} if not isinstance(config, dict): raise RuntimeError("Existing k3s registry configuration must be a mapping") mirrors = config.setdefault("mirrors", {}) if not isinstance(mirrors, dict): raise RuntimeError("Existing k3s registry mirrors must be a mapping") mirror = mirrors.setdefault(endpoint, {}) if not isinstance(mirror, dict): raise RuntimeError("Existing k3s registry mirror must be a mapping") endpoints = ["http://" + endpoint] if mirror.get("endpoint") == endpoints: return if mirror.get("endpoint"): raise RuntimeError("Registry already has custom k3s mirror endpoints; refusing to replace them") mirror["endpoint"] = endpoints with tempfile.TemporaryDirectory(prefix="jeannie-registry-client-") as temporary: candidate = Path(temporary) / "registries.yaml" candidate.write_text(yaml.safe_dump(config)) candidate.chmod(0o600) staged = filename + ".jeannie-tmp" run(["sudo", "-n", "install", "-m", "0600", str(candidate), staged]) if exists: run(["sudo", "-n", "cp", "-a", filename, filename + f".jeannie-backup-{time.time_ns()}"]) run(["sudo", "-n", "mv", "-T", staged, filename]) print("Reloading k3s once to load the local HTTP registry mirror", flush=True) run(["sudo", "-n", "systemctl", "restart", "k3s"], timeout=120) deadline = time.monotonic() + 180 while True: result = subprocess.run(["kubectl", "--kubeconfig", args.kubeconfig, "--request-timeout=5s", "get", "--raw=/readyz"], capture_output=True, text=True, timeout=10) if result.returncode == 0: break if time.monotonic() >= deadline: raise RuntimeError("k3s did not regain API readiness after loading registry mirror") time.sleep(3) if __name__ == "__main__": try: main() except (RuntimeError, OSError, ValueError, subprocess.SubprocessError) as error: print(f"Registry reconciliation refused: {error}", file=sys.stderr) sys.exit(1)