Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ansible/roles/platform/defaults/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ platform_k8tz_warmup_pod_name: bootstrap-image-warmup-k8tz
platform_bootstrap_namespaces:
- home-automation
- media
- platform-system
- selfhosted

platform_bootstrap_releases:
Expand Down
6 changes: 6 additions & 0 deletions ansible/roles/platform/tasks/create_claims.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
- selfhosted/restic/manifests/restic-credentials-store.clustersecretstore
- home-automation/home-automation-backup/manifests/restic-credentials.externalsecret
- media/media-backup/manifests/restic-credentials.externalsecret
- platform-system/platform-system-backup/manifests/restic-credentials.externalsecret

- name: Wait for namespace recovery credentials
ansible.builtin.include_tasks: wait_items.yml
Expand All @@ -40,6 +41,11 @@
namespace: media
name: restic-credentials
condition_type: Ready
- api_version: external-secrets.io/v1
kind: ExternalSecret
namespace: platform-system
name: restic-credentials
condition_type: Ready

- name: Identify this Kubernetes installation
kubernetes.core.k8s_info:
Expand Down
1 change: 1 addition & 0 deletions ansible/roles/restic/defaults/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ restic_restore_excluded_apps:
- root
- media-backup
- home-automation-backup
- platform-system-backup
# Native SQL-and-uploads recovery is documented in the Restic runbook.
- sparkyfitness
restic_restore_excluded_pvcs:
Expand Down
2 changes: 1 addition & 1 deletion ansible/roles/restic/tasks/cold.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
- name: Require a concrete source and exact new destination
ansible.builtin.assert:
that:
- restic_recovery_namespace | default('') in ['media', 'selfhosted', 'home-automation']
- restic_recovery_namespace | default('') in ['home-automation', 'media', 'platform-system', 'selfhosted']
- restic_recovery_claim | default('') is match('^[a-z0-9]([-a-z0-9]*[a-z0-9])?$')
- restic_recovery_uid | default('') is match('^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$')
- restic_restore_snapshot is match('^[0-9a-f]{64}$')
Expand Down
49 changes: 46 additions & 3 deletions apps/platform-system/grafana/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,22 @@ controllers:
strategy: Recreate
annotations:
reloader.stakater.com/auto: "true"
initContainers:
copy-data:
image:
repository: busybox
tag: 1.37.0
command:
- /bin/sh
- /migration/copy.sh
- dpool/pvc-43153b5f-95e7-4574-812c-89d680efdf6a
- grafana.db
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
containers:
app:
image:
Expand Down Expand Up @@ -70,9 +86,36 @@ route:
persistence:
data:
type: persistentVolumeClaim
existingClaim: grafana
globalMounts:
- path: /var/lib/grafana
forceRename: grafana-appdata
accessMode: ReadWriteOnce
storageClass: zfs-appdata
size: 1Gi
advancedMounts:
main:
app:
- path: /var/lib/grafana
subPath: data
copy-data:
- path: /destination
original:
type: custom
volumeSpec:
persistentVolumeClaim:
claimName: grafana
readOnly: true
advancedMounts:
main:
copy-data:
- path: /original
readOnly: true
migration:
type: configMap
name: telemetry-storage-migration
advancedMounts:
main:
copy-data:
- path: /migration
readOnly: true
datasource:
type: configMap
name: grafana-datasource
Expand Down
7 changes: 7 additions & 0 deletions apps/platform-system/platform-system-backup/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
chart:
repo: oci://ghcr.io/bjw-s-labs/helm/app-template
path: "."
version: 5.3.0
sync:
wave: "0"
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
---
apiVersion: v1
kind: ConfigMap
metadata:
name: platform-system-backup
namespace: platform-system
data:
prepare.py: |-
import json
import os
import re
import shutil
import sqlite3
import subprocess
import time
from contextlib import closing
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import urlopen
from uuid import UUID

RUN = str(UUID(os.environ["POD_UID"]))

def stage(claim):
fields = [line.split() for line in Path("/proc/self/mountinfo").read_text().splitlines()]
mounts = [f for f in fields if f[4] == str(claim)]
if len(mounts) != 1:
raise ValueError(f"Missing or ambiguous mount: {claim}")
mount = mounts[0]
i = mount.index("-")
if (mount[3] != "/" or "rw" not in mount[5].split(",") or
mount[i + 1] != "zfs" or not re.fullmatch(r"dpool/k8s/pvc-[0-9a-f-]{36}", mount[i + 2])):
raise ValueError(f"Unexpected appdata mount: {claim}")
if not (claim / "data").is_dir() or (claim / "data").is_symlink():
raise ValueError(f"Application data not ready: {claim}")
staging = claim / ".restic-backup"
staging.mkdir(mode=0o700, exist_ok=True)
if staging.is_symlink() or staging.stat().st_uid != 0:
raise ValueError(f"Unsafe staging directory: {staging}")
# Jobs have a six-hour deadline. Keep a full day before reclaiming another run.
for entry in staging.iterdir():
if (re.fullmatch(r"[0-9a-f-]{36}", entry.name) and not entry.is_symlink()
and entry.is_dir() and (entry.name == RUN or entry.stat().st_mtime < time.time() - 86400)):
shutil.rmtree(entry)
target = staging / RUN / "data"
target.mkdir(parents=True)
return target

def copy_metadata(source, dest):
info = source.stat()
os.chown(dest, info.st_uid, info.st_gid)
shutil.copystat(source, dest)

def backup_grafana(claim):
source = claim / "data"
db = source / "grafana.db"
if not db.is_file() or db.is_symlink():
raise ValueError("Grafana database missing")
target = stage(claim)
copy = target / "grafana.db"
with closing(sqlite3.connect(f"{db.as_uri()}?mode=ro", uri=True)) as live:
with closing(sqlite3.connect(copy)) as saved:
live.backup(saved, pages=256)
if saved.execute("PRAGMA quick_check").fetchall() != [("ok",)]:
raise ValueError("Grafana SQLite integrity check failed")
copy_metadata(db, copy)
for item in source.iterdir():
if item.name not in {"grafana.db", "grafana.db-shm", "grafana.db-wal", "grafana.db-journal"}:
subprocess.run(["cp", "-a", "--", item, target], check=True)
copy_metadata(source, target)

def snapshot_api(action, **fields):
fields["authKey"] = Path("/run/vm-snapshot/key").read_text().strip()
endpoint = "http://victoria-metrics.platform-system.svc:8428/snapshot/" + action
with urlopen(endpoint, urlencode(fields).encode(), timeout=300) as reply:
result = json.load(reply)
if result["status"] != "ok":
raise ValueError(f"VictoriaMetrics snapshot {action} failed")
return result

def link_parts(source, target, data):
# VM's snapshot contains links into its per-partition immutable snapshot trees.
source = source.resolve(strict=True)
if not source.is_relative_to(data):
raise ValueError(f"Snapshot path outside metrics volume: {source}")
if source.is_file():
os.link(source, target)
elif source.is_dir():
target.mkdir(exist_ok=True)
for entry in source.iterdir():
link_parts(entry, target / entry.name, data)
copy_metadata(source, target)
else:
raise ValueError(f"Unexpected entry in metrics snapshot: {source}")

def backup_metrics(claim):
data = claim / "data"
if not (data / "metadata").is_dir():
raise ValueError("VictoriaMetrics storage missing")
target = stage(claim)
name = snapshot_api("create")["snapshot"]
if not re.fullmatch(r"[a-zA-Z0-9_-]+", name):
raise ValueError("Unexpected snapshot name")
try:
snapshot = data / "snapshots" / name
if not (snapshot / "metadata").is_dir() or not (snapshot / "data").is_dir():
raise ValueError("API snapshot missing on mounted volume")
link_parts(snapshot, target, data)
# During the storage migration the app init container checks this record.
marker = data / ".home-ops-copied-from"
if marker.is_file():
subprocess.run(["cp", "-a", "--", marker, target], check=True)
copy_metadata(data, target)
finally:
snapshot_api("delete", snapshot=name)

backup_grafana(Path("/claims/grafana"))
backup_metrics(Path("/claims/metrics"))
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: restic-credentials
namespace: platform-system
spec:
refreshInterval: 5m
secretStoreRef:
name: external-secrets-store
kind: ClusterSecretStore
target:
name: restic-credentials
creationPolicy: Owner
template:
mergePolicy: Merge
data:
VM_SNAPSHOT_KEY: "{{ printf \"victoria-metrics/snapshot/v1:%s\" .RESTIC_PASSWORD | sha256sum }}"
data:
- secretKey: RESTIC_PASSWORD
remoteRef:
key: restic_server_password
- secretKey: RESTIC_REPOSITORY_ID
remoteRef:
key: restic_repository_id
130 changes: 130 additions & 0 deletions apps/platform-system/platform-system-backup/values.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
---
defaultPodOptions:
automountServiceAccountToken: false
securityContext:
runAsUser: 0
runAsGroup: 0
seccompProfile:
type: RuntimeDefault

controllers:
backup:
type: cronjob
cronjob:
schedule: "35 3 * * *"
timeZone: Europe/Warsaw
concurrencyPolicy: Forbid
activeDeadlineSeconds: 21600
backoffLimit: 1
initContainers:
prepare:
image:
repository: python
tag: 3.14-alpine@sha256:5862d971d1f0ae26b258cefa4e893556b1d3aba81bd2ff30888704ad378bab67
command:
- python
- /scripts/prepare.py
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
add:
- CHOWN
- DAC_OVERRIDE
- FOWNER
env:
POD_UID: &podUid
valueFrom:
fieldRef:
fieldPath: metadata.uid
containers:
app:
image:
repository: restic/restic
tag: 0.20.0
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
add:
- DAC_READ_SEARCH
command:
- /bin/sh
- -ec
- |
case "$RESTIC_REPOSITORY_ID" in ""|*[!0-9a-f]*) exit 1 ;; esac
test "${#RESTIC_REPOSITORY_ID}" -eq 64
actual=$(restic --no-lock cat config | sed -n 's/^ *"id": *"\([0-9a-f]*\)"[,]*$/\1/p')
test "$actual" = "$RESTIC_REPOSITORY_ID"
root=/data/appdata/platform-system
for name in grafana-appdata victoria-metrics-appdata; do
awk -v path="$root/$name" -v stage="/.restic-backup/$POD_UID" '
$4 == stage && $5 == path && $6 ~ /(^|,)ro(,|$)/ {
for (i=7; i<NF; i++) if ($i == "-" && $(i+1) == "zfs" && $(i+2) ~ /^dpool\/k8s\/pvc-/) ok=1
} END {exit !ok}' /proc/self/mountinfo
done
test -s "$root/grafana-appdata/data/grafana.db"
test -d "$root/victoria-metrics-appdata/data/metadata"
test -d "$root/victoria-metrics-appdata/data/data"
exec restic --retry-lock 30m backup "$root" --host homelab --tag appdata
env:
POD_UID: *podUid
RESTIC_REPOSITORY: rest:http://restic.selfhosted.svc.cluster.local:8000/
RESTIC_REST_USERNAME: restic
RESTIC_REST_PASSWORD: &password
valueFrom:
secretKeyRef:
name: restic-credentials
key: RESTIC_PASSWORD
RESTIC_PASSWORD: *password
RESTIC_REPOSITORY_ID:
valueFrom:
secretKeyRef:
name: restic-credentials
key: RESTIC_REPOSITORY_ID

persistence:
grafana:
type: persistentVolumeClaim
existingClaim: grafana-appdata
advancedMounts:
backup:
prepare:
- path: /claims/grafana
app:
- path: /data/appdata/platform-system/grafana-appdata
subPathExpr: .restic-backup/$(POD_UID)
readOnly: true
metrics:
type: persistentVolumeClaim
existingClaim: victoria-metrics-appdata
advancedMounts:
backup:
prepare:
- path: /claims/metrics
app:
- path: /data/appdata/platform-system/victoria-metrics-appdata
subPathExpr: .restic-backup/$(POD_UID)
readOnly: true
scripts:
type: configMap
name: platform-system-backup
advancedMounts:
backup:
prepare:
- path: /scripts
readOnly: true
snapshot-key:
type: secret
name: restic-credentials
items:
- key: VM_SNAPSHOT_KEY
path: key
advancedMounts:
backup:
prepare:
- path: /run/vm-snapshot
readOnly: true
Loading