From 53bd363966aebf551ba38399ca6407c694fc65ef Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Tue, 3 Nov 2026 20:26:44 -0600 Subject: [PATCH] Detach retired Debian Kubernetes service hooks --- docs/app-ops.md | 9 ++++ docs/templates/app-ops.md.tmpl | 9 ++++ lib/jeannie/cluster-context.sh | 4 ++ lib/jeannie/commands.sh | 6 ++- lib/jeannie/pipeline.sh | 4 ++ scripts/retire-debian-service-hooks.py | 74 ++++++++++++++++++++++++++ 6 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 scripts/retire-debian-service-hooks.py diff --git a/docs/app-ops.md b/docs/app-ops.md index 5bd1c98..f08de61 100644 --- a/docs/app-ops.md +++ b/docs/app-ops.md @@ -2,6 +2,15 @@ ## Homelab Overview dashboard +When the selected cluster is remote, platform/apps applies and edge route setup +detach retired Kubernetes entry hooks on the Debian deployment laptop after +checking the active cluster identity and confirming local kubelet/K3s and the +API listener are stopped. This prevents old service NAT rules from intercepting +the live Traefik VIP. Docker, Tailscale and registry forwarding rules are kept. +To reconcile immediately, run `LAB_CLUSTER_PROFILE=k3s python3 +scripts/retire-debian-service-hooks.py` on Debian. A private iptables snapshot +is retained under the selected profile's diagnostics directory. + The `Homelab Overview` dashboard (`homelab-overview`) shows host CPU, memory, filesystems and network interfaces, plus Kubernetes node readiness and container usage. It uses Kubernetes node-exporter discovery for whichever diff --git a/docs/templates/app-ops.md.tmpl b/docs/templates/app-ops.md.tmpl index 1a841b9..922fef7 100644 --- a/docs/templates/app-ops.md.tmpl +++ b/docs/templates/app-ops.md.tmpl @@ -2,6 +2,15 @@ ## Homelab Overview dashboard +When the selected cluster is remote, platform/apps applies and edge route setup +detach retired Kubernetes entry hooks on the Debian deployment laptop after +checking the active cluster identity and confirming local kubelet/K3s and the +API listener are stopped. This prevents old service NAT rules from intercepting +the live Traefik VIP. Docker, Tailscale and registry forwarding rules are kept. +To reconcile immediately, run `LAB_CLUSTER_PROFILE=k3s python3 +scripts/retire-debian-service-hooks.py` on Debian. A private iptables snapshot +is retained under the selected profile's diagnostics directory. + The `Homelab Overview` dashboard (`homelab-overview`) shows host CPU, memory, filesystems and network interfaces, plus Kubernetes node readiness and container usage. It uses Kubernetes node-exporter discovery for whichever diff --git a/lib/jeannie/cluster-context.sh b/lib/jeannie/cluster-context.sh index 2566c2a..25c44b2 100644 --- a/lib/jeannie/cluster-context.sh +++ b/lib/jeannie/cluster-context.sh @@ -17,6 +17,10 @@ cluster_context_require_startup() { --kubeconfig "${KUBECONFIG_PATH}" >/dev/null } +retire_debian_service_hooks() { + python3 "${REPO_ROOT}/scripts/retire-debian-service-hooks.py" +} + cluster_context_enable() { export HOMELAB_STATE_DIR LAB_CLUSTER_PROFILE KUBECONFIG_PATH case ":${PATH}:" in diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index 2dfd186..16b34de 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -1131,7 +1131,8 @@ cleanup_debian_k8s_after_pimox_offload() { fi if ! sudo test -e /etc/kubernetes/pki/ca.crt && ! sudo test -d /var/lib/etcd/member; then - echo "No Debian control-plane data remains; skipping retirement cleanup." + retire_debian_service_hooks || return 1 + echo "No Debian control-plane data remains; retired service hooks reconciled." return 0 fi # Retirement touches a different cluster from the active Pimox profile. @@ -1194,7 +1195,8 @@ cleanup_debian_k8s_after_pimox_offload() { sudo ip link delete cni0 2>/dev/null || true sudo ip link delete kube-ipvs0 2>/dev/null || true - echo "Debian Kubernetes runtime cleanup complete. Docker, Gitea, Dex, Tailscale, and edge forwarding rules were left untouched." + retire_debian_service_hooks || return 1 + echo "Debian Kubernetes runtime cleanup complete. Retired service hooks were detached; Docker and Jeannie forwarding rules remain active." } nuke_remote_cleanup_failed() { diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index e50d61f..e850c37 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -780,6 +780,7 @@ run_tofu_stack() { if [[ "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]] || [[ "${stack}" == "bootstrap/cluster" && -f "${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE}/identity.json" ]]; then cluster_context_require || return 1 + retire_debian_service_hooks || return 1 fi # Component applies use OpenTofu targets. Dependencies inside the selected @@ -8625,6 +8626,9 @@ ensure_edge_tailscale_routes() { if disabled_value "${enabled}"; then return 0 fi + if [[ -f "${HOMELAB_STATE_DIR}/clusters/${LAB_CLUSTER_PROFILE}/identity.json" ]]; then + retire_debian_service_hooks || return 1 + fi if ! truthy "${enabled}"; then echo "LAB_EDGE_CONFIGURE_TAILSCALE_ROUTES must be true or false." >&2 exit 1 diff --git a/scripts/retire-debian-service-hooks.py b/scripts/retire-debian-service-hooks.py new file mode 100644 index 0000000..91bbe7c --- /dev/null +++ b/scripts/retire-debian-service-hooks.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Detach retired Kubernetes service hooks from the Debian deployment host.""" + +import importlib.util +import os +from pathlib import Path +import shlex +import subprocess +import time + +import yaml + + +REPO = Path(__file__).resolve().parents[1] + + +def run(command): + return subprocess.run(command, check=True, capture_output=True, text=True, timeout=30).stdout + + +def main(): + inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text()) + profile = os.environ.get("LAB_CLUSTER_PROFILE") or inventory["cluster"]["active_profile"] + if profile == "debian": + return + if profile not in ("pimox", "k3s"): + raise RuntimeError("Select a declared cluster profile") + local_ips = set(run(["hostname", "-I"]).split()) + laptop_ip = inventory["hosts"]["debian"]["lan_ip"] + target_ip = inventory["cluster"]["profiles"][profile]["control_plane"]["lan_ip"] + if laptop_ip not in local_ips or target_ip in local_ips: + raise RuntimeError("Retired service hooks may only be detached on the inactive Debian laptop") + spec = importlib.util.spec_from_file_location("retired_host_context", REPO / "scripts/cluster-context.py") + context = importlib.util.module_from_spec(spec) + spec.loader.exec_module(context) + ctx = context.Context(profile) + ctx.check() + for unit in ("kubelet", "k3s"): + result = subprocess.run(["systemctl", "is-active", unit], capture_output=True, text=True, timeout=10) + if result.stdout.strip() not in ("inactive", "failed", "unknown"): + raise RuntimeError(f"Cannot retire service hooks while Debian {unit} is active or its state is unknown") + if run(["ss", "-lntH", "sport = :6443"]).strip(): + raise RuntimeError("Debian still has a Kubernetes API listener") + saved = run(["sudo", "-n", "iptables-save"]) + table = None + rules = [] + for line in saved.splitlines(): + if line.startswith("*"): + table = line[1:] + elif line == "COMMIT": + table = None + elif line.startswith("-A ") and table in ("nat", "filter", "mangle", "raw"): + rule = shlex.split(line) + if rule[1] in ("INPUT", "OUTPUT", "FORWARD", "PREROUTING", "POSTROUTING") and "-j" in rule: + if rule[rule.index("-j") + 1].startswith("KUBE-"): + rules.append((table, rule)) + if not rules: + return + directory = ctx.root / "diagnostics/retired-debian-network" + directory.mkdir(parents=True, exist_ok=True, mode=0o700) + backup = directory / f"iptables-before-{time.time_ns()}.rules" + descriptor = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(descriptor, "w") as handle: + handle.write(saved) + for table, rule in rules: + run(["sudo", "-n", "iptables", "-t", table, "-D", *rule[1:]]) + print(f"Detached {len(rules)} retired Debian Kubernetes service hooks; snapshot: {backup}", flush=True) + + +if __name__ == "__main__": + try: + main() + except (RuntimeError, OSError, KeyError, ValueError, subprocess.SubprocessError) as error: + raise SystemExit(f"Retired Debian network cleanup refused: {error}")