From c1fe485469b8958fedbf8fca36e0aff86b09d004 Mon Sep 17 00:00:00 2001 From: Lance Walters Date: Thu, 19 Nov 2026 17:14:36 -0500 Subject: [PATCH] apps(backup): cover the remaining stateful gaps off-host MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four pieces of state were still only on the machine they run on. All four now land on the Linode over the WireGuard mesh, in the same /root/cluster-backup tree (or /root/pihost-backup for the Pi) with the same manifest/sha256 habit: * monitoring/kube-prometheus-stack-grafana — new CronJob `monitoring/grafana-backup`. The image is -distroless (no shell), so this mounts the PVC read-write and takes a consistent copy with the sqlite backup API (PRAGMA integrity_check on the copy), then streams it: grafana/grafana-.db, keep 14. * osint/osint-db — plain Postgres Deployment, so neither the CNPG primary lookup nor CNPG_TARGETS reaches it. `forgejo/cluster-backup` gains a PG_TARGETS loop that pg_dump -Fc's inside the pod using its own POSTGRES_USER/POSTGRES_DB (exec-only RBAC in apps/base/osint/), sha256 checked on both sides. * sirius-growth/sgs-leadgen-data — new CronJob `sirius-growth/leadgen-backup`, link-dest snapshot mirror, keep 7. * Pi /etc/wireguard + wgportal sqlite — infrastructure/wireguard/backup/, nightly systemd timer -> root@10.20.0.1:/root/pihost-backup, keep 14. Each tree carries its own retention, so adding artifacts cannot crowd the Linode. Docs §8/§8.1/§8.2 record coverage, the accepted gaps (Prometheus TSDB, camera frames, runner scratch) and the restore procedure — including the TimescaleDB pre/post-restore calls osint needs. --- apps/base/forgejo/cluster-backup.yaml | 35 +++- apps/base/osint/backup-exec-rbac.yaml | 46 +++++ apps/base/osint/kustomization.yaml | 3 + apps/base/sirius-growth/kustomization.yaml | 2 + apps/base/sirius-growth/leadgen-backup.yaml | 150 +++++++++++++++ docs/cluster-overview.md | 90 +++++++-- infrastructure/wireguard/backup/README.md | 82 ++++++++ .../wireguard/backup/wireguard-backup.service | 18 ++ .../wireguard/backup/wireguard-backup.sh | 110 +++++++++++ .../wireguard/backup/wireguard-backup.timer | 13 ++ .../controllers/home/grafana-backup.yaml | 178 ++++++++++++++++++ .../controllers/home/kustomization.yaml | 2 + 12 files changed, 712 insertions(+), 17 deletions(-) create mode 100644 apps/base/osint/backup-exec-rbac.yaml create mode 100644 apps/base/sirius-growth/leadgen-backup.yaml create mode 100644 infrastructure/wireguard/backup/README.md create mode 100644 infrastructure/wireguard/backup/wireguard-backup.service create mode 100644 infrastructure/wireguard/backup/wireguard-backup.sh create mode 100644 infrastructure/wireguard/backup/wireguard-backup.timer create mode 100644 monitoring/controllers/home/grafana-backup.yaml diff --git a/apps/base/forgejo/cluster-backup.yaml b/apps/base/forgejo/cluster-backup.yaml index 1e7386c..5b1518d 100644 --- a/apps/base/forgejo/cluster-backup.yaml +++ b/apps/base/forgejo/cluster-backup.yaml @@ -1,6 +1,7 @@ --- # Nightly backup of every piece of state on this cluster that is not -# rebuildable from git: Forgejo's data PVC and the CloudNativePG databases. +# rebuildable from git: Forgejo's data PVC, the CloudNativePG databases and the +# plain Postgres Deployment in `osint`. # # Why this lives in namespace `forgejo` (and not a `backup` namespace): # the biggest artifact is the `forgejo-data` PVC, and a Kubernetes volume @@ -96,6 +97,11 @@ data: BACKUP_HOST=${BACKUP_HOST:-root@10.10.0.5} BACKUP_DIR=${BACKUP_DIR:-/root/cluster-backup} CNPG_TARGETS=${CNPG_TARGETS:-"forgejo/pg sirius-growth/portal"} + # Plain (non-CNPG) Postgres Deployments: /. There is + # no Cluster CR to ask for a primary, and no superuser path from outside, so + # the dump runs inside the pod and reads its own POSTGRES_USER/POSTGRES_DB + # (local socket, trust auth) — no password in git or in this Job. + PG_TARGETS=${PG_TARGETS:-"osint/osint-db"} DATA_SRC=${DATA_SRC:-/src} DATA_KEEP=${DATA_KEEP:-7} DB_KEEP=${DB_KEEP:-14} @@ -143,6 +149,8 @@ data: ssh_r "cd '$BACKUP_DIR/forgejo-data' && ln -sfn '$STAMP' latest && du -sh '$STAMP'" echo "== databases" + # A previous run killed mid-stream can leave a zero-byte `.part` behind. + ssh_r "find '$BACKUP_DIR/db' -name '*.part' -mmin +60 -delete 2>/dev/null || true" for target in $CNPG_TARGETS; do ns=${target%%/*} cluster=${target##*/} @@ -170,6 +178,29 @@ data: ssh_r "ls -l '$out'" done + echo "== plain Postgres deployments" + for target in $PG_TARGETS; do + ns=${target%%/*} + deploy=${target##*/} + out="$BACKUP_DIR/db/$ns-$deploy-$STAMP.dump" + echo "-- $ns/$deploy -> $out" + sha_file=$(mktemp) + kubectl -n "$ns" exec "deploy/$deploy" -- \ + sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_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})" + ssh_r "rm -f '$out.part'" + 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; \ @@ -234,6 +265,8 @@ spec: value: /root/cluster-backup - name: CNPG_TARGETS value: "forgejo/pg sirius-growth/portal" + - name: PG_TARGETS + value: "osint/osint-db" - name: DATA_KEEP value: "7" - name: DB_KEEP diff --git a/apps/base/osint/backup-exec-rbac.yaml b/apps/base/osint/backup-exec-rbac.yaml new file mode 100644 index 0000000..e2a691d --- /dev/null +++ b/apps/base/osint/backup-exec-rbac.yaml @@ -0,0 +1,46 @@ +--- +# Lets the nightly `forgejo/cluster-backup` CronJob take a `pg_dump` of the +# plain (non-CNPG) Postgres Deployment `osint/osint-db` through the exec API. +# +# `osint-db` is a stock `postgres` Deployment, so there is no Cluster object and +# no `status.currentPrimary` to look up; the dump is taken inside the pod over +# the local socket and uses the pod's own `POSTGRES_USER`/`POSTGRES_DB`, so no +# password is copied into `forgejo`, git or the Job. +# +# Least privilege: the ServiceAccount may run one command inside this +# namespace's pods — nothing else. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: cluster-backup + namespace: osint + labels: + app: cluster-backup +rules: + - apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list"] + - apiGroups: [""] + resources: ["pods/exec"] + verbs: ["create"] + # `kubectl exec deploy/osint-db` resolves the Deployment's ReplicaSet/pod, so + # it needs read access to the deployment itself. + - apiGroups: ["apps"] + resources: ["deployments"] + verbs: ["get"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: cluster-backup + namespace: osint + labels: + app: cluster-backup +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: cluster-backup +subjects: + - kind: ServiceAccount + name: cluster-backup + namespace: forgejo diff --git a/apps/base/osint/kustomization.yaml b/apps/base/osint/kustomization.yaml index af3ccdf..e002a5c 100644 --- a/apps/base/osint/kustomization.yaml +++ b/apps/base/osint/kustomization.yaml @@ -18,3 +18,6 @@ resources: - news-scraper-deployment.yaml - news-summarizer-deployment.yaml - httproute.yaml + # exec-only RBAC so forgejo/cluster-backup can pg_dump this namespace's plain + # Postgres Deployment (osint-db) — not a CNPG cluster, so it needs its own path. + - backup-exec-rbac.yaml diff --git a/apps/base/sirius-growth/kustomization.yaml b/apps/base/sirius-growth/kustomization.yaml index 1c16380..0719d16 100644 --- a/apps/base/sirius-growth/kustomization.yaml +++ b/apps/base/sirius-growth/kustomization.yaml @@ -22,3 +22,5 @@ resources: # 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 + # Snapshot mirror of the lead-gen capture PVC to the Linode. + - leadgen-backup.yaml diff --git a/apps/base/sirius-growth/leadgen-backup.yaml b/apps/base/sirius-growth/leadgen-backup.yaml new file mode 100644 index 0000000..70aa0cf --- /dev/null +++ b/apps/base/sirius-growth/leadgen-backup.yaml @@ -0,0 +1,150 @@ +--- +# backup: `sgs-leadgen-data` PVC (4.9 MiB) -> Linode VPS over the WireGuard mesh. +# +# The lead-gen CronJobs (`cronjob-leadgen.yaml`, `cronjob-leadgen-ncda.yaml`) +# read and write this claim, so a pod of this namespace must mount it — a PVC +# cannot be mounted from `forgejo` where the main cluster-backup job lives. +# The mirror is a hardlink `--link-dest` snapshot chain (same shape as the +# forgejo-data mirror) so each night is a full restorable directory and only +# changed blocks cross the tunnel. +apiVersion: v1 +kind: ConfigMap +metadata: + name: leadgen-backup-scripts + namespace: sirius-growth + labels: + app: leadgen-backup +data: + backup.sh: | + #!/bin/bash + # Snapshot mirror of /src -> $BACKUP_DIR/leadgen-data// + `latest`. + set -euo pipefail + + 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:-root@10.10.0.5} + BACKUP_DIR=${BACKUP_DIR:-/root/cluster-backup} + DATA_SRC=${DATA_SRC:-/src} + DATA_KEEP=${DATA_KEEP:-7} + 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/leadgen-data' '$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 + + ssh_r "cd '$BACKUP_DIR/leadgen-data' && [ -e latest ] || { mkdir -p .empty && ln -sfn .empty latest; }" + + echo "== leadgen-data: $DATA_SRC -> leadgen-data/$STAMP (link-dest)" + rc=0 + rsync -a --numeric-ids --delete --stats --link-dest=../latest \ + -e "ssh ${SSH_OPTS[*]}" \ + "$DATA_SRC/" "$BACKUP_HOST:$BACKUP_DIR/leadgen-data/$STAMP/" || rc=$? + case "$rc" in + 0) ;; + 24) echo "== rsync exit 24: files changed during the copy (expected)" ;; + *) echo "FAIL: rsync exit $rc"; exit "$rc" ;; + esac + ssh_r "cd '$BACKUP_DIR/leadgen-data' && ln -sfn '$STAMP' latest && du -sh '$STAMP'" + + echo "== manifest" + ssh_r "cd '$BACKUP_DIR' && { echo 'stamp $STAMP'; echo \"host \$(hostname -s)\"; \ + echo '--- leadgen-data/latest'; du -shL leadgen-data/latest; \ + find leadgen-data/latest -type f -exec sha256sum {} + | sed 's| leadgen-data/latest/| |'; } \ + >> manifests/$STAMP.txt && tail -8 manifests/$STAMP.txt" + + echo "== retention: last $DATA_KEEP leadgen snapshots" + ssh_r "cd '$BACKUP_DIR/leadgen-data' && ls -1dt 20* 2>/dev/null | tail -n +$((DATA_KEEP + 1)) | xargs -r rm -rf" + ssh_r "df -h '$BACKUP_DIR' | tail -1" + + echo "RESULT=success stamp=$STAMP" +--- +apiVersion: batch/v1 +kind: CronJob +metadata: + name: leadgen-backup + namespace: sirius-growth + labels: + app: leadgen-backup +spec: + # 07 minutes after the grafana job; the dataset is tiny, this is only so the + # three nightly jobs never overlap on the mesh. + schedule: "7 3 * * *" + timeZone: "Etc/UTC" + concurrencyPolicy: Forbid + startingDeadlineSeconds: 1800 + successfulJobsHistoryLimit: 3 + failedJobsHistoryLimit: 3 + jobTemplate: + spec: + activeDeadlineSeconds: 900 + backoffLimit: 1 + template: + metadata: + labels: + app: leadgen-backup + spec: + restartPolicy: Never + # The PVC is local-path on siriussec. + nodeSelector: + kubernetes.io/hostname: siriussec + containers: + - name: backup + image: alpine/k8s:1.36.4 + imagePullPolicy: IfNotPresent + command: ["/bin/bash", "/scripts/backup.sh"] + env: + - name: BACKUP_HOST + value: root@10.10.0.5 + - name: BACKUP_DIR + value: /root/cluster-backup + - name: DATA_KEEP + value: "7" + volumeMounts: + - name: leadgen-data + mountPath: /src + readOnly: true + - name: keys + mountPath: /keys + readOnly: true + - name: scripts + mountPath: /scripts + readOnly: true + resources: + requests: + cpu: 50m + memory: 64Mi + limits: + ephemeral-storage: 512Mi + memory: 256Mi + volumes: + - name: leadgen-data + persistentVolumeClaim: + claimName: sgs-leadgen-data + readOnly: true + - name: keys + secret: + # Copy of forgejo/cluster-backup-ssh, created out of band. + secretName: cluster-backup-ssh + defaultMode: 0400 + - name: scripts + configMap: + name: leadgen-backup-scripts + defaultMode: 0755 diff --git a/docs/cluster-overview.md b/docs/cluster-overview.md index a830994..54823b8 100644 --- a/docs/cluster-overview.md +++ b/docs/cluster-overview.md @@ -485,9 +485,9 @@ StorageClass `local-path` (default, `WaitForFirstConsumer`, no expansion), provi | `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` | 653 M | Forgejo Postgres data — **backed up nightly (pg_dump)** | | `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)** | +| `osint-pgdata` / `osint-camera-snapshots` | osint | 15 Gi / 3 Gi | — | 289 M / 4 K | plain Postgres — **backed up nightly (pg_dump)**; the camera snapshot dir is 4 K of throwaway frames — **accepted gap** | +| `sgs-leadgen-data` | sirius-growth | 1 Gi | — | 4.9 M | lead-gen capture — **mirrored nightly** | +| `kube-prometheus-stack-grafana` | monitoring | 5 Gi | — | 55 M | Grafana sqlite: users/orgs/prefs/API keys/annotations (dashboards, datasources and alert rules are provisioned from git, so they are *not* in the db) — **snapshotted nightly** | | `…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 **~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. @@ -496,23 +496,38 @@ Host disks *(live)*: siriussec `/` 214 G, 167 G used (**83 %**, 37 G free); rpi ### 8.1 Backup coverage -Two independent nightly paths, both **off** the T480 and **off** the Pi: +Three independent scheduled paths, all **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 * * *` + `apps/base/sirius-growth/backup-exec-rbac.yaml` and + `apps/base/osint/backup-exec-rbac.yaml`). Schedule `37 2 * * *` UTC, `concurrencyPolicy: Forbid`. Destination is `root@10.10.0.5:/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/` +2. **Two small PVC mirrors into the same tree**, because a PVC can only be + mounted by a pod in its own namespace: `monitoring/grafana-backup` + (`monitoring/controllers/home/grafana-backup.yaml`, `0 3 * * *`) and + `sirius-growth/leadgen-backup` (`apps/base/sirius-growth/leadgen-backup.yaml`, + `7 3 * * *`). Both mount the claim on siriussec and stream to + `root@10.10.0.5:/root/cluster-backup`, so retention and the manifest habit + are shared with path 1. +3. **Garage object store (Pi) → same Linode**, `infrastructure/garage/backup/` `garage-meta-backup.timer` (hourly) + `garage-data-backup.timer` (nightly) → `root@10.20.0.1:/root/garage-backup`. +A fourth path covers the Pi's own hub state: `infrastructure/wireguard/backup/` +`wireguard-backup.timer` (nightly 04:13) → `root@10.20.0.1:/root/pihost-backup`. + | Artifact | Method | On the Linode | Retention | |---|---|---|---| | `forgejo-data` PVC (`/data`) | `rsync -a --delete --link-dest` snapshot mirror, PVC mounted read-only | `forgejo-data//` + `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-.dump` | 14 | | `sirius-growth/portal` | same, through exec RBAC in `sirius-growth` | `db/sirius-growth-portal-.dump` | 14 | +| `osint/osint-db` (plain Postgres Deployment, has TimescaleDB + PostGIS) | `pg_dump -Fc -Z6` **inside the pod** over the local socket, using its own `POSTGRES_USER`/`POSTGRES_DB` via exec RBAC in `osint` | `db/osint-osint-db-.dump` | 14 | +| `grafana.db` (sqlite) | **sqlite backup API** in a `python:3.12-alpine` pod that mounts the PVC — a `cp` of a live db can capture a torn page; the image is `-distroless`, so there is no shell to exec into | `grafana/grafana-.db` | 14 | +| `sgs-leadgen-data` PVC | `rsync -a --delete --link-dest` snapshot mirror, PVC mounted read-only | `leadgen-data//` + `latest` | 7 | +| Pi `/etc/wireguard/` + wgportal `sqlite.db` | Pi-side systemd timer: tarball (`/etc/wireguard` verbatim incl. `.bak` history + a sqlite-API copy of the peer db), sha256 checked on both sides | `root@10.20.0.1:/root/pihost-backup/wireguard/wireguard-.tar.gz` | 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 @@ -531,18 +546,20 @@ Two independent nightly paths, both **off** the T480 and **off** the Pi: - 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:** +**Accepted gaps (with the reason, not just a TODO):** -- `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 +- **Prometheus TSDB** (2.4 GiB) — deliberately excluded: regenerated metrics + history, and a volume loss only costs graphs, not state. +- **`osint/osint-camera-snapshots`** (4 K) — throwaway camera frames; the + camera re-captures on demand and nothing reads old frames. +- **Runner PVCs** (`forgejo-runner-amd64`, `*-dind`) — CI scratch, rebuildable by design (the dind data-root only holds named build caches). +- **Grafana dashboards / datasources / alert rules are not in the backup and do + not need to be**: they are provisioned from `monitoring/controllers/home/` + in git. The sqlite db carries the parts git cannot rebuild — users, orgs, + preferences, annotations and API keys. +- **Pi `/etc/wireguard` is only as fresh as the last nightly run** — a peer + added today is in the db and on the Pi, and reaches the Linode at 04:13. A new CloudNativePG cluster is **not** picked up automatically: add `/` to `CNPG_TARGETS` in the CronJob env *and* an equivalent @@ -572,6 +589,47 @@ ssh root@10.10.0.5 'cat /root/cluster-backup/db/forgejo-pg-.dump' \ `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). +```bash +# 3. osint-db (plain Postgres **with TimescaleDB**): a naive pg_restore into a +# fresh database fails on hypertable catalog rows ("could not find hypertable +# with id N" / "ONLY option not supported on hypertable operations") and +# silently drops one hypertable's data. Pre/post-restore commands are +# mandatory, and the extensions must exist BEFORE them. +kubectl -n osint exec deploy/osint-db -- psql -U osint -d postgres \ + -c 'create database osint_restore' +kubectl -n osint exec deploy/osint-db -- psql -U osint -d osint_restore \ + -c 'create extension if not exists timescaledb' \ + -c 'create extension if not exists postgis' \ + -c 'select timescaledb_pre_restore()' +ssh root@10.10.0.5 'cat /root/cluster-backup/db/osint-osint-db-.dump' \ + | kubectl -n osint exec -i deploy/osint-db -- \ + pg_restore -U osint -d osint_restore --no-owner --no-privileges +kubectl -n osint exec deploy/osint-db -- psql -U osint -d osint_restore \ + -c 'select timescaledb_post_restore()' + +# 4. Grafana: readable with the sqlite backup API and integrity_check=ok. +# Stop Grafana first (it also runs `strategy: Recreate`) so the restored file +# is not overwritten by the running instance's open handle. +kubectl -n monitoring scale deploy/kube-prometheus-stack-grafana --replicas=0 +ssh root@10.10.0.5 'cat /root/cluster-backup/grafana/grafana-.db' \ + | kubectl -n monitoring exec -i -- \ + sh -c 'cat > /var/lib/grafana/grafana.db && chown 472:472 /var/lib/grafana/grafana.db' +kubectl -n monitoring scale deploy/kube-prometheus-stack-grafana --replicas=1 +# Users come back from the db; dashboards/datasources re-provision from git. + +# 5. Lead-gen capture: plain mirror — pull it back onto the claim with rsync. +rsync -a --delete root@10.10.0.5:/root/cluster-backup/leadgen-data/latest/ /leadgen/ + +# 6. Pi hub state (keys included — pull it to a root-only path, never a shared one). +ssh -i /home/sirius/.ssh/linode_admin root@10.20.0.1 \ + 'cat /root/pihost-backup/wireguard/wireguard-.tar.gz' | sudo tar -tzf - +# stop wg-quick first: SaveConfig = true rewrites wg0.conf from the live iface +sudo wg-quick down wg0 || true +ssh -i /home/sirius/.ssh/linode_admin root@10.20.0.1 \ + 'cat /root/pihost-backup/wireguard/wireguard-.tar.gz' | sudo tar -xzf - -C / +sudo systemctl start wg-quick@wg0 && sudo wg show +``` + --- diff --git a/infrastructure/wireguard/backup/README.md b/infrastructure/wireguard/backup/README.md new file mode 100644 index 0000000..3e04dac --- /dev/null +++ b/infrastructure/wireguard/backup/README.md @@ -0,0 +1,82 @@ +# WireGuard hub state — backup of `/etc/wireguard` + the wgportal peer database + +The Pi (`rpi`, `10.10.0.1`) is the WireGuard **hub** of the mesh *and* a spoke +of the Linode hub (`10.20.0.1`). Two files there are unrebuildable: + +| Path | What it is | +|---|---| +| `/etc/wireguard/wg0.conf` | wgportal-autogenerated hub config: wg0 server key, every peer, every `AllowedIPs` | +| `/etc/wireguard/wg-remote.conf` | the Pi→Linode spoke (key + endpoint) | +| `/opt/wgportal/data/sqlite.db` | wgportal's peer database (identifiers, keys, allowed IPs, display names) | + +A rebuilt Pi comes back from git + Garage's own backup — but the peer set and +the hub key would be gone, and with them every remote-access path. This +directory mirrors `infrastructure/garage/backup/`: a small script plus a +systemd timer that copies the state **off the Pi** to +`root@10.20.0.1:/root/pihost-backup/`. + +## This directory is NOT applied by Flux + +Flux only reconciles `./clusters/homek8s`. Install these by hand (they are host +units, not cluster objects): + +```bash +# from the repo checkout on the Pi (or scp the three files over) +sudo install -m 0755 wireguard-backup.sh /usr/local/sbin/wireguard-backup.sh +sudo install -m 0644 wireguard-backup.service wireguard-backup.timer /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now wireguard-backup.timer + +# one hand-fired run, and read the result (exit code is the truth) +sudo systemctl start wireguard-backup.service +systemctl status wireguard-backup.service --no-pager +journalctl -u wireguard-backup.service -n 40 --no-pager +``` + +Re-run the install after a Pi reinstall — the units do not survive a reimage. + +## What lands on the Linode + +``` +/root/pihost-backup/wireguard/wireguard-.tar.gz mode 0600 +/root/pihost-backup/manifests/.txt sizes + sha256 +``` + +- One tarball per run (`/etc/wireguard/` verbatim, including the `.bak` peer + history, plus `wgportal-sqlite.db`). Retention: **14** tarballs + 14 + manifests, enforced by the script. +- The sqlite copy is taken with the **sqlite backup API** (python3 stdlib — + there is no `sqlite3` CLI on the Pi), not `cp`: a live `cp` can capture a + half-written page. The script runs `PRAGMA integrity_check` on the copy and + fails the unit if it is not `ok`. +- The tarball is checksummed on both sides before the `.part` file is renamed. +- Transport is the `wg-remote` tunnel using the existing `sirius` user key + (`/home/sirius/.ssh/linode_admin`). Never the Linode public IP. + +## Restore + +The tarball contains private keys — treat it as a secret, not an archive. + +```bash +# pull the newest tarball and inspect it WITHOUT writing to /etc +ssh -i /home/sirius/.ssh/linode_admin root@10.20.0.1 \ + 'ls -1t /root/pihost-backup/wireguard/*.tar.gz | head -1' # pick a stamp +ssh -i /home/sirius/.ssh/linode_admin root@10.20.0.1 \ + 'cat /root/pihost-backup/wireguard/wireguard-.tar.gz' \ + | tar -tzf - + +# restore onto a rebuilt Pi (stop the interfaces first so a running wg-quick +# does not rewrite wg0.conf with SaveConfig = true) +sudo systemctl stop wg-quick@wg-remote || true +sudo wg-quick down wg0 || true +ssh ... 'cat /root/pihost-backup/wireguard/wireguard-.tar.gz' | sudo tar -xzf - -C / +sudo install -m 0600 -o root -g root /dev/null /dev/null # no-op, permissions come from the archive +sudo systemctl start wg-quick@wg0 && sudo systemctl start wg-quick@wg-remote +sudo wg show +``` + +If only wgportal lost its database: extract `wgportal-sqlite.db` from the +tarball, run `PRAGMA integrity_check` on it, and copy it over +`/opt/wgportal/data/sqlite.db` while the wgportal container is stopped — a +portal restart rewrites peers from live `wg set` state, so stop/start it +deliberately rather than leaving it running mid-restore. diff --git a/infrastructure/wireguard/backup/wireguard-backup.service b/infrastructure/wireguard/backup/wireguard-backup.service new file mode 100644 index 0000000..701c661 --- /dev/null +++ b/infrastructure/wireguard/backup/wireguard-backup.service @@ -0,0 +1,18 @@ +# /etc/systemd/system/wireguard-backup.service (rpi) +# +# Hub state -> Linode VPS. The peer set and the wg0 server key are the one +# thing on the Pi that neither Flux nor a git repo can rebuild; a Pi disk loss +# would otherwise take remote access with it. +[Unit] +Description=WireGuard hub state (etc/wireguard + wgportal sqlite) -> Linode VPS +After=network-online.target docker.service +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/usr/local/sbin/wireguard-backup.sh +# A slow tunnel is not a reason to retry a small job forever. +TimeoutStartSec=10min +Nice=10 +# The tarball is an archive of private keys. +UMask=0077 diff --git a/infrastructure/wireguard/backup/wireguard-backup.sh b/infrastructure/wireguard/backup/wireguard-backup.sh new file mode 100644 index 0000000..a2092eb --- /dev/null +++ b/infrastructure/wireguard/backup/wireguard-backup.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# WireGuard hub-state backup — /etc/wireguard + the wgportal peer database, +# copied OFF the Pi to the Linode VPS over the wg-remote tunnel. +# +# Why this exists: the Pi is the WireGuard *hub*. Its /etc/wireguard carries the +# wg0 server key and every peer's public key/allowed-ips, and wgportal's sqlite +# is the peer database the UI renders. Losing the Pi's disk would take the whole +# remote-access path with it — including the tunnel you would need to fix it. +# +# Destination is 10.20.0.1 (the hub's VPN address), never the public IP, and +# never the Pi itself: a backup on the machine it protects is not a backup. +# Mirrors infrastructure/garage/backup/ in shape (same key, same host, same +# timer/oneshot style). Not managed by Flux — install it with the steps in +# ./README.md. +# +# Run as root (systemd does): /etc/wireguard is 0600 root:root and +# /opt/wgportal/data is 0700 root:root. +# +# Exit code is the truth: the unit is oneshot, so +# `systemctl status wireguard-backup.service` shows the last result. +set -euo pipefail + +KEY=/home/sirius/.ssh/linode_admin +REMOTE=root@10.20.0.1 +DEST=/root/pihost-backup +KEEP=14 +STAGE=/var/lib/pihost-backup +STAMP=${STAMP:-$(date -u +%Y%m%dT%H%M%SZ)} + +# Host key: root on the Pi has no known_hosts entry for the VPN peer and a +# rebuilt Pi would not have one either. accept-new pins it on first contact and +# still fails loudly if it later changes; the transport is already an +# authenticated WireGuard tunnel. +SSH="ssh -i $KEY -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=20" +log() { printf '%s %s\n' "$(date -u +%FT%TZ)" "$*"; } + +log "target check: $($SSH "$REMOTE" 'hostname; df -h / | tail -1')" +$SSH "$REMOTE" "install -d -m 0700 '$DEST' '$DEST/wireguard' '$DEST/manifests'" + +install -d -m 0700 "$STAGE" +work="$STAGE/$STAMP" +rm -rf "$work"; install -d -m 0700 "$work" +trap 'rm -rf "$work"' EXIT + +log "collecting /etc/wireguard" +# Whole directory including the wgportal-autogenerated wg0.conf, wg-remote.conf +# and their .bak history (the .bak files are how old peer sets survive a bad +# SaveConfig rewrite). +cp -a /etc/wireguard "$work/wireguard" + +if [ -f /opt/wgportal/data/sqlite.db ]; then + log "consistent copy of wgportal sqlite" + # A plain cp of a live sqlite file can capture a half-written page; the + # backup API takes a read transaction instead. python3 is on the Pi, there is + # no sqlite3 CLI. + python3 - "$work/wgportal-sqlite.db" <<'PY' +import sqlite3, sys +src = sqlite3.connect("/opt/wgportal/data/sqlite.db", timeout=30) +src.execute("PRAGMA busy_timeout=30000") +dst = sqlite3.connect(sys.argv[1]) +src.backup(dst) +dst.close() +src.close() +chk = sqlite3.connect(sys.argv[1]) +verdict = chk.execute("PRAGMA integrity_check").fetchone()[0] +peers = chk.execute("SELECT count(*) FROM peers").fetchone()[0] +chk.close() +print(" integrity_check=%s peers=%s" % (verdict, peers)) +if verdict != "ok": + sys.exit("FAIL: wgportal sqlite integrity_check returned %r" % verdict) +PY +else + log "WARN: /opt/wgportal/data/sqlite.db missing — backing up /etc/wireguard only" +fi + +log "manifest" +( cd "$work" && find . -type f -printf '%s %p\n' | sort -k2 | sed 's| \./| |' > MANIFEST.sizes + find . -type f ! -name MANIFEST.sha256 -print0 | sort -z | xargs -0 -r sha256sum > MANIFEST.sha256 ) +manifest_text=$(cat "$work/MANIFEST.sizes") + +tarfile="$STAGE/wireguard-$STAMP.tar.gz" +tar -C "$work" -czf "$tarfile" . +local_sha=$(sha256sum "$tarfile" | awk '{print $1}') +local_size=$(wc -c < "$tarfile") +log "shipping $local_size bytes sha256=$local_sha" + +$SSH "$REMOTE" "cat > '$DEST/wireguard/wireguard-$STAMP.tar.gz.part'" < "$tarfile" +remote_sha=$($SSH "$REMOTE" "sha256sum '$DEST/wireguard/wireguard-$STAMP.tar.gz.part' | awk '{print \$1}'") +if [ "$local_sha" != "${remote_sha:-none}" ]; then + echo "FAIL: sha256 mismatch (local=$local_sha remote=${remote_sha:-none})" + $SSH "$REMOTE" "rm -f '$DEST/wireguard/wireguard-$STAMP.tar.gz.part'" + exit 1 +fi +$SSH "$REMOTE" "mv '$DEST/wireguard/wireguard-$STAMP.tar.gz.part' '$DEST/wireguard/wireguard-$STAMP.tar.gz' && \ + chmod 600 '$DEST/wireguard/wireguard-$STAMP.tar.gz'" + +# Remote manifest: sizes + checksums, the same evidence habit as the cluster +# backup job (/root/cluster-backup/manifests/.txt). +{ + printf 'stamp %s\nhost %s\n' "$STAMP" "$(hostname -s)" + printf -- '--- tarball\n%s %s bytes wireguard-%s.tar.gz\n' "$local_sha" "$local_size" "$STAMP" + printf -- '--- contents\n%s\n' "$manifest_text" +} | $SSH "$REMOTE" "cat > '$DEST/manifests/$STAMP.txt'" + +log "retention: last $KEEP tarballs" +$SSH "$REMOTE" "cd '$DEST/wireguard' && ls -1t *.tar.gz 2>/dev/null | tail -n +$((KEEP + 1)) | xargs -r rm -f" +$SSH "$REMOTE" "cd '$DEST/manifests' && ls -1t *.txt 2>/dev/null | tail -n +$((KEEP + 1)) | xargs -r rm -f" +$SSH "$REMOTE" "ls -l '$DEST/wireguard/wireguard-$STAMP.tar.gz'; df -h '$DEST' | tail -1" + +log "RESULT=success stamp=$STAMP" diff --git a/infrastructure/wireguard/backup/wireguard-backup.timer b/infrastructure/wireguard/backup/wireguard-backup.timer new file mode 100644 index 0000000..c67f423 --- /dev/null +++ b/infrastructure/wireguard/backup/wireguard-backup.timer @@ -0,0 +1,13 @@ +# /etc/systemd/system/wireguard-backup.timer (rpi) +[Unit] +Description=Nightly WireGuard hub-state backup + +[Timer] +# 04:13 local time, jittered so it does not race the 03:36 garage-data run. +OnCalendar=*-*-* 04:13:00 +RandomizedDelaySec=600 +Persistent=true +Unit=wireguard-backup.service + +[Install] +WantedBy=timers.target diff --git a/monitoring/controllers/home/grafana-backup.yaml b/monitoring/controllers/home/grafana-backup.yaml new file mode 100644 index 0000000..2da83fb --- /dev/null +++ b/monitoring/controllers/home/grafana-backup.yaml @@ -0,0 +1,178 @@ +--- +# Nightly backup of Grafana's sqlite state (dashboards, alert rules, users, +# annotations) to the Linode VPS over the WireGuard mesh. +# +# Why a Job in this namespace instead of the `forgejo/cluster-backup` exec +# path: the Grafana image is `-distroless` — there is no shell, no `cp`, no +# `tar`, so `kubectl exec` cannot produce a dump. The PVC is on siriussec +# (`local-path`) and RWO still allows a second pod on the same node, so the +# backup pod mounts the volume read-write and takes a *consistent* copy with +# the sqlite backup API (a plain `cp` of a live database can capture a torn +# page or a half-applied transaction). +# +# Layout on the Linode (same tree/retention style as the cluster-backup job): +# /root/cluster-backup/grafana/grafana-.db +# /root/cluster-backup/manifests/.txt (appended by that job's runs) +apiVersion: v1 +kind: ConfigMap +metadata: + name: grafana-backup-scripts + namespace: monitoring + labels: + app: grafana-backup +data: + backup.sh: | + #!/bin/sh + # Consistent sqlite snapshot -> Linode. Streamed: nothing is staged on the + # T480's root filesystem, the only local file is a ~3 MB copy in /tmp. + set -eu + + 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:-root@10.10.0.5} + BACKUP_DIR=${BACKUP_DIR:-/root/cluster-backup} + DB_KEEP=${DB_KEEP:-14} + MIN_FREE_GB=${MIN_FREE_GB:-8} + STAMP=${STAMP:-$(date -u +%Y%m%dT%H%M%SZ)} + OUT="$BACKUP_DIR/grafana/grafana-$STAMP.db" + + 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/grafana' '$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 + + echo "== sqlite snapshot of /grafana-data/grafana.db" + # The backup API takes a read transaction, so the copy is a consistent + # point-in-time image even while Grafana keeps writing. + python3 - <<'PY' + import sqlite3, sys + src = sqlite3.connect("/grafana-data/grafana.db", timeout=60) + src.execute("PRAGMA busy_timeout=60000") + dst = sqlite3.connect("/tmp/grafana.db") + src.backup(dst) + dst.close() + src.close() + check = sqlite3.connect("/tmp/grafana.db") + verdict = check.execute("PRAGMA integrity_check").fetchone()[0] + rows = {t: check.execute("SELECT count(*) FROM %s" % t).fetchone()[0] + for t in ("dashboard", "dashboard_version", "user", "alert_rule")} + check.close() + print(" integrity_check=%s dashboard=%s versions=%s user=%s alert_rule=%s" + % (verdict, rows["dashboard"], rows["dashboard_version"], + rows["user"], rows["alert_rule"])) + if verdict != "ok": + sys.exit("FAIL: sqlite integrity_check returned %r" % verdict) + PY + + local_sha=$(sha256sum /tmp/grafana.db | awk '{print $1}') + local_size=$(wc -c < /tmp/grafana.db) + echo "== shipping $local_size bytes sha256=$local_sha -> $OUT" + ssh_r "cat > '$OUT.part'" < /tmp/grafana.db + remote_sha=$(ssh_r "sha256sum '$OUT.part' | awk '{print \$1}'") + if [ "$local_sha" != "$remote_sha" ]; then + echo "FAIL: sha256 mismatch for $OUT (local=$local_sha remote=${remote_sha:-none})" + ssh_r "rm -f '$OUT.part'" + exit 1 + fi + ssh_r "mv '$OUT.part' '$OUT'" + rm -f /tmp/grafana.db + + echo "== manifest" + ssh_r "cd '$BACKUP_DIR' && { echo 'stamp $STAMP'; echo \"host \$(hostname -s)\"; \ + echo '--- grafana'; ls -l 'grafana/grafana-$STAMP.db'; \ + sha256sum 'grafana/grafana-$STAMP.db'; } >> manifests/$STAMP.txt && \ + tail -5 manifests/$STAMP.txt" + + echo "== retention: last $DB_KEEP grafana snapshots" + ssh_r "cd '$BACKUP_DIR/grafana' && ls -1t *.db 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: grafana-backup + namespace: monitoring + labels: + app: grafana-backup +spec: + # 23 minutes after the forgejo/cluster-backup job starts (02:37 UTC) so the + # two do not compete for WireGuard bandwidth or the Linode's disk. + schedule: "0 3 * * *" + timeZone: "Etc/UTC" + concurrencyPolicy: Forbid + startingDeadlineSeconds: 1800 + successfulJobsHistoryLimit: 3 + failedJobsHistoryLimit: 3 + jobTemplate: + spec: + activeDeadlineSeconds: 900 + backoffLimit: 1 + template: + metadata: + labels: + app: grafana-backup + spec: + restartPolicy: Never + # The grafana PVC is local-path on siriussec; RWO still allows a + # second pod on the same node. + nodeSelector: + kubernetes.io/hostname: siriussec + containers: + - name: backup + # python3 alpine: the sqlite backup API is the only consistent + # way to copy a live database without a shell inside Grafana. + image: python:3.12-alpine + imagePullPolicy: IfNotPresent + command: ["/bin/sh", "/scripts/backup.sh"] + env: + - name: BACKUP_HOST + value: root@10.10.0.5 + - name: BACKUP_DIR + value: /root/cluster-backup + - name: DB_KEEP + value: "14" + volumeMounts: + - name: grafana-data + mountPath: /grafana-data + - name: keys + mountPath: /keys + readOnly: true + - name: scripts + mountPath: /scripts + readOnly: true + resources: + requests: + cpu: 50m + memory: 64Mi + limits: + ephemeral-storage: 256Mi + memory: 256Mi + volumes: + - name: grafana-data + persistentVolumeClaim: + claimName: kube-prometheus-stack-grafana + - name: keys + secret: + # Copy of forgejo/cluster-backup-ssh, created out of band + # (never in git) — see docs/cluster-overview.md §8.1. + secretName: cluster-backup-ssh + defaultMode: 0400 + - name: scripts + configMap: + name: grafana-backup-scripts + defaultMode: 0755 diff --git a/monitoring/controllers/home/kustomization.yaml b/monitoring/controllers/home/kustomization.yaml index bb12166..0d2b035 100644 --- a/monitoring/controllers/home/kustomization.yaml +++ b/monitoring/controllers/home/kustomization.yaml @@ -9,6 +9,8 @@ resources: - gateway-probe.yaml - garage.yaml - prune-alerts.yaml + # Nightly consistent sqlite snapshot of Grafana's dashboards/alerts/users. + - grafana-backup.yaml - dashboards configMapGenerator: - name: kube-prometheus-stack-values