feat: self-heal stale residual pods
This commit is contained in:
parent
bb7cdce4b6
commit
c077fd9745
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
}
|
||||
3
jeannie
3
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.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
117
scripts/heal
117
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()
|
||||
|
|
|
|||
|
|
@ -27,7 +27,10 @@ DEFAULT_DOCTOR = ["./jeannie", "doctor-homelab", "--json", "--no-local-rca"]
|
|||
SUPPORTED_ALERTS = {
|
||||
"HomelabNodeDiskPressure",
|
||||
"HomelabNodeImageFilesystemPressure",
|
||||
"HomelabStaleResidualPods",
|
||||
"FreeDiskSpaceFailed",
|
||||
"KubePodContainerStatusUnknown",
|
||||
"KubePodEvicted",
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue