diff --git a/docs/grafana-persistence.md b/docs/grafana-persistence.md index 1333cfc..02c683d 100644 --- a/docs/grafana-persistence.md +++ b/docs/grafana-persistence.md @@ -53,16 +53,6 @@ So: changing `grafana-admin` alone on a populated PVC does **nothing**. That is by design (no silent password resets on redeploy), and it is exactly why the recovery path below matters. -> **Drift breaks the sidecars, not just the login.** The pod's sidecars (`grafana-sc-dashboard`, -> `grafana-sc-datasources`) carry `REQ_USERNAME`/`REQ_PASSWORD` from `grafana-admin` and POST -> `/api/admin/provisioning/{dashboards,datasources}/reload` as their "make Grafana read what I just -> wrote" step. Once the DB password has drifted from the Secret that POST returns **401**, so a -> datasource ConfigMap is written into `/etc/grafana/provisioning/datasources` and never loaded: -> the datasource is simply absent from `/api/datasources` while the file sits in the pod. Observable -> 2026-11-27 with the Loki datasource (ConfigMap live, file in the volume, no datasource in Grafana -> for 40 minutes). The DB was then reset to the Secret's value, so the seed and the DB match again -> and the reload answers **200**. Fix drift the same way before debugging a "missing" datasource. - ## Recovery: reset a lost admin password The trap with a persistent DB is that re-applying the Secret no longer helps. diff --git a/docs/logging.md b/docs/logging.md index cbbb092..e28ecc7 100644 --- a/docs/logging.md +++ b/docs/logging.md @@ -186,47 +186,13 @@ the audit history was then re-ingested through the fixed pipeline. ## Querying Grafana datasource `Loki` (`uid: loki`, `infrastructure/logging/datasource.yaml`, -loaded by the kube-prometheus-stack datasource sidecar) → Explore → Loki. The -saved queries live on the **Logs** dashboard (`uid: logs`, -`monitoring/controllers/home/dashboards/logs.yaml`, generated by `build.py`): - -``` -http://10.10.0.2:8081/d/logs/ -``` +loaded by the kube-prometheus-stack datasource sidecar) → Explore → Loki. From inside the cluster: `http://loki.logging.svc.cluster.local:3100`. From the Legion over WireGuard: `kubectl -n logging port-forward svc/loki 3100:3100`. No Gateway/listener is published for this — the store is not exposed outside the mesh and has no auth layer of its own. -**A new or edited datasource ConfigMap needs a provisioning reload.** Grafana -reads `provisioning/datasources` only at startup; the sidecar writes the file but -the thing that makes Grafana read it is the sidecar's own -`POST /api/admin/provisioning/datasources/reload`, authenticated with -`monitoring/grafana-admin`. If the DB password has drifted from that Secret the -POST 401s, the file is on disk and the datasource never appears — which looks -like a broken ConfigMap. Reload by hand with the Secret's credential: - -```bash -kubectl -n monitoring port-forward svc/kube-prometheus-stack-grafana 3000:80 & -curl -u "admin:$GF_ADMIN_PASSWORD" -X POST \ - http://127.0.0.1:3000/api/admin/provisioning/datasources/reload # 200 -``` - -**The audit stream's field names are not the audit event's.** Alloy re-emits each -record as a flat allowlist (`infrastructure/logging/alloy/config.alloy`), so -`objectRef.resource` arrives as the **stream label** `resource` and -`user.username` as the line field `user`: - -```logql -{job="kube/apiserver-audit", resource="secrets"} | json # who touched a Secret -``` - -`{job="kube/apiserver-audit"} | json | objectRef_resource="secrets"` returns -**zero rows** — measured 2026-11-27. `resource`/`verb` are stream labels, so put -them in the selector (Loki prunes streams before parsing); `user`, `ns`, `name`, -`code`, `sourceIP` are JSON fields and need `| json`. - Useful LogQL: ```logql @@ -234,7 +200,6 @@ Useful LogQL: {namespace="kube-system", container="cilium-agent"} |= "error" {job="systemd-journal", node="siriussec"} |= "sshd" # node-level auth activity sum by (namespace) (count_over_time({job="kube/pods"}[1h])) -sum by (user) (count_over_time({job="kube/apiserver-audit", resource="secrets"} | json [5m])) ``` Label cardinality is bounded: `namespace, pod, container, node, stream, job` diff --git a/docs/monitoring-dashboards.md b/docs/monitoring-dashboards.md index 3cd4762..066e529 100644 --- a/docs/monitoring-dashboards.md +++ b/docs/monitoring-dashboards.md @@ -1,6 +1,6 @@ # Monitoring dashboards -Four custom Grafana dashboards, all provisioned from this repo. Nothing on these +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 @@ -11,7 +11,6 @@ a UI edit is overwritten on the next sidecar poll. | 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? | -| Logs | `logs` | Who read a Secret (apiserver audit, by user), what did a pod say before it died, what did the CI runners print? | Open them (WireGuard only, no public hostname — see `docs/internal-wireguard-services.md`): @@ -20,37 +19,28 @@ Open them (WireGuard only, no public hostname — see 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/ -http://10.10.0.2:8081/d/logs/ ``` -`logs` is the odd one out: its panels query the **Loki** datasource (`uid: loki`, -`infrastructure/logging/datasource.yaml`) rather than Prometheus, and its two -template variables are filled from Loki's label API. The audit field names there -are the Alloy pipeline's allowlist, not the raw audit event's — `objectRef.resource` -arrives as the stream label `resource` and `user.username` as the field `user`; -`docs/logging.md` §Querying has the detail and the zero-row proof. - 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 that call only succeeds while the live -admin password still matches `monitoring/grafana-admin`. When the two have drifted -the POST returns **401** and Grafana's own **file** provider imports -`/tmp/dashboards` on its 10 s rescan instead — 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. -(The drift was repaired on 2026-11-27; see `docs/grafana-persistence.md`.) +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/LogQL +├── 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 -└── logs.yaml # GENERATED (Loki panels) +└── home-lab-workloads.yaml # GENERATED ``` **Edit `build.py`, then regenerate.** The generated YAML is committed so Flux @@ -167,22 +157,17 @@ throughput panels query "how many rows stopped inside the last hour" directly ## Adding a panel 1. Edit `monitoring/controllers/home/dashboards/build.py` — `ts()` for a - timeseries, `stat()` for a single number, `note()` for markdown, `logs()` for - a Loki log panel (its target must come from `loki_target()`, and the panel - needs `ds=DS_LOKI`). + timeseries, `stat()` for a single number, `note()` for markdown. 2. Regenerate (command above). -3. **Validate the query, not just the YAML.** `validate_panels.py` (next to +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` / `$runner_ns` - "All" cases and queries the target's own datasource — Prometheus for - PromQL panels, Loki for panels whose datasource is `loki` (a Loki panel is a - failure unless it returns rows, not just series). Anything that returns no - data is a failed panel. It needs both port-forwards: + 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 - kubectl -n monitoring port-forward svc/kube-prometheus-stack-prometheus 9090:9090 & - kubectl -n logging port-forward svc/loki 3100:3100 & python3 monitoring/controllers/home/dashboards/validate_panels.py \ - monitoring/controllers/home/dashboards http://127.0.0.1:9090 http://127.0.0.1:3100 + monitoring/controllers/home/dashboards http://127.0.0.1:9090 ``` 4. Commit + push to `master`, then force the reconcile: ```bash diff --git a/monitoring/controllers/home/dashboards/build.py b/monitoring/controllers/home/dashboards/build.py index 23eadd0..5dad13f 100644 --- a/monitoring/controllers/home/dashboards/build.py +++ b/monitoring/controllers/home/dashboards/build.py @@ -17,9 +17,6 @@ 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"} -# Loki is provisioned by infrastructure/logging/datasource.yaml with a pinned -# uid, so panels can reference it without a lookup. -DS_LOKI = {"type": "loki", "uid": "loki"} CLUSTER_NS = 'namespace=~"$namespace"' _next_id = [0] @@ -39,10 +36,10 @@ def target(expr, legend=None, ref="A", instant=False, fmt="time_series"): def ts(title, targets, grid, unit=None, desc="", stack=False, fill=0, overrides=None, - w=12, h=8, ds=DS): + w=12, h=8): p = { "id": pid(), "type": "timeseries", "title": title, "description": desc, - "datasource": ds, "gridPos": grid, "targets": targets, + "datasource": DS, "gridPos": grid, "targets": targets, "fieldConfig": {"defaults": {"custom": {"lineWidth": 1, "fillOpacity": fill, "showPoints": "never"}, "color": {"mode": "palette-classic"}}, @@ -59,10 +56,10 @@ def ts(title, targets, grid, unit=None, desc="", stack=False, fill=0, overrides= def stat(title, targets, grid, unit=None, desc="", text_size=32, reducer="lastNotNull", - thresholds=None, w=4, h=5, decimals=None, ds=DS): + thresholds=None, w=4, h=5, decimals=None): p = { "id": pid(), "type": "stat", "title": title, "description": desc, - "datasource": ds, "gridPos": grid, "targets": targets, + "datasource": DS, "gridPos": grid, "targets": targets, "fieldConfig": {"defaults": { "color": {"mode": "thresholds"}, "mappings": [], @@ -108,39 +105,6 @@ def row(title, y): "gridPos": {"h": 1, "w": 24, "x": 0, "y": y}, "panels": []} -# ---------------------------------------------------------------- logs -------- -# Loki targets. NOTE the field names are the audit pipeline's, not the raw -# kube-apiserver audit-event ones: infrastructure/logging/alloy/config.alloy -# re-emits each record as a flat allowlist, so `objectRef.resource` arrives as -# the stream label `resource` and `user.username` as `user`. `| json` is only -# needed to reach `user`/`ns`/`name`; the resource filter stays in the selector -# as a label matcher so Loki prunes streams before parsing anything. -AUDIT_SECRETS = '{job="kube/apiserver-audit", resource="secrets"}' -POD_LOGS = '{job="kube/pods"}' -POD_SEL = 'job="kube/pods"' -RUNNER_NS = 'namespace=~"$runner_ns"' - - -def loki_target(expr, legend=None, ref="A", instant=False): - t = {"datasource": DS_LOKI, "expr": expr, "refId": ref, - "queryType": "instant" if instant else "range", - "range": not instant, "instant": instant} - if legend: - t["legendFormat"] = legend - return t - - -def logs(title, targets, grid, desc="", sort="Descending"): - return { - "id": pid(), "type": "logs", "title": title, "description": desc, - "datasource": DS_LOKI, "gridPos": grid, "targets": targets, - "options": {"showTime": True, "showLabels": False, "showCommonLabels": False, - "wrapLogMessage": True, "prettifyLogMessage": False, - "enableLogDetails": True, "dedupStrategy": "none", - "sortOrder": sort}, - } - - def dashboard(uid, title, tags, panels, description, variables=None): return { "uid": uid, "title": title, "description": description, "tags": tags, @@ -166,35 +130,6 @@ def ns_variable(): } -def loki_ns_variable(): - # Same "All = .*" contract as ns_variable, but the option list comes from - # Loki's label API so it also contains namespaces Prometheus never scrapes - # (ci-probe, metabase, ...) and does not need kube-state-metrics. - return { - "name": "namespace", "label": "Namespace", "type": "query", - "datasource": DS_LOKI, "refresh": 2, "includeAll": True, "multi": True, - "allValue": ".*", "current": {"selected": True, "text": ["All"], "value": ["$__all"]}, - "options": [], - "query": {"query": 'label_values(%s, namespace)' % POD_LOGS, "refId": "LokiNamespace"}, - } - - -def loki_runner_ns_variable(): - # Runner namespaces are being moved by t_2bbe34a8 (forgejo -> forgejo-runners, - # with ci-runners also live), so the panels discover them instead of pinning - # one name: "All" expands to a regex that matches any *runner* namespace plus - # forgejo itself (which still runs pods the runners need to be read next to). - return { - "name": "runner_ns", "label": "Runner namespace", "type": "query", - "datasource": DS_LOKI, "refresh": 2, "includeAll": True, "multi": True, - "allValue": ".*(runner|forgejo).*", - "current": {"selected": True, "text": ["All"], "value": ["$__all"]}, - "options": [], - "query": {"query": 'label_values({job="kube/pods", namespace=~".*(runner|forgejo).*"}, ' - 'namespace)', "refId": "LokiRunnerNamespace"}, - } - - # ---------------------------------------------------------------- runners ----- # Only the three runner Deployments' pods. `forgejo-runner-.*` also matches the # `forgejo-runner-prune-*` CronJob pods, which are Completed and permanently @@ -444,82 +379,6 @@ workloads = [ """, {"h": 8, "w": 24, "x": 0, "y": 49}), ] -# ----------------------------------------------------------------- logs ------ -# Time-to-answer panels for an incident: who touched a Secret (apiserver audit) -# and what a pod said before it died. Both run against the Loki datasource -# (infrastructure/logging/datasource.yaml, uid `loki`). -logs_panels = [ - row("kube-apiserver audit — secret access", 0), - stat("Secret events (1h)", - [loki_target("sum(count_over_time(" + AUDIT_SECRETS + "[1h]))", instant=True)], - {"h": 5, "w": 4, "x": 0, "y": 1}, ds=DS_LOKI, - desc="Count of audit records whose object is a Secret, filtered on the stream labels " - "the Alloy audit pipeline emits. No log-line parsing involved."), - ts("Secret access by user", - [loki_target("sum by (user) (count_over_time(" + AUDIT_SECRETS + " | json [5m]))", - legend="{{user}}")], - {"h": 8, "w": 20, "x": 4, "y": 1}, ds=DS_LOKI, fill=10, stack=True, - desc="The 'who read that credential' view. `user` comes from user.username in the audit " - "record, so `| json` is needed for the grouping; the resource filter stays in the " - "selector as a label matcher."), - logs("Secret access log — verb, object, caller", - [loki_target(AUDIT_SECRETS + ' | json | line_format "{{.verb}} ' - '{{.subresource}}{{.ns}}/{{.name}} — {{.user}} ({{.code}})"')], - {"h": 10, "w": 24, "x": 0, "y": 9}, - desc="One line per audit record that touched a Secret. Secret bodies are never stored: " - "the pipeline allowlists fields and drops requestObject/responseObject."), - - row("Pod logs", 19), - logs("Errors — namespace = $namespace", - [loki_target("{" + POD_SEL + ', namespace=~"$namespace"} |= "error"')], - {"h": 9, "w": 12, "x": 0, "y": 20}, - desc="The ordinary 'what did the pod say before it died' query. Substring filter, so it " - "catches `error` anywhere in the line."), - logs("Error / exception / fatal / panic (case-insensitive)", - [loki_target("{" + POD_SEL + ', namespace=~"$namespace"} ' - '|~ "(?i)error|exception|fatal|panic"')], - {"h": 9, "w": 12, "x": 12, "y": 20}, - desc="Wider net for stacks that log `Exception`, `FATAL` or `panic:` instead of the word " - "`error`."), - - row("CI runners (forgejo / forgejo-runners)", 29), - logs("Runner pod logs", - [loki_target("{" + POD_SEL + ", " + RUNNER_NS + "}")], - {"h": 9, "w": 12, "x": 0, "y": 30}, - desc="Everything the runner pods print — job container output, dind, and the runner's own " - "poll/registration lines. The namespace comes from the `runner_ns` variable, which " - "matches any *runner* namespace (forgejo, forgejo-runners, ci-runners) so the panel " - "survives the t_2bbe34a8 move without an edit."), - ts("Runner error / fail lines per 5m", - [loki_target("sum by (namespace) (count_over_time({" + POD_SEL + ", " + RUNNER_NS + - '} |~ "(?i)error|fail" [5m]))', legend="{{namespace}}")], - {"h": 9, "w": 12, "x": 12, "y": 30}, ds=DS_LOKI, fill=10, stack=True, - desc="Coarse CI pain signal. A silent stall (a build looping on `Ign:` with no error) does " - "not show here — check the log panel above for that."), - - row("How to read these streams", 39), - note("Field names and retention", "\n".join([ - "Loki is single-binary in the `logging` namespace: **192 h (8 d)** retention on an 8Gi PVC,", - "fed by the Alloy DaemonSet. These panels only read it.", - "", - "| `job` | source | stream labels |", - "|---|---|---|", - "| `kube/pods` | every container's stdout (`/var/log/pods`) | `namespace, pod, container, node` |", - "| `kube/apiserver-audit` | `siriussec`'s `/var/log/kubernetes/audit/audit.log` | `resource, verb` |", - "| `systemd-journal` | node journals | `unit, host, level` |", - "| `docker/json` | the Pi's docker container logs | `container` |", - "", - "**The audit field names are the Alloy pipeline's allowlist, not the raw audit event's.**", - "`objectRef.resource` arrives as the stream label `resource` and `user.username` as the", - "line field `user`, so the usable query is", - "`{job=\"kube/apiserver-audit\", resource=\"secrets\"} | json` — an `objectRef_resource` or", - "`user_username` matcher returns **zero rows**. Secret bodies are never shipped: the", - "pipeline packs an allowlist and drops `requestObject`/`responseObject`", - "(`docs/logging.md`, `infrastructure/logging/alloy/config.alloy`).", - ]), {"h": 8, "w": 24, "x": 0, "y": 40}, h=8), -] - - DOCS = { "forgejo-runners": ("Forgejo Runners", ["homelab", "forgejo", "runners"], @@ -537,26 +396,16 @@ DOCS = { "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."), - "logs": ("Logs", - ["homelab", "logs", "loki", "audit"], - "Loki queries worth having: who read a Secret (apiserver audit), pod errors by namespace, CI runner output.", - "Loki single-binary in the `logging` namespace (192 h retention) holds pod logs, node journals, " - "the Pi's docker logs and the kube-apiserver audit stream. The audit panels answer 'who read " - "that credential'; the pod panels answer 'what did the pod say before it died'. Field names " - "are the Alloy pipeline's allowlist, not the raw audit event's — see the note panel."), } -PANELS = {"forgejo-runners": runners, "cnpg-postgres": cnpg, "home-lab-workloads": workloads, - "logs": logs_panels} +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 [loki_ns_variable(), loki_runner_ns_variable()] - if uid == "logs" else None)) + variables=[ns_variable()] if uid == "cnpg-postgres" else None) doc = { "apiVersion": "v1", "kind": "ConfigMap", @@ -564,13 +413,12 @@ for uid, panels in PANELS.items(): "name": "grafana-dashboard-" + uid, "namespace": "monitoring", "labels": {"grafana_dashboard": "1", "app.kubernetes.io/part-of": "homelab-dashboards"}, - # No grafana_folder annotation: the sidecar's API-backed import would need - # the admin credential, so the dashboards are imported by Grafana's *file* - # provider, which ignores per-dashboard folder annotations and puts every - # board in General next to the chart's own 28. Verified in grafana.db. - # (Since 2026-11-27 the live admin password equals monitoring/grafana-admin - # again — the DB was reset to the Secret's value — but the sidecar still - # imports by file, so nothing here depends on that.) + # No grafana_folder annotation: the sidecar's API-backed import cannot + # authenticate (Grafana's live admin password is the out-of-band one, + # not monitoring/grafana-admin — that Secret is only the first-boot + # seed), so the dashboards are imported by Grafana's *file* provider, + # which ignores per-dashboard folder annotations and puts every board + # in General next to the chart's own 28. Verified in grafana.db. "annotations": {"homelab.siriusdevops.com/managed-by": "monitoring/controllers/home/dashboards/build.py"}, }, "data": {uid + ".json": json.dumps(d, indent=2) + "\n"}, diff --git a/monitoring/controllers/home/dashboards/kustomization.yaml b/monitoring/controllers/home/dashboards/kustomization.yaml index 8de37f8..7cfdc10 100644 --- a/monitoring/controllers/home/dashboards/kustomization.yaml +++ b/monitoring/controllers/home/dashboards/kustomization.yaml @@ -8,7 +8,3 @@ resources: - forgejo-runners.yaml - cnpg-postgres.yaml - home-lab-workloads.yaml - # Loki panels: secret access from the apiserver audit stream, pod errors by - # namespace, CI runner output. Datasource uid `loki` - # (infrastructure/logging/datasource.yaml). - - logs.yaml diff --git a/monitoring/controllers/home/dashboards/logs.yaml b/monitoring/controllers/home/dashboards/logs.yaml deleted file mode 100644 index df83942..0000000 --- a/monitoring/controllers/home/dashboards/logs.yaml +++ /dev/null @@ -1,523 +0,0 @@ -# GENERATED by monitoring/controllers/home/dashboards/build.py — edit the script, not this file. -# Provisioned by the kube-prometheus-stack dashboard sidecar (label grafana_dashboard=1, -# NAMESPACE=ALL), so it wins over any UI edit. Dashboard uid: logs -apiVersion: v1 -kind: ConfigMap -metadata: - name: grafana-dashboard-logs - namespace: monitoring - labels: - grafana_dashboard: "1" - app.kubernetes.io/part-of: homelab-dashboards - annotations: - homelab.siriusdevops.com/managed-by: monitoring/controllers/home/dashboards/build.py -data: - logs.json: | - { - "uid": "logs", - "title": "Logs", - "description": "Loki single-binary in the `logging` namespace (192 h retention) holds pod logs, node journals, the Pi's docker logs and the kube-apiserver audit stream. The audit panels answer 'who read that credential'; the pod panels answer 'what did the pod say before it died'. Field names are the Alloy pipeline's allowlist, not the raw audit event's \u2014 see the note panel.", - "tags": [ - "homelab", - "logs", - "loki", - "audit" - ], - "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": [ - { - "name": "namespace", - "label": "Namespace", - "type": "query", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "refresh": 2, - "includeAll": true, - "multi": true, - "allValue": ".*", - "current": { - "selected": true, - "text": [ - "All" - ], - "value": [ - "$__all" - ] - }, - "options": [], - "query": { - "query": "label_values({job=\"kube/pods\"}, namespace)", - "refId": "LokiNamespace" - } - }, - { - "name": "runner_ns", - "label": "Runner namespace", - "type": "query", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "refresh": 2, - "includeAll": true, - "multi": true, - "allValue": ".*(runner|forgejo).*", - "current": { - "selected": true, - "text": [ - "All" - ], - "value": [ - "$__all" - ] - }, - "options": [], - "query": { - "query": "label_values({job=\"kube/pods\", namespace=~\".*(runner|forgejo).*\"}, namespace)", - "refId": "LokiRunnerNamespace" - } - } - ] - }, - "panels": [ - { - "id": 68, - "type": "row", - "title": "kube-apiserver audit \u2014 secret access", - "collapsed": false, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 0 - }, - "panels": [] - }, - { - "id": 69, - "type": "stat", - "title": "Secret events (1h)", - "description": "Count of audit records whose object is a Secret, filtered on the stream labels the Alloy audit pipeline emits. No log-line parsing involved.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 5, - "w": 4, - "x": 0, - "y": 1 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "sum(count_over_time({job=\"kube/apiserver-audit\", resource=\"secrets\"}[1h]))", - "refId": "A", - "queryType": "instant", - "range": false, - "instant": true - } - ], - "fieldConfig": { - "defaults": { - "color": { - "mode": "thresholds" - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "red", - "value": null - }, - { - "color": "green", - "value": 1 - } - ] - } - }, - "overrides": [] - }, - "options": { - "colorMode": "value", - "graphMode": "area", - "reduceOptions": { - "calcs": [ - "lastNotNull" - ], - "fields": "", - "values": false - }, - "textMode": "auto", - "justifyMode": "auto" - } - }, - { - "id": 70, - "type": "timeseries", - "title": "Secret access by user", - "description": "The 'who read that credential' view. `user` comes from user.username in the audit record, so `| json` is needed for the grouping; the resource filter stays in the selector as a label matcher.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 8, - "w": 20, - "x": 4, - "y": 1 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "sum by (user) (count_over_time({job=\"kube/apiserver-audit\", resource=\"secrets\"} | json [5m]))", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false, - "legendFormat": "{{user}}" - } - ], - "fieldConfig": { - "defaults": { - "custom": { - "lineWidth": 1, - "fillOpacity": 10, - "showPoints": "never", - "stacking": { - "mode": "normal" - } - }, - "color": { - "mode": "palette-classic" - } - }, - "overrides": [] - }, - "options": { - "legend": { - "displayMode": "list", - "placement": "bottom", - "calcs": [ - "lastNotNull" - ] - }, - "tooltip": { - "mode": "multi", - "sort": "desc" - } - } - }, - { - "id": 71, - "type": "logs", - "title": "Secret access log \u2014 verb, object, caller", - "description": "One line per audit record that touched a Secret. Secret bodies are never stored: the pipeline allowlists fields and drops requestObject/responseObject.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 10, - "w": 24, - "x": 0, - "y": 9 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "{job=\"kube/apiserver-audit\", resource=\"secrets\"} | json | line_format \"{{.verb}} {{.subresource}}{{.ns}}/{{.name}} \u2014 {{.user}} ({{.code}})\"", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false - } - ], - "options": { - "showTime": true, - "showLabels": false, - "showCommonLabels": false, - "wrapLogMessage": true, - "prettifyLogMessage": false, - "enableLogDetails": true, - "dedupStrategy": "none", - "sortOrder": "Descending" - } - }, - { - "id": 72, - "type": "row", - "title": "Pod logs", - "collapsed": false, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 19 - }, - "panels": [] - }, - { - "id": 73, - "type": "logs", - "title": "Errors \u2014 namespace = $namespace", - "description": "The ordinary 'what did the pod say before it died' query. Substring filter, so it catches `error` anywhere in the line.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 9, - "w": 12, - "x": 0, - "y": 20 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "{job=\"kube/pods\", namespace=~\"$namespace\"} |= \"error\"", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false - } - ], - "options": { - "showTime": true, - "showLabels": false, - "showCommonLabels": false, - "wrapLogMessage": true, - "prettifyLogMessage": false, - "enableLogDetails": true, - "dedupStrategy": "none", - "sortOrder": "Descending" - } - }, - { - "id": 74, - "type": "logs", - "title": "Error / exception / fatal / panic (case-insensitive)", - "description": "Wider net for stacks that log `Exception`, `FATAL` or `panic:` instead of the word `error`.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 9, - "w": 12, - "x": 12, - "y": 20 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "{job=\"kube/pods\", namespace=~\"$namespace\"} |~ \"(?i)error|exception|fatal|panic\"", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false - } - ], - "options": { - "showTime": true, - "showLabels": false, - "showCommonLabels": false, - "wrapLogMessage": true, - "prettifyLogMessage": false, - "enableLogDetails": true, - "dedupStrategy": "none", - "sortOrder": "Descending" - } - }, - { - "id": 75, - "type": "row", - "title": "CI runners (forgejo / forgejo-runners)", - "collapsed": false, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 29 - }, - "panels": [] - }, - { - "id": 76, - "type": "logs", - "title": "Runner pod logs", - "description": "Everything the runner pods print \u2014 job container output, dind, and the runner's own poll/registration lines. The namespace comes from the `runner_ns` variable, which matches any *runner* namespace (forgejo, forgejo-runners, ci-runners) so the panel survives the t_2bbe34a8 move without an edit.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 9, - "w": 12, - "x": 0, - "y": 30 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "{job=\"kube/pods\", namespace=~\"$runner_ns\"}", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false - } - ], - "options": { - "showTime": true, - "showLabels": false, - "showCommonLabels": false, - "wrapLogMessage": true, - "prettifyLogMessage": false, - "enableLogDetails": true, - "dedupStrategy": "none", - "sortOrder": "Descending" - } - }, - { - "id": 77, - "type": "timeseries", - "title": "Runner error / fail lines per 5m", - "description": "Coarse CI pain signal. A silent stall (a build looping on `Ign:` with no error) does not show here \u2014 check the log panel above for that.", - "datasource": { - "type": "loki", - "uid": "loki" - }, - "gridPos": { - "h": 9, - "w": 12, - "x": 12, - "y": 30 - }, - "targets": [ - { - "datasource": { - "type": "loki", - "uid": "loki" - }, - "expr": "sum by (namespace) (count_over_time({job=\"kube/pods\", namespace=~\"$runner_ns\"} |~ \"(?i)error|fail\" [5m]))", - "refId": "A", - "queryType": "range", - "range": true, - "instant": false, - "legendFormat": "{{namespace}}" - } - ], - "fieldConfig": { - "defaults": { - "custom": { - "lineWidth": 1, - "fillOpacity": 10, - "showPoints": "never", - "stacking": { - "mode": "normal" - } - }, - "color": { - "mode": "palette-classic" - } - }, - "overrides": [] - }, - "options": { - "legend": { - "displayMode": "list", - "placement": "bottom", - "calcs": [ - "lastNotNull" - ] - }, - "tooltip": { - "mode": "multi", - "sort": "desc" - } - } - }, - { - "id": 78, - "type": "row", - "title": "How to read these streams", - "collapsed": false, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 39 - }, - "panels": [] - }, - { - "id": 79, - "type": "text", - "title": "Field names and retention", - "gridPos": { - "h": 8, - "w": 24, - "x": 0, - "y": 40 - }, - "options": { - "mode": "markdown", - "code": { - "language": "plaintext", - "showLineNumbers": false, - "showMiniMap": false - }, - "content": "Loki is single-binary in the `logging` namespace: **192 h (8 d)** retention on an 8Gi PVC,\nfed by the Alloy DaemonSet. These panels only read it.\n\n| `job` | source | stream labels |\n|---|---|---|\n| `kube/pods` | every container's stdout (`/var/log/pods`) | `namespace, pod, container, node` |\n| `kube/apiserver-audit` | `siriussec`'s `/var/log/kubernetes/audit/audit.log` | `resource, verb` |\n| `systemd-journal` | node journals | `unit, host, level` |\n| `docker/json` | the Pi's docker container logs | `container` |\n\n**The audit field names are the Alloy pipeline's allowlist, not the raw audit event's.**\n`objectRef.resource` arrives as the stream label `resource` and `user.username` as the\nline field `user`, so the usable query is\n`{job=\"kube/apiserver-audit\", resource=\"secrets\"} | json` \u2014 an `objectRef_resource` or\n`user_username` matcher returns **zero rows**. Secret bodies are never shipped: the\npipeline packs an allowlist and drops `requestObject`/`responseObject`\n(`docs/logging.md`, `infrastructure/logging/alloy/config.alloy`)." - } - } - ] - } diff --git a/monitoring/controllers/home/dashboards/validate_panels.py b/monitoring/controllers/home/dashboards/validate_panels.py index 317d2c7..b9ca788 100755 --- a/monitoring/controllers/home/dashboards/validate_panels.py +++ b/monitoring/controllers/home/dashboards/validate_panels.py @@ -1,20 +1,15 @@ #!/usr/bin/env python3 -"""Verify every panel on the custom dashboards returns real data. +"""Verify every panel on the three custom dashboards returns real data. Reads the dashboard JSON out of the provisioned ConfigMap YAML (i.e. exactly what -Grafana loaded), extracts every PromQL/LogQL expression, queries the matching -datasource's HTTP API and prints panel title -> query -> series count -> sample. +Grafana loaded), extracts every PromQL expression, queries the Prometheus HTTP API +and prints panel title -> PromQL -> series count -> sample. -Prometheus panels go to PROM; panels whose datasource is `loki` go to LOKI. A -Loki panel is reported as OK only if its result is non-empty, which for a logs -panel means at least one entry (the series count alone is not enough). - -Usage: validate_panels.py [DASHBOARD_DIR] [PROM_URL] [LOKI_URL] +Usage: validate_panels.py [DASHBOARD_DIR] [PROM_URL] """ import json import os import sys -import time import urllib.parse import urllib.request @@ -23,12 +18,10 @@ import yaml DASH_DIR = sys.argv[1] if len(sys.argv) > 1 else os.path.expanduser( "~/Projects/homek8s/monitoring/controllers/home/dashboards") PROM = sys.argv[2] if len(sys.argv) > 2 else "http://127.0.0.1:9090" -LOKI = sys.argv[3] if len(sys.argv) > 3 else "http://127.0.0.1:3100" # Grafana template variable substitution for the "All" case, so the query the # script runs is the query Grafana runs. -SUBST = {"$namespace": ".*", "${namespace}": ".*", "$__all": ".*", - "$runner_ns": ".*(runner|forgejo).*", "${runner_ns}": ".*(runner|forgejo).*"} +SUBST = {"$namespace": ".*", "${namespace}": ".*", "$__all": ".*"} def substitute(expr): @@ -46,39 +39,6 @@ def query(expr): return body["data"]["result"], None -def query_loki(expr, instant=False): - if instant: - url = "%s/loki/api/v1/query?%s" % (LOKI, urllib.parse.urlencode( - {"query": expr, "time": "%d000000000" % time.time()})) - else: - now = int(time.time()) - url = "%s/loki/api/v1/query_range?%s" % (LOKI, urllib.parse.urlencode( - {"query": expr, "start": "%d000000000" % (now - 21600), - "end": "%d000000000" % now, "limit": 1000})) - with urllib.request.urlopen(url, timeout=30) as r: - body = json.load(r) - if body.get("status") != "success": - return None, 0, body.get("error") or body - result = body["data"]["result"] or [] - # Range/metric queries return {metric|stream, values:[[ts,line],...]}; an - # instant query returns {metric, value:[ts,val]} (singular). Count both, so a - # stat panel's single sample is "1 row" rather than looking empty. - rows = 0 - for x in result: - if "values" in x: - rows += len(x.get("values") or []) - elif "value" in x: - rows += 1 - return result, rows, None - - -def ds_type(panel, target): - ds = target.get("datasource") or panel.get("datasource") - if isinstance(ds, dict): - return ds.get("type") - return None - - def panels_of(dash): out = [] for p in dash.get("panels", []): @@ -106,20 +66,6 @@ for fn in sorted(os.listdir(DASH_DIR)): if not expr: continue total += 1 - if ds_type(p, t) == "loki": - result, rows, err = query_loki(expr, instant=bool(t.get("instant"))) - if err: - bad += 1 - print(" FAIL %-46s %s\n ERROR: %s" - % (p["title"][:46], expr.replace("\n", " ")[:110], err)) - continue - if not result or not rows: - bad += 1 - print(" EMPTY %-46s %s" % (p["title"][:46], expr.replace("\n", " ")[:110])) - continue - print(" OK %-46s %-3d series %-6d rows (loki)" - % (p["title"][:46], len(result), rows)) - continue result, err = query(expr) if err: bad += 1