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 base/api/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ resources:
- rbac/role-binding.yaml
- rbac/role.yaml
- network-policy-chat-video-faststart.yaml
- plugin-databases-secret.yaml
10 changes: 10 additions & 0 deletions base/api/plugin-databases-secret.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# The plugin databases' passwords, one key per database. The api writes them;
# this manifest only makes sure the Secret exists, so it never lists any data:
# kubectl apply removes only the fields it applied before, and it never
# applied the api's keys, so an update leaves them in place.
apiVersion: v1
kind: Secret
metadata:
name: plugin-databases
namespace: 5stack
type: Opaque
12 changes: 12 additions & 0 deletions base/api/rbac/role.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,18 @@ rules:
verbs:
- get
- list
# Only the plugin databases' passwords: never create, which could mint
# a service account token.
- apiGroups:
- ''
resources:
- secrets
resourceNames:
- plugin-databases
verbs:
- get
- patch
- update
- apiGroups:
- ''
resources:
Expand Down
1 change: 1 addition & 0 deletions base/backups/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@ kind: Kustomization

resources:
- postgres-backup-cronjob.yaml
- plugin-databases-backup-cronjob.yaml


259 changes: 259 additions & 0 deletions base/backups/plugin-databases-backup-cronjob.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
apiVersion: batch/v1
kind: CronJob
metadata:
name: plugin-databases-backup
namespace: 5stack
spec:
schedule: "30 3 * * *"
# Today's dump is told apart by its UTC date, so run on UTC too.
timeZone: Etc/UTC
# A night's run never overlaps the next, and a retry skips every database
# that already has today's dump, so it can't push an older one out.
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 1
failedJobsHistoryLimit: 1
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 7200
template:
spec:
restartPolicy: Never
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: 5stack-timescaledb
operator: In
values:
- "true"
containers:
- name: backup
image: postgres:18-alpine
command:
- /bin/sh
- -c
- |
set -euo pipefail

apk add --no-cache zip curl ca-certificates bash aws-cli

TS=$(date -u +"%Y%m%d%H%M%S")
DAY=$(printf '%s' "$TS" | cut -c1-8)

export PGPASSWORD="$POSTGRES_PASSWORD"

if ! PLUGIN_DATABASES=$(psql -h "$POSTGRES_HOST" -p "$POSTGRES_PORT" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -At \
-c "SELECT datname FROM pg_database WHERE datname ~ '^plugin_[a-z0-9_]+\$' AND datallowconn ORDER BY datname"); then
echo "ERROR: could not list the plugin databases, so none of them were backed up"
exit 1
fi

if [ -z "$PLUGIN_DATABASES" ]; then
echo "No plugin databases to back up"
fi

ENDPOINT="${S3_ENDPOINT:-rustfs}"
REMOTE=false
HOST=$(printf '%s' "$ENDPOINT" | tr '[:upper:]' '[:lower:]')
HOST="${HOST#*://}"
HOST="${HOST%%[/:]*}"

# Both names mean the in-cluster store (see the minio alias
# Service in base/rustfs/service.yaml), and so does
# DEMOS_DOMAIN, whose route passes only /5stack on to it.
# Anything else is a real remote bucket reached over https.
if [ "$ENDPOINT" = "rustfs" ] || [ "$ENDPOINT" = "minio" ]; then
ENDPOINT="http://$ENDPOINT:9000"
elif [ -n "${DEMOS_DOMAIN:-}" ] && [ "$HOST" = "$(printf '%s' "$DEMOS_DOMAIN" | tr '[:upper:]' '[:lower:]')" ]; then
ENDPOINT="http://rustfs:9000"
else
ENDPOINT="https://$S3_ENDPOINT"
REMOTE=true
fi

export AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY"
export AWS_SECRET_ACCESS_KEY="$S3_SECRET"
export AWS_DEFAULT_REGION="${S3_REGION:-us-east-1}"

S3_DB_BACKUP_BUCKET="${S3_DB_BACKUP_BUCKET:-5stack-db-backups}"

# Remote bucket names are global, so only upload into a bucket
# owned by the account these keys belong to. On AWS the owner
# check takes the 12-digit account id from STS (list-buckets'
# Owner.ID is a canonical id S3 rejects), and only the s3api
# calls get it: aws s3 cp and rm reject --expected-bucket-owner.
set --
ACCOUNT_ID=""
if [ "$REMOTE" = true ]; then
ENDPOINT_HOST=$(printf '%s' "$S3_ENDPOINT" | tr '[:upper:]' '[:lower:]')
ENDPOINT_HOST="${ENDPOINT_HOST#*://}"
ENDPOINT_HOST="${ENDPOINT_HOST%/}"
case "$ENDPOINT_HOST" in
*.amazonaws.com | *.amazonaws.com.cn)
if ! ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text); then
echo "ERROR: could not look up the AWS account these S3 keys belong to"
exit 1
fi
set -- --expected-bucket-owner "$ACCOUNT_ID"
;;
esac

if BUCKETS=$(aws s3api list-buckets --endpoint-url "$ENDPOINT" --query 'Buckets[].Name' --output text 2>/tmp/list-buckets.err); then
FOUND=false
for NAME in $BUCKETS; do
if [ "$NAME" = "$S3_DB_BACKUP_BUCKET" ]; then
FOUND=true
fi
done
if [ "$FOUND" = false ]; then
echo "ERROR: the backup bucket $S3_DB_BACKUP_BUCKET isn't in the account these S3 keys belong to, so the database dump was NOT uploaded. Create it in your account or set S3_DB_BACKUP_BUCKET"
exit 1
fi
elif grep -Eq 'AccessDenied|Unauthorized|\(40[13]\)' /tmp/list-buckets.err; then
if [ -z "$ACCOUNT_ID" ]; then
echo "Note: couldn't check that $S3_DB_BACKUP_BUCKET is owned by this account because these S3 keys can't list buckets"
fi
else
cat /tmp/list-buckets.err
echo "ERROR: S3 upload failed, could not list the buckets on $ENDPOINT"
exit 1
fi

if [ -n "$ACCOUNT_ID" ] && ! aws s3api head-bucket --bucket "$S3_DB_BACKUP_BUCKET" --endpoint-url "$ENDPOINT" "$@"; then
echo "ERROR: the backup bucket $S3_DB_BACKUP_BUCKET isn't owned by AWS account $ACCOUNT_ID that these S3 keys belong to, or the keys lack s3:ListBucket on it, so the database dump was NOT uploaded. Create it in your account, set S3_DB_BACKUP_BUCKET, or grant s3:ListBucket"
exit 1
fi
fi

FAILED=""
for DATABASE in $PLUGIN_DATABASES; do
PREFIX="plugin-databases/$DATABASE/"

if ! TODAY=$(aws s3api list-objects-v2 \
--bucket "$S3_DB_BACKUP_BUCKET" \
--prefix "${PREFIX}backup-$DAY" \
--query 'Contents[].Key' \
--output text \
--endpoint-url "$ENDPOINT" \
"$@"); then
echo "ERROR: could not check for today's dump of the plugin database $DATABASE"
FAILED="$FAILED $DATABASE"
continue
fi

if [ -n "$TODAY" ] && [ "$TODAY" != "None" ]; then
echo "The plugin database $DATABASE already has today's dump, skipped"
continue
fi

DUMP_FILE="/tmp/$DATABASE-$TS.dump"
ZIP_FILE="/tmp/$DATABASE-$TS.zip"

# Owners and grants stay in, so a restore hands the tables back to the
# plugin's role. A plugin holding a lock can't hang the night's run.
if ! pg_dump -h "$POSTGRES_HOST" -p "$POSTGRES_PORT" -U "$POSTGRES_USER" -d "$DATABASE" \
--lock-wait-timeout=300s -F c -Z 0 -f "$DUMP_FILE" \
|| [ ! -s "$DUMP_FILE" ]; then
echo "ERROR: could not dump the plugin database $DATABASE"
FAILED="$FAILED $DATABASE"
rm -f "$DUMP_FILE"
continue
fi

zip -j "$ZIP_FILE" "$DUMP_FILE"

echo "Uploading to $ENDPOINT : $S3_DB_BACKUP_BUCKET/${PREFIX}backup-$TS.zip"
if ! aws s3 cp "$ZIP_FILE" "s3://$S3_DB_BACKUP_BUCKET/${PREFIX}backup-$TS.zip" --endpoint-url "$ENDPOINT"; then
echo "ERROR: could not upload the plugin database $DATABASE"
FAILED="$FAILED $DATABASE"
rm -f "$DUMP_FILE" "$ZIP_FILE"
continue
fi
rm -f "$DUMP_FILE" "$ZIP_FILE"

KEYS=$(aws s3api list-objects-v2 \
--bucket "$S3_DB_BACKUP_BUCKET" \
--prefix "$PREFIX" \
--query 'reverse(sort_by(Contents, &LastModified))[].Key' \
--output text \
--endpoint-url "$ENDPOINT" \
"$@" || true)

DELETEABLE_KEYS=$(echo "$KEYS" | tr '\t' '\n' | grep -E '/backup-[0-9]+\.zip$' | awk 'NR>7' || true)

if [ -n "$DELETEABLE_KEYS" ]; then
echo "Pruning old dumps of $DATABASE, keeping latest 7"
echo "$DELETEABLE_KEYS" | while IFS= read -r KEY; do
echo "Deleting old backup: $KEY"
aws s3api delete-object --bucket "$S3_DB_BACKUP_BUCKET" --key "$KEY" --endpoint-url "$ENDPOINT" "$@" || true
done
fi
done

# A deleted database's folder: its last week stays restorable,
# then ages out. Trouble here never fails the night's dumps.
if CUTOFF=$(date -u -d "@$(( $(date -u +%s) - 7 * 86400 ))" +"%Y-%m-%dT%H:%M:%S"); then
FOLDERS=$(aws s3api list-objects-v2 \
--bucket "$S3_DB_BACKUP_BUCKET" \
--prefix plugin-databases/ \
--delimiter / \
--query 'CommonPrefixes[].Prefix' \
--output text \
--endpoint-url "$ENDPOINT" \
"$@" || echo "WARNING: could not list the plugin database folders" >&2)

for FOLDER in $(echo "$FOLDERS" | tr '\t' '\n' | grep -E '^plugin-databases/plugin_[a-z0-9_]+/$' || true); do
DATABASE=$(echo "$FOLDER" | cut -d/ -f2)
if printf '%s\n' "$PLUGIN_DATABASES" | grep -qx "$DATABASE"; then
continue
fi

LISTING=$(aws s3api list-objects-v2 \
--bucket "$S3_DB_BACKUP_BUCKET" \
--prefix "$FOLDER" \
--query 'Contents[].[Key,LastModified]' \
--output text \
--endpoint-url "$ENDPOINT" \
"$@" || true)
OLD_KEYS=$(printf '%s\n' "$LISTING" | awk -F '\t' -v cutoff="$CUTOFF" '$2 != "" && $2 < cutoff { print $1 }' || true)

if [ -n "$OLD_KEYS" ]; then
echo "The plugin database $DATABASE is gone, deleting its dumps older than 7 days"
echo "$OLD_KEYS" | while IFS= read -r KEY; do
echo "Deleting old backup: $KEY"
aws s3api delete-object --bucket "$S3_DB_BACKUP_BUCKET" --key "$KEY" --endpoint-url "$ENDPOINT" "$@" || true
done
fi
done
else
echo "WARNING: could not work out last week's date, so no deleted plugin database's dumps were aged out"
fi

if [ -n "$FAILED" ]; then
echo "ERROR: these plugin databases were NOT backed up:$FAILED"
exit 1
fi
envFrom:
- secretRef:
name: timescaledb-secrets
- secretRef:
name: s3-secrets
- configMapRef:
name: s3-config
env:
- name: DEMOS_DOMAIN
valueFrom:
configMapKeyRef:
name: api-config
key: DEMOS_DOMAIN
optional: true
- name: POSTGRES_HOST
value: timescaledb
- name: POSTGRES_PORT
value: "5432"
- name: POSTGRES_DB
value: hasura
- name: POSTGRES_USER
value: hasura
5 changes: 4 additions & 1 deletion base/backups/postgres-backup-cronjob.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,15 @@ spec:

KEYS=$(aws s3api list-objects-v2 \
--bucket "$S3_DB_BACKUP_BUCKET" \
--prefix backup- \
--query 'reverse(sort_by(Contents, &LastModified))[].Key' \
--output text \
--endpoint-url "$ENDPOINT" \
"$@" || true)

DELETEABLE_KEYS=$(echo "$KEYS" | tr '\t' '\n' | awk 'NR>7')
# Only this job's own top-level dumps: the plugin databases'
# sit under plugin-databases/ and keep their own 7.
DELETEABLE_KEYS=$(echo "$KEYS" | tr '\t' '\n' | grep -E '^backup-[0-9]+\.zip$' | awk 'NR>7' || true)

if [ -n "$DELETEABLE_KEYS" ]; then
echo "Pruning old backups, keeping latest 7"
Expand Down
1 change: 1 addition & 0 deletions base/kustomization.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ resources:
- hasura
- rustfs
- timescaledb
- plugin-db-pooler
- redis
- typesense
- web
Expand Down
Loading
Loading