homek8s/monitoring/controllers/home/grafana-backup.yaml
devops 0acc089dc3 feat(backup): run the three nightly backups from a pinned image with an egress allow list
monitoring/grafana-backup, forgejo/cluster-backup and sirius-growth/leadgen-backup
all ran `apk add --no-cache rsync openssh-client` at container start. Every night
that dialled dl-cdn.alpinelinux.org (Fastly anycast 151.101.x.132:443), which is
what `egress-new-dst` kept reporting, and made the backups depend on the public
internet at 03:00 UTC.

- image: forgejo.siriusdevops.com/sirius/backup-tools, built in CI from
  python:3.12-alpine (pinned by digest) + rsync + openssh-client + bash +
  kubectl v1.36.4 (release sha256 verified at build). Pinned by digest in all
  three CronJobs, no apk in any backup path.
- egress: CiliumNetworkPolicy per backup pod — cluster DNS and 10.10.0.5:22 for
  all three, plus kube-apiserver 6443/443 for cluster-backup only, with an
  explicit deny for `world` (Cilium unions namespace policies, so the allow list
  alone would not restrict a pod inside `forgejo`/`sirius-growth`).
- monitoring gains the registry pull secret it never needed before; the job now
  keeps imagePullSecrets: forgejo-pull (SOPS-encrypted in git).

Schedules, retention, destination paths, entrypoints and RBAC are unchanged.
2026-12-04 00:20:34 -05:00

185 lines
7.4 KiB
YAML

---
# 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-<stamp>.db
# /root/cluster-backup/manifests/<stamp>.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
# No package install here on purpose: rsync/openssh-client/python3 are
# baked into the pinned image (images/backup/Dockerfile) and this pod's
# egress policy admits DNS + 10.10.0.5:22 only, so a runtime fetch would
# fail rather than silently dial the Alpine CDN (card t_9d0428d8).
BACKUP_HOST=${BACKUP_HOST:[email protected]}
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
# Pulled from the in-cluster Forgejo registry (which requires auth);
# monitoring had no registry pull secret before this job needed one.
imagePullSecrets:
- name: forgejo-pull
# 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.12-alpine + rsync + openssh-client, baked at build time
# and pinned by digest (images/backup/Dockerfile, CI workflow
# .forgejo/workflows/backup-image.yml). The sqlite backup API is
# the only consistent way to copy a live database without a shell
# inside Grafana. Nothing is installed at run time.
image: forgejo.siriusdevops.com/sirius/backup-tools@sha256:cc8dc1645111b3a80b7c4d5168f6bce3002cae7417b3725683c057976f6e379a
imagePullPolicy: IfNotPresent
command: ["/bin/sh", "/scripts/backup.sh"]
env:
- name: BACKUP_HOST
value: [email protected]
- 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