#!/usr/bin/env python3 """Inspect or reclaim unused K3s images on the selected native node.""" import argparse import importlib.util from pathlib import Path import re import shlex import subprocess from cluster_runtime_context import resolve, environment REPO = Path(__file__).resolve().parents[1] def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("status", "cleanup")) parser.add_argument("--yes", action="store_true") args = parser.parse_args() cluster = resolve() if cluster["runtime"] != "k3s": raise RuntimeError("Native K3s diagnostics require the selected K3s runtime") spec = importlib.util.spec_from_file_location("native_disk_context", REPO / "scripts/cluster-context.py") context = importlib.util.module_from_spec(spec) spec.loader.exec_module(context) ctx = context.Context(cluster["profile"], cluster["kubeconfig"]) if args.action == "cleanup" and args.yes: ctx.check() else: ctx.observed(startup=True) ssh = ["ssh", "-T", "-i", cluster["key"], "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=accept-new", f"{cluster['user']}@{cluster['host']}"] inspection = """set -eu echo '-- K3s service' systemctl is-active k3s || true echo '-- filesystems' df -hP / /data /var/lib/rancher/k3s findmnt -T /var/lib/rancher/k3s -o TARGET,SOURCE,FSTYPE echo '-- K3s image filesystem' sudo -n k3s crictl imagefsinfo || true echo '-- recent K3s errors' sudo -n journalctl -u k3s --since '30 minutes ago' --no-pager -o cat | grep -Ei 'no space|diskpressure|evict|imagegc|failed|error' | tail -12 || true """ if args.action == "cleanup" and args.yes: mount = cluster["required_mount"] endpoint = cluster["inventory"]["cluster"]["profiles"][cluster["profile"]]["registry"]["endpoint"] if not mount or not re.fullmatch(r"/[A-Za-z0-9_./-]+", mount) or ".." in Path(mount).parts: raise RuntimeError("Native runtime requires a declared data mount before disk healing") script = ("set -eu\nmountpoint -q " + shlex.quote(mount) + "\n" + "curl -fsS --connect-timeout 5 --max-time 10 " + shlex.quote("http://" + endpoint + "/v2/") + " >/dev/null\n" + "sudo -n k3s crictl rmi --prune\n" + "sudo -n journalctl --vacuum-time=7d --vacuum-size=200M\n" + inspection) else: script = inspection if args.action == "cleanup": print("Dry run: --yes prunes unused K3s images after a registry reachability check and vacuums host journals. PV data is not a cleanup target.", flush=True) print(f"Native K3s node: {cluster['node']} ({cluster['host']}); profile={cluster['profile']}", flush=True) subprocess.run([*ssh, "bash -s"], input=script, text=True, check=True, timeout=600, env=environment(cluster["profile"])) if __name__ == "__main__": try: main() except (RuntimeError, OSError, ValueError, KeyError, subprocess.SubprocessError) as error: raise SystemExit(f"Native K3s disk operation refused: {error}")