diff --git a/apps/homelab-alerts/prometheus-rules.yaml b/apps/homelab-alerts/prometheus-rules.yaml index b114433..00c1671 100644 --- a/apps/homelab-alerts/prometheus-rules.yaml +++ b/apps/homelab-alerts/prometheus-rules.yaml @@ -34,6 +34,17 @@ spec: annotations: summary: "Deployment {{ $labels.namespace }}/{{ $labels.deployment }} is unavailable" description: "Available replicas are below desired replicas for 10 minutes." + - alert: HomelabStaleResidualPods + expr: | + sum by (namespace, pod) ( + kube_pod_status_phase{phase=~"Failed|Unknown"} == 1 + ) > 0 + for: 30m + labels: + severity: warning + annotations: + summary: "Stale residual pod {{ $labels.namespace }}/{{ $labels.pod }} needs cleanup" + description: "A pod has stayed Failed or Unknown for 30 minutes. Jeannie can clean controller-owned residual pods after node disruption." - name: homelab.storage rules: - alert: HomelabNodeDiskPressure diff --git a/bootstrap/platform/main.tf b/bootstrap/platform/main.tf index dc66718..667ddd9 100644 --- a/bootstrap/platform/main.tf +++ b/bootstrap/platform/main.tf @@ -1885,6 +1885,37 @@ resource "helm_release" "prometheus_stack" { } } alertmanager = { + config = { + global = {} + route = { + receiver = "null" + group_by = ["alertname", "namespace", "pod", "node"] + group_wait = "30s" + group_interval = "5m" + repeat_interval = "4h" + routes = [ + { + receiver = "jeannie-self-heal" + matchers = ["alertname =~ \"HomelabNodeDiskPressure|FreeDiskSpaceFailed|HomelabStaleResidualPods|KubePodContainerStatusUnknown|KubePodEvicted\""] + repeat_interval = "1h" + } + ] + } + receivers = [ + { + name = "null" + }, + { + name = "jeannie-self-heal" + webhook_configs = [ + { + url = "http://${var.jeannie_self_heal_endpoint}/alertmanager" + send_resolved = false + } + ] + } + ] + } alertmanagerSpec = { nodeSelector = local.prometheus_stack_node_selector resources = { @@ -1940,7 +1971,7 @@ resource "helm_release" "prometheus_stack" { job_name = "jeannie-self-heal" static_configs = [ { - targets = ["192.168.100.73:18081"] + targets = [var.jeannie_self_heal_endpoint] labels = { host_group = "automation" } diff --git a/bootstrap/platform/variables.tf b/bootstrap/platform/variables.tf index 23f444e..f65b659 100644 --- a/bootstrap/platform/variables.tf +++ b/bootstrap/platform/variables.tf @@ -248,6 +248,12 @@ variable "observability" { } } +variable "jeannie_self_heal_endpoint" { + description = "Host:port for the Debian-hosted Jeannie Alertmanager webhook and Prometheus metrics endpoint." + type = string + default = "192.168.100.73:18081" +} + variable "prometheus_stack_node_selector" { description = "Node selector applied to kube-prometheus-stack control workloads so they stay off the control plane." type = map(string) diff --git a/infra/jeannie-eventd/alertmanager-route.example.yaml b/infra/jeannie-eventd/alertmanager-route.example.yaml index 4adb02e..f02e1e4 100644 --- a/infra/jeannie-eventd/alertmanager-route.example.yaml +++ b/infra/jeannie-eventd/alertmanager-route.example.yaml @@ -2,7 +2,7 @@ route: receiver: default routes: - matchers: - - alertname =~ "HomelabNodeDiskPressure|FreeDiskSpaceFailed" + - alertname =~ "HomelabNodeDiskPressure|FreeDiskSpaceFailed|HomelabStaleResidualPods|KubePodContainerStatusUnknown|KubePodEvicted" receiver: jeannie-self-heal repeat_interval: 1h diff --git a/infra/jeannie-eventd/stale-residual-pods.sample.json b/infra/jeannie-eventd/stale-residual-pods.sample.json new file mode 100644 index 0000000..76de638 --- /dev/null +++ b/infra/jeannie-eventd/stale-residual-pods.sample.json @@ -0,0 +1,25 @@ +{ + "receiver": "jeannie-self-heal", + "status": "firing", + "alerts": [ + { + "status": "firing", + "labels": { + "alertname": "HomelabStaleResidualPods", + "severity": "warning" + }, + "annotations": { + "summary": "Kubernetes has stale residual pods after node disruption", + "description": "One or more pods are in Evicted, Failed/Error, Unknown, NodeLost, or ContainerStatusUnknown after a replacement pod is already healthy." + }, + "startsAt": "2026-10-07T00:00:00Z", + "fingerprint": "stale-residual-pods-sample" + } + ], + "commonLabels": { + "alertname": "HomelabStaleResidualPods" + }, + "commonAnnotations": { + "summary": "Kubernetes stale residual pods detected" + } +} diff --git a/jeannie b/jeannie index 2ecd879..cf2f376 100755 --- a/jeannie +++ b/jeannie @@ -92,7 +92,8 @@ Operator View And Reports recover-plan Print disaster recovery order and prerequisites. recover-power [--dry-run] Run or preview post-outage recovery. 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. + self-heal {dry-run|serve|install-service [--apply]} + 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. diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index 65edcb1..a841b87 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -2572,7 +2572,18 @@ heal() { 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 + local apply_mode + local service_file + + apply_mode="${LAB_SELF_HEAL_APPLY:-false}" + if [ "${3:-}" = "--apply" ]; then + apply_mode="true" + fi + service_file="$(mktemp)" + sed "s/^Environment=LAB_SELF_HEAL_APPLY=.*/Environment=LAB_SELF_HEAL_APPLY=${apply_mode}/" \ + "${REPO_ROOT}/infra/jeannie-eventd/jeannie-eventd.service" > "${service_file}" + sudo install -m 0644 "${service_file}" /etc/systemd/system/jeannie-eventd.service + rm -f "${service_file}" sudo systemctl daemon-reload sudo systemctl enable --now jeannie-eventd sudo systemctl status jeannie-eventd --no-pager diff --git a/scripts/heal b/scripts/heal index a2412eb..e2e50ae 100755 --- a/scripts/heal +++ b/scripts/heal @@ -236,10 +236,12 @@ def command_for(row: dict[str, str], rule: HealRule) -> tuple[str, str, int]: ) 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): + if not re.search( + r"\b(Evicted|ContainerStatusUnknown|NodeLost|Unknown|Error)\b", text + ): return ( "./jeannie explain status", - "Problem pods are not stale Evicted/ContainerStatusUnknown records; keep this diagnostic-only.", + "Problem pods are not stale residual pod records; keep this diagnostic-only.", 50, ) return rule.command, rule.reason, rule.priority @@ -433,7 +435,54 @@ def apply_plan(plan: list[dict[str, object]], yes: bool) -> int: return 0 -def stale_pods() -> list[dict[str, str]]: +def controller_owner(metadata: dict[str, object]) -> dict[str, str] | None: + owner_refs = metadata.get("ownerReferences") or [] + if not isinstance(owner_refs, list): + return None + for owner in owner_refs: + if not isinstance(owner, dict): + continue + if owner.get("controller") is True: + return { + "kind": str(owner.get("kind") or ""), + "name": str(owner.get("name") or ""), + } + return None + + +def safe_controller_owned(owner: dict[str, str] | None) -> bool: + return bool(owner and owner.get("kind") in {"DaemonSet", "Job", "ReplicaSet", "StatefulSet"}) + + +def stale_reason(status: dict[str, object]) -> str: + phase = str(status.get("phase", "")) + reason = str(status.get("reason", "")) + reasons = {reason} if reason else set() + for container_status in status.get("containerStatuses", []) or []: + if not isinstance(container_status, dict): + continue + state = container_status.get("state", {}) + if not isinstance(state, dict): + continue + waiting = state.get("waiting") or {} + terminated = state.get("terminated") or {} + if isinstance(waiting, dict) and waiting.get("reason"): + reasons.add(str(waiting.get("reason"))) + if isinstance(terminated, dict) and terminated.get("reason"): + reasons.add(str(terminated.get("reason"))) + + if reason in {"Evicted", "NodeLost"}: + return reason + if phase == "Unknown": + return "Unknown" + if "ContainerStatusUnknown" in reasons: + return "ContainerStatusUnknown" + if phase == "Failed" and reasons & {"Error", "NodeLost", "ContainerStatusUnknown"}: + return ",".join(sorted(reasons & {"Error", "NodeLost", "ContainerStatusUnknown"})) + return "" + + +def stale_pods() -> tuple[list[dict[str, str]], list[dict[str, str]]]: process = subprocess.run( [ "kubectl", @@ -457,49 +506,55 @@ def stale_pods() -> list[dict[str, str]]: document = json.loads(process.stdout) pods: list[dict[str, str]] = [] + skipped: list[dict[str, str]] = [] for item in document.get("items", []): metadata = item.get("metadata", {}) status = item.get("status", {}) + if not isinstance(metadata, dict) or not isinstance(status, dict): + continue + annotations = metadata.get("annotations") or {} + if isinstance(annotations, dict) and annotations.get("kubernetes.io/config.mirror"): + continue 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 + reason = stale_reason(status) + if not reason: + continue + owner = controller_owner(metadata) + pod = { + "namespace": namespace, + "name": name, + "phase": phase, + "reason": reason, + "owner": f"{owner['kind']}/{owner['name']}" if owner else "none", + } + if safe_controller_owned(owner): + pods.append(pod) + else: + skipped.append(pod) + return pods, skipped def cleanup_stale_pods(yes: bool) -> int: - pods = stale_pods() + pods, skipped = stale_pods() print("Jeannie Stale Pod Cleanup") print("=========================") - if not pods: - print("No Evicted or ContainerStatusUnknown pods found.") + if not pods and not skipped: + print("No stale residual pods found.") return 0 print(f"targets={len(pods)}") for pod in pods: - print(f" - {pod['namespace']}/{pod['name']} reason={pod['reason']}") + print( + f" - {pod['namespace']}/{pod['name']} reason={pod['reason']} owner={pod['owner']}" + ) + if skipped: + print(f"skipped={len(skipped)}") + for pod in skipped: + print( + f" - {pod['namespace']}/{pod['name']} reason={pod['reason']} owner={pod['owner']} unsafe-unmanaged" + ) if not yes: print() diff --git a/scripts/jeannie-eventd b/scripts/jeannie-eventd index 27bb407..b4247d3 100755 --- a/scripts/jeannie-eventd +++ b/scripts/jeannie-eventd @@ -27,7 +27,10 @@ DEFAULT_DOCTOR = ["./jeannie", "doctor-homelab", "--json", "--no-local-rca"] SUPPORTED_ALERTS = { "HomelabNodeDiskPressure", "HomelabNodeImageFilesystemPressure", + "HomelabStaleResidualPods", "FreeDiskSpaceFailed", + "KubePodContainerStatusUnknown", + "KubePodEvicted", }