Merge pull request 'apps(backup): nightly Forgejo data + CNPG dumps to the Linode, and prove a restore' (#17) from feat/t_dcad85f6-backups into master

Reviewed-on: #17
This commit is contained in:
sirius 2026-11-19 22:11:51 +00:00
commit 094ee2c704
5 changed files with 407 additions and 7 deletions

View file

@ -0,0 +1,272 @@
---
# Nightly backup of every piece of state on this cluster that is not
# rebuildable from git: Forgejo's data PVC and the CloudNativePG databases.
#
# Why this lives in namespace `forgejo` (and not a `backup` namespace):
# the biggest artifact is the `forgejo-data` PVC, and a Kubernetes volume
# cannot be mounted from another namespace. The pod therefore runs beside the
# data it copies; the portal database is reached over the API (see RBAC).
#
# Design notes (see docs/cluster-overview.md §8.1):
# * Destination is the Linode VPS (`[email protected]:/root/cluster-backup`),
# reached over the WireGuard mesh — off the T480 AND off the Pi. The same
# host already carries `/root/garage-backup` from the Garage pass.
# * Forgejo data is a *link-dest snapshot mirror*: rsync only ships changed
# blocks but every night leaves a full, restorable hardlinked snapshot.
# Never staged on the T480's root fs (it runs close to DiskPressure) —
# data flows PVC -> rsync -> ssh, no local temp file.
# * Databases are `pg_dump -Fc` streams taken from inside the CNPG primary
# (local socket, `-U postgres`, no password in the manifest and no
# cross-namespace Secret copy) piped straight to the Linode.
# * Credential-free on the DB side is deliberate: nothing in git, nothing to
# rotate. The only secret is the backup SSH key (`cluster-backup-ssh`,
# created out of band, `from=`-restricted on the Linode).
apiVersion: v1
kind: ServiceAccount
metadata:
name: cluster-backup
namespace: forgejo
labels:
app: cluster-backup
---
# Dump source in this namespace: find the CNPG primary and run pg_dump in it.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: cluster-backup
namespace: forgejo
labels:
app: cluster-backup
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create"]
- apiGroups: ["postgresql.cnpg.io"]
resources: ["clusters"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: cluster-backup
namespace: forgejo
labels:
app: cluster-backup
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: cluster-backup
subjects:
- kind: ServiceAccount
name: cluster-backup
namespace: forgejo
---
apiVersion: v1
kind: ConfigMap
metadata:
name: cluster-backup-scripts
namespace: forgejo
labels:
app: cluster-backup
data:
backup.sh: |
#!/bin/bash
# Nightly state backup: Forgejo data PVC + every CloudNativePG database.
#
# Layout on the Linode:
# /root/cluster-backup/forgejo-data/<UTC stamp>/ hardlinked snapshot
# /root/cluster-backup/forgejo-data/latest -> newest snapshot
# /root/cluster-backup/db/<ns>-<cluster>-<stamp>.dump pg_dump -Fc
# /root/cluster-backup/manifests/<stamp>.txt sizes + sha256
#
# Everything is streamed: no byte of this backup is staged on siriussec
# (the node runs close to DiskPressure and `local-path` lives on it).
set -euo pipefail
# alpine/k8s ships kubectl/bash but not rsync/ssh; install them per run
# (~2 s). Nothing else is needed: the DB dumps run inside the CNPG pod.
if ! command -v rsync >/dev/null || ! command -v ssh >/dev/null; then
echo "== installing rsync + openssh-client"
apk add --no-cache rsync openssh-client >/dev/null
fi
BACKUP_HOST=${BACKUP_HOST:[email protected]}
BACKUP_DIR=${BACKUP_DIR:-/root/cluster-backup}
CNPG_TARGETS=${CNPG_TARGETS:-"forgejo/pg sirius-growth/portal"}
DATA_SRC=${DATA_SRC:-/src}
DATA_KEEP=${DATA_KEEP:-7}
DB_KEEP=${DB_KEEP:-14}
MIN_FREE_GB=${MIN_FREE_GB:-8}
STAMP=${STAMP:-$(date -u +%Y%m%dT%H%M%SZ)}
SSH_OPTS=(-i /keys/id_ed25519
-o UserKnownHostsFile=/keys/known_hosts
-o StrictHostKeyChecking=yes
-o BatchMode=yes
-o ConnectTimeout=20
-o ServerAliveInterval=30)
ssh_r() { ssh "${SSH_OPTS[@]}" "$BACKUP_HOST" "$@"; }
echo "== target: $BACKUP_HOST:$BACKUP_DIR stamp=$STAMP"
ssh_r "mkdir -p '$BACKUP_DIR/forgejo-data' '$BACKUP_DIR/db' '$BACKUP_DIR/manifests'"
avail_gb=$(ssh_r "df -Pk '$BACKUP_DIR' | awk 'NR==2{printf \"%d\", \$4/1048576}'")
avail_gb=${avail_gb:-0}
echo "== remote free space: ${avail_gb} GiB (minimum ${MIN_FREE_GB} GiB)"
if [ "$avail_gb" -lt "$MIN_FREE_GB" ]; then
echo "FAIL: not enough free space on $BACKUP_HOST"
exit 1
fi
# First run: --link-dest needs an existing directory to compare against.
ssh_r "cd '$BACKUP_DIR/forgejo-data' && [ -e latest ] || { mkdir -p .empty && ln -sfn .empty latest; }"
echo "== forgejo-data: /src -> forgejo-data/$STAMP (incremental, link-dest)"
# Forgejo keeps writing while this runs, so a repack/upload can vanish
# mid-copy: rsync reports that as exit 24. That is expected on a live
# instance; anything else (23 = partial transfer, 11/12 = protocol) is a
# real failure. The two transient upload spools are excluded for the same
# reason — they hold half-written packages, never restorable state.
rc=0
rsync -a --numeric-ids --delete --stats --link-dest=../latest \
--exclude=/gitea/data/tmp/ \
--exclude=/gitea/data/repo-archive/tmp/ \
-e "ssh ${SSH_OPTS[*]}" \
"$DATA_SRC/" "$BACKUP_HOST:$BACKUP_DIR/forgejo-data/$STAMP/" || rc=$?
case "$rc" in
0) ;;
24) echo "== rsync exit 24: files changed during the copy (expected on a live Forgejo)" ;;
*) echo "FAIL: rsync exit $rc"; exit "$rc" ;;
esac
ssh_r "cd '$BACKUP_DIR/forgejo-data' && ln -sfn '$STAMP' latest && du -sh '$STAMP'"
echo "== databases"
for target in $CNPG_TARGETS; do
ns=${target%%/*}
cluster=${target##*/}
pod=$(kubectl -n "$ns" get cluster "$cluster" -o jsonpath='{.status.currentPrimary}')
db=$(kubectl -n "$ns" get cluster "$cluster" -o jsonpath='{.spec.bootstrap.initdb.database}')
if [ -z "$pod" ] || [ -z "$db" ]; then
echo "FAIL: $ns/$cluster has no currentPrimary/initdb database"
exit 1
fi
out="$BACKUP_DIR/db/$ns-$cluster-$STAMP.dump"
echo "-- $ns/$cluster primary=$pod db=$db -> $out"
sha_file=$(mktemp)
kubectl -n "$ns" exec -c postgres "$pod" -- \
pg_dump -U postgres -d "$db" -Fc -Z6 \
| tee >(sha256sum | awk '{print $1}' > "$sha_file") \
| ssh_r "cat > '$out.part'"
local_sha=$(cat "$sha_file"); rm -f "$sha_file"
remote_sha=$(ssh_r "sha256sum '$out.part' | awk '{print \$1}'")
if [ -z "$local_sha" ] || [ "$local_sha" != "$remote_sha" ]; then
echo "FAIL: sha256 mismatch for $out (local=${local_sha:-none} remote=${remote_sha:-none})"
exit 1
fi
ssh_r "mv '$out.part' '$out'"
echo " sha256=$local_sha"
ssh_r "ls -l '$out'"
done
echo "== manifest"
ssh_r "cd '$BACKUP_DIR' && { echo \"stamp $STAMP\"; echo \"host \$(hostname -s)\"; \
echo '--- forgejo-data/latest'; du -shL forgejo-data/latest; \
echo '--- db'; sha256sum db/*-$STAMP.dump; \
echo '--- db listing'; ls -l db; } > manifests/$STAMP.txt && cat manifests/$STAMP.txt"
echo "== retention: last $DATA_KEEP data snapshots, last $DB_KEEP dump files"
ssh_r "cd '$BACKUP_DIR/forgejo-data' && ls -1dt 20* 2>/dev/null | tail -n +$((DATA_KEEP + 1)) | xargs -r rm -rf"
ssh_r "cd '$BACKUP_DIR/db' && ls -1t *.dump 2>/dev/null | tail -n +$((DB_KEEP + 1)) | xargs -r rm -f"
ssh_r "cd '$BACKUP_DIR/manifests' && ls -1t *.txt 2>/dev/null | tail -n +$((DB_KEEP + 1)) | xargs -r rm -f"
ssh_r "df -h '$BACKUP_DIR' | tail -1"
echo "RESULT=success stamp=$STAMP"
---
apiVersion: batch/v1
kind: CronJob
metadata:
name: cluster-backup
namespace: forgejo
labels:
app: cluster-backup
spec:
# UTC everywhere, same convention as every other CronJob in this repo.
schedule: "37 2 * * *"
timeZone: "Etc/UTC"
concurrencyPolicy: Forbid
# Missed by more than 30 min (cluster down / node rebooting): skip the night
# instead of starting a mirror at a random time.
startingDeadlineSeconds: 1800
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
# First full mirror of an 18 GiB PVC measured ~15 MB/s over WireGuard
# (~20 min); two hours leaves room for a slow night without being killed
# half-way through a snapshot.
activeDeadlineSeconds: 7200
backoffLimit: 1
template:
metadata:
labels:
app: cluster-backup
spec:
restartPolicy: Never
serviceAccountName: cluster-backup
# The forgejo-data PVC is local-path on siriussec; the pod must run
# where the volume is.
nodeSelector:
kubernetes.io/hostname: siriussec
containers:
- name: backup
# alpine/k8s carries kubectl 1.36.4 (== cluster version) so the
# CNPG dumps can be taken through the exec API; rsync + openssh
# are added at start (the pod has normal egress).
image: alpine/k8s:1.36.4
imagePullPolicy: IfNotPresent
command: ["/bin/bash", "/scripts/backup.sh"]
env:
- name: BACKUP_HOST
value: [email protected]
- name: BACKUP_DIR
value: /root/cluster-backup
- name: CNPG_TARGETS
value: "forgejo/pg sirius-growth/portal"
- name: DATA_KEEP
value: "7"
- name: DB_KEEP
value: "14"
volumeMounts:
- name: forgejo-data
mountPath: /src
readOnly: true
- name: keys
mountPath: /keys
readOnly: true
- name: scripts
mountPath: /scripts
readOnly: true
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
# Streaming only — this is a hard cap so a regression can
# never stage the 18 GiB PVC on the T480's root filesystem.
ephemeral-storage: 1Gi
memory: 512Mi
volumes:
- name: forgejo-data
persistentVolumeClaim:
claimName: forgejo-data
readOnly: true
- name: keys
secret:
secretName: cluster-backup-ssh
defaultMode: 0400
- name: scripts
configMap:
name: cluster-backup-scripts
defaultMode: 0755

View file

@ -18,3 +18,6 @@ resources:
- runner-amd64.yaml - runner-amd64.yaml
- runner-deploy-arm64.yaml - runner-deploy-arm64.yaml
- prune-cronjob.yaml - prune-cronjob.yaml
# Nightly disaster-recovery backup of forgejo-data + every CNPG database to
# the Linode VPS. Lives here because a PVC cannot be mounted cross-namespace.
- cluster-backup.yaml

View file

@ -0,0 +1,41 @@
---
# Lets the nightly `forgejo/cluster-backup` CronJob take a `pg_dump` of this
# namespace's CloudNativePG cluster through the exec API (namespace `forgejo`
# cannot mount a Secret from here, and the dump runs as the in-pod `postgres`
# superuser over the local socket, so no database password exists in git).
#
# Least privilege: that ServiceAccount may look up the Cluster object and run
# one command inside this namespace's pods — nothing else.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: cluster-backup
namespace: sirius-growth
labels:
app: cluster-backup
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create"]
- apiGroups: ["postgresql.cnpg.io"]
resources: ["clusters"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: cluster-backup
namespace: sirius-growth
labels:
app: cluster-backup
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: cluster-backup
subjects:
- kind: ServiceAccount
name: cluster-backup
namespace: forgejo

View file

@ -19,3 +19,6 @@ resources:
- pvc-leadgen.yaml - pvc-leadgen.yaml
- cronjob-leadgen.yaml - cronjob-leadgen.yaml
- cronjob-leadgen-ncda.yaml - cronjob-leadgen-ncda.yaml
# exec-only RBAC so forgejo/cluster-backup can pg_dump this namespace's CNPG
# cluster (portal) without copying a database password across namespaces.
- backup-exec-rbac.yaml

View file

@ -481,16 +481,97 @@ StorageClass `local-path` (default, `WaitForFirstConsumer`, no expansion), provi
| PVC | NS | Size | On-disk dir | Used | Holds | | PVC | NS | Size | On-disk dir | Used | Holds |
|---|---|---|---|---|---| |---|---|---|---|---|---|
| `forgejo-data` | forgejo | 20 Gi | `pvc-75ba7bc3…_forgejo_forgejo-data` | **12 G** | Forgejo repos, LFS, avatars, attachments — **must be backed up** | | `forgejo-data` | forgejo | 20 Gi | `pvc-75ba7bc3…_forgejo_forgejo-data` | **19 G** | Forgejo repos, LFS, avatars, attachments (13.6 G of that is package-registry blobs) — **backed up nightly** |
| `forgejo-runner-amd64` | forgejo | 20 Gi | `pvc-b867904c…_forgejo_forgejo-runner-amd64` | **18 G** (18 G of it the dind `/docker` data-root) | CI scratch — **disposable**, but see the hazard below | | `forgejo-runner-amd64` | forgejo | 20 Gi | `pvc-b867904c…_forgejo_forgejo-runner-amd64` | **22 G** (the dind `/docker` data-root) | CI scratch — **disposable**, but see the hazard below |
| `pg-1` | forgejo | 10 Gi | `pvc-3c0ba824…_forgejo_pg-1` | 643 M | Forgejo Postgres data — **must be backed up** | | `pg-1` | forgejo | 10 Gi | `pvc-3c0ba824…_forgejo_pg-1` | 653 M | Forgejo Postgres data — **backed up nightly (pg_dump)** |
| `portal-1` | sirius-growth | 5 Gi | `pvc-3348c52c…_sirius-growth_portal-1` | 224 M | SGS portal Postgres data — **must be backed up** | | `portal-1` | sirius-growth | 5 Gi | `pvc-3348c52c…_sirius-growth_portal-1` | 595 M | SGS portal Postgres data — **backed up nightly (pg_dump)** |
| `osint-pgdata` / `osint-camera-snapshots` | osint | 15 Gi / 3 Gi | — | 289 M / 4 K | plain Postgres + camera snapshots — **no backup job (gap)** |
| `sgs-leadgen-data` | sirius-growth | 1 Gi | — | 4.9 M | lead-gen capture — **no backup job (gap)** |
| `kube-prometheus-stack-grafana` | monitoring | 5 Gi | — | 55 M | Grafana sqlite (dashboards, alert rules) — **no backup job (gap)** |
| `…prometheus-…-db-…prometheus-0` | monitoring | 10 Gi | — | 2.4 G | Prometheus TSDB — rebuildable metrics history, **not backed up** |
**Dind growth hazard.** The amd64 runner's PVC is nominally 20 Gi and currently sits at **18 G (90%)**. It has previously grown to ~50 GB from heavy Android/Rust builds and pushed the node into `DiskPressure`, which evicted the runner and left Forgejo and `pg-1` Pending. Docker image GC does not reclaim the data-root. Rule: when it approaches the cap, scale the runner to 0 **first**, then wipe `.../docker/*` (keeping `runner.ini` beside it), then scale back and re-pull the job image — wiping it under a live or restarting pod leaves `dockerd` half-initialised and every pull fails. Note the data-root also hosts the named volumes CI depends on (`cargo-target`, Android SDK, Gradle cache), so a wipe makes the next run fully cold. **Dind growth hazard.** The amd64 runner's PVC is nominally 20 Gi and currently sits at **~22 G**: it has previously grown to ~50 GB from heavy Android/Rust builds and pushed the node into `DiskPressure`, which evicted the runner and left Forgejo and `pg-1` Pending. Docker image GC does not reclaim the data-root. Rule: when it approaches the cap, scale the runner to 0 **first**, then wipe `.../docker/*` (keeping `runner.ini` beside it), then scale back and re-pull the job image — wiping it under a live or restarting pod leaves `dockerd` half-initialised and every pull fails. Note the data-root also hosts the named volumes CI depends on (`cargo-target`, Android SDK, Gradle cache), so a wipe makes the next run fully cold.
**What must be backed up:** `forgejo-data`, both Postgres data dirs (`pg-1`, `portal-1`), the Pi's Garage `data/` + `meta/`, and `/etc/wireguard/` on the Pi. The runner PVC and the Pi's Docker images are rebuildable. Host disks *(live)*: siriussec `/` 214 G, 167 G used (**83 %**, 37 G free); rpi `/` 917 G, 506 G used (58 %, 374 G free); linode `/` 79 G, 11 G used (**14 %**, 64 G free — this is the backup target).
### 8.1 Backup coverage
Two independent nightly paths, both **off** the T480 and **off** the Pi:
1. **Cluster state → Linode VPS**, CronJob `forgejo/cluster-backup`
(`apps/base/forgejo/cluster-backup.yaml`; exec-only RBAC in
`apps/base/sirius-growth/backup-exec-rbac.yaml`). Schedule `37 2 * * *`
UTC, `concurrencyPolicy: Forbid`. Destination is
`[email protected]:/root/cluster-backup` — **the mesh address, never the public
IP**. Everything is streamed: no dump is staged on siriussec.
2. **Garage object store (Pi) → same Linode**, `infrastructure/garage/backup/`
`garage-meta-backup.timer` (hourly) + `garage-data-backup.timer` (nightly) →
`[email protected]:/root/garage-backup`.
| Artifact | Method | On the Linode | Retention |
|---|---|---|---|
| `forgejo-data` PVC (`/data`) | `rsync -a --delete --link-dest` snapshot mirror, PVC mounted read-only | `forgejo-data/<stamp>/` + `latest` symlink | 7 snapshots (hardlinked: 1 full copy + nightly deltas) |
| `forgejo/pg` | `pg_dump -Fc -Z6` **inside the CNPG primary** over the local socket — no DB password exists in git or in the Job | `db/forgejo-pg-<stamp>.dump` | 14 |
| `sirius-growth/portal` | same, through exec RBAC in `sirius-growth` | `db/sirius-growth-portal-<stamp>.dump` | 14 |
- The data mirror is a *snapshot* mirror, not a rolling one: each night writes a
new directory whose unchanged files are hardlinks to the previous night's, so
a corrupted file in the source cannot rewrite history.
- DB dumps are checksummed on **both** sides (`sha256sum` on the pod's copy of
the stream vs the remote file) before the `.part` file is renamed; a short
stream fails the Job instead of silently shipping a broken archive.
- Each run appends sizes + checksums to `/root/cluster-backup/manifests/<stamp>.txt`.
- The Job fails (a red Job, not a silent skip) if the Linode has less than
8 GiB free, so a growing registry cannot quietly eat the last snapshot's room.
- The only secret is the backup SSH key: `forgejo/cluster-backup-ssh` (created
out of band, **not in git**, so Flux never reverts it) holding an ed25519 key
that is `from="10.10.0.0/24,10.244.0.0/16,10.20.0.0/24"`-restricted,
`no-pty`, no forwarding in `root@linode:~/.ssh/authorized_keys`. Host key is
pinned (`known_hosts` for `10.10.0.5`), so a MITM on the mesh fails closed.
- The Job lives in namespace `forgejo` (not a `backup` namespace) because a PVC
cannot be mounted cross-namespace and `forgejo-data` is the largest artifact.
**Not covered — honest gaps:**
- `monitoring/kube-prometheus-stack-grafana` (55 MiB sqlite: dashboards, alert
rules) — **no backup**. Prometheus' 2.4 GiB TSDB is deliberately excluded
(regenerated metrics history).
- `osint/osint-pgdata` (289 MiB, a plain Postgres **Deployment**, not CNPG) and
`osint/osint-camera-snapshots`, `sirius-growth/sgs-leadgen-data` (4.9 MiB) —
**no backup**.
- `/etc/wireguard/` on the Pi — still only on the Pi (wgportal's sqlite is the
live source; a Pi disk loss takes the peer set with it).
- The runner PVCs (`forgejo-runner-amd64`, `*-dind`) are CI scratch, rebuildable
by design (the dind data-root only holds named build caches).
A new CloudNativePG cluster is **not** picked up automatically: add
`<ns>/<cluster>` to `CNPG_TARGETS` in the CronJob env *and* an equivalent
exec-only Role/RoleBinding for the `forgejo/cluster-backup` ServiceAccount in
that namespace.
### 8.2 Restoring
Rehearsed on 2026-11-19 (see the completion note on task `t_dcad85f6`); the DB
restore below was exercised against a throwaway Postgres pod and produced the
live row count.
```bash
# 1. Forgejo data: stop Forgejo, then mirror the newest snapshot back.
kubectl -n forgejo scale deploy/forgejo --replicas=0
# on the node holding the PVC (siriussec), or from any pod that mounts it:
# rsync -a --delete root@10.10.0.5:/root/cluster-backup/forgejo-data/latest/ /data/
kubectl -n forgejo scale deploy/forgejo --replicas=1
# 2. A CNPG database: pull the dump and restore it with pg_restore, e.g. into a
# scratch pod or a scratch database on the cluster:
ssh root@10.10.0.5 'cat /root/cluster-backup/db/forgejo-pg-<stamp>.dump' \
| kubectl -n forgejo exec -i <pod> -c postgres -- \
pg_restore -U postgres -d <target-db> --no-owner --no-privileges
```
`pg_restore` is **not** installed on the Linode — pull the dump and restore with
a Postgres client (the `ghcr.io/cloudnative-pg/postgresql:16` primary has one).
Host disks *(live)*: siriussec `/` 214 G, 141 G used (**70%**, 62 G free); rpi `/` 917 G, 506 G used (58%, 374 G free).
--- ---