forked from mtusi2026/mtusi2026lab7
80 lines
3.5 KiB
Python
80 lines
3.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Run EVERY query of the provisioned dashboard through Grafana (/api/ds/query) and report, per
|
|
panel: error / no data / number of series. Proves that the dashboard refers to metric names,
|
|
labels and datasource UIDs that really exist (not only that the JSON was imported).
|
|
|
|
python scripts/check_dashboard.py [--minutes 30] [--output evidence/dashboard-check.txt]
|
|
Exit code 1 if a query fails. "no data" is reported, not failed: an incident-only series
|
|
(5xx, failed spans) is legitimately empty on a healthy stand.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "scripts"))
|
|
import obs # noqa: E402
|
|
|
|
|
|
def post(path: str, body: dict) -> dict:
|
|
request = urllib.request.Request(obs.GRAFANA + path, data=json.dumps(body).encode(), method="POST",
|
|
headers={"Authorization": obs._auth(), "Content-Type": "application/json"})
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=60) as response:
|
|
return json.loads(response.read())
|
|
except urllib.error.HTTPError as exc:
|
|
return json.loads(exc.read() or b"{}") | {"_status": exc.code}
|
|
|
|
|
|
def get(path: str) -> dict:
|
|
request = urllib.request.Request(obs.GRAFANA + path, headers={"Authorization": obs._auth()})
|
|
with urllib.request.urlopen(request, timeout=30) as response:
|
|
return json.loads(response.read())
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--minutes", type=int, default=30)
|
|
parser.add_argument("--output")
|
|
args = parser.parse_args()
|
|
dashboard = get("/api/dashboards/uid/messenger-lab6")["dashboard"]
|
|
now = int(time.time() * 1000)
|
|
lines, failed = [], 0
|
|
lines.append(f"dashboard {dashboard['uid']} \"{dashboard['title']}\" (provisioned), window {args.minutes} min")
|
|
for panel in dashboard["panels"]:
|
|
if panel["type"] == "row":
|
|
lines.append(f"== {panel['title']}")
|
|
continue
|
|
results = []
|
|
for target in panel.get("targets", []):
|
|
query = {k: v for k, v in target.items()}
|
|
query.setdefault("datasource", panel["datasource"])
|
|
query["intervalMs"], query["maxDataPoints"] = 15000, 200
|
|
if query["datasource"]["type"] == "tempo":
|
|
query.update({"queryType": "traceql", "tableType": "traces"})
|
|
response = post("/api/ds/query", {"queries": [query], "from": str(now - args.minutes * 60000), "to": str(now)})
|
|
result = response.get("results", {}).get(target["refId"], {})
|
|
if "_status" in response or result.get("error"):
|
|
failed += 1
|
|
results.append(f"{target['refId']}: ERROR {result.get('error') or response.get('message')}")
|
|
continue
|
|
frames = result.get("frames", [])
|
|
rows = sum(len(f.get("data", {}).get("values", [[]])[0]) if f.get("data", {}).get("values") else 0 for f in frames)
|
|
results.append(f"{target['refId']}: {len(frames)} series/{rows} points" if rows else f"{target['refId']}: no data")
|
|
lines.append(f" [{panel['type']}] {panel['title']}: " + "; ".join(results))
|
|
lines.append(f"queries failed: {failed}")
|
|
text = "\n".join(lines)
|
|
print(text)
|
|
if args.output:
|
|
Path(args.output).write_text(text + "\n", encoding="utf-8", newline="\n")
|
|
return 1 if failed else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|