homek8s/docs/logging.md
Lance Walters 4a933a0403 infra(logging): drop osint scrapy item payloads so 8 days fits the PVC
Measured during a crawl (2026-11-27 04:45-05:45Z): osint/news-scraper produced
~150 MB/h, 88 % of it one JSON item dump per crawled article (up to 4.7 kB per
line, the same rows are in the osint Postgres DB). At the observed 2.9x
compression that is ~10 GB over 192h and would not fit the 8Gi PVC, so drop
exactly those lines by prefix for that one container. Operational lines
(INFO/WARNING/ERROR, tracebacks, duplicate-URL warnings) still ship.

docs/logging.md: document the drop rule and the two measured regimes.
2026-11-27 00:45:42 -05:00

209 lines
10 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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.
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. Counter:
`loki_process_dropped_lines_total{reason="osint_article_payload"}`. Everything
else from that container — INFO/WARNING/ERROR, tracebacks, the duplicate-URL
warnings — 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:32–05:36 UTC, after backfill finished)
```
# steady state, 240 s window, post-restart so no backfill in the counters
loki_distributor_bytes_received_total 305,988 -> 1,304,004 (+998,016 B / 240 s)
loki_distributor_lines_received_total 1,247 -> 4,618 (+3,371 lines / 240 s)
=> 4.2 kB/s = ~360 MB/day raw (~14 lines/s, ~1.2 M lines/day)
# what that costs on disk (whole retained window, ~5 days of backfilled pod
# logs + 8 days of journal already in the store: 206 MB raw received)
du -sh …/pvc-…_logging_loki-data 64M (37M chunks + 27M WAL + <1M index)
=> ~5.6x compression
```
Projection, with the *worst measured* window instead of the quiet one. Two
distinct regimes showed up on 2026-11-27:
- quiet: ~4 kB/s ≈ 360 MB/day raw (`osint` idle);
- **during an osint news-scraper crawl: 155 MB/h ≈ 3.7 GB/day raw**, of which
~88 % was the scrapy item payload dumps now dropped — that regime is what
forced the drop rule, because ~3 GB/day at the observed ~2.9x compression
(JSON-heavy lines compress worse than plain text) is ~10 GB over 8 days and
would not fit the PVC.
After the drop rule the `osint` container keeps only operational lines
(~22 MB/30 min ≈ 44 MB/h ≈ 1 GB/day raw at crawl rate, ~350 MB/day
compressed):
| | |
|---|---|
| raw ingest, drop rule applied | ~1 GB/day (crawl) / ~0.4 GB/day (quiet) |
| compression | 2.9–5.6x depending on mix |
| compressed chunks | ≤ 350 MB/day |
| + TSDB index / cache / WAL | ~10 % → **≤ 2.5 GiB over 192h** |
| PVC budget | 8 GiB (≈3x headroom at crawl rate) |
| node free before / after deploy | 103 GiB → 100 GiB (`/dev/nvme0n1p3`, 214 GiB) |
| house floor | 32 GiB free — untouched |
So the answer to "does it fit": yes, but the margin is set by the osint crawl,
not by the rest of the cluster. The levers, in order, if that changes:
`retention_period` 192h → 168h (still the 7-day floor), then widen the osint
drop rule, then raise the PVC. The ingest-rate alert
(`LokiIngestRateAboveBudget`, >12 MiB/s sustained) is the early warning.
## 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
7-day-old line for a real workload, `kube-system` Cilium agent (a DaemonSet pod
log, recovered from the rotated file the node still had):
```
$ kubectl get --raw "/api/v1/namespaces/logging/services/loki:3100/proxy/loki/api/v1/query_range?\
query={namespace=\"kube-system\",pod=\"cilium-bvqsg\"}&start=2026-11-20T05:15:00Z&end=2026-11-20T05:20:00Z&limit=1&direction=forward"
2026-11-20T05:16:26.454025Z time=2026-11-20T05:16:26.453900772Z level=error
msg="Envoy: Version check failed" module=agent.controlplane.envoy-proxy
(pod=cilium-bvqsg container=cilium-agent node=rpi namespace=kube-system)
```
Same query shape returns `2026-11-20T05:15:48Z` lines for
`{job="systemd-journal", node="siriussec"}` (18 days of journal existed) and
`2026-11-20T05:15:45Z` for `node="linode"`. Verified again *after* deleting the
Loki pod: the PVC is what holds the history, not the pod.
Per-namespace depth at deploy time (oldest line available, 2026-11-27 05:16 UTC):
| namespace | oldest line | note |
|---|---|---|
| `forgejo` | 2026-11-19T05:59Z | arm64 runner pod log file from 2026-10-27 |
| `kube-system` | 2026-11-19T05:16Z | cilium-agent on rpi/linode |
| `siriusdevops` | 2026-11-21T21:07Z | everything the node still had |
| `sirius-growth` | 2026-11-21T21:06Z | " |
| `piedmont` | 2026-11-21T21:06Z | " |
| `osint` | 2026-11-21T21:26Z | " |
From here the floor is a property of the store, not of what happened to be on
disk: every namespace keeps ≥7 days from 2026-11-27 onwards.
## 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.