diff --git a/docs/logging.md b/docs/logging.md index 074ebf4..e28ecc7 100644 --- a/docs/logging.md +++ b/docs/logging.md @@ -26,15 +26,20 @@ Sources (all in `infrastructure/logging/alloy/config.alloy`): 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. 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. +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 @@ -66,49 +71,117 @@ Three independent bounds: (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) +### Measured (2026-11-27 05:50–06:10 UTC, fresh store, backfill included) ``` -# 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 +# 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) ``` -Projection, with the *worst measured* window instead of the quiet one. Two -distinct regimes showed up on 2026-11-27: +Two clearly different regimes, so both are reported: -- 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. +| 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 | -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): +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: | | | |---|---| -| 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) | +| 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 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. +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 @@ -136,36 +209,43 @@ 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): +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): -``` -$ 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" +```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) -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) +{job="systemd-journal", node="siriussec"} + -> 2026-11-20T06:05:57.643Z [1795154757.6430] device (wlan0): + set-hw-addr: set MAC address to 42:3E:A4:51:71:77 (scanning) + (unit=NetworkManager.service, host=siriussec) ``` -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. +Retained depth in the store right now (oldest line per source, 2026-11-27 +06:30 UTC): -Per-namespace depth at deploy time (oldest line available, 2026-11-27 05:16 UTC): - -| namespace | oldest line | note | +| source | oldest line | age | |---|---|---| -| `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 | " | +| `{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 | -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. +**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 diff --git a/infrastructure/logging/monitoring.yaml b/infrastructure/logging/monitoring.yaml index 0d21ffb..2880b3b 100644 --- a/infrastructure/logging/monitoring.yaml +++ b/infrastructure/logging/monitoring.yaml @@ -43,20 +43,22 @@ spec: - name: logging-storage rules: - alert: LokiIngestRateAboveBudget - # ~1 GiB/day of *compressed* chunk data would blow the 8Gi bound - # before the compactor can keep up; the baseline is ~1% of this. + # 200 kB/s raw ~= 17 GB/day ~= 2 GB/day compressed, which fills the + # 8Gi PVC inside the 192h window. Measured baselines: 4 kB/s quiet, + # ~37 kB/s during an osint crawl (2026-11-27, see docs/logging.md), + # so this only fires on a real runaway (log loop, debug left on). expr: | - sum(rate(loki_distributor_bytes_received_total[30m])) > 12 * 1024 * 1024 + sum(rate(loki_distributor_bytes_received_total[30m])) > 200 * 1024 for: 1h labels: severity: warning annotations: summary: Loki ingest is above the storage budget description: >- - Loki is receiving {{ $value | humanize1024 }}B/s (>12 MiB/s), which - is ~1 GiB/day of chunk data — more than the 8Gi PVC can hold for - 192h. Either a workload started logging in a loop, or retention / - limits need revisiting before the disk does. + Loki is receiving {{ $value | humanize1024 }}B/s (>200 kB/s), which + is ~17 GB/day raw — enough to fill the 8Gi PVC before the 192h + retention can delete anything. Either a workload started logging in + a loop, or retention / limits need revisiting before the disk does. - alert: LokiDown expr: up{job="loki"} == 0 for: 10m