173 lines
7.9 KiB
Python
173 lines
7.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Read-only readiness checks for Helm and Operator monitoring workloads."""
|
|
|
|
import argparse
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
|
|
|
|
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):
|
|
result = subprocess.run(
|
|
["kubectl", "--kubeconfig", args.kubeconfig, "--request-timeout=10s", *command],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=15,
|
|
check=False,
|
|
)
|
|
if result.returncode:
|
|
raise RuntimeError(result.stderr.strip()[:1500])
|
|
return json.loads(result.stdout)
|
|
|
|
|
|
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)
|
|
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)
|
|
except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError) as exc:
|
|
errors = [f"Unable to read monitoring controllers: {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())
|