#!/usr/bin/env bash
# check_k8s_prometheus.sh：检查指定 Prometheus job 下的所有 Targets
set -euo pipefail

prom_url="${PROM_URL:-http://localhost:9090}"
job_name="${JOB_NAME:-k8s-node-exporter}"

curl -fsS --max-time 15 "${prom_url%/}/api/v1/targets" | python3 -c '
import json
import sys

data = json.load(sys.stdin)
job = sys.argv[1]
if data.get("status") != "success":
    print("ERROR: Prometheus API returned an error")
    sys.exit(1)

targets = [t for t in data.get("data", {}).get("activeTargets", [])
           if t.get("labels", {}).get("job") == job]

if not targets:
    print("FAILED: no targets found for job", job)
    sys.exit(1)

failed = False
print("JOB:", job)
for t in targets:
    instance = t.get("labels", {}).get("instance", "unknown")
    health = t.get("health", "unknown")
    print("{:<25} {}".format(instance, health))
    if health != "up":
        failed = True
        if t.get("lastError"):
            print("  lastError:", t["lastError"])

print("TOTAL:", len(targets), "FAILED:", sum(t.get("health") != "up" for t in targets))
sys.exit(1 if failed else 0)
' "$job_name"
