#!/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}")