Merge pull request 'infra(logging): Loki single-binary + Alloy DaemonSet with 192h bounded retention (F4)' (#52) from wt/t_34ddaa83 into master

This commit is contained in:
sirius 2026-11-27 05:37:13 +00:00
commit 8619a8f07d
10 changed files with 890 additions and 0 deletions

View file

@ -0,0 +1,20 @@
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: logging
namespace: flux-system
spec:
interval: 10m0s
retryInterval: 1m
timeout: 5m
sourceRef:
kind: GitRepository
name: flux-system
path: ./infrastructure/logging
prune: true
# Namespace + local-path PVC provisioning come from infrastructure; the
# ServiceMonitor/PrometheusRule CRDs come from kube-prometheus-stack via
# monitoring, so nothing here is applied before its CRDs exist.
dependsOn:
- name: infrastructure
- name: monitoring

188
docs/logging.md Normal file
View file

@ -0,0 +1,188 @@
# 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.
`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 *higher* of the two observed rates (an earlier 181 s window
measured 502 MB/day raw, before backfill fully drained — used as the bound):
| | |
|---|---|
| raw ingest | ≤ 502 MB/day |
| compressed chunks | ≤ 90 MB/day (5.6x) |
| + TSDB index / cache | ~10 % → ≤ 100 MB/day |
| 192h retained window | **≤ 0.8 GiB** |
| PVC budget | 8 GiB (≈8x headroom) |
| node free before / after deploy | 103 GiB → 101 GiB (`/dev/nvme0n1p3`, 214 GiB) |
| house floor | 32 GiB free — untouched |
So the answer to "does it fit": yes, with an order of magnitude to spare; it uses
~1 % of the free space on `siriussec` and does not approach the floor. If the
volume ever grows 10x, the documented lever is `retention_period` (168h still
satisfies the 7-day floor) before anything touches the PVC size.
## 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.

View file

@ -0,0 +1,122 @@
# Grafana Alloy as a per-node collector.
#
# Runs on all three nodes (DaemonSet, tolerating rpi's
# dedicated=network:PreferNoSchedule and the control-plane taint set) because
# every node owns the logs of its own pods.
#
# No ServiceAccount, no ClusterRole: the config reads files only, so the
# default SA is all it needs. That is deliberately the smallest possible
# blast radius for a component that reads every log line in the cluster.
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: alloy
namespace: logging
labels:
app.kubernetes.io/name: alloy
app.kubernetes.io/part-of: logging
spec:
selector:
matchLabels:
app.kubernetes.io/name: alloy
updateStrategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
template:
metadata:
labels:
app.kubernetes.io/name: alloy
app.kubernetes.io/part-of: logging
spec:
tolerations:
- operator: Exists
# Reading /var/log/journal (0640 root:systemd-journal) and the kubelet
# log tree needs root; this is the same posture as node-exporter, which
# also reads host state. Dropped capabilities keep it unprivileged in
# practice — file reads need no capability.
securityContext:
runAsUser: 0
runAsGroup: 0
seccompProfile:
type: RuntimeDefault
containers:
- name: alloy
image: grafana/alloy:v1.13.0
imagePullPolicy: IfNotPresent
args:
- run
- /etc/alloy/config.alloy
- --server.http.listen-addr=127.0.0.1:12345
- --storage.path=/var/lib/alloy-data
- --disable-reporting
env:
- name: NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
resources:
requests:
cpu: 30m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
volumeMounts:
- name: config
mountPath: /etc/alloy
readOnly: true
- name: podlogs
mountPath: /var/log/pods
readOnly: true
- name: journal
mountPath: /var/log/journal
readOnly: true
- name: machine-id
mountPath: /etc/machine-id
readOnly: true
- name: dockerlogs
mountPath: /var/lib/docker/containers
readOnly: true
# NOT /var/lib/alloy/...: that path is 0770 alloy:alloy in the
# image, and this pod drops ALL capabilities (so root has no
# CAP_DAC_OVERRIDE) — traversal of the parent is denied. /var/lib
# is world-traversable, so the positions live here instead.
- name: data
mountPath: /var/lib/alloy-data
- name: tmp
mountPath: /tmp
terminationGracePeriodSeconds: 30
volumes:
- name: config
configMap:
name: alloy-config
- name: podlogs
hostPath:
path: /var/log/pods
- name: journal
hostPath:
path: /var/log/journal
- name: machine-id
hostPath:
path: /etc/machine-id
type: File
# Only the Pi runs Docker containers outside the cluster (registry,
# Garage). On the other nodes this path does not exist and the file
# match simply yields nothing; `DirectoryOrCreate` keeps the mount from
# blocking the DaemonSet rollout there.
- name: dockerlogs
hostPath:
path: /var/lib/docker/containers
type: DirectoryOrCreate
- name: data
hostPath:
path: /var/lib/alloy-data
type: DirectoryOrCreate
- name: tmp
emptyDir: {}

View file

@ -0,0 +1,194 @@
// Grafana Alloy — log collection for the house cluster.
//
// Three sources, and none of them touch the Kubernetes API (everything is read
// off the node's filesystem), so this DaemonSet needs ZERO RBAC beyond the
// default ServiceAccount:
//
// 1. kube/pods — /var/log/pods/<ns>_<pod>_<uid>/<container>/*.log
// 2. systemd-journal — /var/log/journal (kubelet, containerd, sshd, kernel)
// 3. docker/json — /var/lib/docker/containers/*/*-json.log (Pi-only
// services that are not pods: local image registry, Garage)
//
// `tail_from_end = false` on both file sources is deliberate: the nodes already
// hold history (pod log files reach back days; the linode's cilium-agent file
// reaches back 18 days, the Pi's registry json log 31 days). Ingesting those
// files from byte 0 is what gives the store real depth on day one instead of
// starting the 7-day clock at deploy time. The `timestamp` stages stamp every
// entry with the timestamp carried by the line itself rather than the ingest
// time — without that, backfill would land as "now" and be worthless.
//
// Positions live on a hostPath (/var/lib/alloy-data) so a pod restart resumes
// instead of re-shipping every byte.
logging {
level = "info"
format = "logfmt"
}
loki.write "local" {
endpoint {
url = "http://loki.logging.svc.cluster.local:3100/loki/api/v1/push"
}
external_labels = {
cluster = "homek8s",
}
}
// --------------------------------------------------------------- pod stdout
local.file_match "pod_logs" {
path_targets = [{ "__path__" = "/var/log/pods/*/*/*.log*" }]
sync_period = "15s"
}
discovery.relabel "pod_logs" {
targets = local.file_match.pod_logs.targets
rule {
source_labels = ["__path__"]
regex = "/var/log/pods/([^/]+)_([^_]+)_([^/]+)/([^/]+)/[^/]+"
target_label = "namespace"
replacement = "$1"
}
rule {
source_labels = ["__path__"]
regex = "/var/log/pods/([^/]+)_([^_]+)_([^/]+)/([^/]+)/[^/]+"
target_label = "pod"
replacement = "$2"
}
rule {
source_labels = ["__path__"]
regex = "/var/log/pods/([^/]+)_([^_]+)_([^/]+)/([^/]+)/[^/]+"
target_label = "container"
replacement = "$4"
}
rule {
target_label = "job"
replacement = "kube/pods"
}
rule {
target_label = "node"
replacement = sys.env("NODE_NAME")
}
}
loki.source.file "pod_logs" {
targets = discovery.relabel.pod_logs.output
forward_to = [loki.process.pod_logs.receiver]
tail_from_end = false
}
loki.process "pod_logs" {
// CRI format: "<RFC3339Nano> <stdout|stderr> <F|P> <message>"
stage.cri {}
stage.timestamp {
source = "time"
format = "RFC3339Nano"
}
stage.labels {
values = {
stream = "stream",
}
}
forward_to = [loki.write.local.receiver]
}
// ----------------------------------------------------------- systemd journal
loki.relabel "journal" {
forward_to = []
rule {
source_labels = ["__journal__systemd_unit"]
target_label = "unit"
}
rule {
source_labels = ["__journal_priority_keyword"]
target_label = "level"
}
rule {
source_labels = ["__journal__hostname"]
target_label = "host"
}
rule {
target_label = "job"
replacement = "systemd-journal"
}
rule {
target_label = "node"
replacement = sys.env("NODE_NAME")
}
}
loki.source.journal "system" {
path = "/var/log/journal"
// 192h matches the store's retention: read the whole retained window once,
// then follow. The default is 7h, which would drop most of the history.
max_age = "192h"
relabel_rules = loki.relabel.journal.rules
forward_to = [loki.write.local.receiver]
}
// ------------------------------------------------- non-pod Docker containers
local.file_match "docker_logs" {
path_targets = [{ "__path__" = "/var/lib/docker/containers/*/*-json.log" }]
sync_period = "30s"
}
discovery.relabel "docker_logs" {
targets = local.file_match.docker_logs.targets
rule {
source_labels = ["__path__"]
regex = "/var/lib/docker/containers/([0-9a-f]{12})[0-9a-f]*/[^/]+-json\\.log"
target_label = "container_id"
replacement = "$1"
}
rule {
target_label = "job"
replacement = "docker/json"
}
rule {
target_label = "node"
replacement = sys.env("NODE_NAME")
}
}
loki.source.file "docker_logs" {
targets = discovery.relabel.docker_logs.output
forward_to = [loki.process.docker_logs.receiver]
tail_from_end = false
}
loki.process "docker_logs" {
stage.json {
expressions = {
log = "log",
time = "time",
}
}
stage.timestamp {
source = "time"
format = "RFC3339Nano"
}
stage.output {
source = "log"
}
forward_to = [loki.write.local.receiver]
}

View file

@ -0,0 +1,35 @@
# Grafana datasource for the log store.
#
# Lives in the monitoring namespace because the kube-prometheus-stack Grafana
# sidecar only watches its own release namespace (sidecar.datasources
# .searchNamespace is unset). The label `grafana_datasource` is what the
# sidecar selects on; the CM lands here from the logging Kustomization (see
# clusters/homek8s/logging.yaml) so the monitoring tree stays untouched.
#
# uid is pinned: dashboards and saved Explore queries can reference `uid: loki`
# without a lookup, and re-creating the datasource does not orphan links.
apiVersion: v1
kind: ConfigMap
metadata:
name: loki-datasource
namespace: monitoring
labels:
grafana_datasource: "1"
app.kubernetes.io/part-of: logging
data:
loki-datasource.yaml: |
apiVersion: 1
datasources:
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki.logging.svc.cluster.local:3100
isDefault: false
editable: false
jsonData:
maxLines: 1000
timeout: 60
# path-level hints so the Explore log browser shows namespace/pod/
# container as columns instead of raw label soup.
derivedFields: []

View file

@ -0,0 +1,28 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
# No top-level `namespace:` on purpose: the Grafana datasource ConfigMap must
# land in `monitoring` (the sidecar's namespace) while everything else lives in
# `logging`. Each resource declares its own namespace explicitly.
resources:
- namespace.yaml
- loki.yaml
- alloy.yaml
- datasource.yaml
- monitoring.yaml
configMapGenerator:
- name: loki-config
namespace: logging
files:
- config.yaml=loki/config.yaml
- name: alloy-config
namespace: logging
files:
- config.alloy=alloy/config.alloy
# Keep the content hash on the generated ConfigMaps: a config edit then changes
# the pod template and actually rolls the Deployment/DaemonSet. Without it, Flux
# updates the ConfigMap and the running process keeps the old config forever.
generatorOptions:
disableNameSuffixHash: false

View file

@ -0,0 +1,138 @@
# Loki single-binary: one pod, one local-path PVC on siriussec.
#
# Off-node-ephemeral is satisfied by the PVC, not by the node's filesystem:
# the store lives in /opt/local-path-provisioner/... on the NVMe, survives
# pod restarts (and kubelet GC of /var/log/pods), and is re-mounted on node
# reboot. 8Gi is the bound; the measured need is well under 1 GiB (see
# docs/logging.md), so the PVC is ~10x the projected 8-day footprint.
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: loki-data
namespace: logging
labels:
app.kubernetes.io/name: loki
app.kubernetes.io/part-of: logging
spec:
accessModes:
- ReadWriteOnce
storageClassName: local-path
resources:
requests:
storage: 8Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: loki
namespace: logging
labels:
app.kubernetes.io/name: loki
app.kubernetes.io/part-of: logging
spec:
replicas: 1
# RWO local-path volume: a rolling update would deadlock with the new pod
# Pending on the volume (same reason Grafana uses Recreate here).
strategy:
type: Recreate
selector:
matchLabels:
app.kubernetes.io/name: loki
template:
metadata:
labels:
app.kubernetes.io/name: loki
app.kubernetes.io/part-of: logging
spec:
# The PVC is provisioned by local-path on whichever node first mounts it;
# pin to the node with the NVMe and the free space.
nodeSelector:
kubernetes.io/hostname: siriussec
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
fsGroupChangePolicy: OnRootMismatch
seccompProfile:
type: RuntimeDefault
containers:
- name: loki
image: grafana/loki:3.7.1
imagePullPolicy: IfNotPresent
args:
- -config.file=/etc/loki/config.yaml
- -log.level=info
ports:
- name: http
containerPort: 3100
protocol: TCP
- name: grpc
containerPort: 9096
protocol: TCP
resources:
requests:
cpu: 50m
memory: 256Mi
limits:
cpu: "1"
memory: 1Gi
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
readinessProbe:
httpGet:
path: /ready
port: http
initialDelaySeconds: 15
periodSeconds: 10
failureThreshold: 6
livenessProbe:
httpGet:
path: /ready
port: http
initialDelaySeconds: 60
periodSeconds: 30
failureThreshold: 4
volumeMounts:
- name: config
mountPath: /etc/loki
readOnly: true
- name: data
mountPath: /loki
- name: tmp
mountPath: /tmp
terminationGracePeriodSeconds: 60
volumes:
- name: config
configMap:
name: loki-config
- name: data
persistentVolumeClaim:
claimName: loki-data
- name: tmp
emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
name: loki
namespace: logging
labels:
app.kubernetes.io/name: loki
app.kubernetes.io/part-of: logging
spec:
type: ClusterIP
selector:
app.kubernetes.io/name: loki
ports:
- name: http
port: 3100
targetPort: http
protocol: TCP
- name: grpc
port: 9096
targetPort: grpc
protocol: TCP

View file

@ -0,0 +1,82 @@
# Loki single-binary configuration.
#
# Why single-binary and not the microservices chart: this is a 3-node house
# cluster whose entire log volume is well under 1 GiB/day. One process, one
# PVC, no object store, no ring to babysit.
#
# Retention: `retention_period: 192h` (8 days) — the deliverable is a *7-day
# floor*, and the compactor deletes relative to "now", so a 7-day-old line has
# a full day of margin before the compactor would touch it. 168h would put the
# 7-day boundary exactly on the deletion edge, which makes the acceptance query
# flaky. 192h is still a hard bound, not "keep everything".
#
# Storage is bounded three ways: (1) the 8Gi PVC, (2) compactor retention
# deleting whole chunks past 192h, (3) ingestion rate limits + a per-stream
# rate limit so one noisy pod cannot outrun deletion.
auth_enabled: false
server:
http_listen_address: 0.0.0.0
http_listen_port: 3100
grpc_listen_port: 9096
log_level: info
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2026-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
storage_config:
tsdb_shipper:
active_index_directory: /loki/tsdb-index
cache_location: /loki/tsdb-cache
limits_config:
# The floor. Compactor deletes anything older; nothing re-creates it.
retention_period: 192h
# Backfill is deliberate (pre-existing kubelet files + node journals carry
# real historical timestamps), so accept samples up to the retention horizon.
reject_old_samples: true
reject_old_samples_max_age: 192h
ingestion_rate_mb: 8
ingestion_burst_size_mb: 16
per_stream_rate_limit: 3MB
per_stream_rate_limit_burst: 6MB
max_streams_per_user: 10000
max_entries_limit_per_query: 5000
allow_structured_metadata: true
volume_enabled: true
# One day per sub-query keeps the single-binary querier inside its memory
# limit when someone scans a full week.
split_queries_by_interval: 24h
max_query_parallelism: 8
query_timeout: 2m
compactor:
working_directory: /loki/compactor
compaction_interval: 10m
retention_enabled: true
delete_request_store: filesystem
retention_delete_delay: 2h
retention_delete_worker_count: 150
analytics:
reporting_enabled: false

View file

@ -0,0 +1,70 @@
# Loki's own metrics -> Prometheus (scrape + ingest-rate guard).
#
# The ServiceMonitor sits in the monitoring namespace (where the Prometheus
# serviceMonitorSelector lives) and reaches the Service in `logging` through
# namespaceSelector, mirroring monitoring/controllers/home/garage.yaml.
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: loki
namespace: monitoring
labels:
release: kube-prometheus-stack
app.kubernetes.io/part-of: logging
spec:
namespaceSelector:
matchNames:
- logging
selector:
matchLabels:
app.kubernetes.io/name: loki
endpoints:
- port: http
path: /metrics
interval: 60s
scrapeTimeout: 20s
---
# Storage is bounded by retention + the 8Gi PVC, but local-path does not
# enforce the PVC request, so the one number worth watching is the ingest rate:
# sustained ingest far above the measured baseline (~100 MiB/day) is what would
# eventually outrun chunk deletion. No Alertmanager is deployed in this stack,
# so this surfaces under Prometheus -> /alerts (the same posture as every other
# rule in monitoring/controllers/home/prune-alerts.yaml).
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: loki-ingest-guard
namespace: monitoring
labels:
release: kube-prometheus-stack
app.kubernetes.io/part-of: logging
spec:
groups:
- 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.
expr: |
sum(rate(loki_distributor_bytes_received_total[30m])) > 12 * 1024 * 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.
- alert: LokiDown
expr: up{job="loki"} == 0
for: 10m
labels:
severity: critical
annotations:
summary: Loki is not being scraped
description: >-
The log store is down: nothing is being written or queried, and
the 192h retention clock is no longer being maintained by the
compactor.

View file

@ -0,0 +1,13 @@
apiVersion: v1
kind: Namespace
metadata:
name: logging
labels:
app.kubernetes.io/part-of: logging
# Alloy is a per-node log collector: it mounts /var/log/pods,
# /var/log/journal and the Docker container log tree as hostPath, which the
# `baseline` PodSecurity profile rejects outright. The namespace therefore
# has to be privileged. The pods themselves still drop ALL capabilities and
# run with a read-only root filesystem; the only real privilege is the root
# UID needed to read journal files (0640 root:systemd-journal).
pod-security.kubernetes.io/enforce: privileged