456 lines
26 KiB
Python
456 lines
26 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("--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"]):
|
|
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 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):
|
|
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)
|