homek8s/docs/logging.md

289 lines
15 KiB
Markdown
Raw Permalink Normal View History

# Cluster log store — Loki + Alloy, 8-day bounded retention
Status: **live since 2026-11-27 05:12 UTC** (kanban `t_34ddaa83`, finding F4 of the
2026-11-27 cluster-netsec audit). Before this there was no log store at all: pod
logs existed only as kubelet files under `/var/log/pods` and died with the pod
(deepest measured history for a busy workload was ~8 h).
Manifests: `infrastructure/logging/` (Flux Kustomization `logging`, see
`clusters/homek8s/logging.yaml`). Nothing here is created by hand.
## What runs
| Component | Shape | Where | Why |
|---|---|---|---|
| `loki` | 1 Deployment, 1 PVC `loki-data` (8Gi, `local-path`) | `siriussec` only | single-binary Loki: one process, no object store, no ring. 3-node house cluster does not need the microservices chart. |
| `alloy` | DaemonSet, 3 pods | all nodes | per-node collector, **no Kubernetes API access at all** (filesystem only), so its ServiceAccount has no RBAC. |
Sources (all in `infrastructure/logging/alloy/config.alloy`):
1. `job="kube/pods"` — `/var/log/pods/<ns>_<pod>_<uid>/<container>/*.log*`, labels
`namespace, pod, container, node, stream` derived from the path.
2. `job="systemd-journal"` — `/var/log/journal`, labels `node, unit, level, host`.
This is the node-level half of the picture (kubelet, containerd, sshd, ufw,
kernel) and it is what a "scan log batches for abnormalities" job needs.
3. `job="docker/json"` — `/var/lib/docker/containers/*/*-json.log`, only
meaningful on `rpi` where the local image registry and Garage run outside the
cluster. Label is `container_id` (12 hex), not a name: the file path has no
name.
4. `job="kube/apiserver-audit"` — `/var/log/kubernetes/audit/audit.log` plus the
rotated `.gz` archives, `siriussec` only, via a read-only hostPath (a pod-log
collector cannot see a host file). Labels `verb, resource`. See
[§ Audit log](#audit-log-apiserver) — the records are **rebuilt from an
allowlist**, never forwarded verbatim.
One **drop rule**, deliberately narrow: `osint`/`news-scraper` lines starting
with `{'title':` are scrapy *item payload dumps* (one per crawled article, up to
4.7 kB, ~88 % of that namespace's volume; the same rows are in the osint
Postgres DB). They are not operational log lines, and keeping them would push
8 days of retention past the 8Gi PVC. Verify with
`sum(count_over_time({namespace="osint", container="news-scraper"} |= "{\'title\':" [24h]))`
→ 0. Everything else from that container — INFO/WARNING/ERROR, tracebacks, the
duplicate-URL warnings, the per-URL 403/404 lines — still ships.
`tail_from_end = false` + `stage.timestamp` on both file sources is deliberate.
The nodes already held history when this was deployed (the linode's
`cilium-agent` file reaches back 18 days, the Pi's registry log 31 days, the Pi's
`forgejo-runner-deploy-arm64` file to 2026-10-27). Ingesting from byte 0 and
stamping each line with the timestamp *in the line* is what gave the store real
depth on day one instead of starting the 7-day clock at deploy time. Anything
outside the retention horizon is rejected at ingest
(`reject_old_samples_max_age: 192h`) rather than stored and immediately deleted.
Collector positions are on a hostPath (`/var/lib/alloy-data`), so a DaemonSet
restart resumes instead of re-shipping every byte.
## Retention and the disk bound
Three independent bounds:
1. **Time** — `limits_config.retention_period: 192h` plus
`compactor.retention_enabled: true` (`delete_request_store: filesystem`).
192h, not 168h, on purpose: the compactor deletes relative to *now*, so a
7-day-old line has a full day of margin before it is a deletion candidate.
168h would put the acceptance query exactly on the edge.
2. **Rate** — `ingestion_rate_mb: 8`, `per_stream_rate_limit: 3MB`, so one
noisy pod cannot outrun deletion.
3. **Size** — an 8Gi PVC. Note `local-path` does **not** enforce the PVC request
(it is a directory on the node's root filesystem), so (1)+(2) are what keep
the directory small; the PVC number is the budget, not a quota. The guard is
the `LokiIngestRateAboveBudget` rule in `infrastructure/logging/monitoring.yaml`
(fires above ~1 GiB/day of ingest) plus the existing
`NodeFilesystemFillingUp`/`Critical` rules from `monitoring/controllers/home/prune-alerts.yaml`.
### Measured (2026-11-27 05:50–06:10 UTC, fresh store, backfill included)
```
# ingest + what it cost on disk (whole retained window: ~5 days of backfilled
# pod log files + 8 days of journal, all with their original timestamps)
loki_distributor_bytes_received_total 106,090,252 B
loki_distributor_lines_received_total 552,952 lines
du -sh …/pvc-…_logging_loki-data 130M (15M chunks + 116M WAL + <1M index)
loki_ingester_chunk_stored_bytes_total 16,228,194 B => 7.0x compression (113 MB received)
```
Two clearly different regimes, so both are reported:
| regime | raw | lines | compressed (7.0x) |
|---|---|---|---|
| quiet (`osint` idle) | 4.2 kB/s ≈ **360 MB/day** | ~14/s | ~43 MB/day |
| `osint` news-scraper crawl (403/404 storm) | 106 MB/h ≈ **2.5 GB/day** for that container alone, ~**3.2 GB/day** whole cluster | ~120/s | ~385 MB/day |
The crawl numbers are the ones that matter, because they are what a full
re-crawl of the news backlog produces (one `Ignoring response <403|404>` line per
blocked URL, ~113/s). Projection at that sustained rate:
| | |
|---|---|
| compressed chunks + index | ≤ 460 MB/day → **≤ 3.7 GiB over 192h** |
| quiet-window equivalent | ~0.5 GiB over 192h |
| PVC budget | 8 GiB (≥2.1x headroom at the sustained-crawl rate) |
| node free before / after deploy | 103 GiB → 99 GiB (`/dev/nvme0n1p3`, 214 GiB) |
| house floor | 32 GiB free — untouched |
So it fits with margin at *both* regimes, and the margin is set by the osint
crawler, not by the rest of the cluster. Levers if that changes, in order:
`retention_period` 192h → 168h (still the 7-day floor), then widen the osint drop
rule to the 403/404 lines, then raise the PVC. `LokiIngestRateAboveBudget` fires
at 200 kB/s sustained (~17 GB/day raw, i.e. the PVC would fill inside the
retention window) — that is the early warning, not an alarm about normal crawls.
## Audit log (apiserver)
`t_104f62a6` made the apiserver audit log live on `siriussec`:
`/var/log/kubernetes/audit/audit.log`, mode `600 root`, ~2.2 GB/day, rotated by
the apiserver itself (`maxsize=100MB`, `maxbackup=48`, `maxage=7`, `compress` →
hard ceiling ~4.8 GB). A pod-log collector never sees a host file, so Alloy gets
a **read-only hostPath** for that directory and reads the live file plus the
rotated `.gz` archives (`decompression { format = "gz" }`).
**The records are never shipped verbatim.** At `level: RequestResponse` every
`get secrets` record carries `responseObject.data` — the plaintext secret — and
74 of 75 secret reads in the live file did. Copying that into a second
queryable system is exactly the mistake a log store invites. The shipper parses
each record with one JMESPath multi-select hash and replaces the line with the
allowlist:
```
level, stage, verb, user, resource, apiGroup, ns, name, subresource,
code, sourceIP, userAgent, auditID, requestURI
```
`requestObject` / `responseObject` (and every other key) are discarded with the
parsed record; a line that does not parse is dropped, never forwarded. `verb`
and `resource` are promoted to labels, `user` and the object name stay in the
body so the stream count stays flat.
Verify, with LogQL JSON parsing rather than a substring match (a substring match
matches the *audit record of your own query*, because the query text is in
`requestURI`):
```logql
sum(count_over_time({job="kube/apiserver-audit"} | json | responseObject != "" [24h])) # 0
sum(count_over_time({job="kube/apiserver-audit"} | json | requestObject != "" [24h])) # 0
```
```
$ {job="kube/apiserver-audit", resource="secrets", verb="get"}
2026-11-27T05:57:49Z {"user":"kubernetes-admin","resource":"secrets",
"ns":"metabase","name":"metabase-data-source-creds","verb":"get","code":200,
"sourceIP":"10.10.0.3","level":"RequestResponse","stage":"ResponseComplete", ...}
```
Two retention policies coexist and do not fight: the apiserver rotates (and
only it rotates) that directory — the collector never writes to or prunes it —
while Loki keeps its own stored copy for 192h.
**Incident, 2026-11-27 05:52–05:58 UTC:** the first two cuts of this source were
wrong. `stage.pack` embeds the original line under `_entry`, so plaintext secret
bodies were written into Loki for a few minutes. Caught by querying for the
field, before this was reported as done. Fix: JMESPath allowlist + `stage.output`
(verified offline with `loki.echo` against a record carrying
`data.password` → 0 occurrences). Purge: the PVC was deleted and re-created and
the Alloy positions were reset, so the store contains no pre-fix bytes at all;
the audit history was then re-ingested through the fixed pipeline.
## Pitfalls (cost real time here)
- **`alloy validate` does not catch component build errors.** A bad JMESPath
expression validates fine on the CLI and then kills the whole collector at
load (`could not compile JMES expression`). Test the stage chain for real:
point the `forward_to` at `loki.echo` and run it on a sample line.
- **`stage.json` expressions are JMESPath, not GJSON.** Array access is
`sourceIPs[0]`, not `sourceIPs.0`.
- **`stage.pack` keeps the original line in `_entry`.** Never use it to build a
redacted view of a record.
- **`loki.source.file` does not use the line's timestamp.** Without a
`stage.timestamp` (and `stage.cri` for kubelet files) all backfill lands with
the ingest time, which quietly destroys the value of backfilling.
- **Alloy positions under `/var/lib/alloy/...` fail as a non-privileged-root
pod:** that path is `0770 alloy:alloy` inside the image and the pod drops
`CAP_DAC_OVERRIDE`, so traversal is denied. Use `/var/lib/alloy-data`.
- **`kubectl port-forward` dies between shell invocations** — for ad-hoc queries
prefer `kubectl get --raw "/api/v1/namespaces/logging/services/loki:3100/proxy/..."`,
which needs no forwarded port.
## Querying
Grafana datasource `Loki` (`uid: loki`, `infrastructure/logging/datasource.yaml`,
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.
Useful LogQL:
```logql
{namespace="forgejo"} # everything from a namespace
{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]))
```
Label cardinality is bounded: `namespace, pod, container, node, stream, job`
per pod stream, plus `unit, level, host` for journal streams. `filename` is also
a stream label (Loki adds it for file sources) — expected, it makes rotated
files distinguishable.
## Acceptance evidence
Two real 7-day-old lines, one from a workload behind Docker and one from the node
journal (queries as sent to the Loki API through the apiserver proxy, where
`start`/`end` are `now-7d` and nanoseconds):
```logql
{job="docker/json", node="rpi"}
-> 2026-11-20T06:29:56.449Z time="2026-11-20T06:29:56.448Z" level=info
msg="PurgeUploads starting: olderThan=2026-11-13 06:29:56 ..."
(container_id=c3b830c5a4ae = the local image registry, node=rpi)
{job="systemd-journal", node="siriussec"}
-> 2026-11-20T06:05:57.643Z <info> [1795154757.6430] device (wlan0):
set-hw-addr: set MAC address to 42:3E:A4:51:71:77 (scanning)
(unit=NetworkManager.service, host=siriussec)
```
Retained depth in the store right now (oldest line per source, 2026-11-27
06:30 UTC):
| source | oldest line | age |
|---|---|---|
| `{job="systemd-journal"}` (siriussec/linode/rpi) | 2026-11-19T06:04Z | 7 d 24 h |
| `{job="docker/json"}` (rpi registry) | 2026-11-19T06:29Z | 7 d 24 h |
| `{job="kube/pods"}` — deepest pod log anywhere | 2026-11-21T21:05Z | 5 d 9 h |
| `{job="kube/apiserver-audit"}` | first record of the file | minutes |
**The pod-log row is honest, not a defect of the store:** no kubelet log file on
any node reaches further back than that. The deepest files that *did* (a Cilium
agent rotated file with 18 days, an arm64 runner file from 2026-10-27) were
removed when those pods were replaced during this window — the same pod churn
that makes the original finding (~8 h) real. Everything from 2026-11-27 05:50
UTC onwards is in the store, so every namespace crosses the 7-day mark on
2026-12-04 *and stays there*; the floor is now a property of the store rather
than of whatever happens to be on the node.
Verified after a Loki pod restart (see #5 of the task): the 7-day query returned
the same lines from the PVC with the pod replaced.
## Resources
| pod | request | limit |
|---|---|---|
| `loki` | 50m / 256Mi | 1 CPU / 1Gi |
| `alloy` (per node) | 30m / 128Mi | 500m / 512Mi |
All containers drop ALL capabilities, `allowPrivilegeEscalation: false`,
`readOnlyRootFilesystem: true`, `seccompProfile: RuntimeDefault`. Loki runs as
uid 10001. Alloy runs as root **only** because the journal files are
`0640 root:systemd-journal` and the kubelet log tree is root-owned; it needs no
capability and no API access for that. The `logging` namespace is
`pod-security.kubernetes.io/enforce: privileged` for exactly one reason: the
`baseline` profile rejects hostPath volumes, which Alloy cannot work without.
Its positions directory is `/var/lib/alloy-data`, not
`/var/lib/alloy/data` — the latter is `0770 alloy:alloy` *inside the image* and
a pod without `CAP_DAC_OVERRIDE` cannot traverse it.
## Runbook
- **Is it ingesting?** `kubectl -n logging logs ds/alloy --tail=20` (look for
`tail routine started`; `status=400 ... timestamp too old` is *expected* during
backfill and harmless), and `rate(loki_distributor_bytes_received_total[10m])`
in Prometheus.
- **Did retention run?** `kubectl -n logging logs deploy/loki | grep -i compactor`
— it waits 10 min for ring stability at startup, then deletes past 192h.
- **Disk growing unexpectedly?** `du -sh` the PVC (path contains
`_logging_loki-data`), then check the ingest-rate alert. Do not "fix" it by
raising the PVC before the rate is understood.
- **`loki` won't start after a config edit:** `strategy: Recreate` is required by
the RWO volume; a rolling update deadlocks on a Pending pod.
- **Config changes need a rollout:** the ConfigMaps are generated with a content
hash, so editing `loki/config.yaml` / `alloy/config.alloy` changes the pod
template — Flux applies it and the pods actually restart. No manual
`rollout restart` step.
- **Scale down scope instead of the floor:** drop `systemd-journal` from the
Alloy config first (it is ~40 % of the volume and the least business-critical),
then lower `retention_period` to 168h. Never enable
`containerLogMaxSize` cluster-wide as a substitute — that only lengthens the
ephemeral window and pushes the node toward DiskPressure.