626 lines
38 KiB
Python
626 lines
38 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, cipher=None):
|
|
options = ["ssh", "-T", "-i", key, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes",
|
|
"-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=accept-new"]
|
|
if cipher:
|
|
options.extend(["-v", "-o", f"Ciphers={cipher}", "-o", "Compression=no",
|
|
"-o", "ControlMaster=no", "-o", "ControlPath=none",
|
|
"-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=2"])
|
|
return [*options, f"{user}@{host}", command]
|
|
|
|
|
|
def registry_source_ssh(args, command, cipher=None):
|
|
target = ssh(args.source_host, args.source_user, args.source_key, command, cipher=cipher)
|
|
# Bulk A/B tests verified this path while direct worker LAN traffic
|
|
# failed SSH integrity checks. Proxy SSH uses the destination host's key;
|
|
# no private key or registry credentials are copied to the hypervisor.
|
|
proxy = ["ssh", "-T", "-i", args.hypervisor_key, "-o", "BatchMode=yes",
|
|
"-o", "IdentitiesOnly=yes", "-o", "ConnectTimeout=10",
|
|
"-o", "StrictHostKeyChecking=accept-new", "-o", "ControlPath=none",
|
|
"-c", "aes256-gcm@openssh.com", "-W", "%h:%p",
|
|
f"{args.hypervisor_user}@{args.hypervisor_host}"]
|
|
return [*target[:-2], "-o", "ProxyCommand=" + shlex.join(proxy), *target[-2:]]
|
|
|
|
|
|
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("--destination-host")
|
|
parser.add_argument("--destination-user")
|
|
parser.add_argument("--destination-key")
|
|
parser.add_argument("--required-data-mount", default="")
|
|
parser.add_argument("--registry-endpoint", required=True)
|
|
parser.add_argument("--transfer-cipher", default=os.environ.get("LAB_REGISTRY_TRANSFER_CIPHER", "aes256-gcm@openssh.com"),
|
|
choices=("aes256-gcm@openssh.com", "aes128-gcm@openssh.com", "chacha20-poly1305@openssh.com"))
|
|
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"]):
|
|
receipt = json.loads((Path(args.state_dir) / "registry-migration.json").read_text())
|
|
if (receipt.get("destination_host"), receipt.get("node"), receipt.get("destination")) != (args.destination_host, target, path):
|
|
raise RuntimeError("Remote registry storage requires a matching offline transition receipt")
|
|
if not all((args.destination_host, args.destination_user, args.destination_key)) or not any(
|
|
a["type"] == "InternalIP" and a["address"] == args.destination_host for a in selected["status"]["addresses"]):
|
|
raise RuntimeError("Remote registry target does not match the live destination node")
|
|
remote = lambda command: run(ssh(args.destination_host, args.destination_user, args.destination_key, command), timeout=1800)
|
|
require_remote_data_mount(remote, args.required_data_mount)
|
|
present = remote("set -eu; sudo -n true; if sudo -n test -d " + shlex.quote(path) +
|
|
"; then echo present; else echo missing; fi")
|
|
if present != "present":
|
|
raise RuntimeError(f"Retained registry directory {path} is absent on the mounted host; "
|
|
"do not restart a running registry or create an empty replacement before recovering its data")
|
|
host_directory = remote("sudo -n stat -c %d:%i " + shlex.quote(path))
|
|
pods = json.loads(run(kubectl + ["-n", "container-registry", "get", "pods", "-l", "app=local-registry", "-o", "json"]))
|
|
running_registry = False
|
|
for pod in pods.get("items") or []:
|
|
if not any(status.get("name") == "registry" and status.get("state", {}).get("running")
|
|
for status in pod.get("status", {}).get("containerStatuses") or []):
|
|
continue
|
|
running_registry = True
|
|
pod_directory = run(kubectl + ["-n", "container-registry", "exec", pod["metadata"]["name"],
|
|
"-c", "registry", "--", "stat", "-c", "%d:%i", "/var/lib/registry"])
|
|
if pod_directory != host_directory:
|
|
raise RuntimeError("Running registry volume does not match the host directory's filesystem/inode; "
|
|
"preserve its mounted data before any pod restart or storage change")
|
|
if not raw_pv:
|
|
current = remote_manifest(remote, path)
|
|
if hashlib.sha256(current.encode()).hexdigest() != receipt["manifest_sha256"]:
|
|
if running_registry:
|
|
raise RuntimeError("Registry is running while its preseeded data differs from the receipt; refusing offline verification")
|
|
baseline = local_manifest(path)
|
|
if hashlib.sha256(baseline.encode()).hexdigest() != receipt["manifest_sha256"]:
|
|
raise RuntimeError("Retained registry baseline does not match the migration receipt")
|
|
original_files, current_files = manifest_files(baseline), manifest_files(current)
|
|
if any(current_files.get(name) != digest for name, digest in original_files.items()):
|
|
raise RuntimeError("Remote registry is missing or changed a file from its verified baseline")
|
|
blob_pattern = re.compile(r"^\./docker/registry/v2/blobs/sha256/([0-9a-f]{2})/([0-9a-f]{64})/data$")
|
|
for name, digest in current_files.items():
|
|
match = blob_pattern.fullmatch(name)
|
|
if match and (match.group(1) != match.group(2)[:2] or match.group(2) != digest):
|
|
raise RuntimeError("Remote registry contains a blob whose contents do not match its digest")
|
|
if remote_manifest(remote, path) != current:
|
|
raise RuntimeError("Remote registry changed during offline verification")
|
|
print(f"Verified retained registry baseline and {len(current_files) - len(original_files)} additional files on {target}", flush=True)
|
|
if os.environ.get("LAB_CLUSTER_RUNTIME") == "k3s":
|
|
ensure_k3s_data_mount_dependency(remote, args.required_data_mount)
|
|
print(f"Preserving verified remote registry storage on {target}:{path}", flush=True)
|
|
else:
|
|
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 remote_manifest(remote, path):
|
|
special = remote("sudo -n find " + shlex.quote(path) + " -mindepth 1 ! -type f ! -type d -print -quit")
|
|
if special:
|
|
raise RuntimeError("Remote registry contains special files; refusing publication")
|
|
command = "cd " + shlex.quote(path) + " && find . -type f -print0 | sort -z | xargs -0 -r sha256sum"
|
|
return remote("sudo -n bash -o pipefail -c " + shlex.quote(command))
|
|
|
|
|
|
def require_remote_data_mount(remote, mount):
|
|
if not mount:
|
|
return
|
|
if not re.fullmatch(r"/[A-Za-z0-9_./-]+", mount) or ".." in Path(mount).parts:
|
|
raise RuntimeError("Required data mount must be a specific absolute path without whitespace")
|
|
mounts = json.loads(remote("findmnt -J -T " + shlex.quote(mount) + " -o TARGET,SOURCE,OPTIONS"))
|
|
filesystems = mounts.get("filesystems") or []
|
|
if len(filesystems) != 1 or filesystems[0].get("target") != mount:
|
|
raise RuntimeError(f"Required data filesystem is not mounted at {mount}; refusing root-filesystem fallback")
|
|
if "rw" not in str(filesystems[0].get("options", "")).split(","):
|
|
raise RuntimeError(f"Required data filesystem at {mount} is not writable")
|
|
|
|
|
|
def ensure_k3s_data_mount_dependency(remote, mount):
|
|
if not mount:
|
|
return
|
|
require_remote_data_mount(remote, mount)
|
|
# An owned drop-in adds ordering without replacing user overrides or
|
|
# restarting a live service. The same file can precede first installation.
|
|
filename = "/etc/systemd/system/k3s.service.d/20-jeannie-data-mount.conf"
|
|
content = f"[Unit]\nRequiresMountsFor={mount}\nConditionPathIsMountPoint={mount}\n"
|
|
result = remote("set -eu; sudo -n install -d -m 0755 /etc/systemd/system/k3s.service.d; "
|
|
"if printf %s " + shlex.quote(content) + " | sudo -n cmp -s - " + filename + "; then echo unchanged; "
|
|
"else if sudo -n test -e " + filename + "; then sudo -n cp -a " + filename +
|
|
" " + filename + f".before-{time.time_ns()}; fi; printf %s " + shlex.quote(content) +
|
|
" | sudo -n tee " + filename + ".tmp >/dev/null; sudo -n chmod 0644 " + filename + ".tmp; "
|
|
"sudo -n mv -T " + filename + ".tmp " + filename + "; sudo -n systemctl daemon-reload; echo installed; fi")
|
|
if result == "installed":
|
|
print(f"K3s now requires mounted storage at {mount} on future starts; live service left running", flush=True)
|
|
|
|
|
|
def publish_remote(args, source_path, control, receipt):
|
|
"""Publish a verified offline copy without replacing existing remote data."""
|
|
remote = lambda command: run(ssh(control["lan_ip"], control["user"], control["ssh_key_path"], command), timeout=1800)
|
|
required_mount = getattr(args, "required_data_mount", "")
|
|
require_remote_data_mount(remote, required_mount)
|
|
if remote("systemctl is-active k3s 2>/dev/null || true") not in ("inactive", "failed", "unknown"):
|
|
raise RuntimeError("Remote K3s must remain stopped during registry publication")
|
|
path = "/data/openebs/local/registry"
|
|
quoted = shlex.quote(path)
|
|
expected = local_manifest(source_path)
|
|
# Refuse symlink destinations and parent paths before root extraction.
|
|
remote("set -eu; for p in /data /data/openebs /data/openebs/local " + quoted + "; do "
|
|
"if sudo -n test -L \"$p\"; then exit 1; fi; done; sudo -n mkdir -p /data/openebs/local")
|
|
exists = remote("if sudo -n test -e " + quoted + "; then echo yes; else echo no; fi") == "yes"
|
|
if exists:
|
|
if remote_manifest(remote, path) != expected:
|
|
raise RuntimeError("Remote registry already has different data; both copies preserved for review")
|
|
else:
|
|
needed = int(run(["sudo", "-n", "du", "-sb", source_path]).split()[0])
|
|
available = int(remote("df -B1 --output=avail /data/openebs/local").splitlines()[-1])
|
|
if available < needed + 256 * 1024 * 1024:
|
|
raise RuntimeError("Insufficient Orange Pi storage for the registry copy")
|
|
stage = remote("sudo -n mktemp -d /data/openebs/local/.registry-native.XXXXXX")
|
|
print(f"Copying verified registry onto {control['lan_ip']} (staging retained on failure)...", flush=True)
|
|
source = subprocess.Popen(["sudo", "-n", "tar", "-C", source_path, "-cpf", "-", "."], stdout=subprocess.PIPE)
|
|
try:
|
|
transfer = ssh(control["lan_ip"], control["user"], control["ssh_key_path"],
|
|
"sudo -n tar -C " + shlex.quote(stage) + " -xpf - --no-same-owner", cipher=args.transfer_cipher)
|
|
transfer.remove("-v")
|
|
destination = subprocess.run(transfer,
|
|
stdin=source.stdout, timeout=1800)
|
|
source.stdout.close()
|
|
source_status = source.wait(timeout=30)
|
|
if destination.returncode or source_status:
|
|
raise RuntimeError(f"Remote registry transfer failed; unpublished staging retained at {stage}")
|
|
finally:
|
|
if source.poll() is None:
|
|
source.kill()
|
|
source.wait()
|
|
if remote_manifest(remote, stage) != expected or local_manifest(source_path) != expected:
|
|
raise RuntimeError(f"Registry checksum mismatch; unpublished staging retained at {stage}")
|
|
remote("set -eu; sudo -n chown -R 1000:1000 " + shlex.quote(stage) +
|
|
"; sudo -n chmod 0750 " + shlex.quote(stage) +
|
|
"; sudo -n test ! -e " + quoted + "; sudo -n mv -T " + shlex.quote(stage) + " " + quoted)
|
|
# Install the HTTP mirror before K3s starts. Keep all unrelated settings.
|
|
import yaml
|
|
raw = remote("if sudo -n test -e /etc/rancher/k3s/registries.yaml; then sudo -n cat /etc/rancher/k3s/registries.yaml; fi")
|
|
config = yaml.safe_load(raw) or {}
|
|
if not isinstance(config, dict):
|
|
raise RuntimeError("Native K3s registry configuration must be a mapping")
|
|
endpoints = ["http://" + args.registry_endpoint]
|
|
mirrors = config.setdefault("mirrors", {})
|
|
if not isinstance(mirrors, dict):
|
|
raise RuntimeError("Native K3s registry mirrors must be a mapping")
|
|
mirror = mirrors.setdefault(args.registry_endpoint, {})
|
|
if not isinstance(mirror, dict):
|
|
raise RuntimeError("Native K3s registry mirror must be a mapping")
|
|
if mirror.get("endpoint") and mirror["endpoint"] != endpoints:
|
|
raise RuntimeError("Native K3s has custom mirror endpoints; refusing to replace them")
|
|
mirror["endpoint"] = endpoints
|
|
remote("set -eu; sudo -n install -d -m 0755 /etc/rancher/k3s; "
|
|
"if sudo -n test -e /etc/rancher/k3s/registries.yaml; then sudo -n cp -a /etc/rancher/k3s/registries.yaml "
|
|
f"/etc/rancher/k3s/registries.yaml.before-transition-{time.time_ns()}; fi; "
|
|
"sudo -n install -m 0600 /dev/null /etc/rancher/k3s/registries.yaml.jeannie-tmp")
|
|
subprocess.run(ssh(control["lan_ip"], control["user"], control["ssh_key_path"],
|
|
"sudo -n tee /etc/rancher/k3s/registries.yaml.jeannie-tmp >/dev/null"),
|
|
input=yaml.safe_dump(config), text=True, capture_output=True, check=True, timeout=60)
|
|
remote("sudo -n mv -T /etc/rancher/k3s/registries.yaml.jeannie-tmp /etc/rancher/k3s/registries.yaml")
|
|
ensure_k3s_data_mount_dependency(remote, required_mount)
|
|
temporary = receipt.with_suffix(".tmp")
|
|
temporary.write_text(json.dumps({"node": control["node_name"], "destination_host": control["lan_ip"],
|
|
"destination": path, "manifest_sha256": hashlib.sha256(expected.encode()).hexdigest()}) + "\n")
|
|
temporary.chmod(0o600)
|
|
os.replace(temporary, receipt)
|
|
|
|
|
|
def resolve_registry_links(args, conflicts, source_files, destination_files):
|
|
"""Prefer the traced active registry only for verified mutable tag links.
|
|
|
|
dc59dc8 moved the registry and its endpoint forwarding from Debian to
|
|
Pimox. That establishes source lineage, not per-file timestamp ordering.
|
|
Immutable blob conflicts must never be resolved by host or modification time.
|
|
"""
|
|
decisions = []
|
|
verified = set()
|
|
|
|
def source_read(relative):
|
|
return run(registry_source_ssh(args,
|
|
"sudo -n cat -- " + shlex.quote(str(Path(args.source_path) / relative))), timeout=60)
|
|
|
|
def verify_digest(digest, expand_manifest=False, depth=0):
|
|
if not re.fullmatch(r"sha256:[a-f0-9]{64}", digest):
|
|
raise RuntimeError("Registry tag contains an unsupported digest")
|
|
if depth > 12 or len(verified) > 4096:
|
|
raise RuntimeError("Registry manifest graph exceeds verification bounds")
|
|
hex_digest = digest.split(":", 1)[1]
|
|
relative = f"docker/registry/v2/blobs/sha256/{hex_digest[:2]}/{hex_digest}/data"
|
|
if source_files.get("./" + relative) != hex_digest:
|
|
raise RuntimeError("Preferred Pimox manifest references missing or invalid blob content")
|
|
if not expand_manifest or digest in verified:
|
|
return
|
|
verified.add(digest)
|
|
manifest = json.loads(source_read(relative))
|
|
if not isinstance(manifest, dict) or manifest.get("schemaVersion") != 2:
|
|
raise RuntimeError("Preferred registry tag is not a supported schema-2 manifest")
|
|
if "manifests" in manifest:
|
|
for descriptor in manifest["manifests"]:
|
|
verify_digest(descriptor["digest"], expand_manifest=True, depth=depth + 1)
|
|
else:
|
|
if not isinstance(manifest.get("config"), dict) or not isinstance(manifest.get("layers"), list):
|
|
raise RuntimeError("Preferred registry image has no complete config/layer descriptors")
|
|
verify_digest(manifest["config"]["digest"], depth=depth + 1)
|
|
for descriptor in manifest["layers"]:
|
|
verify_digest(descriptor["digest"], depth=depth + 1)
|
|
|
|
for name in conflicts:
|
|
match = re.fullmatch(r"\./docker/registry/v2/repositories/(.+)/_manifests/tags/([^/]+)/current/link", name)
|
|
if not match:
|
|
raise RuntimeError(f"Conflicting non-tag registry file requires review: {name}; both versions preserved")
|
|
relative = name.removeprefix("./")
|
|
preferred = source_read(relative)
|
|
if hashlib.sha256((preferred + "\n").encode()).hexdigest() != source_files[name] and hashlib.sha256(preferred.encode()).hexdigest() != source_files[name]:
|
|
raise RuntimeError("Source tag link changed during conflict inspection")
|
|
verify_digest(preferred, expand_manifest=True)
|
|
decisions.append({"path": name, "preferred": "source", "source_sha256": source_files[name],
|
|
"destination_sha256": destination_files[name], "manifest_digest": preferred,
|
|
"basis": "dc59dc8 moved the active registry and push forwarding to Pimox"})
|
|
print(f"Registry conflict resolved: {match[1]}:{match[2]} uses verified Pimox manifest {preferred[:23]}... (pipeline lineage dc59dc8)", flush=True)
|
|
return decisions
|
|
|
|
|
|
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: registry_source_ssh(args, 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):
|
|
native_state = run(hyper_ssh("systemctl is-active k3s 2>/dev/null || true"), timeout=20)
|
|
if native_state not in ("inactive", "failed", "unknown"):
|
|
raise RuntimeError("Stop Orange Pi host K3s before temporarily starting a source VM for registry migration")
|
|
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 = {}
|
|
conflict_decisions = []
|
|
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:
|
|
conflict_decisions = resolve_registry_links(args, conflicts, source_files, destination_files)
|
|
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} through {args.hypervisor_host} using {args.transfer_cipher}", flush=True)
|
|
diagnostics = state / "diagnostics"
|
|
diagnostics.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
transfer_id = str(time.time_ns())
|
|
source_log = diagnostics / f"registry-transfer-{transfer_id}-source.log"
|
|
destination_log = diagnostics / f"registry-transfer-{transfer_id}-destination.log"
|
|
with source_log.open("w+b") as source_errors, destination_log.open("w+b") as destination_errors:
|
|
source_log.chmod(0o600)
|
|
destination_log.chmod(0o600)
|
|
source_command = registry_source_ssh(args,
|
|
"sudo -n tar -C " + shlex.quote(args.source_path) + " -cpf - .",
|
|
cipher=args.transfer_cipher)
|
|
source = subprocess.Popen(source_command, stdout=subprocess.PIPE, stderr=source_errors)
|
|
try:
|
|
destination = subprocess.run(["sudo", "-n", "tar", "-C", stage, "-xpf", "-", "--no-same-owner"], stdin=source.stdout, stderr=destination_errors, timeout=1800)
|
|
source.stdout.close()
|
|
source_status = source.wait(timeout=30)
|
|
if destination.returncode or source_status:
|
|
print(f"Registry archive exit codes: source={source_status}, destination={destination.returncode}", file=sys.stderr)
|
|
for label, stream, filename in (("source", source_errors, source_log), ("destination", destination_errors, destination_log)):
|
|
stream.flush()
|
|
stream.seek(0, 2)
|
|
stream.seek(max(0, stream.tell() - 8192))
|
|
for line in stream.read().decode("utf-8", errors="replace").splitlines()[-4:]:
|
|
print(f" tar {label}: {line[:300]}", file=sys.stderr)
|
|
print(f"Private {label} diagnostic: {filename}", file=sys.stderr)
|
|
raise RuntimeError("Registry archive transfer failed; detailed tar diagnostics retained, source preserved")
|
|
except subprocess.TimeoutExpired:
|
|
print(f"Archive transfer timed out; private diagnostics: {source_log}, {destination_log}", file=sys.stderr)
|
|
raise
|
|
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,
|
|
"conflict_decisions": conflict_decisions}) + "\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, KeyError, TypeError, subprocess.SubprocessError) as error:
|
|
print(f"Registry reconciliation refused: {error}", file=sys.stderr)
|
|
sys.exit(1)
|