dashboards: zero-render stats, drop the aspirational folder annotation, keep the validator in the repo

- every count-style stat that can legitimately have no series now ends in
  'or vector(0)', so an empty result renders 0 instead of 'No data' (that bit
  the Pending-pods stat the moment the one Pending pod went away)
- no grafana_folder annotation: the sidecar's API reload 401s (Grafana's live
  admin password is the out-of-band one; the Secret is the first-boot seed), so
  the dashboards are imported by Grafana's file provider, which has no
  per-dashboard folder option and puts them in General. The annotation described
  a path the boards never take.
- validate_panels.py lives next to build.py: reads the panel PromQL out of the
  provisioned ConfigMap and queries Prometheus, so 'every panel returns data' is
  a command, not a claim. 55/55 targets pass.
This commit is contained in:
Lance Walters 2026-10-27 01:40:15 -04:00
commit e63af123c5
6 changed files with 149 additions and 21 deletions

View file

@ -21,7 +21,16 @@ http://10.10.0.2:8081/d/cnpg-postgres/
http://10.10.0.2:8081/d/home-lab-workloads/ http://10.10.0.2:8081/d/home-lab-workloads/
``` ```
They land in the Grafana folder **Homelab** (the `grafana_folder` annotation). They land in the default **General** folder, next to the chart's own dashboards —
not in a custom folder. That is a consequence of *how* they get imported: the
sidecar's API-backed import POSTs to `/api/admin/provisioning/dashboards/reload`
with `GF_SECURITY_ADMIN_USER/PASSWORD`, and on this Grafana that returns **401**
because the live admin password is the out-of-band one set in the UI
(`docs/grafana-persistence.md`) while `monitoring/grafana-admin` is only the
first-boot seed. Grafana's own **file** provider then imports `/tmp/dashboards`
on its 10 s rescan anyway — that is what actually registers these boards — and
the file provider has no per-dashboard folder option. Hence no `grafana_folder`
annotation: it would only describe a path the boards do not take.
## Where the files live ## Where the files live
@ -110,8 +119,8 @@ comparison into 0/1 so the product is always a number (a bare `and` would render
"No data" instead of a green 0). "No data" instead of a green 0).
```promql ```promql
max((cnpg_actions_queue_depth{cluster="pg"} > bool 0) max((cnpg_actions_queue_depth{namespace="forgejo"} > bool 0)
* (cnpg_actions_running_total{cluster="pg"} > bool 0)) * (cnpg_actions_running_total{namespace="forgejo"} > bool 0))
``` ```
**Days to full.** Linear fit of free space, floored and capped: **Days to full.** Linear fit of free space, floored and capped:
@ -150,20 +159,52 @@ throughput panels query "how many rows stopped inside the last hour" directly
1. Edit `monitoring/controllers/home/dashboards/build.py` — `ts()` for a 1. Edit `monitoring/controllers/home/dashboards/build.py` — `ts()` for a
timeseries, `stat()` for a single number, `note()` for markdown. timeseries, `stat()` for a single number, `note()` for markdown.
2. Regenerate (command above). 2. Regenerate (command above).
3. Commit + push to `master`, then force the reconcile: 3. **Validate the PromQL, not just the YAML.** `validate_panels.py` (next to
`build.py`) reads the dashboard JSON *out of the provisioned ConfigMap*,
extracts every target expression, substitutes the `$namespace` "All" case and
queries Prometheus. Anything that returns no series is a failed panel. It
needs a Prometheus port-forward (`kubectl -n monitoring port-forward
svc/kube-prometheus-stack-prometheus 9090:9090`).
```bash
python3 monitoring/controllers/home/dashboards/validate_panels.py \
monitoring/controllers/home/dashboards http://127.0.0.1:9090
```
4. Commit + push to `master`, then force the reconcile:
```bash ```bash
kubectl -n flux-system annotate gitrepository flux-system \ kubectl -n flux-system annotate gitrepository flux-system \
reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite
kubectl -n flux-system annotate kustomization monitoring \ kubectl -n flux-system annotate kustomization monitoring \
reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite
``` ```
4. Wait for the sidecar (it polls; a ConfigMap change is picked up within a (`kustomization monitoring` will sit on `dependency 'flux-system/infrastructure'
minute) and confirm the board answers `/api/search?query=<uid>` with your UID. is not ready` until you also annotate `kustomization infrastructure` — its
Ready condition is stale, not broken.)
5. Confirm the board registered. Grafana 13 stores dashboards in **unified
storage**, so `dashboard` table is empty and the UID lives in `resource`:
```bash
ssh Lancelot@10.10.0.2 "sudo sqlite3 /opt/local-path-provisioner/pvc-*_monitoring_kube-prometheus-stack-grafana/grafana.db \
\"select name, json_extract(value,'\$.spec.title') from resource where resource='dashboards' and name='<uid>';\""
```
Dashboards are data sources for humans: if a new panel needs a metric that does Dashboards are data sources for humans: if a new panel needs a metric that does
not exist yet, add it to `pg-actions-queries.yaml` (Postgres) rather than not exist yet, add it to `pg-actions-queries.yaml` (Postgres) rather than
deploying another exporter. deploying another exporter.
### Panel-query patterns worth copying
- **A stat that can legitimately have no series needs `or vector(0)`.** A bare
`sum(x == 1)` over zero matching series is an *empty vector*, and Grafana
renders that as "No data" — which looks identical to a broken query. Every
count-style stat here that can hit zero ends in `or vector(0)`.
- **Beware broad pod regexes.** `pod=~"forgejo-runner-.*"` also matches the
`forgejo-runner-prune-*` CronJob pods, which are `Completed` and therefore
permanently "not Ready" — that turned a not-Ready stat from 0 into 3 until the
selector was narrowed to the three Deployment pod prefixes.
- **CNPG custom-query metrics carry `namespace`/`pod` from the scrape, not the
exporter's `cluster` label.** `cnpg_collector_*` has `cluster`; the
`cnpg_actions_*` and `cnpg_pg_stat_*` families do not. Filter those by
`namespace="forgejo"`.
## Known unknowns (deliberate, documented on the boards themselves) ## Known unknowns (deliberate, documented on the boards themselves)
- **Arm64 runner jobs are invisible to kube metrics.** `forgejo-runner-arm64` - **Arm64 runner jobs are invisible to kube metrics.** `forgejo-runner-arm64`

View file

@ -140,7 +140,7 @@ RPI_FS = 'instance="10.10.0.1:9100",mountpoint="/"'
runners = [ runners = [
row("Runners & queue", 0), row("Runners & queue", 0),
stat("Runner pods Ready", [target('sum(kube_deployment_status_replicas_ready{namespace="forgejo",deployment=~"forgejo-runner-.*"})')], stat("Runner pods Ready", [target('sum(kube_deployment_status_replicas_ready{namespace="forgejo",deployment=~"forgejo-runner-.*"}) or vector(0)')],
{"h": 5, "w": 4, "x": 0, "y": 1}, desc="replicas_ready summed across the three runner Deployments. Expected 3.", {"h": 5, "w": 4, "x": 0, "y": 1}, desc="replicas_ready summed across the three runner Deployments. Expected 3.",
thresholds=[{"color": "red", "value": None}, {"color": "yellow", "value": 2}, {"color": "green", "value": 3}]), thresholds=[{"color": "red", "value": None}, {"color": "yellow", "value": 2}, {"color": "green", "value": 3}]),
stat("Runner pods not Ready", [target('sum(kube_pod_status_ready{%s,condition="false"} == 1) or vector(0)' % RUN)], stat("Runner pods not Ready", [target('sum(kube_pod_status_ready{%s,condition="false"} == 1) or vector(0)' % RUN)],
@ -309,13 +309,13 @@ cnpg = [
# -------------------------------------------------------------- workloads ----- # -------------------------------------------------------------- workloads -----
workloads = [ workloads = [
row("Cluster", 0), row("Cluster", 0),
stat("Nodes Ready", [target('count(kube_node_status_condition{condition="Ready",status="true"} == 1)')], stat("Nodes Ready", [target('count(kube_node_status_condition{condition="Ready",status="true"} == 1) or vector(0)')],
{"h": 5, "w": 4, "x": 0, "y": 1}, thresholds=[{"color": "red", "value": None}, {"color": "yellow", "value": 2}, {"color": "green", "value": 3}]), {"h": 5, "w": 4, "x": 0, "y": 1}, thresholds=[{"color": "red", "value": None}, {"color": "yellow", "value": 2}, {"color": "green", "value": 3}]),
stat("Nodes with DiskPressure", [target('sum(kube_node_status_condition{condition="DiskPressure",status="true"} == 1) or vector(0)')], stat("Nodes with DiskPressure", [target('sum(kube_node_status_condition{condition="DiskPressure",status="true"} == 1) or vector(0)')],
{"h": 5, "w": 4, "x": 4, "y": 1}, {"h": 5, "w": 4, "x": 4, "y": 1},
desc="The taint that evicted Forgejo and pg-1 in the past. >0 here is an incident, not a warning.", desc="The taint that evicted Forgejo and pg-1 in the past. >0 here is an incident, not a warning.",
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}]), thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}]),
stat("Pending pods", [target('sum(kube_pod_status_phase{phase="Pending"} == 1)')], stat("Pending pods", [target('sum(kube_pod_status_phase{phase="Pending"} == 1) or vector(0)')],
{"h": 5, "w": 4, "x": 8, "y": 1}, {"h": 5, "w": 4, "x": 8, "y": 1},
desc="Pods that cannot be scheduled — usually an unschedulable taint or an exhausted resource request.", desc="Pods that cannot be scheduled — usually an unschedulable taint or an exhausted resource request.",
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}]), thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}]),
@ -323,7 +323,7 @@ workloads = [
{"h": 5, "w": 4, "x": 12, "y": 1}, {"h": 5, "w": 4, "x": 12, "y": 1},
desc="blackbox-exporter probes of http://10.10.0.2:8081/ and :8084/ (monitoring/controllers/home/gateway-probe.yaml). 2 = both internal services answering.", desc="blackbox-exporter probes of http://10.10.0.2:8081/ and :8084/ (monitoring/controllers/home/gateway-probe.yaml). 2 = both internal services answering.",
thresholds=[{"color": "red", "value": None}, {"color": "yellow", "value": 1}, {"color": "green", "value": 2}]), thresholds=[{"color": "red", "value": None}, {"color": "yellow", "value": 1}, {"color": "green", "value": 2}]),
stat("PVCs bound", [target('sum(kube_persistentvolumeclaim_status_phase{phase="Bound"} == 1)')], stat("PVCs bound", [target('sum(kube_persistentvolumeclaim_status_phase{phase="Bound"} == 1) or vector(0)')],
{"h": 5, "w": 4, "x": 16, "y": 1}), {"h": 5, "w": 4, "x": 16, "y": 1}),
stat("PVC capacity requested", [target('sum(kube_persistentvolumeclaim_resource_requests_storage_bytes)')], stat("PVC capacity requested", [target('sum(kube_persistentvolumeclaim_resource_requests_storage_bytes)')],
{"h": 5, "w": 4, "x": 20, "y": 1}, unit="bytes", {"h": 5, "w": 4, "x": 20, "y": 1}, unit="bytes",
@ -409,8 +409,13 @@ for uid, panels in PANELS.items():
"name": "grafana-dashboard-" + uid, "name": "grafana-dashboard-" + uid,
"namespace": "monitoring", "namespace": "monitoring",
"labels": {"grafana_dashboard": "1", "app.kubernetes.io/part-of": "homelab-dashboards"}, "labels": {"grafana_dashboard": "1", "app.kubernetes.io/part-of": "homelab-dashboards"},
"annotations": {"grafana_folder": "Homelab", # No grafana_folder annotation: the sidecar's API-backed import cannot
"homelab.siriusdevops.com/managed-by": "monitoring/controllers/home/dashboards/build.py"}, # authenticate (Grafana's live admin password is the out-of-band one,
# not monitoring/grafana-admin — that Secret is only the first-boot
# seed), so the dashboards are imported by Grafana's *file* provider,
# which ignores per-dashboard folder annotations and puts every board
# in General next to the chart's own 28. Verified in grafana.db.
"annotations": {"homelab.siriusdevops.com/managed-by": "monitoring/controllers/home/dashboards/build.py"},
}, },
"data": {uid + ".json": json.dumps(d, indent=2) + "\n"}, "data": {uid + ".json": json.dumps(d, indent=2) + "\n"},
} }
@ -422,8 +427,7 @@ for uid, panels in PANELS.items():
# hand-rolled YAML emitter: keeps the JSON block literal and diffable # hand-rolled YAML emitter: keeps the JSON block literal and diffable
f.write("apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: %s\n namespace: monitoring\n" % doc["metadata"]["name"]) f.write("apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: %s\n namespace: monitoring\n" % doc["metadata"]["name"])
f.write(" labels:\n grafana_dashboard: \"1\"\n app.kubernetes.io/part-of: homelab-dashboards\n") f.write(" labels:\n grafana_dashboard: \"1\"\n app.kubernetes.io/part-of: homelab-dashboards\n")
f.write(" annotations:\n grafana_folder: Homelab\n") f.write(" annotations:\n homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py\n")
f.write(" homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py\n")
f.write("data:\n %s.json: |\n" % uid) f.write("data:\n %s.json: |\n" % uid)
for line in doc["data"][uid + ".json"].rstrip("\n").split("\n"): for line in doc["data"][uid + ".json"].rstrip("\n").split("\n"):
f.write(" " + line + "\n") f.write(" " + line + "\n")

View file

@ -10,7 +10,6 @@ metadata:
grafana_dashboard: "1" grafana_dashboard: "1"
app.kubernetes.io/part-of: homelab-dashboards app.kubernetes.io/part-of: homelab-dashboards
annotations: annotations:
grafana_folder: Homelab
homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py
data: data:
cnpg-postgres.json: | cnpg-postgres.json: |

View file

@ -10,7 +10,6 @@ metadata:
grafana_dashboard: "1" grafana_dashboard: "1"
app.kubernetes.io/part-of: homelab-dashboards app.kubernetes.io/part-of: homelab-dashboards
annotations: annotations:
grafana_folder: Homelab
homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py
data: data:
forgejo-runners.json: | forgejo-runners.json: |
@ -88,7 +87,7 @@ data:
"type": "prometheus", "type": "prometheus",
"uid": "prometheus" "uid": "prometheus"
}, },
"expr": "sum(kube_deployment_status_replicas_ready{namespace=\"forgejo\",deployment=~\"forgejo-runner-.*\"})", "expr": "sum(kube_deployment_status_replicas_ready{namespace=\"forgejo\",deployment=~\"forgejo-runner-.*\"}) or vector(0)",
"refId": "A", "refId": "A",
"editorMode": "code", "editorMode": "code",
"range": true, "range": true,

View file

@ -10,7 +10,6 @@ metadata:
grafana_dashboard: "1" grafana_dashboard: "1"
app.kubernetes.io/part-of: homelab-dashboards app.kubernetes.io/part-of: homelab-dashboards
annotations: annotations:
grafana_folder: Homelab
homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py
data: data:
home-lab-workloads.json: | home-lab-workloads.json: |
@ -87,7 +86,7 @@ data:
"type": "prometheus", "type": "prometheus",
"uid": "prometheus" "uid": "prometheus"
}, },
"expr": "count(kube_node_status_condition{condition=\"Ready\",status=\"true\"} == 1)", "expr": "count(kube_node_status_condition{condition=\"Ready\",status=\"true\"} == 1) or vector(0)",
"refId": "A", "refId": "A",
"editorMode": "code", "editorMode": "code",
"range": true, "range": true,
@ -219,7 +218,7 @@ data:
"type": "prometheus", "type": "prometheus",
"uid": "prometheus" "uid": "prometheus"
}, },
"expr": "sum(kube_pod_status_phase{phase=\"Pending\"} == 1)", "expr": "sum(kube_pod_status_phase{phase=\"Pending\"} == 1) or vector(0)",
"refId": "A", "refId": "A",
"editorMode": "code", "editorMode": "code",
"range": true, "range": true,
@ -351,7 +350,7 @@ data:
"type": "prometheus", "type": "prometheus",
"uid": "prometheus" "uid": "prometheus"
}, },
"expr": "sum(kube_persistentvolumeclaim_status_phase{phase=\"Bound\"} == 1)", "expr": "sum(kube_persistentvolumeclaim_status_phase{phase=\"Bound\"} == 1) or vector(0)",
"refId": "A", "refId": "A",
"editorMode": "code", "editorMode": "code",
"range": true, "range": true,

View file

@ -0,0 +1,86 @@
#!/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)