forgejo/prune: prune every Docker daemon, cap builder cache by age, alert on growth

The nightly CronJob reported Complete while never reclaiming build cache:
docker 27/buildx 0.20.1 accepts --keep-storage and --max-used-space but
returns 'Total: 0B' for both (measured: 21.44GB cache with a 20GB cap, and
541MB cache with a 100MB cap). The comment claiming 53GB reclaimed was true
on an older CLI and is now false. --filter until= does reclaim, so the cash
cap is enforced by walking age windows down (72h -> 0s) and stopping as soon
as the cache is under the cap.

Coverage is now every daemon, discovered not listed: the Pi host socket and
every in-cluster dind pod matching label app=forgejo-runner with a dind
container, pruned over pods/exec with a namespace-scoped ServiceAccount, so
the arm64 dind migration is picked up without editing this job.

Busy guard skips a daemon with a live build and still exits 0. Named volumes
are never pruned; their sizes are printed every run. Adds PrometheusRule
forgejo-prune: cronjob staleness/failure plus node filesystem high-watermark.
This commit is contained in:
Lance Walters 2026-10-27 01:43:20 -04:00
commit f1fcf21a94
3 changed files with 497 additions and 28 deletions

View file

@ -1,14 +1,263 @@
---
# Disk hygiene for the Pi's build host.
# Disk hygiene for every Docker daemon the Forgejo Actions runners build on.
#
# Every push builds images on the Pi's own docker daemon (deploy-site's arm64
# image, onionwire's ci build containers) and nothing ever removed them: the
# single / volume sat at 76% (666G/917G) with weeks of exited job containers
# and superseded image layers. On one volume that is a slow-motion outage.
# Two kinds of daemon exist in this lab and the old version of this job only
# ever saw the first one:
#
# Prune keeps a week of images (a rollback window), 48h of exited containers,
# and 72h of builder cache. It runs against the host socket, so it sees exactly
# the containers the runners created.
# 1. the Pi's *host* daemon (arm64 runners bind /var/run/docker.sock),
# reachable from a pod only through a hostPath socket, and
# 2. the in-pod `docker:dind` daemons (amd64 runner today, the arm64
# migration adds more) which live on their own PVC and are reachable
# only by exec'ing into the pod.
#
# So the Job runs two containers: `host-daemon` mounts the Pi socket,
# `dind-daemons` discovers dind pods by label and prunes each one over the
# Kubernetes exec API with a namespace-scoped ServiceAccount. No pod names are
# hardcoded; a new dind runner is picked up the first night it exists.
#
# The build-cache cap is enforced by *age windows*, not by the capacity flags.
# `--keep-storage` / `--max-storage` / `--max-used-space` are accepted by the
# installed buildx (0.20.1) but do not reclaim anything here (measured
# 2026-10-27: 21.44 GB cache with `--max-used-space 20GB` -> "Total: 0B";
# 541 MB cache with `--max-used-space 100MB` -> "Total: 0B"). That no-op is
# why the previous job reported `Complete` while 21 GB of builder cache sat
# untouched. `--filter until=<age>` *does* reclaim (541 MB -> 0 with
# `until=1s`), so the script walks the window down from CACHE_AGE_H to 0s and
# stops as soon as the cache is under the cap: newest layers survive, a cold
# cache is the last resort, never the default.
#
# Named volumes are NEVER pruned (docker volume prune is forbidden): they hold
# the shared CI caches (onionwire-target-ci, the Android SDK/Gradle/registry
# volumes). Their sizes are printed every run and their growth is covered by
# the `RunnerDindPvc*` / `NodeFilesystemFillingUp` alerts.
apiVersion: v1
kind: ServiceAccount
metadata:
name: forgejo-prune
namespace: forgejo
labels:
app: forgejo-runner
role: prune
---
# Least privilege: the job needs to find dind pods (get/list) and to run
# docker inside them (pods/exec create) — in namespace forgejo only.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: forgejo-prune
namespace: forgejo
labels:
app: forgejo-runner
role: prune
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: forgejo-prune
namespace: forgejo
labels:
app: forgejo-runner
role: prune
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: forgejo-prune
subjects:
- kind: ServiceAccount
name: forgejo-prune
namespace: forgejo
---
apiVersion: v1
kind: ConfigMap
metadata:
name: forgejo-prune-scripts
namespace: forgejo
labels:
app: forgejo-runner
role: prune
data:
host-daemon.sh: |
#!/bin/sh
# Prune the Pi's host Docker daemon (the socket the arm64 runners use).
set -eu
CAP_BYTES=${CACHE_CAP_BYTES:-20000000000}
CACHE_AGE_H=${CACHE_AGE_H:-72}
IMAGE_AGE_H=${IMAGE_AGE_H:-168}
CONTAINER_AGE_H=${CONTAINER_AGE_H:-48}
BUSY_MINUTES=${BUSY_MINUTES:-180}
to_bytes() {
awk -v v="$1" 'BEGIN{
n = v + 0; u = "B";
if (match(v, /[A-Za-z]+$/)) u = substr(v, RSTART);
m = 1;
if (u == "kB") m = 1e3; else if (u == "MB") m = 1e6;
else if (u == "GB") m = 1e9; else if (u == "TB") m = 1e12;
printf "%.0f\n", n * m }'
}
cache_bytes() {
docker buildx du 2>/dev/null | awk '/^Total:/{print $2}' | tail -n1 \
| { read -r v; to_bytes "${v:-0B}"; }
}
# A build is live if a *running* container was started inside the busy
# window. The Pi's standing containers (sites, garage, registry) are days
# old, so this needs no name whitelist: job containers are minutes old.
busy() {
docker ps --format '{{.Names}}|{{.Status}}' | awk -F'|' -v win="$1" '
{ st = $2; sub(/^Up /, "", st); split(st, a, " ");
if (st ~ /^Less than a second/) age = 0;
else if (st ~ /^About a minute/) age = 60;
else { n = a[1] + 0; u = a[2];
if (u ~ /^seconds?$/) age = n;
else if (u ~ /^minutes?$/) age = n * 60;
else if (u ~ /^hours?$/) age = n * 3600;
else if (u ~ /^days?$/) age = n * 86400;
else if (u ~ /^weeks?$/) age = n * 604800;
else age = 99999999 }
if (age < win * 60) { print " " $1 " (Up " st ")"; found = 1 } }
END { exit(found ? 0 : 1) }'
}
echo "== daemon: pi-host (/var/run/docker.sock)"
docker system df
echo "== named volumes (never pruned, listed for growth tracking)"
docker system df -v | sed -n '/Local Volumes/,$p'
echo "== df -h / (before)"; df -h / | tail -n1
if busy "$BUSY_MINUTES"; then
echo "BUSY: a build looks live on this daemon (running container younger than ${BUSY_MINUTES}m above)"
echo "SKIP: not pruning pi-host tonight (job exits 0 by design)"
exit 0
fi
echo "== container prune (exited > ${CONTAINER_AGE_H}h)"
docker container prune -f --filter until="${CONTAINER_AGE_H}h" 2>&1 | tail -n1
echo "== image prune (unused, created > ${IMAGE_AGE_H}h)"
docker image prune -af --filter until="${IMAGE_AGE_H}h" 2>&1 | tail -n1
echo "== builder prune (cap ${CAP_BYTES}B by age window)"
for w in "${CACHE_AGE_H}h" 48h 24h 12h 6h 3h 1h 0s; do
cur=$(cache_bytes)
echo "[builder] cache=${cur}B cap=${CAP_BYTES}B (next window until=$w)"
if [ "$cur" -le "$CAP_BYTES" ]; then
echo "[builder] within cap — warm cache kept"
break
fi
echo "[builder] over cap -> docker builder prune -af --filter until=$w"
docker builder prune -af --filter until="$w" 2>&1 | tail -n1
done
echo "[builder] final cache=$(cache_bytes)B"
echo "== after"
docker system df
echo "== df -h / (after)"; df -h / | tail -n1
echo "daemon pi-host: OK"
dind-daemons.sh: |
#!/bin/sh
# Prune every in-cluster dind daemon, discovered by label.
# Selector: pods with app=forgejo-runner in namespace forgejo that have a
# container named `dind`. Nothing here is keyed to a pod name, so a new
# dind runner (e.g. the arm64 migration) is pruned the night it appears.
set -u
NS=${NAMESPACE:-forgejo}
CAP_BYTES=${CACHE_CAP_BYTES:-4000000000}
CACHE_AGE_H=${CACHE_AGE_H:-72}
CONTAINER_AGE_H=${CONTAINER_AGE_H:-48}
to_bytes() {
awk -v v="$1" 'BEGIN{
n = v + 0; u = "B";
if (match(v, /[A-Za-z]+$/)) u = substr(v, RSTART);
m = 1;
if (u == "kB") m = 1e3; else if (u == "MB") m = 1e6;
else if (u == "GB") m = 1e9; else if (u == "TB") m = 1e12;
printf "%.0f\n", n * m }'
}
dk() { kubectl -n "$NS" exec -c dind "$pod" -- docker "$@"; }
dk_cache_bytes() {
dk buildx du 2>/dev/null | awk '/^Total:/{print $2}' | tail -n1 \
| { read -r v; to_bytes "${v:-0B}"; }
}
found=0
failed=0
skipped=0
for pod in $(kubectl -n "$NS" get pods -l app=forgejo-runner \
-o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'); do
phase=$(kubectl -n "$NS" get pod "$pod" -o jsonpath='{.status.phase}' 2>/dev/null || echo Unknown)
if [ "$phase" != "Running" ]; then
echo "skip pod/$pod: phase $phase"
continue
fi
ctrs=$(kubectl -n "$NS" get pod "$pod" -o jsonpath='{.spec.containers[*].name}' 2>/dev/null || echo "")
case " $ctrs " in
*" dind "*) ;;
*) echo "skip pod/$pod: no dind container (containers: ${ctrs:-none})"; continue ;;
esac
found=$((found + 1))
echo "=============================================================="
echo "== daemon: dind in pod/$pod"
if ! dk system df; then
echo "FAILED: docker not answering in pod/$pod"
failed=$((failed + 1))
continue
fi
echo "== named volumes in pod/$pod (never pruned, listed for growth tracking)"
dk system df -v | sed -n '/Local Volumes/,$p'
running=$(dk ps -q | wc -l)
if [ "$running" -gt 0 ]; then
echo "BUSY: pod/$pod has $running running container(s) — a job is in flight"
echo "SKIP: not pruning dind in pod/$pod (job exits 0 by design)"
skipped=$((skipped + 1))
continue
fi
before=$(dk_cache_bytes)
echo "== container prune in pod/$pod (exited > ${CONTAINER_AGE_H}h)"
dk container prune -f --filter until="${CONTAINER_AGE_H}h" 2>&1 | tail -n1
# Dangling images only. An `until` filter on pulled images compares the
# image's *creation* date (the upstream build date), so it would delete
# node:20-bullseye / rust:*-bookworm every night and make every job cold.
echo "== dangling image prune in pod/$pod"
dk image prune -f 2>&1 | tail -n1
echo "== builder prune in pod/$pod (cap ${CAP_BYTES}B by age window)"
for w in "${CACHE_AGE_H}h" 48h 24h 12h 6h 3h 1h 0s; do
cur=$(dk_cache_bytes)
echo "[builder $pod] cache=${cur}B cap=${CAP_BYTES}B (next window until=$w)"
if [ "$cur" -le "$CAP_BYTES" ]; then
echo "[builder $pod] within cap — warm cache kept"
break
fi
echo "[builder $pod] over cap -> docker builder prune -af --filter until=$w"
dk builder prune -af --filter until="$w" 2>&1 | tail -n1
done
after=$(dk_cache_bytes)
echo "== after pod/$pod (build cache ${before}B -> ${after}B)"
dk system df
done
echo "=============================================================="
echo "summary: dind daemons found=$found pruned=$((found - failed - skipped)) skipped=$skipped failed=$failed"
if [ "$found" -eq 0 ]; then
echo "WARNING: no dind pod matched label app=forgejo-runner in ns $NS"
fi
[ "$failed" -eq 0 ]
---
apiVersion: batch/v1
kind: CronJob
metadata:
@ -19,20 +268,34 @@ metadata:
role: prune
spec:
schedule: "17 4 * * *"
# One timezone convention for every CronJob in this repo: UTC.
timeZone: "Etc/UTC"
concurrencyPolicy: Forbid
# Missed by more than 30 min (Pi down, cluster flapping): skip the night
# rather than start a prune at an unpredictable time.
startingDeadlineSeconds: 1800
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
backoffLimit: 1
# Container/image removal on the Pi runs at minutes-per-dozen under load
# (measured: 48 containers in ~10 min with a ci job live). One hour keeps
# the nightly run from being killed half-way through the image prune.
# (measured: 48 containers in ~10 min). One hour keeps a slow night from
# being killed half-way through a prune.
activeDeadlineSeconds: 3600
# A failed prune is worth one retry (transient API/exec hiccup), not a
# loop: a broken prune must show up as a failed Job (and alert) instead
# of retrying all night.
backoffLimit: 1
template:
metadata:
labels:
app: forgejo-runner
role: prune
spec:
restartPolicy: Never
serviceAccountName: forgejo-prune
# The Pi socket only exists on rpi; the dind daemons are reached over
# the API, so both containers ride along here.
nodeSelector:
kubernetes.io/hostname: rpi
tolerations:
@ -41,35 +304,64 @@ spec:
value: network
effect: PreferNoSchedule
containers:
- name: prune
- name: host-daemon
image: docker:27-cli
imagePullPolicy: IfNotPresent
command:
- sh
- -c
- |
set -e
echo "== before"; docker system df
docker container prune -f --filter until=48h || true
docker image prune -af --filter until=168h || true
# --filter until=72h reclaimed 0 B on a 74 GB cache (proven
# 2026-10-23): the filter is a no-op here, --keep-storage is
# deterministic and reclaimed 53 GB keeping a 20 GB warm cache.
# Never prune volumes: onionwire-target-ci and the mobile
# SDK/Gradle caches are "unused" between runs but essential.
docker builder prune -af --keep-storage 20GB || true
echo "== after"; docker system df
command: ["/bin/sh", "/scripts/host-daemon.sh"]
env:
- name: CACHE_CAP_BYTES
value: "20000000000"
- name: CACHE_AGE_H
value: "72"
- name: IMAGE_AGE_H
value: "168"
- name: CONTAINER_AGE_H
value: "48"
- name: BUSY_MINUTES
value: "180"
volumeMounts:
- name: docker-sock
mountPath: /var/run/docker.sock
- name: scripts
mountPath: /scripts
readOnly: true
resources:
requests:
cpu: 10m
memory: 32Mi
limits:
memory: 128Mi
memory: 256Mi
- name: dind-daemons
# kubectl 1.36.4 == the cluster version; alpine/k8s ships kubectl,
# bash and awk on arm64, so it can exec into the dind pods.
image: alpine/k8s:1.36.4
imagePullPolicy: IfNotPresent
command: ["/bin/sh", "/scripts/dind-daemons.sh"]
env:
- name: NAMESPACE
value: forgejo
- name: CACHE_CAP_BYTES
value: "4000000000"
- name: CACHE_AGE_H
value: "72"
- name: CONTAINER_AGE_H
value: "48"
volumeMounts:
- name: scripts
mountPath: /scripts
readOnly: true
resources:
requests:
cpu: 10m
memory: 32Mi
limits:
memory: 256Mi
volumes:
- name: docker-sock
hostPath:
path: /var/run/docker.sock
type: Socket
- name: scripts
configMap:
name: forgejo-prune-scripts
defaultMode: 0755

View file

@ -7,6 +7,7 @@ resources:
- release.yaml
- httproute.yaml
- gateway-probe.yaml
- prune-alerts.yaml
- dashboards
configMapGenerator:
- name: kube-prometheus-stack-values

View file

@ -0,0 +1,176 @@
# Alerts for the disk-reclamation job and the daemons it prunes.
#
# Context: `forgejo/forgejo-runner-prune` reclaims build cache nightly. Its
# own success/failure is invisible unless kube-state-metrics is watched, and
# the failure mode it exists to prevent (a full disk on siriussec → DiskPressure
# → Forgejo + Postgres evicted, public 503) shows up in node_exporter first.
#
# What is measurable here:
# - node filesystem utilisation per node (node-exporter, all three nodes);
# on siriussec the local-path PVs — including the runner's dind data-root —
# live on `/`, so this is the DiskPressure precursor and the PVC watchdog
# in one series.
# - CronJob last-success timestamp and Job failure counters
# (kube-state-metrics).
#
# What is NOT measurable here: kubelet_volume_stats_* does not exist on this
# cluster. Verified 2026-10-27: kubelet v1.36.4 exposes
# kubelet_volume_metric_collection_duration_seconds but no
# kubelet_volume_stats_used_bytes / _capacity_bytes on any node
# (`kubectl get --raw /api/v1/nodes/<node>/proxy/metrics | grep volume_stats`
# is empty, and Prometheus has zero series). So the per-PVC rules below are
# written against those metric names but stay inert until a kubelet exports
# them; the node-filesystem rules are the live coverage. Per-PVC and per-Docker
# -volume sizes are printed by the prune job every night
# (`docker system df -v`), which is the record of growth.
#
# Alertmanager is disabled in this stack (monitoring card), so these surface in
# Prometheus → Alerts and Grafana → Alerting. No external receiver is added.
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: forgejo-prune
namespace: monitoring
labels:
release: kube-prometheus-stack
spec:
groups:
- name: forgejo-prune
rules:
- alert: ForgejoPruneCronJobStale
# 04:17 UTC nightly; 26 h leaves room for one missed tick before it
# pages a human. `or absent(...)` catches the job being deleted or
# never having succeeded at all.
expr: |
(
time() - kube_cronjob_status_last_successful_time{namespace="forgejo", cronjob="forgejo-runner-prune"} > 26 * 3600
)
or
absent(kube_cronjob_status_last_successful_time{namespace="forgejo", cronjob="forgejo-runner-prune"})
for: 10m
labels:
severity: warning
annotations:
summary: >-
forgejo-runner-prune has not completed successfully in over 26 h
description: >-
Build cache, exited containers and unused images are not being
reclaimed on the Pi host daemon or on the dind daemons. Check
`kubectl -n forgejo get jobs -l role=prune` and the pod logs of
the newest Job; the job skips (exit 0) when a build is live, but
a *stale* success means it has not run at all. Force one run:
kubectl -n forgejo create job --from=cronjob/forgejo-runner-prune prune-manual-$(date +%s)
- alert: ForgejoPruneJobFailed
# kube_job_failed was removed from kube-state-metrics; the supported
# series is kube_job_status_failed (0 for a successful job, >0 when a
# pod failed). Only the most recent jobs are kept in Prometheus, so a
# transient failure ages out on its own after the history limit.
expr: |
max by (job_name) (
kube_job_status_failed{namespace="forgejo", job_name=~"forgejo-runner-prune-.*"}
) > 0
for: 5m
labels:
severity: warning
annotations:
summary: forgejo-runner-prune Job {{ $labels.job_name }} has a failed pod
description: >-
A prune run failed (or its dind discovery/exec container did).
Read `kubectl -n forgejo logs job/{{ $labels.job_name }} -c
dind-daemons` — a failure there means a running dind daemon was
not reachable over the exec API, so that daemon is growing
unpruned. One retry is allowed by backoffLimit; persistent
failures need the RBAC or the pod checked.
# Per-PVC rules: correct expressions, currently inert (see the header —
# this cluster's kubelet exports no kubelet_volume_stats_* series). They
# start working the day that comes back, and they cost nothing until
# then. Coverage today is NodeFilesystemFillingUp on siriussec, where
# every local-path PV physically lives.
- alert: RunnerDindPvcHighWatermark
expr: |
max by (namespace, persistentvolumeclaim) (
kubelet_volume_stats_used_bytes{namespace="forgejo", persistentvolumeclaim=~"forgejo-runner-.*"}
)
/
max by (namespace, persistentvolumeclaim) (
kubelet_volume_stats_capacity_bytes{namespace="forgejo", persistentvolumeclaim=~"forgejo-runner-.*"}
) > 0.85
for: 15m
labels:
severity: warning
annotations:
summary: >-
dind PVC {{ $labels.persistentvolumeclaim }} is over 85% full
description: >-
The image/build-cache/volume footprint on this runner's dind
daemon is approaching the 20Gi PVC. Inspect it with
`kubectl -n forgejo exec <runner-pod> -c dind -- docker system df -v`;
the nightly prune caps build cache but never deletes named
volumes.
- alert: RunnerDindPvcCritical
expr: |
max by (namespace, persistentvolumeclaim) (
kubelet_volume_stats_used_bytes{namespace="forgejo", persistentvolumeclaim=~"forgejo-runner-.*"}
)
/
max by (namespace, persistentvolumeclaim) (
kubelet_volume_stats_capacity_bytes{namespace="forgejo", persistentvolumeclaim=~"forgejo-runner-.*"}
) > 0.95
for: 5m
labels:
severity: critical
annotations:
summary: >-
dind PVC {{ $labels.persistentvolumeclaim }} is over 95% full
description: >-
Builds will start failing with ENOSPC. Scale the runner to 0,
raise the PVC, or clear the dind data-root deliberately (see the
DiskPressure runbook in the home-k8s skill) — do not wipe it
while the runner pod is up.
- name: disk-capacity
rules:
- alert: NodeFilesystemFillingUp
# Root filesystem per node, named by hostname rather than IP so the
# alert is actionable. 85% is where kubelet's imagefs/nodefs GC and
# the DiskPressure taint start to matter on siriussec; the Pi's
# Docker volumes (169 GB of CI caches) live here too.
expr: |
(
1 - (
node_filesystem_avail_bytes{mountpoint="/", fstype=~"ext4|xfs|btrfs"}
/
node_filesystem_size_bytes{mountpoint="/", fstype=~"ext4|xfs|btrfs"}
)
) * on (instance) group_left (nodename) node_uname_info > 0.85
for: 30m
labels:
severity: warning
annotations:
summary: "{{ $labels.nodename }} root filesystem is {{ $value | humanizePercentage }} full"
description: >-
Reclaim with `kubectl -n forgejo create job
--from=cronjob/forgejo-runner-prune prune-manual-$(date +%s)` (it
prunes the Pi host daemon and every dind daemon), and read that
job's `docker system df -v` output for the volumes that are
growing. At 85% kubelet starts evicting on siriussec — that is
the Forgejo 503 failure mode.
- alert: NodeFilesystemCritical
expr: |
(
1 - (
node_filesystem_avail_bytes{mountpoint="/", fstype=~"ext4|xfs|btrfs"}
/
node_filesystem_size_bytes{mountpoint="/", fstype=~"ext4|xfs|btrfs"}
)
) * on (instance) group_left (nodename) node_uname_info > 0.92
for: 10m
labels:
severity: critical
annotations:
summary: "{{ $labels.nodename }} root filesystem is {{ $value | humanizePercentage }} full"
description: >-
DiskPressure is imminent/immediate. Free space before the next
build: prune now, then check `docker system df -v` on that host
for the named volume that grew (never delete named volumes
blind — onionwire-target-ci and the Android SDK/Gradle caches
are shared CI state).