From fb492c13f6926feaa773b2def703ade159eadd5d Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Mon, 2 Nov 2026 21:34:00 -0600 Subject: [PATCH] Reconcile retained registry placement and copy existing Pimox data --- apps/container-registry/kustomization.yaml | 6 + bootstrap/apps/README.md | 50 ++++ bootstrap/apps/main.tf | 27 ++ bootstrap/apps/variables.tf | 12 + bootstrap/platform/README.md | 12 +- lib/jeannie/pipeline.sh | 44 +++- scripts/registry-storage-reconcile.py | 285 +++++++++++++++++++++ scripts/scheduling-preflight.py | 22 +- 8 files changed, 442 insertions(+), 16 deletions(-) create mode 100644 apps/container-registry/kustomization.yaml create mode 100644 bootstrap/apps/README.md create mode 100644 scripts/registry-storage-reconcile.py diff --git a/apps/container-registry/kustomization.yaml b/apps/container-registry/kustomization.yaml new file mode 100644 index 0000000..33bf6df --- /dev/null +++ b/apps/container-registry/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - namespace.yaml + - registry-storage.yaml + - registry-deployment.yaml diff --git a/bootstrap/apps/README.md b/bootstrap/apps/README.md new file mode 100644 index 0000000..69196cd --- /dev/null +++ b/bootstrap/apps/README.md @@ -0,0 +1,50 @@ +# Registry discovery and retained-data migration + +`./jeannie apps` and `./jeannie apps container-registry` reconcile registry +storage before updating the Argo Application. This uses pinned cluster identity, +live nodes/PVs and the existing worker inventory, rather than a profile-specific +manifest directory. + +Existing local PVs retain their node, path and resource names. A fresh cluster +with the old registry worker still present uses that worker. A fresh single-node +cluster on the deployment host instead prepares its local retained directory. +An existing PV pointing to a missing node is refused rather than rewritten. + +For the local destination, Jeannie inspects the previous registry worker over +SSH. If the worker is stopped, it checks its Proxmox VMID and name, temporarily +starts only that VM, and restores its stopped state with a graceful shutdown. +It does not start the old control plane. Failure to reach or inspect the source +blocks deployment; it is not treated as missing registry data. + +If source data exists, it is copied into a new staging directory after a disk +capacity check. Source manifests before/after the copy and the copied files must +have identical SHA-256 checksums. Changed source data, special files, failed +transfers or verification errors stop publication. Staging directories are +retained for investigation, and source data is never removed. If source +inspection confirms an absent or empty directory, an empty retained destination +is prepared instead. Unrecorded, nonempty destination directories are refused +instead of overwritten or merged. + +Successful copies write a profile-scoped `registry-migration.json` receipt. +Subsequent runs preserve existing destination data. The storage and deployment +placement are passed to Argo through `registry_placement` Kustomize patches; +the scheduling preflight renders those same patches. Legacy PV/PVC names remain +stable to preserve existing Pimox deployments. + +When serving locally, only firewall rules bearing Jeannie's exact +`homelab-pimox-registry-forward` comment are retired, together with the matching +forwarding service. If the local runtime is k3s, its registry configuration is +merged with the HTTP mirror needed for the existing registry endpoint. Existing +configuration is backed up; custom mirror endpoints are refused. The first +configuration change restarts k3s and waits for API readiness. Repeat runs avoid +that restart. + +Discovery overrides, when inventory uses different locations: + +- `LAB_PIMOX_REGISTRY_STORAGE_PATH`: previous registry directory. +- `LAB_REGISTRY_STORAGE_PATH`: local destination directory. +- `LAB_PIMOX_REGISTRY_SOURCE_VMID`: source VMID (defaults to worker base VMID). + +Registry paths must be specific directories below `/data`. Migration requires +passwordless sudo on the destination, source worker and Proxmox host. This is a +copy, not ongoing replication or failover between registries. diff --git a/bootstrap/apps/main.tf b/bootstrap/apps/main.tf index 88d8953..445375f 100644 --- a/bootstrap/apps/main.tf +++ b/bootstrap/apps/main.tf @@ -30,6 +30,33 @@ locals { kustomize = { images = ["${var.registry_endpoint}/demos-static=${var.demos_image_ref}"] } + } : {}, + name == "container-registry" ? { + kustomize = { + patches = [ + { + target = { kind = "Deployment", name = "local-registry" } + patch = yamlencode([ + { + op = "replace" + path = "/spec/template/spec/affinity/nodeAffinity/requiredDuringSchedulingIgnoredDuringExecution/nodeSelectorTerms/0/matchExpressions/0/values" + value = [var.registry_placement.node] + }, + ]) + }, + { + target = { kind = "PersistentVolume", name = "registry-data-pimox-worker-01" } + patch = yamlencode([ + { op = "replace", path = "/spec/local/path", value = var.registry_placement.path }, + { + op = "replace" + path = "/spec/nodeAffinity/required/nodeSelectorTerms/0/matchExpressions/0/values" + value = [var.registry_placement.node] + }, + ]) + }, + ] + } } : {} ) } diff --git a/bootstrap/apps/variables.tf b/bootstrap/apps/variables.tf index c0b494e..fe541d1 100644 --- a/bootstrap/apps/variables.tf +++ b/bootstrap/apps/variables.tf @@ -28,6 +28,18 @@ variable "registry_endpoint" { default = "192.168.100.73:30500" } +variable "registry_placement" { + description = "Discovered retained registry location, prepared before application deployment. Existing resource identities are preserved." + type = object({ + node = string + path = string + }) + default = { + node = "pimox-worker-01" + path = "/data/openebs/local/registry" + } +} + variable "applications" { type = map(object({ project = string diff --git a/bootstrap/platform/README.md b/bootstrap/platform/README.md index 77fc669..75cbf60 100644 --- a/bootstrap/platform/README.md +++ b/bootstrap/platform/README.md @@ -74,12 +74,12 @@ an uninitialized network plugin. Existing CNI failures remain blocking. Planned OpenTofu StorageClasses are included in the estimate; Loki, Mimir and the Prometheus stack depend on creation of the retained OpenEBS class. -Before deploying applications on a different topology, review the current -registry manifests: their retained PV/PVC and required node affinity explicitly -target `pimox-worker-01`. That data must be migrated deliberately or an alternate -registry must be configured; relabeling a different host cannot move local data. -The Gitea runner also requires an app-node selector and a host Docker socket. -These application requirements are not satisfied merely by installing k3s. +Application deployment now discovers the registry's retained placement and can +copy source data to a fresh single-node destination before Argo changes its +node affinity. See [registry migration](../apps/README.md) for discovery, +verification, restart behavior and refusal cases. The Gitea runner requires +an app-node selector and host Docker socket when enabled; a zero-replica runner +is left disabled across all profiles. The k3s installer currently also enables its bundled metrics-server and ServiceLB, while the platform manages metrics-server and MetalLB. Check live diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index 6bb06f3..791da11 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -7578,6 +7578,34 @@ pimox_primary_worker_inventory() { return 1 } +reconcile_app_registry_storage() { + local inventory source_host source_user source_node source_key result + cluster_context_require || return 1 + inventory="$(pimox_primary_worker_inventory)" || { + echo "Cannot discover the previous registry host; refusing to assume its data is absent." >&2 + return 1 + } + IFS=$'\t' read -r source_host source_user source_node source_key <<<"${inventory}" + result="$(mktemp "${TMPDIR:-/tmp}/jeannie-registry-placement.XXXXXX")" || return 1 + if ! python3 "${REPO_ROOT}/scripts/registry-storage-reconcile.py" \ + --kubeconfig "${KUBECONFIG_PATH}" \ + --destination-node "${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME}" \ + --destination-path "${LAB_REGISTRY_STORAGE_PATH:-/data/openebs/local/registry}" \ + --source-host "${source_host}" --source-user "${source_user}" --source-key "${source_key}" \ + --source-node "${source_node}" --source-path "${LAB_PIMOX_REGISTRY_STORAGE_PATH:-/data/openebs/local/registry}" \ + --hypervisor-host "${LAB_CLUSTER_PIMOX_HOST:-${LAB_PIMOX_HOST:-192.168.100.80}}" \ + --hypervisor-user "${LAB_CLUSTER_PIMOX_USER:-jv}" \ + --hypervisor-key "${LAB_PIMOX_SSH_KEY_PATH:-${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH:-/home/jv/.ssh/id_ed25519}}" \ + --source-vmid "${LAB_PIMOX_REGISTRY_SOURCE_VMID:-${LAB_PIMOX_WORKER_BASE_VMID:-9010}}" \ + --registry-endpoint "${TF_VAR_registry_endpoint:-${LAB_REGISTRY_ENDPOINT}}" \ + --state-dir "${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE}" --result "${result}"; then + rm -f "${result}" + return 1 + fi + export TF_VAR_registry_placement="$(<"${result}")" + rm -f "${result}" +} + ensure_pimox_registry_storage_path() { local enabled="${LAB_PIMOX_REGISTRY_PREPARE_STORAGE:-true}" local inventory @@ -8125,6 +8153,7 @@ apps() { require_argocd_application_controller require_pimox_app_worker_capacity "${app_selector}" if [[ "${deploy_website}" == "true" || "${deploy_demos}" == "true" || "${deploy_registry}" == "true" ]]; then + reconcile_app_registry_storage || return 1 ensure_pimox_registry_storage_path ensure_pimox_registry_endpoint_forwarding "${registry_endpoint}" ensure_pimox_containerd_registry_refresh "${registry_endpoint}" @@ -8289,16 +8318,15 @@ apps() { fi if [[ "${app_selector}" == "all" || "${app_selector}" == "gitea-runner" ]]; then - apply_gitea_runner_secret_file refresh_argocd_application gitea-runner - if [[ "${LAB_CLUSTER_PROFILE:-debian}" == "pimox" ]] && ! truthy "${LAB_APPS_WAIT_GITEA_RUNNER_ON_PIMOX:-false}"; then - wait_for_namespace gitea-runner gitea-runner "${app_resource_wait_seconds}" - wait_for_namespaced_resource gitea-runner deployment gitea-runner gitea-runner "${app_resource_wait_seconds}" - scale_down_disabled_deployment gitea-runner gitea-runner app=gitea-runner gitea-runner - echo "Skipping Gitea Kubernetes runner readiness on Pimox; the current runner manifest needs a Docker socket and is kept scaled down." + wait_for_namespace gitea-runner gitea-runner "${app_resource_wait_seconds}" + wait_for_namespaced_resource gitea-runner deployment gitea-runner gitea-runner "${app_resource_wait_seconds}" + local runner_replicas + runner_replicas="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n gitea-runner get deployment gitea-runner -o jsonpath='{.spec.replicas}')" || return 1 + if [[ "${runner_replicas}" == 0 ]]; then + echo "Gitea Kubernetes runner is disabled (zero replicas); readiness wait skipped." else - wait_for_namespace gitea-runner gitea-runner "${app_resource_wait_seconds}" - wait_for_namespaced_resource gitea-runner deployment gitea-runner gitea-runner "${app_resource_wait_seconds}" + apply_gitea_runner_secret_file wait_for_deployment_ready gitea-runner gitea-runner gitea-runner "${app_ready_wait_seconds}" fi fi diff --git a/scripts/registry-storage-reconcile.py b/scripts/registry-storage-reconcile.py new file mode 100644 index 0000000..a031d81 --- /dev/null +++ b/scripts/registry-storage-reconcile.py @@ -0,0 +1,285 @@ +#!/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) diff --git a/scripts/scheduling-preflight.py b/scripts/scheduling-preflight.py index b482587..3ad0c0e 100644 --- a/scripts/scheduling-preflight.py +++ b/scripts/scheduling-preflight.py @@ -10,6 +10,7 @@ import copy import json import math import re +import shutil import subprocess import sys import tempfile @@ -546,7 +547,7 @@ def manifests_from_plan(args, plan, kubectl): source = item.get("spec", {}).get("source") or {} if not source.get("path") or any(source.get(key) for key in ("helm", "plugin", "directory")): raise CannotCheck(f"{item['metadata']['name']}: only local Kustomize/plain-manifest Application sources are supported") - if set(source.get("kustomize") or {}) - {"images"}: + if set(source.get("kustomize") or {}) - {"images", "patches"}: raise CannotCheck(f"{item['metadata']['name']}: Argo-specific Kustomize placement overrides require separate rendering") path = (Path(args.repo_root) / source["path"]).resolve() if not path.is_relative_to(Path(args.repo_root).resolve()): @@ -570,7 +571,24 @@ def manifests_from_plan(args, plan, kubectl): # A no-op Application CR does not mean its Git workloads are # unchanged. Only trust it when Argo has synced this checkout. already_synced = change.get("actions") == ["no-op"] and not dirty and sync.get("status") == "Synced" and sync.get("revision") == checkout_revision - if any((path / name).exists() for name in ("kustomization.yaml", "kustomization.yml", "Kustomization")): + kustomize = source.get("kustomize") or {} + if kustomize.get("patches"): + # Render the same placement patches Argo will use. Never + # rewrite the checkout or estimate the unpatched source. + if kustomize.get("images"): + raise CannotCheck("Combined image/placement overrides require explicit rendering support") + with tempfile.TemporaryDirectory(prefix="jeannie-app-render-") as temporary: + render_path = Path(temporary) / "source" + shutil.copytree(path, render_path) + filename = next((render_path / n for n in ("kustomization.yaml", "kustomization.yml", "Kustomization") + if (render_path / n).exists()), None) + if filename is None: + raise CannotCheck("Application placement patches require a Kustomization") + config = yaml.safe_load(filename.read_text()) + config["patches"] = (config.get("patches") or []) + kustomize["patches"] + filename.write_text(yaml.safe_dump(config)) + rendered = list(yaml.safe_load_all(run(kubectl + ["kustomize", str(render_path)]))) + elif any((path / name).exists() for name in ("kustomization.yaml", "kustomization.yml", "Kustomization")): rendered = list(yaml.safe_load_all(run(kubectl + ["kustomize", str(path)]))) else: rendered = []