#!/usr/bin/env python3 """Every Prometheus query of the provisioned dashboard must parse and return data (after some traffic). python3 student-tests/check_dashboard.py """ import json import sys import urllib.error from pathlib import Path import obs ROOT = Path(__file__).resolve().parents[1] dash = json.loads((ROOT / "infra/grafana/dashboards/messenger.json").read_text(encoding="utf-8")) bad = 0 for panel in dash["panels"]: for t in panel.get("targets", []): if t.get("datasource", {}).get("type") != "prometheus": continue expr = t["expr"].replace("$__rate_interval", "2m") try: rows = obs.prom(expr) status = "ok %3d series" % len(rows) if rows else "EMPTY" except urllib.error.HTTPError as exc: status, rows = "ERROR %s" % exc.read()[:120], None if not rows: bad += 1 print("%-16s %-48s %s" % (status, panel["title"][:48], t.get("legendFormat", ""))) print("panels: %d, prometheus queries without data: %d" % (len(dash["panels"]), bad)) # ---------------------------------------------------------------- the same panels executed BY GRAFANA (/api/ds/query) # Proves the provisioned datasources work from Grafana itself (Prometheus, Loki and Tempo), with Grafana macros. import base64 # noqa: E402 import urllib.request # noqa: E402 password = (ROOT / "secrets/bootstrap/grafana_admin_password").read_text().strip() import ssl # noqa: E402 GRAFANA_TLS = ssl.create_default_context(cafile=str(ROOT / "secrets/pki/ca.crt")) # lab7: Grafana is HTTPS-only auth = "Basic " + base64.b64encode(("admin:" + password).encode()).decode() via_bad = 0 for panel in dash["panels"]: for t in panel.get("targets", []): q = dict(t) q.setdefault("datasource", panel.get("datasource")) if q["datasource"]["type"] == "tempo": # Grafana 11 runs TraceQL search in the browser through the datasource proxy, not /api/ds/query # ("backend TraceQL search queries are not supported"): check exactly that proxy path. import time as _t import urllib.parse as _p url = ("https://localhost:3000/api/datasources/proxy/uid/tempo/api/search?" + _p.urlencode({"q": q["query"], "limit": q.get("limit", 20), "start": int(_t.time()) - 1800, "end": int(_t.time())})) req = urllib.request.Request(url, headers={"Authorization": auth}) try: with urllib.request.urlopen(req, timeout=60, context=GRAFANA_TLS) as response: n = len(json.loads(response.read()).get("traces", [])) status = "ok %5d traces" % n if n else "EMPTY" except urllib.error.HTTPError as exc: status = "ERROR HTTP %s" % exc.code if not status.startswith("ok"): via_bad += 1 print("grafana %-8s %-18s %-48s (datasource proxy)" % ("tempo", status, panel["title"][:48])) continue body = json.dumps({"queries": [q], "from": "now-30m", "to": "now"}).encode() req = urllib.request.Request("https://localhost:3000/api/ds/query", data=body, method="POST", headers={"Content-Type": "application/json", "Authorization": auth}) try: with urllib.request.urlopen(req, timeout=60, context=GRAFANA_TLS) as response: res = json.loads(response.read())["results"][q["refId"]] frames = res.get("frames", []) rows = sum(len((f.get("data") or {}).get("values", [[]])[0] or []) for f in frames) status = "ERROR %s" % res["error"][:100] if res.get("error") else ("ok %5d values" % rows if rows else "EMPTY") except urllib.error.HTTPError as exc: status = "ERROR HTTP %s %s" % (exc.code, exc.read()[:100]) if not status.startswith("ok"): via_bad += 1 print("grafana %-8s %-18s %-48s" % (q["datasource"]["type"], status, panel["title"][:48])) print("via Grafana: queries without data or with errors: %d" % via_bad)