monitoring: custom Forgejo runner, CNPG and workload dashboards from git
Dashboards (uid forgejo-runners, cnpg-postgres, home-lab-workloads) live as ConfigMaps generated from monitoring/controllers/home/dashboards/build.py and are loaded by the kube-prometheus-stack grafana sidecar. Postgres was not scraped at all before this: add a hand-written PodMonitor per CNPG cluster (release=kube-prometheus-stack, which is what this Prometheus's podMonitorSelectorNilUsesHelmValues default requires) plus spec.monitoring.customQueriesConfigMap on both Clusters. enablePodMonitor stays false — deprecated in CNPG 1.27 and it gives no control over labels. pg-actions-queries.yaml adds the Forgejo Actions queue/outcome/last_online metrics that only the forgejo database can answer. prometheus-node-exporter is no longer pinned to siriussec: the arm64 runner's jobs are host containers on rpi, so the Pi's root filesystem is the disk that matters there and kubelet cannot see it. docs/monitoring-dashboards.md documents the PromQL, the exporter GRANT and the known unknowns (arm64 per-job breakdown, hostPath PVs have no kubelet volume stats, single-instance replication, no backups).
This commit is contained in:
parent
de30bc43e7
commit
9e851f4dfe
15 changed files with 4400 additions and 5 deletions
|
|
@ -24,3 +24,19 @@ spec:
|
||||||
memory: 256Mi
|
memory: 256Mi
|
||||||
limits:
|
limits:
|
||||||
memory: 1Gi
|
memory: 1Gi
|
||||||
|
# Metrics on :9187 (CNPG's instance manager), scraped by the PodMonitor in
|
||||||
|
# podmonitor.yaml. `enablePodMonitor` stays false: the operator-generated
|
||||||
|
# PodMonitor cannot carry the `release: kube-prometheus-stack` label that this
|
||||||
|
# Prometheus needs, and upstream deprecated the flag in CNPG 1.27.
|
||||||
|
#
|
||||||
|
# `customQueriesConfigMap` points at the operator's own default query set plus
|
||||||
|
# pg-actions-queries.yaml — the Forgejo Actions queue/outcome metrics that only
|
||||||
|
# this database can answer.
|
||||||
|
monitoring:
|
||||||
|
enablePodMonitor: false
|
||||||
|
disableDefaultQueries: false
|
||||||
|
customQueriesConfigMap:
|
||||||
|
- name: cnpg-default-monitoring
|
||||||
|
key: queries
|
||||||
|
- name: forgejo-actions-queries
|
||||||
|
key: queries
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,8 @@ resources:
|
||||||
- httproute.yaml
|
- httproute.yaml
|
||||||
- pvc.yaml
|
- pvc.yaml
|
||||||
- cluster.yaml
|
- cluster.yaml
|
||||||
|
- podmonitor.yaml
|
||||||
|
- pg-actions-queries.yaml
|
||||||
- deployment.yaml
|
- deployment.yaml
|
||||||
- service.yaml
|
- service.yaml
|
||||||
- runner-configmap.yaml
|
- runner-configmap.yaml
|
||||||
|
|
|
||||||
111
apps/base/forgejo/pg-actions-queries.yaml
Normal file
111
apps/base/forgejo/pg-actions-queries.yaml
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
# Custom CNPG monitoring queries for Forgejo's Actions tables.
|
||||||
|
#
|
||||||
|
# Why this ConfigMap exists: Forgejo's Actions queue lives in PostgreSQL, not in
|
||||||
|
# any exporter. `action_run_job` is the only place that knows how many jobs are
|
||||||
|
# waiting for a runner and how the last N runs ended, so the runner dashboard
|
||||||
|
# reads it through CNPG's built-in metrics exporter (`:9187`) instead of
|
||||||
|
# inventing a new exporter.
|
||||||
|
#
|
||||||
|
# How it is wired: `Cluster/pg` lists this ConfigMap under
|
||||||
|
# `spec.monitoring.customQueriesConfigMap` (alongside the operator's own
|
||||||
|
# `cnpg-default-monitoring`), so every query here runs on the cluster's *main*
|
||||||
|
# database — `forgejo` for this cluster, per CNPG's initdb.database rule — and is
|
||||||
|
# exported as `cnpg_<name>_<column>` on the instance's metrics port.
|
||||||
|
#
|
||||||
|
# Privileges: CNPG runs custom queries as the `cnpg_metrics_exporter` role
|
||||||
|
# (pg_monitor, NOT superuser). That role cannot read Forgejo's tables until it
|
||||||
|
# is granted, and the grant is a database-side step that cannot live in this
|
||||||
|
# file. When the dashboard shows an empty queue metric, run:
|
||||||
|
#
|
||||||
|
# GRANT USAGE ON SCHEMA public TO cnpg_metrics_exporter;
|
||||||
|
# GRANT SELECT ON action_run_job, action_task,
|
||||||
|
# action_runner TO cnpg_metrics_exporter;
|
||||||
|
#
|
||||||
|
# (see docs/monitoring-dashboards.md for the exact kubectl one-liner).
|
||||||
|
#
|
||||||
|
# Semantics, verified against this instance rather than guessed (task t_c45b2d73):
|
||||||
|
# action_run_job.status / action_run.status: 1 = success, 2 = failure,
|
||||||
|
# 3 = cancelled, 4 = skipped. Cross-checked against
|
||||||
|
# GET /api/v1/repos/sirius/onionwire/actions/runs, where DB run 1189
|
||||||
|
# (status 1) reports conclusion "success" and run 1191 (status 2) "failure".
|
||||||
|
# A job that has not started yet carries started = 0; a job that has not
|
||||||
|
# finished carries stopped = 0. Rows for skipped jobs never start, never stop
|
||||||
|
# and are kept forever, so queue depth deliberately excludes status 4 —
|
||||||
|
# otherwise the queue would read "3" at all times with nothing queued.
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: ConfigMap
|
||||||
|
metadata:
|
||||||
|
name: forgejo-actions-queries
|
||||||
|
namespace: forgejo
|
||||||
|
data:
|
||||||
|
queries: |
|
||||||
|
# Queue depth: jobs handed to a runner that have not started, plus the age
|
||||||
|
# of the oldest of them. Always returns exactly one row, so the panel shows
|
||||||
|
# a hard 0 instead of "No data" when the queue is empty.
|
||||||
|
actions_queue:
|
||||||
|
query: |
|
||||||
|
SELECT count(*) AS depth
|
||||||
|
, COALESCE(max(EXTRACT(EPOCH FROM pg_catalog.now())::bigint - NULLIF(j.created, 0)), 0) AS oldest_pending_seconds
|
||||||
|
FROM action_run_job j
|
||||||
|
WHERE j.started = 0
|
||||||
|
AND j.stopped = 0
|
||||||
|
AND j.status <> 4
|
||||||
|
metrics:
|
||||||
|
- depth:
|
||||||
|
usage: "GAUGE"
|
||||||
|
description: "Jobs assigned to a runner that have not started yet"
|
||||||
|
- oldest_pending_seconds:
|
||||||
|
usage: "GAUGE"
|
||||||
|
description: "Age in seconds of the oldest not-yet-started job"
|
||||||
|
# Jobs currently executing (a runner picked them up and has not finished).
|
||||||
|
actions_running:
|
||||||
|
query: |
|
||||||
|
SELECT count(*) AS total
|
||||||
|
FROM action_run_job j
|
||||||
|
WHERE j.started > 0
|
||||||
|
AND j.stopped = 0
|
||||||
|
metrics:
|
||||||
|
- total:
|
||||||
|
usage: "GAUGE"
|
||||||
|
description: "Jobs currently running on a runner"
|
||||||
|
# Job outcomes inside a rolling window. A rolling count (not a counter):
|
||||||
|
# Forgejo prunes old rows, so rate() over a row count would lie; asking for
|
||||||
|
# "stopped within the last hour/day" is always right.
|
||||||
|
actions_jobs_window:
|
||||||
|
query: |
|
||||||
|
SELECT w.label AS window
|
||||||
|
, s.status AS status
|
||||||
|
, COALESCE((
|
||||||
|
SELECT count(*)
|
||||||
|
FROM action_run_job j
|
||||||
|
WHERE j.status = s.status
|
||||||
|
AND j.stopped > (EXTRACT(EPOCH FROM pg_catalog.now())::bigint - w.secs)
|
||||||
|
), 0) AS total
|
||||||
|
FROM (VALUES ('1h', 3600), ('24h', 86400)) AS w(label, secs)
|
||||||
|
CROSS JOIN (VALUES (0), (1), (2), (3), (4)) AS s(status)
|
||||||
|
metrics:
|
||||||
|
- window:
|
||||||
|
usage: "LABEL"
|
||||||
|
description: "Rolling window: 1h or 24h"
|
||||||
|
- status:
|
||||||
|
usage: "LABEL"
|
||||||
|
description: "1 success, 2 failure, 3 cancelled, 4 skipped"
|
||||||
|
- total:
|
||||||
|
usage: "GAUGE"
|
||||||
|
description: "Jobs that finished inside the window with this status"
|
||||||
|
# How long ago each runner last polled Forgejo. This is the only signal that
|
||||||
|
# says "the runner process is alive" independently of the pod being Ready —
|
||||||
|
# a runner that cannot reach the forge stays Running but goes stale here.
|
||||||
|
actions_runners:
|
||||||
|
query: |
|
||||||
|
SELECT r.name AS runner
|
||||||
|
, COALESCE(EXTRACT(EPOCH FROM pg_catalog.now())::bigint - NULLIF(r.last_online, 0), -1) AS last_online_seconds
|
||||||
|
FROM action_runner r
|
||||||
|
metrics:
|
||||||
|
- runner:
|
||||||
|
usage: "LABEL"
|
||||||
|
description: "Runner name as registered with Forgejo"
|
||||||
|
- last_online_seconds:
|
||||||
|
usage: "GAUGE"
|
||||||
|
description: "Seconds since the runner last polled (-1 = never)"
|
||||||
32
apps/base/forgejo/podmonitor.yaml
Normal file
32
apps/base/forgejo/podmonitor.yaml
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
# Prometheus scrape config for the Forgejo Postgres cluster (CNPG).
|
||||||
|
#
|
||||||
|
# Hand-written on purpose. CNPG's `spec.monitoring.enablePodMonitor: true` still
|
||||||
|
# works on operator 1.30 but is deprecated upstream (CloudNativePG 1.27 release
|
||||||
|
# notes: "we strongly recommend you remove or set enablePodMonitor to false and
|
||||||
|
# manually create a PodMonitor"), because the operator-owned PodMonitor gives no
|
||||||
|
# control over labels — and labels are exactly what this stack needs:
|
||||||
|
# Prometheus here keeps the chart defaults
|
||||||
|
# (`podMonitorSelectorNilUsesHelmValues: true`), so it only honours PodMonitors
|
||||||
|
# carrying `release: kube-prometheus-stack`. The Cilium ServiceMonitors in
|
||||||
|
# kube-system land for the same reason. Owning the PodMonitor in git makes that
|
||||||
|
# selector contract explicit instead of depending on what the operator decides
|
||||||
|
# to stamp on the object.
|
||||||
|
#
|
||||||
|
# One PodMonitor per cluster, in the cluster's own namespace: the PodMonitor
|
||||||
|
# namespaceSelector is empty on the Prometheus CRD, so any namespace is honoured.
|
||||||
|
apiVersion: monitoring.coreos.com/v1
|
||||||
|
kind: PodMonitor
|
||||||
|
metadata:
|
||||||
|
name: cnpg-pg
|
||||||
|
namespace: forgejo
|
||||||
|
labels:
|
||||||
|
release: kube-prometheus-stack
|
||||||
|
spec:
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
cnpg.io/cluster: pg
|
||||||
|
podMetricsEndpoints:
|
||||||
|
- port: metrics
|
||||||
|
interval: 30s
|
||||||
|
# The instance manager serves /metrics on 9187 for the primary; replicas
|
||||||
|
# serve it too, so a future `instances: 2` needs no change here.
|
||||||
|
|
@ -24,3 +24,13 @@ spec:
|
||||||
memory: 256Mi
|
memory: 256Mi
|
||||||
limits:
|
limits:
|
||||||
memory: 1Gi
|
memory: 1Gi
|
||||||
|
# Scraped via podmonitor.yaml in this directory (hand-written; see the comment
|
||||||
|
# in apps/base/forgejo/podmonitor.yaml for why enablePodMonitor is false).
|
||||||
|
# Only the operator's default query set here — this database needs no custom
|
||||||
|
# application metrics.
|
||||||
|
monitoring:
|
||||||
|
enablePodMonitor: false
|
||||||
|
disableDefaultQueries: false
|
||||||
|
customQueriesConfigMap:
|
||||||
|
- name: cnpg-default-monitoring
|
||||||
|
key: queries
|
||||||
|
|
|
||||||
|
|
@ -11,3 +11,4 @@ resources:
|
||||||
- httproute.yaml
|
- httproute.yaml
|
||||||
- deployer.yaml
|
- deployer.yaml
|
||||||
- cluster.yaml
|
- cluster.yaml
|
||||||
|
- podmonitor.yaml
|
||||||
|
|
|
||||||
17
apps/base/sirius-growth/podmonitor.yaml
Normal file
17
apps/base/sirius-growth/podmonitor.yaml
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
# Prometheus scrape config for the Sirius Growth Postgres cluster (CNPG).
|
||||||
|
# See apps/base/forgejo/podmonitor.yaml for why this is hand-written rather than
|
||||||
|
# produced by `spec.monitoring.enablePodMonitor` (deprecated as of CNPG 1.27).
|
||||||
|
apiVersion: monitoring.coreos.com/v1
|
||||||
|
kind: PodMonitor
|
||||||
|
metadata:
|
||||||
|
name: cnpg-portal
|
||||||
|
namespace: sirius-growth
|
||||||
|
labels:
|
||||||
|
release: kube-prometheus-stack
|
||||||
|
spec:
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
cnpg.io/cluster: portal
|
||||||
|
podMetricsEndpoints:
|
||||||
|
- port: metrics
|
||||||
|
interval: 30s
|
||||||
196
docs/monitoring-dashboards.md
Normal file
196
docs/monitoring-dashboards.md
Normal file
|
|
@ -0,0 +1,196 @@
|
||||||
|
# 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 Grafana folder **Homelab** (the `grafana_folder` annotation).
|
||||||
|
|
||||||
|
## 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{cluster="pg"} > bool 0)
|
||||||
|
* (cnpg_actions_running_total{cluster="pg"} > 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. 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
|
||||||
|
```
|
||||||
|
4. Wait for the sidecar (it polls; a ConfigMap change is picked up within a
|
||||||
|
minute) and confirm the board answers `/api/search?query=<uid>` with your 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.
|
||||||
|
|
||||||
|
## 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.
|
||||||
427
monitoring/controllers/home/dashboards/build.py
Normal file
427
monitoring/controllers/home/dashboards/build.py
Normal file
|
|
@ -0,0 +1,427 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Build the three homelab Grafana dashboards as provisioned ConfigMaps.
|
||||||
|
|
||||||
|
Emits monitoring/controllers/home/dashboards/*.yaml in ~/Projects/homek8s.
|
||||||
|
The JSON dashboard lives inside the ConfigMap under a `.json` key, which is what
|
||||||
|
the kube-prometheus-stack grafana dashboard sidecar (LABEL=grafana_dashboard,
|
||||||
|
LABEL_VALUE=1, NAMESPACE=ALL) mounts.
|
||||||
|
|
||||||
|
Kept as a script so panel edits are reviewable and the validation step
|
||||||
|
(validate_panels.py) can re-read the same JSON from the emitted YAML.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
OUT_DIR = sys.argv[1] if len(sys.argv) > 1 else os.path.expanduser(
|
||||||
|
"~/Projects/homek8s/monitoring/controllers/home/dashboards")
|
||||||
|
|
||||||
|
DS = {"type": "prometheus", "uid": "prometheus"}
|
||||||
|
CLUSTER_NS = 'namespace=~"$namespace"'
|
||||||
|
|
||||||
|
_next_id = [0]
|
||||||
|
|
||||||
|
|
||||||
|
def pid():
|
||||||
|
_next_id[0] += 1
|
||||||
|
return _next_id[0]
|
||||||
|
|
||||||
|
|
||||||
|
def target(expr, legend=None, ref="A", instant=False, fmt="time_series"):
|
||||||
|
t = {"datasource": DS, "expr": expr, "refId": ref,
|
||||||
|
"editorMode": "code", "range": not instant, "instant": instant}
|
||||||
|
if legend:
|
||||||
|
t["legendFormat"] = legend
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
def ts(title, targets, grid, unit=None, desc="", stack=False, fill=0, overrides=None,
|
||||||
|
w=12, h=8):
|
||||||
|
p = {
|
||||||
|
"id": pid(), "type": "timeseries", "title": title, "description": desc,
|
||||||
|
"datasource": DS, "gridPos": grid, "targets": targets,
|
||||||
|
"fieldConfig": {"defaults": {"custom": {"lineWidth": 1, "fillOpacity": fill,
|
||||||
|
"showPoints": "never"},
|
||||||
|
"color": {"mode": "palette-classic"}},
|
||||||
|
"overrides": overrides or []},
|
||||||
|
"options": {"legend": {"displayMode": "list", "placement": "bottom",
|
||||||
|
"calcs": ["lastNotNull"]},
|
||||||
|
"tooltip": {"mode": "multi", "sort": "desc"}},
|
||||||
|
}
|
||||||
|
if unit:
|
||||||
|
p["fieldConfig"]["defaults"]["unit"] = unit
|
||||||
|
if stack:
|
||||||
|
p["fieldConfig"]["defaults"]["custom"]["stacking"] = {"mode": "normal"}
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def stat(title, targets, grid, unit=None, desc="", text_size=32, reducer="lastNotNull",
|
||||||
|
thresholds=None, w=4, h=5, decimals=None):
|
||||||
|
p = {
|
||||||
|
"id": pid(), "type": "stat", "title": title, "description": desc,
|
||||||
|
"datasource": DS, "gridPos": grid, "targets": targets,
|
||||||
|
"fieldConfig": {"defaults": {
|
||||||
|
"color": {"mode": "thresholds"},
|
||||||
|
"mappings": [],
|
||||||
|
"thresholds": {"mode": "absolute", "steps": thresholds or [
|
||||||
|
{"color": "red", "value": None},
|
||||||
|
{"color": "green", "value": 1}]},
|
||||||
|
}, "overrides": []},
|
||||||
|
"options": {"colorMode": "value", "graphMode": "area",
|
||||||
|
"reduceOptions": {"calcs": [reducer], "fields": "", "values": False},
|
||||||
|
"textMode": "auto", "justifyMode": "auto"},
|
||||||
|
}
|
||||||
|
if unit:
|
||||||
|
p["fieldConfig"]["defaults"]["unit"] = unit
|
||||||
|
if decimals is not None:
|
||||||
|
p["fieldConfig"]["defaults"]["decimals"] = decimals
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def bargauge(title, targets, grid, unit=None, desc="", w=8, h=8):
|
||||||
|
return {
|
||||||
|
"id": pid(), "type": "bargauge", "title": title, "description": desc,
|
||||||
|
"datasource": DS, "gridPos": grid, "targets": targets,
|
||||||
|
"fieldConfig": {"defaults": {"unit": unit or "short", "min": 0,
|
||||||
|
"color": {"mode": "palette-classic"},
|
||||||
|
"mappings": []}, "overrides": []},
|
||||||
|
"options": {"displayMode": "gradient", "orientation": "horizontal",
|
||||||
|
"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False},
|
||||||
|
"showUnfilled": True, "valueMode": "color"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def note(title, md, grid, h=6):
|
||||||
|
return {
|
||||||
|
"id": pid(), "type": "text", "title": title, "gridPos": grid,
|
||||||
|
"options": {"mode": "markdown", "code": {"language": "plaintext", "showLineNumbers": False,
|
||||||
|
"showMiniMap": False},
|
||||||
|
"content": md},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def row(title, y):
|
||||||
|
return {"id": pid(), "type": "row", "title": title, "collapsed": False,
|
||||||
|
"gridPos": {"h": 1, "w": 24, "x": 0, "y": y}, "panels": []}
|
||||||
|
|
||||||
|
|
||||||
|
def dashboard(uid, title, tags, panels, description, variables=None):
|
||||||
|
return {
|
||||||
|
"uid": uid, "title": title, "description": description, "tags": tags,
|
||||||
|
"timezone": "browser", "editable": True, "graphTooltip": 1,
|
||||||
|
"schemaVersion": 39, "version": 1, "refresh": "30s",
|
||||||
|
"time": {"from": "now-6h", "to": "now"},
|
||||||
|
"annotations": {"list": [{"builtIn": 1, "datasource": {"type": "grafana", "uid": "-- Grafana --"},
|
||||||
|
"enable": True, "hide": True, "iconColor": "rgba(0, 211, 255, 1)",
|
||||||
|
"name": "Annotations & Alerts", "type": "dashboard"}]},
|
||||||
|
"links": [],
|
||||||
|
"templating": {"list": variables or []},
|
||||||
|
"panels": panels,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def ns_variable():
|
||||||
|
return {
|
||||||
|
"name": "namespace", "label": "Postgres cluster (namespace)", "type": "query",
|
||||||
|
"datasource": DS, "refresh": 1, "includeAll": True, "multi": True,
|
||||||
|
"allValue": ".*", "current": {"selected": True, "text": ["All"], "value": ["$__all"]},
|
||||||
|
"options": [],
|
||||||
|
"query": {"query": "label_values(cnpg_collector_up, namespace)", "refId": "PromQLNamespace"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- runners -----
|
||||||
|
RUN = 'namespace="forgejo",pod=~"forgejo-runner-.*"'
|
||||||
|
SIRIUSSEC_FS = 'instance="10.10.0.2:9100",mountpoint="/"'
|
||||||
|
RPI_FS = 'instance="10.10.0.1:9100",mountpoint="/"'
|
||||||
|
|
||||||
|
runners = [
|
||||||
|
row("Runners & queue", 0),
|
||||||
|
stat("Runner pods Ready", [target('sum(kube_deployment_status_replicas_ready{namespace="forgejo",deployment=~"forgejo-runner-.*"})')],
|
||||||
|
{"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}]),
|
||||||
|
stat("Runner pods not Ready", [target('sum(kube_pod_status_ready{%s,condition="false"} == 1)' % RUN)],
|
||||||
|
{"h": 5, "w": 4, "x": 4, "y": 1}, desc="Running-but-not-Ready runner pods (crashloop, failing probe).",
|
||||||
|
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}], reducer="lastNotNull"),
|
||||||
|
stat("Last runner poll age", [target('max(cnpg_actions_runners_last_online_seconds{cluster="pg"})')],
|
||||||
|
{"h": 5, "w": 4, "x": 8, "y": 1}, unit="s",
|
||||||
|
desc="Worst of the three runners, from Forgejo's action_runner.last_online. A Running pod whose poll age climbs is a runner that cannot reach the forge.",
|
||||||
|
thresholds=[{"color": "green", "value": None}, {"color": "yellow", "value": 90}, {"color": "red", "value": 300}]),
|
||||||
|
stat("Queue depth", [target('max(cnpg_actions_queue_depth{cluster="pg"})')],
|
||||||
|
{"h": 5, "w": 4, "x": 12, "y": 1},
|
||||||
|
desc="Jobs assigned to a runner that have not started (action_run_job: started=0, stopped=0, status<>4).",
|
||||||
|
thresholds=[{"color": "green", "value": None}, {"color": "yellow", "value": 1}, {"color": "red", "value": 3}]),
|
||||||
|
stat("Running now", [target('max(cnpg_actions_running_total{cluster="pg"})')],
|
||||||
|
{"h": 5, "w": 4, "x": 16, "y": 1},
|
||||||
|
desc="Jobs currently executing. capacity=1 per runner, so >3 here means something is stuck."),
|
||||||
|
stat("Queue while running = contention", [target('max((cnpg_actions_queue_depth{cluster="pg"} > bool 0) * (cnpg_actions_running_total{cluster="pg"} > bool 0))')],
|
||||||
|
{"h": 5, "w": 4, "x": 20, "y": 1},
|
||||||
|
desc="1 = jobs are queued while another job runs, i.e. the single-slot runners are the bottleneck (this is why capacity stays 1: two concurrent jobs clobbered the shared docker volumes).",
|
||||||
|
thresholds=[{"color": "green", "value": None}, {"color": "orange", "value": 1}]),
|
||||||
|
|
||||||
|
row("Action throughput & outcomes", 6),
|
||||||
|
ts("Jobs finished, by status (24h window)",
|
||||||
|
[target('cnpg_actions_jobs_window_total{cluster="pg",window="24h"}', "status {{status}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 0, "y": 7}, unit="short",
|
||||||
|
desc="Rolling 24h count of action_run_job rows with stopped in the window. status 1=success 2=failure 3=cancelled 4=skipped (codes validated against /api/v1 .../actions/runs)."),
|
||||||
|
ts("Successes / hour and failures / hour",
|
||||||
|
[target('max(cnpg_actions_jobs_window_total{cluster="pg",window="1h",status="1"})', "success, last 60m"),
|
||||||
|
target('max(cnpg_actions_jobs_window_total{cluster="pg",window="1h",status="2"})', "failure, last 60m", ref="B")],
|
||||||
|
{"h": 8, "w": 8, "x": 8, "y": 7}, unit="short",
|
||||||
|
desc="Jobs that finished inside the last rolling hour. A true rolling count, not rate() over a row count — Forgejo prunes rows, so rate() would drift."),
|
||||||
|
ts("Oldest not-yet-started job age",
|
||||||
|
[target('cnpg_actions_queue_oldest_pending_seconds{cluster="pg"}')],
|
||||||
|
{"h": 8, "w": 8, "x": 16, "y": 7}, unit="s",
|
||||||
|
desc="How long the oldest queued job has been waiting. Flat 0 = nothing queued."),
|
||||||
|
|
||||||
|
row("Runner pods", 15),
|
||||||
|
ts("Runner pod restarts (24h)", [target('sum by (pod, container) (increase(kube_pod_container_status_restarts_total{%s}[24h]))' % RUN, "{{pod}} / {{container}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 0, "y": 16}, unit="short",
|
||||||
|
desc="increase() over 24h from kube-state-metrics. The history behind this board: the amd64 runner crashlooped on dind socket permissions."),
|
||||||
|
ts("CPU usage per runner pod", [target('sum by (pod) (rate(container_cpu_usage_seconds_total{%s,container!=""}[5m]))' % RUN, "{{pod}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 8, "y": 16}, unit="cores",
|
||||||
|
desc="cAdvisor CPU per runner pod. The dind sidecar of forgejo-runner-amd64 does the actual build work."),
|
||||||
|
ts("Memory working set per runner pod", [target('sum by (pod) (container_memory_working_set_bytes{%s,container!=""}' % RUN, "{{pod}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 16, "y": 16}, unit="bytes",
|
||||||
|
desc="cAdvisor working set. Note the amd64 runner's dind keeps a 1Gi memory limit — a build that OOMs shows here first."),
|
||||||
|
|
||||||
|
row("Disk — the one that actually bites", 24),
|
||||||
|
ts("Runner pod network I/O", [target('sum by (pod) (rate(container_network_receive_bytes_total{%s}[5m]))' % RUN, "{{pod}} in"),
|
||||||
|
target('sum by (pod) (rate(container_network_transmit_bytes_total{%s}[5m]))' % RUN, "{{pod}} out", ref="B")],
|
||||||
|
{"h": 8, "w": 8, "x": 0, "y": 25}, unit="Bps", desc="Image pulls and artifact traffic through the pod interface."),
|
||||||
|
stat("dind PVC nominal size", [target('max(kube_persistentvolumeclaim_resource_requests_storage_bytes{namespace="forgejo",persistentvolumeclaim="forgejo-runner-amd64"})')],
|
||||||
|
{"h": 8, "w": 4, "x": 8, "y": 25}, unit="bytes",
|
||||||
|
desc="Requested size of the forgejo-runner-amd64 PVC (docker data-root + named CI volumes). This is the ceiling, not the usage — see the note on this row."),
|
||||||
|
stat("siriussec root fs used", [target('100 * (1 - node_filesystem_avail_bytes{%s} / node_filesystem_size_bytes{%s})' % (SIRIUSSEC_FS, SIRIUSSEC_FS))],
|
||||||
|
{"h": 8, "w": 4, "x": 12, "y": 25}, unit="percent",
|
||||||
|
desc="The dind data-root lives on /opt/local-path-provisioner inside this filesystem, so this IS the number that caused the DiskPressure evictions at ~86%.",
|
||||||
|
thresholds=[{"color": "green", "value": None}, {"color": "yellow", "value": 75}, {"color": "red", "value": 85}]),
|
||||||
|
stat("siriussec days to full", [target('clamp_max(node_filesystem_avail_bytes{%s} / clamp_min(-deriv(node_filesystem_avail_bytes{%s}[1h]), 0.0000001) / 86400, 365)' % (SIRIUSSEC_FS, SIRIUSSEC_FS))],
|
||||||
|
{"h": 8, "w": 4, "x": 16, "y": 25}, unit="d", decimals=1,
|
||||||
|
desc="Linear projection from the last hour of free-space trend; 365 = not shrinking. Only meaningful after a few hours of history.",
|
||||||
|
thresholds=[{"color": "red", "value": None}, {"color": "yellow", "value": 30}, {"color": "green", "value": 90}]),
|
||||||
|
ts("rpi root fs used %", [target('100 * (1 - node_filesystem_avail_bytes{%s} / node_filesystem_size_bytes{%s})' % (RPI_FS, RPI_FS))],
|
||||||
|
{"h": 8, "w": 4, "x": 20, "y": 25}, unit="percent",
|
||||||
|
desc="The arm64 runners run their jobs as HOST docker containers on rpi, so their writes land here, not in any PVC. node-exporter on rpi is what makes this visible."),
|
||||||
|
|
||||||
|
note("What this board can and cannot see", """\
|
||||||
|
**Measured:** runner Deployments (kube-state-metrics), runner pods CPU/mem/net/restarts (cAdvisor),
|
||||||
|
runner liveness as *Forgejo* sees it (`action_runner.last_online`), queue depth and job outcomes
|
||||||
|
(`action_run_job` via the CNPG exporter), and the host filesystems that CI fills (node-exporter).
|
||||||
|
|
||||||
|
**Not measurable — by design, not by omission:**
|
||||||
|
|
||||||
|
- **Per-job breakdown on the arm64 runner.** `forgejo-runner-arm64` and
|
||||||
|
`forgejo-runner-deploy-arm64` drive the **host** Docker socket (gid 984), so their jobs are
|
||||||
|
plain host containers with no pod identity. cAdvisor/kube-state-metrics see only the runner
|
||||||
|
pod itself. There is no per-job CPU/mem/disk on rpi and there cannot be one without changing
|
||||||
|
the runner to dind — which this board deliberately does not propose.
|
||||||
|
- **Per-PV bytes for the dind PVC.** local-path PVs are `hostPath`, and kubelet publishes no
|
||||||
|
`kubelet_volume_stats_*` for hostPath volumes (verified: the only `kubelet_volume_*` series on
|
||||||
|
this cluster are the collector-duration histograms). The usable proxy is siriussec's root
|
||||||
|
filesystem usage plus the PVC's requested size, both on this row.
|
||||||
|
""", {"h": 7, "w": 24, "x": 0, "y": 33}),
|
||||||
|
]
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------- cnpg -------
|
||||||
|
cnpg = [
|
||||||
|
row("Cluster health", 0),
|
||||||
|
stat("Instances up", [target('min by (namespace) (cnpg_collector_up{%s})' % CLUSTER_NS)],
|
||||||
|
{"h": 5, "w": 4, "x": 0, "y": 1}, desc="cnpg_collector_up from the instance manager (:9187) — 1 = PostgreSQL answering."),
|
||||||
|
stat("Nodes used / instances", [target('max by (namespace) (cnpg_collector_nodes_used{%s})' % CLUSTER_NS)],
|
||||||
|
{"h": 5, "w": 4, "x": 4, "y": 1}, desc="1 with instances: 1 — no HA. Documented as a known limit, not a fault."),
|
||||||
|
stat("Connections used", [target('sum by (namespace) (cnpg_backends_total{%s})' % CLUSTER_NS)],
|
||||||
|
{"h": 5, "w": 4, "x": 8, "y": 1}, desc="pg_stat_activity backends, all states."),
|
||||||
|
stat("Connections / max_connections", [target('100 * sum by (namespace) (cnpg_backends_total{%s}) / max by (namespace) (cnpg_pg_settings_setting{%s,name="max_connections"})' % (CLUSTER_NS, CLUSTER_NS))],
|
||||||
|
{"h": 5, "w": 4, "x": 12, "y": 1}, unit="percent",
|
||||||
|
desc="Used against the server's own max_connections setting, so it stays right if the setting changes.",
|
||||||
|
thresholds=[{"color": "green", "value": None}, {"color": "yellow", "value": 70}, {"color": "red", "value": 90}]),
|
||||||
|
stat("Manual switchover required", [target('max by (namespace) (cnpg_collector_manual_switchover_required{%s})' % CLUSTER_NS)],
|
||||||
|
{"h": 5, "w": 4, "x": 16, "y": 1},
|
||||||
|
desc="1 = the operator is asking for a manual switchover (e.g. after a fencing event).",
|
||||||
|
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}]),
|
||||||
|
stat("Last available backup", [target('max by (namespace) (cnpg_collector_last_available_backup_timestamp{%s})' % CLUSTER_NS)],
|
||||||
|
{"h": 5, "w": 4, "x": 20, "y": 1}, unit="dateTimeAsIso",
|
||||||
|
desc="0 = never. There are NO Backup/Cluster backup resources in this cluster (verified: `kubectl get backups.postgresql.cnpg.io -A` is empty), so a 0 here is the honest answer, not a broken panel.",
|
||||||
|
thresholds=[{"color": "red", "value": None}, {"color": "green", "value": 1}]),
|
||||||
|
|
||||||
|
row("Throughput", 6),
|
||||||
|
ts("Transactions/s — commit vs rollback",
|
||||||
|
[target('sum by (namespace) (rate(cnpg_pg_stat_database_xact_commit{%s}[5m]))' % CLUSTER_NS, "{{namespace}} commit"),
|
||||||
|
target('sum by (namespace) (rate(cnpg_pg_stat_database_xact_rollback{%s}[5m]))' % CLUSTER_NS, "{{namespace}} rollback", ref="B")],
|
||||||
|
{"h": 8, "w": 12, "x": 0, "y": 7}, unit="ops",
|
||||||
|
desc="From pg_stat_database, which Forgejo's connection pool drives directly."),
|
||||||
|
ts("Commit share", [target('sum(rate(cnpg_pg_stat_database_xact_commit{%s}[5m])) / clamp_min(sum(rate(cnpg_pg_stat_database_xact_commit{%s}[5m])) + sum(rate(cnpg_pg_stat_database_xact_rollback{%s}[5m])), 0.0000001)' % (CLUSTER_NS, CLUSTER_NS, CLUSTER_NS))],
|
||||||
|
{"h": 8, "w": 6, "x": 12, "y": 7}, unit="percentunit",
|
||||||
|
desc="Commit / (commit + rollback). clamp_min keeps a quiet database from rendering NaN."),
|
||||||
|
ts("Cache hit ratio", [target('sum by (namespace) (rate(cnpg_pg_stat_database_blks_hit{%s}[5m])) / clamp_min(sum by (namespace) (rate(cnpg_pg_stat_database_blks_hit{%s}[5m])) + sum by (namespace) (rate(cnpg_pg_stat_database_blks_read{%s}[5m])), 0.0000001)' % (CLUSTER_NS, CLUSTER_NS, CLUSTER_NS), "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 6, "x": 18, "y": 7}, unit="percentunit",
|
||||||
|
desc="shared_buffers hit ratio. A lab database with 256Mi request will sit high; a drop means the working set outgrew the buffers."),
|
||||||
|
|
||||||
|
row("Errors and pressure", 15),
|
||||||
|
ts("Deadlocks (24h increase)", [target('sum by (namespace) (increase(cnpg_pg_stat_database_deadlocks{%s}[24h]))' % CLUSTER_NS, "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 0, "y": 16}, unit="short",
|
||||||
|
desc="increase() on a counter that exists on every database, so a quiet DB renders a hard 0 rather than 'No data'."),
|
||||||
|
ts("Temp bytes/s", [target('sum by (namespace) (rate(cnpg_pg_stat_database_temp_bytes{%s}[5m]))' % CLUSTER_NS, "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 8, "y": 16}, unit="Bps",
|
||||||
|
desc="Spill to disk from sorts/hashes that did not fit work_mem. Non-zero during Forgejo Actions index scans is expected."),
|
||||||
|
ts("Longest transaction age", [target('max by (namespace) (cnpg_backends_max_tx_duration_seconds{%s})' % CLUSTER_NS, "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 16, "y": 16}, unit="s",
|
||||||
|
desc="Longest open transaction (pg_stat_activity.xact_start). The CNPG default query set exposes transaction age, not per-statement query age — see docs."),
|
||||||
|
|
||||||
|
row("Size, WAL, replication", 24),
|
||||||
|
ts("Database size", [target('max by (namespace, datname) (cnpg_pg_database_size_bytes{%s,datname!~"template.*|postgres"})' % CLUSTER_NS, "{{namespace}}/{{datname}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 0, "y": 25}, unit="bytes",
|
||||||
|
desc="pg_database_size. Both PVs are 10Gi (forgejo/pg) and 5Gi (sirius-growth/portal) — this is the trend that fills them."),
|
||||||
|
ts("WAL generation", [target('sum by (namespace) (rate(cnpg_collector_wal_bytes{%s}[5m]))' % CLUSTER_NS, "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 8, "y": 25}, unit="Bps",
|
||||||
|
desc="Bytes of WAL written per second. On a cluster with no backups, WAL has nothing archiving it away."),
|
||||||
|
ts("WAL archiver failures", [target('max by (namespace) (cnpg_pg_stat_archiver_failed_count{%s})' % CLUSTER_NS, "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 16, "y": 25}, unit="short",
|
||||||
|
desc="pg_stat_archiver.failed_count. Archiving is not configured on either cluster (no ObjectStore/backup), so treat non-zero here as 'something was attempted and failed'."),
|
||||||
|
|
||||||
|
row("Replication (single instance — panels are honest about it)", 33),
|
||||||
|
ts("Replication lag", [target('max by (namespace) (cnpg_pg_replication_lag{%s})' % CLUSTER_NS, "{{namespace}}")],
|
||||||
|
{"h": 6, "w": 8, "x": 0, "y": 34}, unit="s",
|
||||||
|
desc="0 on the primary with no standby. With instances: 1 this metric is structurally zero, not evidence that replication is healthy."),
|
||||||
|
ts("Streaming replicas / in recovery", [target('max by (namespace) (cnpg_pg_replication_streaming_replicas{%s})' % CLUSTER_NS, "{{namespace}} streaming"),
|
||||||
|
target('max by (namespace) (cnpg_pg_replication_in_recovery{%s})' % CLUSTER_NS, "{{namespace}} in recovery", ref="B")],
|
||||||
|
{"h": 6, "w": 8, "x": 8, "y": 34}, unit="short",
|
||||||
|
desc="Both clusters run instances: 1, so 0 streaming replicas and in_recovery=0 is the correct reading. A future replica would light these up with no dashboard change."),
|
||||||
|
note("Known unknowns on the CNPG board", """\
|
||||||
|
- **No backups exist.** `kubectl get backups.postgresql.cnpg.io -A` returns nothing; neither Cluster
|
||||||
|
declares `spec.backup`. The "Last available backup" stat therefore reads 0 (never) — that is the
|
||||||
|
real state, not a missing metric.
|
||||||
|
- **Single instance.** Both clusters run `instances: 1`, so replication lag / streaming replicas /
|
||||||
|
in recovery are structurally zero. The panels show the zero and say so instead of hiding them.
|
||||||
|
- **Query age vs transaction age.** CNPG's default query set exposes
|
||||||
|
`cnpg_backends_max_tx_duration_seconds` (transaction age). Per-statement `query_start` age is not in
|
||||||
|
the default set; adding it would need another custom query in the cluster's
|
||||||
|
`customQueriesConfigMap`.
|
||||||
|
- **Permissions.** Custom queries run as `cnpg_metrics_exporter`, not superuser. See
|
||||||
|
docs/monitoring-dashboards.md for the GRANT the Forgejo Actions metrics need.
|
||||||
|
""", {"h": 8, "w": 24, "x": 0, "y": 40}),
|
||||||
|
]
|
||||||
|
|
||||||
|
# -------------------------------------------------------------- workloads -----
|
||||||
|
workloads = [
|
||||||
|
row("Cluster", 0),
|
||||||
|
stat("Nodes Ready", [target('count(kube_node_status_condition{condition="Ready",status="true"} == 1)')],
|
||||||
|
{"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)')],
|
||||||
|
{"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.",
|
||||||
|
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}]),
|
||||||
|
stat("Pending pods", [target('sum(kube_pod_status_phase{phase="Pending"} == 1)')],
|
||||||
|
{"h": 5, "w": 4, "x": 8, "y": 1},
|
||||||
|
desc="Pods that cannot be scheduled — usually an unschedulable taint or an exhausted resource request.",
|
||||||
|
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 1}]),
|
||||||
|
stat("Internal gateway probes OK", [target('sum(probe_success{job="internal-gateway"})')],
|
||||||
|
{"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.",
|
||||||
|
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)')],
|
||||||
|
{"h": 5, "w": 4, "x": 16, "y": 1}),
|
||||||
|
stat("PVC capacity requested", [target('sum(kube_persistentvolumeclaim_resource_requests_storage_bytes)')],
|
||||||
|
{"h": 5, "w": 4, "x": 20, "y": 1}, unit="bytes",
|
||||||
|
desc="Sum of every PVC request (local-path: all on siriussec's disk). Usage per PV is not available — see the note at the bottom."),
|
||||||
|
|
||||||
|
row("Requests vs usage", 6),
|
||||||
|
ts("CPU usage by namespace", [target('sum by (namespace) (rate(container_cpu_usage_seconds_total{container!=""}[5m]))', "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 12, "x": 0, "y": 7}, unit="cores",
|
||||||
|
desc="cAdvisor, all containers including pause-less init containers. Compare with the requests panel next to it."),
|
||||||
|
ts("CPU requests by namespace", [target('sum by (namespace) (kube_pod_container_resource_requests{resource="cpu"})', "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 12, "x": 12, "y": 7}, unit="cores",
|
||||||
|
desc="Scheduler-visible requests — this is what makes a pod Pending, not usage."),
|
||||||
|
ts("Memory usage by namespace", [target('sum by (namespace) (container_memory_working_set_bytes{container!=""})', "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 12, "x": 0, "y": 15}, unit="bytes"),
|
||||||
|
ts("Memory requests by namespace", [target('sum by (namespace) (kube_pod_container_resource_requests{resource="memory"})', "{{namespace}}")],
|
||||||
|
{"h": 8, "w": 12, "x": 12, "y": 15}, unit="bytes"),
|
||||||
|
|
||||||
|
row("Top pods", 23),
|
||||||
|
ts("Top 10 pods by CPU", [target('topk(10, sum by (namespace, pod) (rate(container_cpu_usage_seconds_total{container!=""}[5m])))', "{{namespace}}/{{pod}}")],
|
||||||
|
{"h": 8, "w": 12, "x": 0, "y": 24}, unit="cores"),
|
||||||
|
ts("Top 10 pods by memory", [target('topk(10, sum by (namespace, pod) (container_memory_working_set_bytes{container!=""}))', "{{namespace}}/{{pod}}")],
|
||||||
|
{"h": 8, "w": 12, "x": 12, "y": 24}, unit="bytes"),
|
||||||
|
ts("Pod restarts (24h, top 10)", [target('topk(10, sum by (namespace, pod) (increase(kube_pod_container_status_restarts_total[24h])))', "{{namespace}}/{{pod}}")],
|
||||||
|
{"h": 8, "w": 12, "x": 0, "y": 32}, unit="short",
|
||||||
|
desc="increase() over 24h. Values below 1 are container restarts that happened before the current scrape window started."),
|
||||||
|
ts("Internal gateway probe result", [target('probe_success{job="internal-gateway"}', "{{instance}}")],
|
||||||
|
{"h": 8, "w": 12, "x": 12, "y": 32}, unit="short",
|
||||||
|
desc="1 = HTTP 2xx/3xx from blackbox-exporter every 30s. There is no Alertmanager in this stack, so this panel and Prometheus /alerts are the alerting surface."),
|
||||||
|
|
||||||
|
row("Nodes", 40),
|
||||||
|
ts("Node CPU utilisation", [target('100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))', "{{instance}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 0, "y": 41}, unit="percent"),
|
||||||
|
ts("Node memory used", [target('100 * (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)', "{{instance}}")],
|
||||||
|
{"h": 8, "w": 8, "x": 8, "y": 41}, unit="percent"),
|
||||||
|
ts("Filesystem used %",
|
||||||
|
[target('100 * (1 - node_filesystem_avail_bytes{mountpoint="/",fstype!~"tmpfs|overlay"} / node_filesystem_size_bytes{mountpoint="/",fstype!~"tmpfs|overlay"})', "{{instance}} /")],
|
||||||
|
{"h": 8, "w": 8, "x": 16, "y": 41}, unit="percent",
|
||||||
|
desc="Root filesystem per node — the local-path PVs, the dind data-root and the Pi's host-docker job containers all land on these."),
|
||||||
|
|
||||||
|
note("Known unknowns on this board", """\
|
||||||
|
- **PVC usage is not charted, only requested capacity.** local-path provisions `hostPath` PVs and kubelet
|
||||||
|
publishes no `kubelet_volume_stats_used_bytes` for them (this cluster only emits the
|
||||||
|
`kubelet_volume_metric_collection_duration_seconds` histograms). Node filesystem usage is the honest
|
||||||
|
proxy for "how full is the disk these PVs live on".
|
||||||
|
- **Namespaces are not filtered.** With this few workloads an unfiltered board is more useful than a
|
||||||
|
variable that hides the one namespace you needed to see.
|
||||||
|
- **No Alertmanager.** Alerts from `PrometheusRule` objects are visible in Prometheus /alerts and in
|
||||||
|
Grafana → Alerting, but nothing pages.
|
||||||
|
""", {"h": 8, "w": 24, "x": 0, "y": 49}),
|
||||||
|
]
|
||||||
|
|
||||||
|
DOCS = {
|
||||||
|
"forgejo-runners": ("Forgejo Runners",
|
||||||
|
["homelab", "forgejo", "runners"],
|
||||||
|
"Runners, CI queue depth and job outcomes, plus the disk that CI actually fills.",
|
||||||
|
"Runner health as the cluster sees it (kube-state-metrics/cAdvisor) and as Forgejo "
|
||||||
|
"sees it (action_runner.last_online, action_run_job), plus the filesystem that the "
|
||||||
|
"dind data-root and the Pi's host-docker jobs consume."),
|
||||||
|
"cnpg-postgres": ("CNPG Postgres",
|
||||||
|
["homelab", "postgres", "cnpg"],
|
||||||
|
"Both CloudNativePG clusters: connections, throughput, errors, size, WAL, replication.",
|
||||||
|
"Metrics come from CNPG's instance-manager exporter on :9187, scraped by the "
|
||||||
|
"per-cluster PodMonitors in apps/base/*/podmonitor.yaml."),
|
||||||
|
"home-lab-workloads": ("Home lab workloads",
|
||||||
|
["homelab", "overview"],
|
||||||
|
"Per-namespace requests vs usage, top pods, node health and internal-service availability.",
|
||||||
|
"Cluster-wide view: who is using CPU/memory, what is Pending or restarting, how full "
|
||||||
|
"the nodes' disks are, and whether the WireGuard-only internal services answer."),
|
||||||
|
}
|
||||||
|
|
||||||
|
PANELS = {"forgejo-runners": runners, "cnpg-postgres": cnpg, "home-lab-workloads": workloads}
|
||||||
|
|
||||||
|
os.makedirs(OUT_DIR, exist_ok=True)
|
||||||
|
for uid, panels in PANELS.items():
|
||||||
|
_next_id[0] = 0
|
||||||
|
title, tags, desc, long_desc = DOCS[uid]
|
||||||
|
d = dashboard(uid, title, tags, panels, long_desc,
|
||||||
|
variables=[ns_variable()] if uid == "cnpg-postgres" else None)
|
||||||
|
doc = {
|
||||||
|
"apiVersion": "v1",
|
||||||
|
"kind": "ConfigMap",
|
||||||
|
"metadata": {
|
||||||
|
"name": "grafana-dashboard-" + uid,
|
||||||
|
"namespace": "monitoring",
|
||||||
|
"labels": {"grafana_dashboard": "1", "app.kubernetes.io/part-of": "homelab-dashboards"},
|
||||||
|
"annotations": {"grafana_folder": "Homelab",
|
||||||
|
"homelab.siriusdevops.com/managed-by": "monitoring/controllers/home/dashboards/build.py"},
|
||||||
|
},
|
||||||
|
"data": {uid + ".json": json.dumps(d, indent=2) + "\n"},
|
||||||
|
}
|
||||||
|
path = os.path.join(OUT_DIR, uid + ".yaml")
|
||||||
|
with open(path, "w") as f:
|
||||||
|
f.write("# GENERATED by monitoring/controllers/home/dashboards/build.py — edit the script, not this file.\n")
|
||||||
|
f.write("# Provisioned by the kube-prometheus-stack dashboard sidecar (label grafana_dashboard=1,\n")
|
||||||
|
f.write("# NAMESPACE=ALL), so it wins over any UI edit. Dashboard uid: %s\n" % uid)
|
||||||
|
# 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(" labels:\n grafana_dashboard: \"1\"\n app.kubernetes.io/part-of: homelab-dashboards\n")
|
||||||
|
f.write(" annotations:\n grafana_folder: Homelab\n")
|
||||||
|
f.write(" homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py\n")
|
||||||
|
f.write("data:\n %s.json: |\n" % uid)
|
||||||
|
for line in doc["data"][uid + ".json"].rstrip("\n").split("\n"):
|
||||||
|
f.write(" " + line + "\n")
|
||||||
|
print("wrote", path)
|
||||||
1211
monitoring/controllers/home/dashboards/cnpg-postgres.yaml
Normal file
1211
monitoring/controllers/home/dashboards/cnpg-postgres.yaml
Normal file
File diff suppressed because it is too large
Load diff
1209
monitoring/controllers/home/dashboards/forgejo-runners.yaml
Normal file
1209
monitoring/controllers/home/dashboards/forgejo-runners.yaml
Normal file
File diff suppressed because it is too large
Load diff
1149
monitoring/controllers/home/dashboards/home-lab-workloads.yaml
Normal file
1149
monitoring/controllers/home/dashboards/home-lab-workloads.yaml
Normal file
File diff suppressed because it is too large
Load diff
10
monitoring/controllers/home/dashboards/kustomization.yaml
Normal file
10
monitoring/controllers/home/dashboards/kustomization.yaml
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||||
|
kind: Kustomization
|
||||||
|
# Custom dashboards, loaded by the kube-prometheus-stack grafana sidecar
|
||||||
|
# (label grafana_dashboard=1, NAMESPACE=ALL, folder annotation grafana_folder).
|
||||||
|
# Regenerate the YAML from build.py after editing a panel; the JSON inside each
|
||||||
|
# ConfigMap is the deliverable, the .yaml is generated.
|
||||||
|
resources:
|
||||||
|
- forgejo-runners.yaml
|
||||||
|
- cnpg-postgres.yaml
|
||||||
|
- home-lab-workloads.yaml
|
||||||
|
|
@ -7,6 +7,7 @@ resources:
|
||||||
- release.yaml
|
- release.yaml
|
||||||
- httproute.yaml
|
- httproute.yaml
|
||||||
- gateway-probe.yaml
|
- gateway-probe.yaml
|
||||||
|
- dashboards
|
||||||
configMapGenerator:
|
configMapGenerator:
|
||||||
- name: kube-prometheus-stack-values
|
- name: kube-prometheus-stack-values
|
||||||
files:
|
files:
|
||||||
|
|
|
||||||
|
|
@ -152,11 +152,14 @@ kube-state-metrics:
|
||||||
memory: 256Mi
|
memory: 256Mi
|
||||||
|
|
||||||
prometheus-node-exporter:
|
prometheus-node-exporter:
|
||||||
# DaemonSet; pinned to siriussec per the stack's scheduling rule. Only
|
# DaemonSet on EVERY node (deliberately not pinned to siriussec). The arm64
|
||||||
# siriussec's node metrics are collected (kubelet/cAdvisor metrics for the
|
# Forgejo runner runs its jobs as *host* Docker containers on rpi, so the disk
|
||||||
# other nodes still arrive via the kubelet ServiceMonitor).
|
# pressure that matters there is the Pi's root filesystem — invisible to
|
||||||
nodeSelector:
|
# kubelet/cAdvisor, which only describe pods. The runner dashboard's "Pi disk
|
||||||
kubernetes.io/hostname: siriussec
|
# free" panel needs node-exporter on rpi to exist at all, and the same applies
|
||||||
|
# to linode. node-exporter is a read-only host-metrics DaemonSet (hostPath
|
||||||
|
# /proc + /sys, host network); it adds ~700 series per node, well inside the
|
||||||
|
# 8GB retentionSize cap, and rpi's PreferNoSchedule taint does not exclude it.
|
||||||
resources:
|
resources:
|
||||||
requests:
|
requests:
|
||||||
cpu: 20m
|
cpu: 20m
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue