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).
427 lines
30 KiB
Python
427 lines
30 KiB
Python
#!/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)
|