268 lines
12 KiB
Python
268 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Monitoring readiness checks with opt-in recovery of stale unscheduled Grafana pods."""
|
|
|
|
import argparse
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
|
|
def owned(name, release):
|
|
return any(
|
|
name.startswith(prefix)
|
|
for prefix in (release + "-", "prometheus-" + release + "-", "alertmanager-" + release + "-")
|
|
)
|
|
|
|
|
|
def readiness_errors(items, release):
|
|
"""Check desired controller state, including Operator-created StatefulSets."""
|
|
errors = []
|
|
roles = set()
|
|
for item in items:
|
|
metadata = item.get("metadata", {})
|
|
name = metadata.get("name", "")
|
|
if not owned(name, release):
|
|
continue
|
|
kind = item.get("kind", "")
|
|
if name.startswith("prometheus-" + release + "-") and kind == "StatefulSet":
|
|
roles.add("Prometheus")
|
|
if name == release + "-grafana":
|
|
roles.add("Grafana")
|
|
if name.endswith("-operator") and kind == "Deployment":
|
|
roles.add("Prometheus Operator")
|
|
|
|
spec = item.get("spec", {})
|
|
status = item.get("status", {})
|
|
desired = spec.get("replicas", 1)
|
|
if kind == "DaemonSet":
|
|
desired = status.get("desiredNumberScheduled", 0)
|
|
ready = status.get("numberReady", 0)
|
|
updated = status.get("updatedNumberScheduled", 0)
|
|
else:
|
|
ready = status.get("readyReplicas", 0)
|
|
updated = status.get("updatedReplicas", 0)
|
|
observed = status.get("observedGeneration", 0) >= metadata.get("generation", 1)
|
|
complete = observed and ready >= desired and updated >= desired
|
|
if kind == "Deployment":
|
|
complete = complete and status.get("replicas", 0) == desired
|
|
if kind == "StatefulSet" and desired:
|
|
complete = complete and status.get("currentRevision") == status.get("updateRevision")
|
|
if kind == "DaemonSet" and not desired:
|
|
complete = False
|
|
if name == release + "-grafana" and not desired:
|
|
complete = False
|
|
if name.startswith("prometheus-" + release + "-") and not desired:
|
|
complete = False
|
|
if not complete:
|
|
errors.append(f"{kind}/{name}: ready={ready}/{desired} updated={updated} observed={observed}")
|
|
|
|
for role in sorted({"Prometheus", "Grafana", "Prometheus Operator"} - roles):
|
|
errors.append(f"{role}: workload not created yet")
|
|
return errors
|
|
|
|
|
|
def kubectl(args, *command, input_text=None):
|
|
result = subprocess.run(
|
|
["kubectl", "--kubeconfig", args.kubeconfig, "--request-timeout=10s", *command],
|
|
capture_output=True,
|
|
text=True,
|
|
input=input_text,
|
|
timeout=15,
|
|
check=False,
|
|
)
|
|
if result.returncode:
|
|
raise RuntimeError(result.stderr.strip()[:1500])
|
|
return json.loads(result.stdout)
|
|
|
|
|
|
def stale_pending_grafana(statefulset, pod, release):
|
|
"""Only an old, unscheduled pod of the single-replica Grafana is eligible."""
|
|
metadata = statefulset.get("metadata", {})
|
|
spec = statefulset.get("spec", {})
|
|
status = statefulset.get("status", {})
|
|
pod_meta = pod.get("metadata", {})
|
|
pod_spec = pod.get("spec", {})
|
|
pod_status = pod.get("status", {})
|
|
strategy = spec.get("updateStrategy", {})
|
|
target_revision = status.get("updateRevision")
|
|
old_revision = pod_meta.get("labels", {}).get("controller-revision-hash")
|
|
target_priority = spec.get("template", {}).get("spec", {}).get("priorityClassName")
|
|
return (
|
|
statefulset.get("kind") == "StatefulSet"
|
|
and metadata.get("name") == release + "-grafana"
|
|
and bool(metadata.get("uid"))
|
|
and not metadata.get("deletionTimestamp")
|
|
and spec.get("replicas", 1) == 1
|
|
and strategy.get("type", "RollingUpdate") == "RollingUpdate"
|
|
and strategy.get("rollingUpdate", {}).get("partition", 0) == 0
|
|
and status.get("observedGeneration", 0) >= metadata.get("generation", 1)
|
|
and bool(target_revision)
|
|
and bool(old_revision)
|
|
and old_revision != target_revision
|
|
and target_priority == "homelab-monitoring"
|
|
and pod_spec.get("priorityClassName") != target_priority
|
|
and pod_meta.get("name") == release + "-grafana-0"
|
|
and bool(pod_meta.get("namespace"))
|
|
and pod_meta.get("namespace") == metadata.get("namespace")
|
|
and bool(pod_meta.get("uid"))
|
|
and bool(pod_meta.get("resourceVersion"))
|
|
and not pod_meta.get("deletionTimestamp")
|
|
and not pod_spec.get("nodeName")
|
|
and pod_status.get("phase") == "Pending"
|
|
and any(c.get("type") == "PodScheduled" and c.get("status") == "False"
|
|
and c.get("reason") == "Unschedulable"
|
|
for c in pod_status.get("conditions", []))
|
|
and any(owner.get("kind") == "StatefulSet" and owner.get("controller") is True
|
|
and owner.get("uid") == metadata["uid"]
|
|
for owner in pod_meta.get("ownerReferences", []))
|
|
)
|
|
|
|
|
|
def recover_stale_grafana(args, items):
|
|
name = args.release + "-grafana"
|
|
statefulset = next((item for item in items if item.get("kind") == "StatefulSet"
|
|
and item.get("metadata", {}).get("name") == name), None)
|
|
if not statefulset:
|
|
return
|
|
status = statefulset.get("status", {})
|
|
if not status.get("updateRevision") or status.get("currentRevision") == status["updateRevision"]:
|
|
return
|
|
pods = kubectl(args, "-n", args.namespace, "get", "pods", "--field-selector",
|
|
"metadata.name=" + name + "-0", "-o", "json")["items"]
|
|
if not pods:
|
|
return
|
|
# Re-read the StatefulSet so eligibility follows its latest desired state.
|
|
statefulset = kubectl(args, "-n", args.namespace, "get", "statefulset", name, "-o", "json")
|
|
pod = pods[0]
|
|
if not stale_pending_grafana(statefulset, pod, args.release):
|
|
return
|
|
metadata = pod["metadata"]
|
|
options = {
|
|
"apiVersion": "v1",
|
|
"kind": "DeleteOptions",
|
|
"preconditions": {"uid": metadata["uid"], "resourceVersion": metadata["resourceVersion"]},
|
|
"propagationPolicy": "Orphan",
|
|
}
|
|
path = "/api/v1/namespaces/" + quote(args.namespace, safe="") + "/pods/" + quote(metadata["name"], safe="")
|
|
guard = subprocess.run(
|
|
[sys.executable, str(Path(__file__).resolve().with_name("cluster-context.py")),
|
|
"check", "--kubeconfig", args.kubeconfig],
|
|
text=True, stdout=subprocess.DEVNULL, check=False,
|
|
)
|
|
if guard.returncode:
|
|
raise RuntimeError("Cluster identity check refused Grafana recovery")
|
|
print(f"Recovering stale unscheduled Grafana pod {metadata['name']}; PVC preserved.", flush=True)
|
|
try:
|
|
# UID/RV preconditions prevent deleting a replacement or a pod that
|
|
# became scheduled after the eligibility check. No force deletion.
|
|
kubectl(args, "delete", "--raw", path, "-f", "-", input_text=json.dumps(options))
|
|
except RuntimeError as exc:
|
|
if "(Conflict)" in str(exc) or "(NotFound)" in str(exc):
|
|
print("Grafana pod changed during recovery; rechecking controller state.", flush=True)
|
|
return
|
|
raise
|
|
|
|
|
|
def diagnostics(args):
|
|
"""Print scheduling inputs without container environments or secret data."""
|
|
print("Monitoring scheduling diagnostics:", file=sys.stderr)
|
|
for resource in ("pods", "pvc", "events"):
|
|
try:
|
|
items = kubectl(args, "-n", args.namespace, "get", resource, "-o", "json")["items"]
|
|
if resource == "events":
|
|
items = sorted(items, key=lambda x: x.get("lastTimestamp") or x["metadata"].get("creationTimestamp", ""))
|
|
# Background audit events can fill the diagnostic tail and
|
|
# hide actual scheduling, admission, mount, or container errors.
|
|
items = [item for item in items if item.get("type") == "Warning"
|
|
and item.get("reason") != "PolicyViolation"]
|
|
for item in items[-10:]:
|
|
target = item.get("involvedObject", {}).get("name", "")
|
|
print(f"event {target} {item.get('reason')}: {item.get('message', '')[:1000]}", file=sys.stderr)
|
|
continue
|
|
for item in items:
|
|
name = item["metadata"]["name"]
|
|
if not owned(name, args.release) and not name.startswith("storage-" + args.release + "-"):
|
|
continue
|
|
spec = item.get("spec", {})
|
|
status = item.get("status", {})
|
|
record = {"name": name, "phase": status.get("phase")}
|
|
if resource == "pods":
|
|
conditions = status.get("conditions", [])
|
|
if status.get("phase") in ("Succeeded", "Failed") or any(
|
|
c.get("type") == "Ready" and c.get("status") == "True"
|
|
for c in conditions
|
|
):
|
|
continue
|
|
record.update(
|
|
node=spec.get("nodeName"),
|
|
selector=spec.get("nodeSelector"),
|
|
priority=spec.get("priorityClassName"),
|
|
revision=item["metadata"].get("labels", {}).get("controller-revision-hash"),
|
|
conditions=[{"type": c.get("type"), "reason": c.get("reason"),
|
|
"message": c.get("message")}
|
|
for c in conditions if c.get("status") != "True"],
|
|
containers=[{"name": c.get("name"), "state": c.get("state")}
|
|
for c in status.get("initContainerStatuses", [])
|
|
+ status.get("containerStatuses", []) if not c.get("ready")],
|
|
requests=[c.get("resources", {}).get("requests", {}) for c in spec.get("containers", [])],
|
|
)
|
|
else:
|
|
record["volume"] = spec.get("volumeName")
|
|
print(json.dumps(record), file=sys.stderr)
|
|
except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError) as exc:
|
|
print(f"Cannot read {resource}: {exc}", file=sys.stderr)
|
|
try:
|
|
volumes = kubectl(args, "get", "pv", "-o", "json")["items"]
|
|
for volume in volumes:
|
|
claim = volume.get("spec", {}).get("claimRef", {})
|
|
if claim.get("namespace") == args.namespace:
|
|
print(json.dumps({"claim": claim.get("name"), "nodeAffinity": volume["spec"].get("nodeAffinity")}), file=sys.stderr)
|
|
except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError) as exc:
|
|
print(f"Cannot read volume placement: {exc}", file=sys.stderr)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--kubeconfig", required=True)
|
|
parser.add_argument("--namespace", default="monitoring")
|
|
parser.add_argument("--release", default="prometheus-stack")
|
|
parser.add_argument("--timeout", type=int, default=300)
|
|
parser.add_argument("--recover-stale-pending", action="store_true",
|
|
help="Replace only a stale, unscheduled Grafana pod blocked on an old priority revision")
|
|
args = parser.parse_args()
|
|
if args.timeout < 1:
|
|
parser.error("--timeout must be positive")
|
|
deadline = time.monotonic() + args.timeout
|
|
previous = None
|
|
while True:
|
|
try:
|
|
items = kubectl(args, "-n", args.namespace, "get", "deployment,statefulset,daemonset", "-o", "json")["items"]
|
|
errors = readiness_errors(items, args.release)
|
|
if errors and args.recover_stale_pending:
|
|
recover_stale_grafana(args, items)
|
|
except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError) as exc:
|
|
errors = [f"Unable to reconcile monitoring readiness: {exc}"]
|
|
if not errors:
|
|
print("Prometheus stack workloads are ready (including Prometheus and Grafana).")
|
|
return 0
|
|
if errors != previous:
|
|
print("Waiting for monitoring: " + "; ".join(errors), flush=True)
|
|
previous = errors
|
|
remaining = deadline - time.monotonic()
|
|
if remaining <= 0:
|
|
diagnostics(args)
|
|
# Terraform can retain only the tail of provisioner output. Keep
|
|
# the actual blockers after the longer diagnostic details.
|
|
for error in errors:
|
|
print("BLOCKED " + error, file=sys.stderr)
|
|
print("Monitoring readiness timed out; PVC placement and resource requests were preserved.", file=sys.stderr)
|
|
return 1
|
|
time.sleep(min(5, remaining))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|