homek8s/docs/monitoring-dashboards.md

237 lines
12 KiB
Markdown
Raw Normal View History

# Monitoring dashboards
Three custom Grafana dashboards, all provisioned from this repo. Nothing on these
boards is created in the UI: the `kube-prometheus-stack` Grafana sidecar watches
for ConfigMaps labelled `grafana_dashboard=1` in **every** namespace
(`NAMESPACE=ALL`, `LABEL_VALUE=1`, `FOLDER=/tmp/dashboards`) and reloads them, so
a UI edit is overwritten on the next sidecar poll.
| Dashboard | UID | Answers |
|---|---|---|
| Forgejo Runners | `forgejo-runners` | Are the runners alive and polling, is CI queueing, how do runs end, and how full is the disk CI fills? |
| CNPG Postgres | `cnpg-postgres` | Are both Postgres clusters up, how busy, how big, how much WAL, is anything erroring? |
| Home lab workloads | `home-lab-workloads` | Which namespace is burning CPU/memory, what is Pending or restarting, are the nodes healthy, do the internal services answer? |
Open them (WireGuard only, no public hostname — see
`docs/internal-wireguard-services.md`):
```
http://10.10.0.2:8081/d/forgejo-runners/
http://10.10.0.2:8081/d/cnpg-postgres/
http://10.10.0.2:8081/d/home-lab-workloads/
```
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
```
monitoring/controllers/home/dashboards/
├── build.py # source of truth: panel definitions + PromQL
├── kustomization.yaml
├── forgejo-runners.yaml # GENERATED ConfigMap (JSON inside)
├── cnpg-postgres.yaml # GENERATED
└── home-lab-workloads.yaml # GENERATED
```
**Edit `build.py`, then regenerate.** The generated YAML is committed so Flux
applies exactly what was reviewed, but a hand edit to the YAML fights the next
regeneration.
```bash
cd ~/Projects/homek8s
python3 monitoring/controllers/home/dashboards/build.py monitoring/controllers/home/dashboards
```
## Getting Postgres metrics at all
Neither CNPG cluster was scraped before this work. Two pieces, both in git:
1. **A PodMonitor per cluster** — `apps/base/forgejo/podmonitor.yaml`,
`apps/base/sirius-growth/podmonitor.yaml`. They carry
`release: kube-prometheus-stack`, which is mandatory: Prometheus here keeps
the chart default `podMonitorSelectorNilUsesHelmValues: true`, so its selector
is literally `release=kube-prometheus-stack` (same reason the Cilium
ServiceMonitors in `kube-system` land). A PodMonitor without that label exists
happily and is never scraped — the failure mode is silence, not an error.
2. **`spec.monitoring.customQueriesConfigMap` on each `Cluster`** — the
operator's own `cnpg-default-monitoring` query set, plus, for `forgejo/pg`,
`forgejo-actions-queries`.
`spec.monitoring.enablePodMonitor` is deliberately **false**. It still works on
operator 1.30, but CNPG deprecated it in 1.27 ("we strongly recommend you remove
or set `enablePodMonitor` to `false` and manually create a PodMonitor") and the
operator-generated object gives no control over labels — which is precisely the
knob this stack needs. Owning the PodMonitor in git is both the upstream
recommendation and the only way to make the selector contract explicit.
### The Forgejo Actions metrics and their GRANT
`apps/base/forgejo/pg-actions-queries.yaml` adds four queries against the
`forgejo` database (CNPG runs custom queries on the cluster's *main* database —
`initdb.database`, i.e. `forgejo` here):
| Metric | Meaning |
|---|---|
| `cnpg_actions_queue_depth` | jobs handed to a runner that have not started (`started=0, stopped=0, status<>4`) |
| `cnpg_actions_queue_oldest_pending_seconds` | age of the oldest of those |
| `cnpg_actions_running_total` | jobs executing right now |
| `cnpg_actions_jobs_window_total{window,status}` | jobs finished in a rolling 1h/24h window, by status |
| `cnpg_actions_runners_last_online_seconds{runner}` | seconds since each runner polled Forgejo |
**Custom queries run as `cnpg_metrics_exporter`, not as `postgres`.** That role
has `pg_monitor` but no rights on Forgejo's tables, and a query that cannot read
its table yields **no metric at all** — silently. So once per database (not once
per deploy; it survives as long as the data directory does):
```bash
kubectl -n forgejo exec pg-1 -c postgres -- psql -U postgres -d forgejo -c \
'GRANT USAGE ON SCHEMA public TO cnpg_metrics_exporter;
GRANT SELECT ON action_run_job, action_task, action_runner TO cnpg_metrics_exporter;'
```
Re-apply it after a restore into a fresh cluster (a fresh `initdb` has no grants).
### Status codes
`action_run_job.status` / `action_run.status` are **1 = success, 2 = failure,
3 = cancelled, 4 = skipped**. This was verified on this instance, not assumed:
DB run 1189 (status 1) reports `conclusion: success` on
`/api/v1/repos/sirius/onionwire/actions/runs`, run 1191 (status 2) `failure`.
Queue depth excludes status 4 because skipped jobs never start, never stop, and
are never pruned — including them would pin the queue at "3" forever.
## The tricky panels, and the PromQL behind them
**Queue while a job is running (contention).** The single-slot runners are
deliberate (`capacity = 1`), so the useful signal is "queued *and* running":
`(queue > bool 0) * (running > bool 0)` — the `bool` modifier turns each
comparison into 0/1 so the product is always a number (a bare `and` would render
"No data" instead of a green 0).
```promql
max((cnpg_actions_queue_depth{namespace="forgejo"} > bool 0)
* (cnpg_actions_running_total{namespace="forgejo"} > bool 0))
```
**Days to full.** Linear fit of free space, floored and capped:
```promql
clamp_max(node_filesystem_avail_bytes{instance="10.10.0.2:9100",mountpoint="/"}
/ clamp_min(-deriv(node_filesystem_avail_bytes{instance="10.10.0.2:9100",mountpoint="/"}[1h]), 0.0000001)
/ 86400, 365)
```
`clamp_min` on the *denominator* keeps a growing-filesystem division from going
negative or infinite; `clamp_max 365` renders "not filling" as a flat year rather
than a huge number. It needs a few hours of history to be meaningful.
**Commit share / cache hit ratio.** Both are `a / (a + b)` and both would render
`NaN` on an idle database, so the denominator is floored:
```promql
sum(rate(cnpg_pg_stat_database_xact_commit[5m]))
/ clamp_min(sum(rate(cnpg_pg_stat_database_xact_commit[5m]))
+ sum(rate(cnpg_pg_stat_database_xact_rollback[5m])), 0.0000001)
```
**Quiet-database error counters.** `increase()` over a counter that exists
(e.g. `cnpg_pg_stat_database_deadlocks`) returns a hard `0`, so deadlocks read 0
instead of "No data". Never use a `> 0` filter for these — it deletes the panel's
only series.
**Rolling job counts instead of `rate()`.** Forgejo prunes old `action_run_job`
rows. `rate()` over a row count would show a fake drop at every prune, so the
throughput panels query "how many rows stopped inside the last hour" directly
(`cnpg_actions_jobs_window_total{window="1h"}`).
## Adding a panel
1. Edit `monitoring/controllers/home/dashboards/build.py` — `ts()` for a
timeseries, `stat()` for a single number, `note()` for markdown.
2. Regenerate (command above).
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
kubectl -n flux-system annotate gitrepository flux-system \
reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite
kubectl -n flux-system annotate kustomization monitoring \
reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite
```
(`kustomization monitoring` will sit on `dependency 'flux-system/infrastructure'
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
not exist yet, add it to `pg-actions-queries.yaml` (Postgres) rather than
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)
- **Arm64 runner jobs are invisible to kube metrics.** `forgejo-runner-arm64`
and `forgejo-runner-deploy-arm64` drive the Pi's **host** Docker socket, so
their jobs are host containers with no pod identity. cAdvisor and
kube-state-metrics see only the runner pod. Per-job CPU/mem/disk on rpi is
therefore unavailable — the board shows rpi's root filesystem instead, because
that is where those containers write.
- **No per-PV usage.** local-path provisions `hostPath` PVs; kubelet publishes no
`kubelet_volume_stats_used_bytes` for hostPath volumes (on this cluster the only
`kubelet_volume_*` series are the collector-duration histograms). The dind PVC's
20Gi is shown as *requested capacity* next to siriussec's root-filesystem usage,
which is the number that actually produced the DiskPressure evictions.
- **Single-instance Postgres.** Both clusters run `instances: 1`, so replication
lag, streaming replicas and in-recovery are structurally zero. The panels show
the zero and say why instead of being hidden.
- **No CNPG backups exist** (`kubectl get backups.postgresql.cnpg.io -A` is
empty), so "Last available backup" reads 0 = never. That is the state, not a
broken panel.
- **No Alertmanager.** `PrometheusRule` objects (e.g. `InternalGatewayUnreachable`)
surface on Prometheus `/alerts` and in Grafana → Alerting; nothing pages.
## Cardinality / retention
`retention: 7d` and `retentionSize: 8GB` are unchanged. The additions are small:
two Postgres instances add a few hundred series each (the CNPG default query set
plus the four Forgejo queries), and `prometheus-node-exporter` now runs on every
node instead of only siriussec (~700 series per node) — that is what makes the
Pi's disk visible at all, and it costs far less than one day of cAdvisor for a
build pod.