monitoring(logs): a readable Loki — Logs dashboard + provisioning-reload runbook

The log store shipped in t_34ddaa83 but nothing could read it: the Loki datasource
ConfigMap was live and written into Grafana's provisioning volume, and Grafana still
listed only Prometheus + Alertmanager. Root cause was not the ConfigMap. The
datasource sidecar writes the file and then POSTs
/api/admin/provisioning/datasources/reload with monitoring/grafana-admin, which was
401-ing because Grafana's DB password had drifted from that Secret (the documented
"the Secret is only the seed" behaviour) — Grafana reads provisioning/datasources
only at startup, so the datasource never loaded.

- Reset the live admin password to the Secret's value (in-pod `grafana cli
  admin reset-admin-password`, value read from the Secret and never printed), so
  seed and DB match again and the sidecar's reload returns 200. Documented in
  docs/grafana-persistence.md, including the sidecar consequence of drift.
- New generated dashboard `logs` (uid: logs) with the two queries worth having:
  secret access over time by user from the apiserver audit stream, and pod errors
  by namespace, plus the runner namespaces and a note panel on field names.
- The audit stream's names are the Alloy allowlist's, not the audit event's:
  objectRef.resource arrives as the stream label `resource` and user.username as
  the field `user`. `| json | objectRef_resource="secrets"` returns 0 rows
  (measured); the panels use `resource="secrets"` in the selector + `| json` for
  the user dimension. No pipeline, retention or filter change.
- Runner panels discover their namespace via a `runner_ns` variable
  (.*(runner|forgejo).*) instead of pinning one name, so the t_2bbe34a8 move to
  ci-runners needs no edit here.
- validate_panels.py now dispatches on the target's datasource and queries Loki
  for `loki` panels (a logs panel must return rows, not just series).
This commit is contained in:
Lance Walters 2026-11-27 01:23:03 -05:00
commit 6b91152a79
7 changed files with 828 additions and 35 deletions

View file

@ -17,6 +17,9 @@ 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]
@ -36,10 +39,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):
w=12, h=8, ds=DS):
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"}},
@ -56,10 +59,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):
thresholds=None, w=4, h=5, decimals=None, ds=DS):
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": [],
@ -105,6 +108,39 @@ 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,
@ -130,6 +166,35 @@ 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
@ -379,6 +444,82 @@ 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"],
@ -396,16 +537,26 @@ 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}
PANELS = {"forgejo-runners": runners, "cnpg-postgres": cnpg, "home-lab-workloads": workloads,
"logs": logs_panels}
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)
variables=([ns_variable()] if uid == "cnpg-postgres"
else [loki_ns_variable(), loki_runner_ns_variable()]
if uid == "logs" else None))
doc = {
"apiVersion": "v1",
"kind": "ConfigMap",
@ -413,12 +564,13 @@ 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 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.
# 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.)
"annotations": {"homelab.siriusdevops.com/managed-by": "monitoring/controllers/home/dashboards/build.py"},
},
"data": {uid + ".json": json.dumps(d, indent=2) + "\n"},