diff --git a/bootstrap/platform/grafana-dashboards/homelab-self-heal.json b/bootstrap/platform/grafana-dashboards/homelab-self-heal.json new file mode 100644 index 0000000..b8e1dcf --- /dev/null +++ b/bootstrap/platform/grafana-dashboards/homelab-self-heal.json @@ -0,0 +1,418 @@ +{ + "annotations": { + "list": [ + { + "builtIn": 1, + "datasource": { + "type": "grafana", + "uid": "-- Grafana --" + }, + "enable": true, + "hide": true, + "iconColor": "rgba(0, 211, 255, 1)", + "name": "Annotations & Alerts", + "type": "dashboard" + } + ] + }, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "id": null, + "links": [], + "liveNow": false, + "panels": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 0, + "y": 0 + }, + "id": 1, + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "auto", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "textMode": "auto" + }, + "targets": [ + { + "expr": "sum(jeannie_self_heal_events_total)", + "legendFormat": "events", + "refId": "A" + } + ], + "title": "Self-Heal Events", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 1 + } + ] + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 6, + "y": 0 + }, + "id": 2, + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "auto", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "textMode": "auto" + }, + "targets": [ + { + "expr": "sum(jeannie_self_heal_actions_total{status=\"applied\"})", + "legendFormat": "applied", + "refId": "A" + } + ], + "title": "Applied Actions", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 12, + "y": 0 + }, + "id": 3, + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "auto", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "textMode": "auto" + }, + "targets": [ + { + "expr": "sum(jeannie_self_heal_events_total{status=~\"failed|apply_failed\"})", + "legendFormat": "failed", + "refId": "A" + } + ], + "title": "Failed Events", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": null + }, + { + "color": "green", + "value": 1 + } + ] + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 7, + "w": 6, + "x": 18, + "y": 0 + }, + "id": 4, + "options": { + "colorMode": "value", + "graphMode": "area", + "justifyMode": "auto", + "orientation": "auto", + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "textMode": "auto" + }, + "targets": [ + { + "expr": "max(jeannie_self_heal_info)", + "legendFormat": "up", + "refId": "A" + } + ], + "title": "Webhook Metrics Up", + "type": "stat" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 2, + "showPoints": "never" + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 0, + "y": 7 + }, + "id": 5, + "options": { + "legend": { + "calcs": [ + "lastNotNull" + ], + "displayMode": "table", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "targets": [ + { + "expr": "increase(jeannie_self_heal_events_total[$__range])", + "legendFormat": "{{status}} / {{mode}}", + "refId": "A" + } + ], + "title": "Events By Status", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "custom": { + "drawStyle": "line", + "fillOpacity": 10, + "lineWidth": 2, + "showPoints": "never" + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { + "h": 9, + "w": 12, + "x": 12, + "y": 7 + }, + "id": 6, + "options": { + "legend": { + "calcs": [ + "lastNotNull" + ], + "displayMode": "table", + "placement": "bottom" + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "targets": [ + { + "expr": "increase(jeannie_self_heal_actions_total[$__range])", + "legendFormat": "{{action}} / {{status}}", + "refId": "A" + } + ], + "title": "Applied Actions By Type", + "type": "timeseries" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "fieldConfig": { + "defaults": { + "custom": { + "align": "auto", + "cellOptions": { + "type": "auto" + }, + "inspect": false + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + } + ] + } + }, + "overrides": [] + }, + "gridPos": { + "h": 8, + "w": 24, + "x": 0, + "y": 16 + }, + "id": 7, + "options": { + "cellHeight": "sm", + "footer": { + "countRows": false, + "fields": "", + "reducer": [ + "sum" + ], + "show": false + }, + "showHeader": true + }, + "targets": [ + { + "expr": "jeannie_self_heal_alerts_total", + "format": "table", + "instant": true, + "legendFormat": "__auto", + "refId": "A" + } + ], + "title": "Alert Event Counts", + "type": "table" + } + ], + "refresh": "30s", + "schemaVersion": 39, + "tags": [ + "homelab", + "jeannie", + "self-heal" + ], + "templating": { + "list": [] + }, + "time": { + "from": "now-24h", + "to": "now" + }, + "timepicker": {}, + "timezone": "", + "title": "Homelab Self-Heal", + "uid": "homelab-self-heal", + "version": 1, + "weekStart": "" +} diff --git a/bootstrap/platform/main.tf b/bootstrap/platform/main.tf index aebf1b2..dc66718 100644 --- a/bootstrap/platform/main.tf +++ b/bootstrap/platform/main.tf @@ -1936,6 +1936,25 @@ resource "helm_release" "prometheus_stack" { } ] }, + { + job_name = "jeannie-self-heal" + static_configs = [ + { + targets = ["192.168.100.73:18081"] + labels = { + host_group = "automation" + } + } + ] + metrics_path = "/metrics" + scheme = "http" + relabel_configs = [ + { + source_labels = ["__address__"] + target_label = "instance" + } + ] + }, { job_name = "oci-edge-node" static_configs = [ diff --git a/docs/deployment.md b/docs/deployment.md index e2c15d4..57dfe5a 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -205,6 +205,79 @@ 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/ +``` + +The webhook also exposes Prometheus metrics at `/metrics`. The platform +Prometheus scrape config collects `192.168.100.73:18081`, and the +repo-provisioned `Homelab Self-Heal` Grafana dashboard shows event totals, +applied action totals, failed events, and alert counts. Rebuild dashboards +after pulling this change: + +```bash +./jeannie grafana-dashboards apply +``` + ## Model Behavior Observatory Stable prompts track local model behavior, latency, refusal behavior, and @@ -3602,4 +3675,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..14b61d9 100644 --- a/docs/templates/deployment.md.tmpl +++ b/docs/templates/deployment.md.tmpl @@ -205,6 +205,79 @@ 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/ +``` + +The webhook also exposes Prometheus metrics at `/metrics`. The platform +Prometheus scrape config collects `192.168.100.73:18081`, and the +repo-provisioned `Homelab Self-Heal` Grafana dashboard shows event totals, +applied action totals, failed events, and alert counts. Rebuild dashboards +after pulling this change: + +```bash +./{{ main_script }} grafana-dashboards apply +``` + ## Model Behavior Observatory Stable prompts track local model behavior, latency, refusal behavior, and @@ -3602,4 +3675,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..27bb407 --- /dev/null +++ b/scripts/jeannie-eventd @@ -0,0 +1,325 @@ +#!/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 re +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 prom_escape(value: object) -> str: + text = str(value) + return text.replace("\\", "\\\\").replace("\n", "\\n").replace('"', '\\"') + + +def action_name(command: str) -> str: + if "cleanup-stale-pods" in command: + return "cleanup_stale_pods" + if not command: + return "none" + return re.sub(r"[^a-zA-Z0-9_]+", "_", command.strip()).strip("_")[:80] or "unknown" + + +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 planned_command(plan_output: str) -> str: + for line in plan_output.splitlines(): + line = line.strip() + if line.startswith("command:"): + return line.removeprefix("command:").strip() + return "" + + +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, + "planned_command": planned_command(plan.stdout), + } + 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 result_documents() -> list[tuple[Path, dict[str, Any]]]: + documents: list[tuple[Path, dict[str, Any]]] = [] + if not EVENT_DIR.is_dir(): + return documents + for path in sorted(EVENT_DIR.glob("*/result.json")): + try: + document = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + continue + if isinstance(document, dict): + documents.append((path, document)) + return documents + + +def unix_timestamp_from_audit_dir(path: Path) -> int: + stamp = path.parent.name.split("-", 1)[0] + try: + parsed = dt.datetime.strptime(stamp, "%Y%m%dT%H%M%SZ").replace(tzinfo=dt.UTC) + except ValueError: + return 0 + return int(parsed.timestamp()) + + +def metrics_text() -> str: + documents = result_documents() + event_counts: dict[tuple[str, str], int] = {} + alert_counts: dict[tuple[str, str], int] = {} + action_counts: dict[tuple[str, str], int] = {} + last_timestamp = 0 + last_status = "none" + last_action = "none" + + for path, document in documents: + status = str(document.get("status") or "unknown") + mode = str(document.get("mode") or "unknown") + command = str(document.get("planned_command") or "") + action = action_name(command) + timestamp = unix_timestamp_from_audit_dir(path) + event_counts[(status, mode)] = event_counts.get((status, mode), 0) + 1 + for alert in document.get("alerts") or ["unknown"]: + alert_counts[(str(alert), status)] = alert_counts.get((str(alert), status), 0) + 1 + if mode == "apply": + action_counts[(action, status)] = action_counts.get((action, status), 0) + 1 + if timestamp >= last_timestamp: + last_timestamp = timestamp + last_status = status + last_action = action + + lines = [ + "# HELP jeannie_self_heal_info Jeannie self-heal webhook static info.", + "# TYPE jeannie_self_heal_info gauge", + 'jeannie_self_heal_info{service="jeannie-eventd"} 1', + "# HELP jeannie_self_heal_events_total Count of Jeannie self-heal webhook events by result status and mode.", + "# TYPE jeannie_self_heal_events_total counter", + ] + for (status, mode), count in sorted(event_counts.items()): + lines.append( + f'jeannie_self_heal_events_total{{status="{prom_escape(status)}",mode="{prom_escape(mode)}"}} {count}' + ) + lines.extend( + [ + "# HELP jeannie_self_heal_alerts_total Count of alert names processed by Jeannie self-heal.", + "# TYPE jeannie_self_heal_alerts_total counter", + ] + ) + for (alert, status), count in sorted(alert_counts.items()): + lines.append( + f'jeannie_self_heal_alerts_total{{alertname="{prom_escape(alert)}",status="{prom_escape(status)}"}} {count}' + ) + lines.extend( + [ + "# HELP jeannie_self_heal_actions_total Count of apply-mode Jeannie self-heal actions by action and result.", + "# TYPE jeannie_self_heal_actions_total counter", + ] + ) + for (action, status), count in sorted(action_counts.items()): + lines.append( + f'jeannie_self_heal_actions_total{{action="{prom_escape(action)}",status="{prom_escape(status)}"}} {count}' + ) + lines.extend( + [ + "# HELP jeannie_self_heal_last_event_timestamp_seconds Unix timestamp for latest Jeannie self-heal event.", + "# TYPE jeannie_self_heal_last_event_timestamp_seconds gauge", + f'jeannie_self_heal_last_event_timestamp_seconds{{status="{prom_escape(last_status)}",action="{prom_escape(last_action)}"}} {last_timestamp}', + "", + ] + ) + return "\n".join(lines) + + +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_GET(self) -> None: # noqa: N802 + if self.path != "/metrics": + self.send_error(404) + return + body = metrics_text().encode() + self.send_response(200) + self.send_header("content-type", "text/plain; version=0.0.4; charset=utf-8") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + 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())