From 97bb185858323af9163c63bccbff865e64bd27a7 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Wed, 7 Oct 2026 08:56:15 -0600 Subject: [PATCH] feat: add first Jeannie self-heal alert loop --- docs/deployment.md | 64 +++++- docs/templates/deployment.md.tmpl | 64 +++++- infra/agent-sandbox/policy.tsv | 1 + .../alertmanager-route.example.yaml | 14 ++ .../free-disk-space-failed.sample.json | 34 +++ infra/jeannie-eventd/jeannie-eventd.service | 19 ++ jeannie | 6 +- lib/jeannie/commands.sh | 12 ++ scripts/heal | 122 ++++++++++- scripts/jeannie-eventd | 201 ++++++++++++++++++ 10 files changed, 528 insertions(+), 9 deletions(-) create mode 100644 infra/jeannie-eventd/alertmanager-route.example.yaml create mode 100644 infra/jeannie-eventd/free-disk-space-failed.sample.json create mode 100644 infra/jeannie-eventd/jeannie-eventd.service create mode 100755 scripts/jeannie-eventd diff --git a/docs/deployment.md b/docs/deployment.md index e2c15d4..68ee785 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -205,6 +205,69 @@ Failed heal actions are placed on a short cooldown so Jeannie does not loop on the same VM restart; the next plan escalates to diagnostics instead. Destructive actions remain blocked. +### Alertmanager-driven first self-heal loop + +The first headless self-heal path is intentionally narrow and targets node image +filesystem pressure / `FreeDiskSpaceFailed` symptoms. Alertmanager can call the +Debian-hosted `jeannie-eventd` webhook, which runs `doctor-homelab` in JSON +mode, feeds the findings into `scripts/heal`, and applies only one +allowlisted action per event. + +For the first phase, the only automatic mutation is: + +- delete stale Kubernetes pod records where the reason is `Evicted`, + `NodeLost`, `Unknown`, or `ContainerStatusUnknown`. + +It does not prune container images, delete PVCs, delete namespaces, mutate +OpenTofu state, or SSH into nodes for disk cleanup. If image garbage collection +already freed zero bytes, Jeannie reports the node/image/log investigation path +instead of guessing. + +Test the event pipeline without mutating anything: + +```bash +./jeannie self-heal dry-run infra/jeannie-eventd/free-disk-space-failed.sample.json +``` + +Preview stale pod cleanup directly: + +```bash +./jeannie heal cleanup-stale-pods +``` + +Apply the narrow cleanup when the dry-run targets are correct: + +```bash +./jeannie heal cleanup-stale-pods --yes +``` + +Run the webhook locally in dry-run mode: + +```bash +./jeannie self-heal serve +``` + +Install or refresh the Debian systemd webhook service through Jeannie: + +```bash +./jeannie self-heal install-service +``` + +Enable apply mode only after the dry-run output and audit files look correct: + +```bash +LAB_SELF_HEAL_APPLY=true ./jeannie self-heal serve +``` + +The systemd example binds the webhook to the Debian LAN address path so the +cluster can reach it. Keep it limited to the homelab network/firewall. + +Audit artifacts are written under: + +```text +${HOMELAB_STATE_DIR:-~/.local/share/homelab}/self-heal-events/ +``` + ## Model Behavior Observatory Stable prompts track local model behavior, latency, refusal behavior, and @@ -3602,4 +3665,3 @@ under `/data/openebs/local`. For multi-node labs, set `WORKER_SSH_TARGETS` to a space-separated list of SSH targets. It defaults to an empty string so worker nodes are not cleaned unless you explicitly include them. - diff --git a/docs/templates/deployment.md.tmpl b/docs/templates/deployment.md.tmpl index f0fabf0..47ee947 100644 --- a/docs/templates/deployment.md.tmpl +++ b/docs/templates/deployment.md.tmpl @@ -205,6 +205,69 @@ Failed heal actions are placed on a short cooldown so Jeannie does not loop on the same VM restart; the next plan escalates to diagnostics instead. Destructive actions remain blocked. +### Alertmanager-driven first self-heal loop + +The first headless self-heal path is intentionally narrow and targets node image +filesystem pressure / `FreeDiskSpaceFailed` symptoms. Alertmanager can call the +Debian-hosted `jeannie-eventd` webhook, which runs `doctor-homelab` in JSON +mode, feeds the findings into `scripts/heal`, and applies only one +allowlisted action per event. + +For the first phase, the only automatic mutation is: + +- delete stale Kubernetes pod records where the reason is `Evicted`, + `NodeLost`, `Unknown`, or `ContainerStatusUnknown`. + +It does not prune container images, delete PVCs, delete namespaces, mutate +OpenTofu state, or SSH into nodes for disk cleanup. If image garbage collection +already freed zero bytes, Jeannie reports the node/image/log investigation path +instead of guessing. + +Test the event pipeline without mutating anything: + +```bash +./{{ main_script }} self-heal dry-run infra/jeannie-eventd/free-disk-space-failed.sample.json +``` + +Preview stale pod cleanup directly: + +```bash +./{{ main_script }} heal cleanup-stale-pods +``` + +Apply the narrow cleanup when the dry-run targets are correct: + +```bash +./{{ main_script }} heal cleanup-stale-pods --yes +``` + +Run the webhook locally in dry-run mode: + +```bash +./{{ main_script }} self-heal serve +``` + +Install or refresh the Debian systemd webhook service through Jeannie: + +```bash +./{{ main_script }} self-heal install-service +``` + +Enable apply mode only after the dry-run output and audit files look correct: + +```bash +LAB_SELF_HEAL_APPLY=true ./{{ main_script }} self-heal serve +``` + +The systemd example binds the webhook to the Debian LAN address path so the +cluster can reach it. Keep it limited to the homelab network/firewall. + +Audit artifacts are written under: + +```text +${HOMELAB_STATE_DIR:-~/.local/share/homelab}/self-heal-events/ +``` + ## Model Behavior Observatory Stable prompts track local model behavior, latency, refusal behavior, and @@ -3602,4 +3665,3 @@ under `/data/openebs/local`. For multi-node labs, set `WORKER_SSH_TARGETS` to a space-separated list of SSH targets. It defaults to an empty string so worker nodes are not cleaned unless you explicitly include them. - diff --git a/infra/agent-sandbox/policy.tsv b/infra/agent-sandbox/policy.tsv index b4a84cc..5faa6c0 100644 --- a/infra/agent-sandbox/policy.tsv +++ b/infra/agent-sandbox/policy.tsv @@ -1,6 +1,7 @@ pattern decision reason ./jeannie status allow Read-only health report. ./jeannie doctor- allow Read-only focused doctor command. +./jeannie heal cleanup-stale-pods allow Deletes only stale Evicted/ContainerStatusUnknown pod records through the guarded heal engine. ./jeannie capacity allow Read-only capacity report. ./jeannie validate allow Read-only repository validation. ./jeannie safety-case allow Read-only change safety review. diff --git a/infra/jeannie-eventd/alertmanager-route.example.yaml b/infra/jeannie-eventd/alertmanager-route.example.yaml new file mode 100644 index 0000000..4adb02e --- /dev/null +++ b/infra/jeannie-eventd/alertmanager-route.example.yaml @@ -0,0 +1,14 @@ +route: + receiver: default + routes: + - matchers: + - alertname =~ "HomelabNodeDiskPressure|FreeDiskSpaceFailed" + receiver: jeannie-self-heal + repeat_interval: 1h + +receivers: + - name: default + - name: jeannie-self-heal + webhook_configs: + - url: http://192.168.100.73:18081/alertmanager + send_resolved: false diff --git a/infra/jeannie-eventd/free-disk-space-failed.sample.json b/infra/jeannie-eventd/free-disk-space-failed.sample.json new file mode 100644 index 0000000..09ac083 --- /dev/null +++ b/infra/jeannie-eventd/free-disk-space-failed.sample.json @@ -0,0 +1,34 @@ +{ + "receiver": "jeannie-self-heal", + "status": "firing", + "alerts": [ + { + "status": "firing", + "labels": { + "alertname": "FreeDiskSpaceFailed", + "node": "pimox-worker-01", + "severity": "warning" + }, + "annotations": { + "summary": "Node pimox-worker-01 image filesystem is nearly full", + "description": "Insufficient free disk space on the node's image filesystem. Failed to free sufficient space by deleting unused images.", + "reason": "FreeDiskSpaceFailed" + }, + "startsAt": "2026-10-07T00:00:00Z", + "fingerprint": "free-disk-space-failed-sample" + } + ], + "groupLabels": { + "alertname": "FreeDiskSpaceFailed" + }, + "commonLabels": { + "alertname": "FreeDiskSpaceFailed", + "node": "pimox-worker-01", + "severity": "warning" + }, + "commonAnnotations": { + "summary": "Node pimox-worker-01 image filesystem is nearly full" + }, + "version": "4", + "groupKey": "sample" +} diff --git a/infra/jeannie-eventd/jeannie-eventd.service b/infra/jeannie-eventd/jeannie-eventd.service new file mode 100644 index 0000000..6f7b84e --- /dev/null +++ b/infra/jeannie-eventd/jeannie-eventd.service @@ -0,0 +1,19 @@ +[Unit] +Description=Jeannie Alertmanager self-heal webhook +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=jv +WorkingDirectory=/home/jv/my-homelab-configs +Environment=LAB_CLUSTER_PROFILE=pimox +Environment=LAB_SELF_HEAL_HOST=0.0.0.0 +Environment=LAB_SELF_HEAL_PORT=18081 +Environment=LAB_SELF_HEAL_APPLY=false +ExecStart=/home/jv/my-homelab-configs/scripts/jeannie-eventd serve +Restart=on-failure +RestartSec=10 + +[Install] +WantedBy=multi-user.target diff --git a/jeannie b/jeannie index 62c3566..2ecd879 100755 --- a/jeannie +++ b/jeannie @@ -91,7 +91,8 @@ Operator View And Reports capacity-limits [namespace] Recommend requests/limits YAML snippets. recover-plan Print disaster recovery order and prerequisites. recover-power [--dry-run] Run or preview post-outage recovery. - heal {plan|apply} Plan/apply guarded self-healing actions. + heal {plan|apply|cleanup-stale-pods} Plan/apply guarded self-healing actions. + self-heal {dry-run|serve|install-service} Run Alertmanager-driven Jeannie self-heal loop. incident {list|replay|triage} Classify incident text and suggest read-only next steps. safety-case [--since REF] [PATH...] Generate risk, blast-radius, test, and rollback case. agent-sandbox {check|policy} Classify proposed commands against agent policy. @@ -315,6 +316,9 @@ case "${1:-}" in heal) heal "$@" ;; + self-heal) + self_heal "$@" + ;; incident) incident_commander "$@" ;; diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index 8e661c3..65edcb1 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -2569,6 +2569,18 @@ heal() { "${REPO_ROOT}/scripts/heal" "${@:2}" } +self_heal() { + require_debian_server "self-heal" + if [ "${2:-}" = "install-service" ]; then + sudo install -m 0644 "${REPO_ROOT}/infra/jeannie-eventd/jeannie-eventd.service" /etc/systemd/system/jeannie-eventd.service + sudo systemctl daemon-reload + sudo systemctl enable --now jeannie-eventd + sudo systemctl status jeannie-eventd --no-pager + return + fi + "${REPO_ROOT}/scripts/jeannie-eventd" "${@:2}" +} + validate_homelab() { "${REPO_ROOT}/scripts/validate-homelab" } diff --git a/scripts/heal b/scripts/heal index 8439da7..a2412eb 100755 --- a/scripts/heal +++ b/scripts/heal @@ -148,11 +148,11 @@ RULES = [ ), HealRule( "No problem pods", - "./jeannie explain status", - "diagnostic", - "Pod states need root-cause context; avoid blind deletes.", - False, - 50, + "./jeannie heal cleanup-stale-pods --yes", + "low", + "Only deletes stale Evicted/ContainerStatusUnknown pods; live pods and PVCs are untouched.", + True, + 88, ), HealRule( "Recent deployments healthy", @@ -234,6 +234,14 @@ def command_for(row: dict[str, str], rule: HealRule) -> tuple[str, str, int]: f"Restart Pimox VM for pimox-worker-{index:02d}; a running VM with a NotReady kubelet can be wedged.", 98, ) + if rule.check == "No problem pods": + text = " ".join(str(row.get(key, "")) for key in ("summary", "detail", "check")) + if not re.search(r"\b(Evicted|ContainerStatusUnknown)\b", text): + return ( + "./jeannie explain status", + "Problem pods are not stale Evicted/ContainerStatusUnknown records; keep this diagnostic-only.", + 50, + ) return rule.command, rule.reason, rule.priority @@ -260,9 +268,14 @@ def build_plan(status: dict[str, object]) -> list[dict[str, object]]: continue command, reason, priority = command_for(row, rule) auto = rule.auto + risk = rule.risk + if rule.check == "No problem pods" and command == "./jeannie explain status": + auto = False + risk = "diagnostic" if command in blocked: failed_finding = blocked[command] auto = False + risk = "diagnostic" command = "./jeannie doctor-cluster --details" reason = f"Previous heal action did not clear this finding recently; escalate to diagnostics before retrying. Last failure: {failed_finding}" priority = max(priority - 20, 1) @@ -275,7 +288,7 @@ def build_plan(status: dict[str, object]) -> list[dict[str, object]]: "area": row.get("area", ""), "status": row.get("status", ""), "command": command, - "risk": rule.risk, + "risk": risk, "auto": auto, "priority": priority, "reason": reason, @@ -420,6 +433,98 @@ def apply_plan(plan: list[dict[str, object]], yes: bool) -> int: return 0 +def stale_pods() -> list[dict[str, str]]: + process = subprocess.run( + [ + "kubectl", + "--kubeconfig", + str(DEFAULT_KUBECONFIG), + "get", + "pods", + "-A", + "-o", + "json", + ], + cwd=REPO_ROOT, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=False, + ) + if process.returncode != 0: + print(process.stderr.strip() or "kubectl get pods failed", file=sys.stderr) + raise SystemExit(process.returncode) + + document = json.loads(process.stdout) + pods: list[dict[str, str]] = [] + for item in document.get("items", []): + metadata = item.get("metadata", {}) + status = item.get("status", {}) + namespace = str(metadata.get("namespace", "default")) + name = str(metadata.get("name", "")) + phase = str(status.get("phase", "")) + reason = str(status.get("reason", "")) + reasons = {reason} if reason else set() + for container_status in status.get("containerStatuses", []) or []: + state = container_status.get("state", {}) + waiting = state.get("waiting") or {} + terminated = state.get("terminated") or {} + if waiting.get("reason"): + reasons.add(str(waiting.get("reason"))) + if terminated.get("reason"): + reasons.add(str(terminated.get("reason"))) + if ( + reason in {"Evicted", "NodeLost"} + or phase == "Unknown" + or "ContainerStatusUnknown" in reasons + ): + pods.append( + { + "namespace": namespace, + "name": name, + "phase": phase, + "reason": reason or ",".join(sorted(reasons)), + } + ) + return pods + + +def cleanup_stale_pods(yes: bool) -> int: + pods = stale_pods() + print("Jeannie Stale Pod Cleanup") + print("=========================") + if not pods: + print("No Evicted or ContainerStatusUnknown pods found.") + return 0 + + print(f"targets={len(pods)}") + for pod in pods: + print(f" - {pod['namespace']}/{pod['name']} reason={pod['reason']}") + + if not yes: + print() + print("Dry run only. Re-run with: ./jeannie heal cleanup-stale-pods --yes") + return 0 + + for pod in pods: + command = [ + "kubectl", + "--kubeconfig", + str(DEFAULT_KUBECONFIG), + "-n", + pod["namespace"], + "delete", + "pod", + pod["name"], + "--ignore-not-found=true", + ] + print("+ " + " ".join(command)) + process = subprocess.run(command, cwd=REPO_ROOT, text=True, check=False) + if process.returncode != 0: + return process.returncode + return 0 + + def load_heal_state() -> dict[str, object]: if not HEAL_STATE_FILE.is_file(): return {"failed_actions": {}} @@ -551,8 +656,13 @@ def main() -> int: apply_parser.add_argument("--status-json", type=Path) apply_parser.add_argument("--yes", action="store_true") apply_parser.add_argument("--ai", action="store_true") + cleanup_parser = subparsers.add_parser("cleanup-stale-pods") + cleanup_parser.add_argument("--yes", action="store_true") args = parser.parse_args() + if args.command == "cleanup-stale-pods": + return cleanup_stale_pods(args.yes) + status = load_status(getattr(args, "status_json", None)) plan = build_plan(status) if args.command == "plan": diff --git a/scripts/jeannie-eventd b/scripts/jeannie-eventd new file mode 100755 index 0000000..efd71c2 --- /dev/null +++ b/scripts/jeannie-eventd @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Headless Alertmanager webhook runner for Jeannie-native self-healing.""" + +from __future__ import annotations + +import argparse +import datetime as dt +import hashlib +import json +import os +import subprocess +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any + +REPO_ROOT = Path(__file__).resolve().parents[1] +STATE_DIR = Path( + os.environ.get( + "HOMELAB_STATE_DIR", + Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "homelab", + ) +) +EVENT_DIR = Path(os.environ.get("LAB_SELF_HEAL_EVENT_DIR", STATE_DIR / "self-heal-events")) +DEFAULT_DOCTOR = ["./jeannie", "doctor-homelab", "--json", "--no-local-rca"] + +SUPPORTED_ALERTS = { + "HomelabNodeDiskPressure", + "HomelabNodeImageFilesystemPressure", + "FreeDiskSpaceFailed", +} + + +def utc_stamp() -> str: + return dt.datetime.now(dt.UTC).strftime("%Y%m%dT%H%M%SZ") + + +def event_key(payload: dict[str, Any]) -> str: + alerts = payload.get("alerts") or [] + if alerts and isinstance(alerts, list): + fingerprint = str(alerts[0].get("fingerprint") or "") + if fingerprint: + return fingerprint + labels = alerts[0].get("labels") or {} + if isinstance(labels, dict): + label_blob = json.dumps(labels, sort_keys=True) + return hashlib.sha256(label_blob.encode()).hexdigest()[:16] + return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:16] + + +def alert_names(payload: dict[str, Any]) -> set[str]: + names: set[str] = set() + for alert in payload.get("alerts") or []: + if not isinstance(alert, dict): + continue + labels = alert.get("labels") or {} + annotations = alert.get("annotations") or {} + for value in ( + labels.get("alertname"), + labels.get("reason"), + annotations.get("reason"), + ): + if value: + names.add(str(value)) + blob = json.dumps(alert, sort_keys=True) + if "FreeDiskSpaceFailed" in blob: + names.add("FreeDiskSpaceFailed") + return names + + +def supported(payload: dict[str, Any]) -> bool: + return bool(alert_names(payload) & SUPPORTED_ALERTS) + + +def write_text(path: Path, text: str) -> None: + path.write_text(text, encoding="utf-8") + + +def run_command(command: list[str], audit_dir: Path, name: str) -> subprocess.CompletedProcess[str]: + process = subprocess.run( + command, + cwd=REPO_ROOT, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=False, + ) + write_text(audit_dir / f"{name}.cmd", " ".join(command) + "\n") + write_text(audit_dir / f"{name}.log", process.stdout) + write_text(audit_dir / f"{name}.status", f"{process.returncode}\n") + return process + + +def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]: + key = event_key(payload) + audit_dir = EVENT_DIR / f"{utc_stamp()}-{key}" + audit_dir.mkdir(parents=True, exist_ok=True) + (audit_dir / "alertmanager.json").write_text( + json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + names = sorted(alert_names(payload)) + if not supported(payload): + result = { + "status": "skipped", + "reason": "alert is not in first-phase self-heal allowlist", + "alerts": names, + "audit_dir": str(audit_dir), + } + write_text(audit_dir / "result.json", json.dumps(result, indent=2) + "\n") + return result + + doctor = run_command(DEFAULT_DOCTOR, audit_dir, "doctor-homelab") + if doctor.returncode != 0 and not doctor.stdout.strip(): + result = { + "status": "failed", + "reason": "doctor-homelab produced no JSON", + "alerts": names, + "audit_dir": str(audit_dir), + } + write_text(audit_dir / "result.json", json.dumps(result, indent=2) + "\n") + return result + + status_json = audit_dir / "doctor-homelab.log" + plan = run_command( + ["./scripts/heal", "plan", "--status-json", str(status_json)], + audit_dir, + "heal-plan", + ) + result: dict[str, Any] = { + "status": "planned", + "mode": "dry-run", + "alerts": names, + "audit_dir": str(audit_dir), + "doctor_status": doctor.returncode, + "plan_status": plan.returncode, + } + if apply: + apply_result = run_command( + ["./scripts/heal", "apply", "--status-json", str(status_json), "--yes"], + audit_dir, + "heal-apply", + ) + result["status"] = "applied" if apply_result.returncode == 0 else "apply_failed" + result["mode"] = "apply" + result["apply_status"] = apply_result.returncode + + write_text(audit_dir / "result.json", json.dumps(result, indent=2, sort_keys=True) + "\n") + return result + + +def load_payload(path: str) -> dict[str, Any]: + if path == "-": + return json.loads(os.sys.stdin.read()) + return json.loads(Path(path).read_text(encoding="utf-8")) + + +class Handler(BaseHTTPRequestHandler): + apply = False + + def do_POST(self) -> None: # noqa: N802 + length = int(self.headers.get("content-length", "0")) + payload = json.loads(self.rfile.read(length)) + result = handle_payload(payload, apply=self.apply) + body = json.dumps(result, indent=2, sort_keys=True).encode() + self.send_response(200) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + print(f"jeannie-eventd: {format % args}") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + subparsers = parser.add_subparsers(dest="command", required=True) + dry_run = subparsers.add_parser("dry-run") + dry_run.add_argument("alert_json") + dry_run.add_argument("--apply", action="store_true") + serve = subparsers.add_parser("serve") + serve.add_argument("--host", default=os.environ.get("LAB_SELF_HEAL_HOST", "127.0.0.1")) + serve.add_argument("--port", type=int, default=int(os.environ.get("LAB_SELF_HEAL_PORT", "18081"))) + serve.add_argument("--apply", action="store_true") + args = parser.parse_args() + + if args.command == "dry-run": + result = handle_payload(load_payload(args.alert_json), apply=args.apply) + print(json.dumps(result, indent=2, sort_keys=True)) + return 0 + + if args.command == "serve": + Handler.apply = bool(args.apply or os.environ.get("LAB_SELF_HEAL_APPLY") == "true") + server = ThreadingHTTPServer((args.host, args.port), Handler) + print(f"jeannie-eventd listening on http://{args.host}:{args.port} apply={Handler.apply}") + server.serve_forever() + return 2 + + +if __name__ == "__main__": + raise SystemExit(main())