#!/usr/bin/env python3 """Verify every panel on the custom dashboards returns real data. Reads the dashboard JSON out of the provisioned ConfigMap YAML (i.e. exactly what Grafana loaded), extracts every PromQL/LogQL expression, queries the matching datasource's HTTP API and prints panel title -> query -> series count -> sample. Prometheus panels go to PROM; panels whose datasource is `loki` go to LOKI. A Loki panel is reported as OK only if its result is non-empty, which for a logs panel means at least one entry (the series count alone is not enough). Usage: validate_panels.py [DASHBOARD_DIR] [PROM_URL] [LOKI_URL] """ import json import os import sys import time import urllib.parse import urllib.request import yaml DASH_DIR = sys.argv[1] if len(sys.argv) > 1 else os.path.expanduser( "~/Projects/homek8s/monitoring/controllers/home/dashboards") PROM = sys.argv[2] if len(sys.argv) > 2 else "http://127.0.0.1:9090" LOKI = sys.argv[3] if len(sys.argv) > 3 else "http://127.0.0.1:3100" # Grafana template variable substitution for the "All" case, so the query the # script runs is the query Grafana runs. SUBST = {"$namespace": ".*", "${namespace}": ".*", "$__all": ".*", "$runner_ns": ".*(runner|forgejo).*", "${runner_ns}": ".*(runner|forgejo).*"} def substitute(expr): for k, v in SUBST.items(): expr = expr.replace(k, v) return expr def query(expr): url = "%s/api/v1/query?%s" % (PROM, urllib.parse.urlencode({"query": expr})) with urllib.request.urlopen(url, timeout=20) as r: body = json.load(r) if body.get("status") != "success": return None, body.get("error", "unknown error") return body["data"]["result"], None def query_loki(expr, instant=False): if instant: url = "%s/loki/api/v1/query?%s" % (LOKI, urllib.parse.urlencode( {"query": expr, "time": "%d000000000" % time.time()})) else: now = int(time.time()) url = "%s/loki/api/v1/query_range?%s" % (LOKI, urllib.parse.urlencode( {"query": expr, "start": "%d000000000" % (now - 21600), "end": "%d000000000" % now, "limit": 1000})) with urllib.request.urlopen(url, timeout=30) as r: body = json.load(r) if body.get("status") != "success": return None, 0, body.get("error") or body result = body["data"]["result"] or [] # Range/metric queries return {metric|stream, values:[[ts,line],...]}; an # instant query returns {metric, value:[ts,val]} (singular). Count both, so a # stat panel's single sample is "1 row" rather than looking empty. rows = 0 for x in result: if "values" in x: rows += len(x.get("values") or []) elif "value" in x: rows += 1 return result, rows, None def ds_type(panel, target): ds = target.get("datasource") or panel.get("datasource") if isinstance(ds, dict): return ds.get("type") return None def panels_of(dash): out = [] for p in dash.get("panels", []): out.append(p) out.extend(p.get("panels", []) or []) return out total = 0 bad = 0 for fn in sorted(os.listdir(DASH_DIR)): if not fn.endswith(".yaml"): continue doc = yaml.safe_load(open(os.path.join(DASH_DIR, fn))) if not isinstance(doc, dict) or "data" not in doc: continue # kustomization.yaml, build.py helpers, etc. key = [k for k in doc["data"] if k.endswith(".json")][0] dash = json.loads(doc["data"][key]) print("\n=== %s (uid: %s) ===" % (dash["title"], dash["uid"])) for p in panels_of(dash): if p.get("type") in ("row", "text"): continue for t in p.get("targets", []): expr = substitute(t.get("expr", "")) if not expr: continue total += 1 if ds_type(p, t) == "loki": result, rows, err = query_loki(expr, instant=bool(t.get("instant"))) if err: bad += 1 print(" FAIL %-46s %s\n ERROR: %s" % (p["title"][:46], expr.replace("\n", " ")[:110], err)) continue if not result or not rows: bad += 1 print(" EMPTY %-46s %s" % (p["title"][:46], expr.replace("\n", " ")[:110])) continue print(" OK %-46s %-3d series %-6d rows (loki)" % (p["title"][:46], len(result), rows)) continue result, err = query(expr) if err: bad += 1 print(" FAIL %-46s %s\n ERROR: %s" % (p["title"][:46], expr.replace("\n", " ")[:110], err)) continue if not result: bad += 1 print(" EMPTY %-46s %s" % (p["title"][:46], expr.replace("\n", " ")[:110])) continue sample = result[0] labels = {k: v for k, v in sample["metric"].items() if k not in ("__name__", "job", "instance", "namespace", "container", "endpoint", "pod", "service", "uid")} print(" OK %-46s %-3d series sample=%s %s" % (p["title"][:46], len(result), sample["value"][1], labels or "")) print("\n%d targets checked, %d empty/failed" % (total, bad)) sys.exit(1 if bad else 0)