homek8s/monitoring/controllers/home/dashboards/validate_panels.py

86 lines
3 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
"""Verify every panel on the three custom dashboards returns real data.
Reads the dashboard JSON out of the provisioned ConfigMap YAML (i.e. exactly what
Grafana loaded), extracts every PromQL expression, queries the Prometheus HTTP API
and prints panel title -> PromQL -> series count -> sample.
Usage: validate_panels.py [DASHBOARD_DIR] [PROM_URL]
"""
import json
import os
import sys
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"
# Grafana template variable substitution for the "All" case, so the query the
# script runs is the query Grafana runs.
SUBST = {"$namespace": ".*", "${namespace}": ".*", "$__all": ".*"}
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 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
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)