my-homelab-configs/scripts/registry-storage-reconcile.py

359 lines
20 KiB
Python

#!/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 manifest_files(manifest):
files = {}
for line in manifest.splitlines():
checksum, separator, name = line.partition(" ")
if not separator or not re.fullmatch(r"[a-f0-9]{64}", checksum) or not name.startswith("./"):
raise RuntimeError("Unsupported registry filename/checksum format; refusing ambiguous reconciliation")
files[name] = checksum
return files
def local_manifest(path):
special = run(["sudo", "-n", "find", path, "-mindepth", "1", "!", "-type", "f", "!", "-type", "d", "-print", "-quit"])
if special:
raise RuntimeError("Registry destination contains non-regular files; refusing staged reconciliation")
return run(["sudo", "-n", "bash", "-o", "pipefail", "-c",
"cd " + shlex.quote(path) + " && find . -type f -print0 | sort -z | xargs -0 -r sha256sum"], timeout=1800)
def require_no_local_writer(path):
docker = shutil.which("docker") or "/usr/bin/docker"
if not Path(docker).exists():
return
ids = run(["sudo", "-n", docker, "ps", "-q"]).splitlines()
if not ids:
return
for container in json.loads(run(["sudo", "-n", docker, "inspect", *ids])):
for mount in container.get("Mounts") or []:
source = mount.get("Source", "")
if not source.startswith("/") or not mount.get("RW", True):
continue
common = os.path.commonpath([os.path.realpath(source), os.path.realpath(path)])
if common in (os.path.realpath(source), os.path.realpath(path)):
raise RuntimeError("A running Docker container can write registry storage; refusing to swap its directory")
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])
destination_manifest = local_manifest(path) if exists else ""
destination_files = manifest_files(destination_manifest)
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
source_files = {}
if has_data:
source_bytes = int(run(source_ssh("sudo -n du -sb " + shlex.quote(args.source_path))).split()[0])
destination_bytes = int(run(["sudo", "du", "-sb", path]).split()[0]) if exists else 0
available = int(run(["df", "-B1", "--output=avail", parent]).splitlines()[-1].strip())
if available < source_bytes + destination_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)
source_files = manifest_files(before)
conflicts = [name for name, checksum in source_files.items()
if name in destination_files and destination_files[name] != checksum]
if conflicts:
raise RuntimeError(f"Registry has {len(conflicts)} conflicting source/destination file(s); both copies preserved, automatic overwrite refused")
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; preserving any existing destination data", flush=True)
backup = None
# A complete existing destination is authoritative and stays in
# place. This covers earlier successful copies without a receipt.
reuse = exists and bool(destination_files) and all(
destination_files.get(name) == checksum for name, checksum in source_files.items())
if reuse:
if local_manifest(path) != destination_manifest:
raise RuntimeError("Destination changed during reconciliation; refusing to record a completed migration")
print(f"Existing registry at {path} already contains all source files; reusing it unchanged", flush=True)
if not has_data:
run(["sudo", "rmdir", stage])
stage = None
else:
if exists:
require_no_local_writer(path)
run(["sudo", "cp", "-a", "--no-clobber", path + "/.", stage + "/"], timeout=1800)
if local_manifest(path) != destination_manifest:
raise RuntimeError("Destination changed during staged merge; original data preserved")
expected = dict(destination_files, **source_files)
if manifest_files(local_manifest(stage)) != expected:
raise RuntimeError("Merged registry file verification failed; original directories preserved")
run(["sudo", "chown", "-R", "1000:1000", stage])
run(["sudo", "chmod", "0750", stage])
if exists:
require_no_local_writer(path)
backup = path + f".before-migration-{time.time_ns()}"
run(["sudo", "mv", "-T", path, backup])
try:
run(["sudo", "mv", "-T", stage, path])
except subprocess.SubprocessError:
if backup:
run(["sudo", "mv", "-T", backup, path])
raise
stage = None
if backup:
print(f"Original destination retained at {backup}", flush=True)
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, "destination_backup": backup,
"reused_destination": reuse,
"staged_source_backup": stage}) + "\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)