Detach retired Debian Kubernetes service hooks
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-11-03 20:26:44 -06:00
parent 34389f7624
commit 53bd363966
6 changed files with 104 additions and 2 deletions

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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() {

View File

@ -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

View File

@ -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}")