From 42000006b86378d88dbd8d80365bbe37b39f01dc Mon Sep 17 00:00:00 2001 From: Luke Policinski Date: Mon, 23 Nov 2026 11:15:08 -0500 Subject: [PATCH 1/5] feature: a PgBouncer pooler for plugin databases, 100 connections kept for the panel, a Secret for plugin passwords, and nightly plugin database backups --- base/api/kustomization.yaml | 1 + base/api/plugin-databases-secret.yaml | 10 ++ base/api/rbac/role.yaml | 12 ++ base/backups/postgres-backup-cronjob.yaml | 89 +++++++++++--- base/kustomization.yaml | 1 + base/plugin-db-pooler/configmap.yaml | 35 ++++++ base/plugin-db-pooler/deployment.yaml | 143 ++++++++++++++++++++++ base/plugin-db-pooler/kustomization.yaml | 7 ++ base/plugin-db-pooler/service.yaml | 15 +++ base/timescaledb/stateful-set.yaml | 5 + tests/scripts/postgres_backup_test.sh | 92 +++++++++++++- 11 files changed, 389 insertions(+), 21 deletions(-) create mode 100644 base/api/plugin-databases-secret.yaml create mode 100644 base/plugin-db-pooler/configmap.yaml create mode 100644 base/plugin-db-pooler/deployment.yaml create mode 100644 base/plugin-db-pooler/kustomization.yaml create mode 100644 base/plugin-db-pooler/service.yaml diff --git a/base/api/kustomization.yaml b/base/api/kustomization.yaml index b12b7433..556a5ebe 100644 --- a/base/api/kustomization.yaml +++ b/base/api/kustomization.yaml @@ -14,3 +14,4 @@ resources: - rbac/role-binding.yaml - rbac/role.yaml - network-policy-chat-video-faststart.yaml + - plugin-databases-secret.yaml diff --git a/base/api/plugin-databases-secret.yaml b/base/api/plugin-databases-secret.yaml new file mode 100644 index 00000000..ddb6bda2 --- /dev/null +++ b/base/api/plugin-databases-secret.yaml @@ -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 diff --git a/base/api/rbac/role.yaml b/base/api/rbac/role.yaml index 31bd8285..5f0e9ba2 100644 --- a/base/api/rbac/role.yaml +++ b/base/api/rbac/role.yaml @@ -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: diff --git a/base/backups/postgres-backup-cronjob.yaml b/base/backups/postgres-backup-cronjob.yaml index f6db7eaf..289faccb 100644 --- a/base/backups/postgres-backup-cronjob.yaml +++ b/base/backups/postgres-backup-cronjob.yaml @@ -129,22 +129,79 @@ spec: echo "Backup complete: $ZIP_FILE" - KEYS=$(aws s3api list-objects-v2 \ - --bucket "$S3_DB_BACKUP_BUCKET" \ - --query 'reverse(sort_by(Contents, &LastModified))[].Key' \ - --output text \ - --endpoint-url "$ENDPOINT" \ - "$@" || true) - - DELETEABLE_KEYS=$(echo "$KEYS" | tr '\t' '\n' | awk 'NR>7') - - if [ -n "$DELETEABLE_KEYS" ]; then - echo "Pruning old backups, 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 - echo "Pruning complete" + # Keeps the newest 7 keys under a prefix that match the + # pattern; plugin dumps live under plugin-databases/, so the + # main backups only ever count top-level backup-*.zip keys. + prune() { + PREFIX="$1" + PATTERN="$2" + shift 2 + 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 "$PATTERN" | awk 'NR>7' || true) + + if [ -n "$DELETEABLE_KEYS" ]; then + echo "Pruning old backups under ${PREFIX:-the bucket root}, 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 + echo "Pruning complete" + fi + } + + prune "backup-" '^backup-[0-9]+\.zip$' "$@" + + rm -f "$DUMP_FILE" "$ZIP_FILE" + + # Each plugin database is its own dump, in its own folder, + # with its owner and grants kept so a restore hands its + # tables back to the plugin's role. The main backup is + # already uploaded, so a plugin that fails only fails the + # job at the end. + FAILED_PLUGIN_DATABASES="" + 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 + + for PLUGIN_DATABASE in $PLUGIN_DATABASES; do + PLUGIN_DUMP="/tmp/$PLUGIN_DATABASE-$TS.dump" + PLUGIN_ZIP="/tmp/$PLUGIN_DATABASE-$TS.zip" + PLUGIN_KEY="plugin-databases/$PLUGIN_DATABASE/backup-$TS.zip" + + if ! pg_dump -h "$POSTGRES_HOST" -p "$POSTGRES_PORT" -U "$POSTGRES_USER" -d "$PLUGIN_DATABASE" -F c -Z 0 -f "$PLUGIN_DUMP" \ + || [ ! -s "$PLUGIN_DUMP" ]; then + echo "ERROR: could not dump the plugin database $PLUGIN_DATABASE" + FAILED_PLUGIN_DATABASES="$FAILED_PLUGIN_DATABASES $PLUGIN_DATABASE" + rm -f "$PLUGIN_DUMP" + continue + fi + + zip -j "$PLUGIN_ZIP" "$PLUGIN_DUMP" + + echo "Uploading the plugin database $PLUGIN_DATABASE to $S3_DB_BACKUP_BUCKET/$PLUGIN_KEY" + if ! aws s3 cp "$PLUGIN_ZIP" "s3://$S3_DB_BACKUP_BUCKET/$PLUGIN_KEY" --endpoint-url "$ENDPOINT"; then + echo "ERROR: could not upload the plugin database $PLUGIN_DATABASE" + FAILED_PLUGIN_DATABASES="$FAILED_PLUGIN_DATABASES $PLUGIN_DATABASE" + rm -f "$PLUGIN_DUMP" "$PLUGIN_ZIP" + continue + fi + + rm -f "$PLUGIN_DUMP" "$PLUGIN_ZIP" + prune "plugin-databases/$PLUGIN_DATABASE/" '/backup-[0-9]+\.zip$' "$@" + done + + if [ -n "$FAILED_PLUGIN_DATABASES" ]; then + echo "ERROR: the main database was backed up, but these plugin databases were NOT:$FAILED_PLUGIN_DATABASES" + exit 1 fi envFrom: - secretRef: diff --git a/base/kustomization.yaml b/base/kustomization.yaml index f8e93af7..24a0884b 100644 --- a/base/kustomization.yaml +++ b/base/kustomization.yaml @@ -9,6 +9,7 @@ resources: - hasura - rustfs - timescaledb + - plugin-db-pooler - redis - typesense - web diff --git a/base/plugin-db-pooler/configmap.yaml b/base/plugin-db-pooler/configmap.yaml new file mode 100644 index 00000000..19d57015 --- /dev/null +++ b/base/plugin-db-pooler/configmap.yaml @@ -0,0 +1,35 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: plugin-db-pooler + namespace: 5stack +data: + pgbouncer.ini: | + [databases] + * = host=timescaledb port=5432 + + [pgbouncer] + listen_addr = 0.0.0.0 + listen_port = 6432 + unix_socket_dir = + + ; Only plugin roles get in: the lookup returns nothing for any other name. + auth_type = scram-sha-256 + auth_file = /var/run/plugin-db-pooler/userlist.txt + auth_user = pgbouncer_auth + auth_dbname = hasura + auth_query = SELECT usename, passwd FROM pgbouncer.plugin_user_lookup($1) + + ; Many game servers share few real connections. Npgsql prepares on the + ; protocol level, which transaction pooling needs max_prepared_statements for. + pool_mode = transaction + max_prepared_statements = 200 + default_pool_size = 20 + max_db_connections = 100 + max_client_conn = 2000 + track_extra_parameters = IntervalStyle, search_path + ignore_startup_parameters = extra_float_digits, options + + server_tls_sslmode = prefer + log_connections = 0 + log_disconnections = 0 diff --git a/base/plugin-db-pooler/deployment.yaml b/base/plugin-db-pooler/deployment.yaml new file mode 100644 index 00000000..101778b9 --- /dev/null +++ b/base/plugin-db-pooler/deployment.yaml @@ -0,0 +1,143 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: plugin-db-pooler + namespace: 5stack + labels: + app: plugin-db-pooler +spec: + # One pod at a time: each start gives pgbouncer_auth a new password, which + # an older pod still running would no longer have. + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app: plugin-db-pooler + template: + metadata: + labels: + app: plugin-db-pooler + spec: + dnsConfig: + options: + - name: ndots + value: "1" + affinity: + nodeAffinity: + requiredDuringSchedulingIgnoredDuringExecution: + nodeSelectorTerms: + - matchExpressions: + - key: 5stack-timescaledb + operator: In + values: + - 'true' + securityContext: + fsGroup: 996 + # As the superuser, gives pgbouncer_auth a fresh password that only this + # pod knows, so it is stored nowhere, and a lookup that returns the SCRAM + # verifier of plugin roles only. The api's lockdown closes the panel's + # database to PUBLIC and never revisits it, so CONNECT is granted here. + initContainers: + - name: auth + image: timescale/timescaledb:2.32.0-pg18@sha256:83952d54cfc74d9aebe4aba6ecf2af829c2bcf1f30058dded4c18ab3720a247a + command: + - sh + - -c + - | + set -e + umask 027 + AUTH_PASSWORD="$(head -c 48 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c 40)" + export PGPASSWORD="$POSTGRES_PASSWORD" + psql -h timescaledb -U hasura -d hasura -v ON_ERROR_STOP=1 -v auth_password="$AUTH_PASSWORD" <<'SQL' + SET pg_stat_statements.track_utility = off; + SELECT 'CREATE ROLE pgbouncer_auth' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'pgbouncer_auth')\gexec + ALTER ROLE pgbouncer_auth WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION CONNECTION LIMIT 10 PASSWORD :'auth_password'; + ALTER ROLE pgbouncer_auth SET fivestack.app_key = ''; + GRANT CONNECT ON DATABASE hasura TO pgbouncer_auth; + CREATE SCHEMA IF NOT EXISTS pgbouncer; + REVOKE ALL ON SCHEMA pgbouncer FROM PUBLIC; + GRANT USAGE ON SCHEMA pgbouncer TO pgbouncer_auth; + CREATE OR REPLACE FUNCTION pgbouncer.plugin_user_lookup(p_usename text, OUT usename text, OUT passwd text) + RETURNS record + LANGUAGE sql + SECURITY DEFINER + SET search_path = pg_catalog + AS $lookup$ + SELECT rolname::text, rolpassword::text + FROM pg_catalog.pg_authid + WHERE rolname = p_usename + AND rolname ~ '^plugin_[a-z0-9_]+$' + AND rolcanlogin + AND NOT rolsuper + AND (rolvaliduntil IS NULL OR rolvaliduntil > now()) + $lookup$; + REVOKE ALL ON FUNCTION pgbouncer.plugin_user_lookup(text) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION pgbouncer.plugin_user_lookup(text) TO pgbouncer_auth; + SQL + printf '"pgbouncer_auth" "%s"\n' "$AUTH_PASSWORD" > /var/run/plugin-db-pooler/userlist.txt + chgrp 996 /var/run/plugin-db-pooler/userlist.txt + env: + - name: POSTGRES_PASSWORD + valueFrom: + secretKeyRef: + name: timescaledb-secrets + key: POSTGRES_PASSWORD + volumeMounts: + - name: auth + mountPath: /var/run/plugin-db-pooler + containers: + - name: pgbouncer + image: ghcr.io/cloudnative-pg/pgbouncer:1.26.1@sha256:6c91fd7383b8b098bc0c3b71dba4e98bd568c0d301b9fc66027fbc23259c6a7d + args: + - /etc/pgbouncer/pgbouncer.ini + securityContext: + runAsNonRoot: true + runAsUser: 998 + runAsGroup: 996 + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + resources: + requests: + memory: "32Mi" + cpu: "50m" + limits: + memory: "256Mi" + ports: + - containerPort: 6432 + protocol: TCP + startupProbe: + tcpSocket: + port: 6432 + periodSeconds: 5 + failureThreshold: 12 + readinessProbe: + tcpSocket: + port: 6432 + periodSeconds: 5 + failureThreshold: 3 + livenessProbe: + tcpSocket: + port: 6432 + initialDelaySeconds: 15 + periodSeconds: 15 + failureThreshold: 3 + volumeMounts: + - name: config + mountPath: /etc/pgbouncer/pgbouncer.ini + subPath: pgbouncer.ini + readOnly: true + - name: auth + mountPath: /var/run/plugin-db-pooler + readOnly: true + volumes: + - name: config + configMap: + name: plugin-db-pooler + - name: auth + emptyDir: + medium: Memory + sizeLimit: 1Mi diff --git a/base/plugin-db-pooler/kustomization.yaml b/base/plugin-db-pooler/kustomization.yaml new file mode 100644 index 00000000..25a7c2cb --- /dev/null +++ b/base/plugin-db-pooler/kustomization.yaml @@ -0,0 +1,7 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization + +resources: + - configmap.yaml + - deployment.yaml + - service.yaml diff --git a/base/plugin-db-pooler/service.yaml b/base/plugin-db-pooler/service.yaml new file mode 100644 index 00000000..b357c097 --- /dev/null +++ b/base/plugin-db-pooler/service.yaml @@ -0,0 +1,15 @@ +# Game servers use host networking without cluster DNS, so the api hands them +# this Service's cluster IP for their plugin databases. +apiVersion: v1 +kind: Service +metadata: + name: plugin-db-pooler + namespace: 5stack +spec: + ports: + - name: postgres + port: 5432 + protocol: TCP + targetPort: 6432 + selector: + app: plugin-db-pooler diff --git a/base/timescaledb/stateful-set.yaml b/base/timescaledb/stateful-set.yaml index 9e298c1d..56ae25db 100644 --- a/base/timescaledb/stateful-set.yaml +++ b/base/timescaledb/stateful-set.yaml @@ -43,6 +43,11 @@ spec: - postgres - '-c' - max_connections=500 + # The panel's api and Hasura log in as the hasura superuser, so + # 100 of the 500 are theirs alone: the plugin databases' + # roles can never take the connections the panel needs. + - '-c' + - superuser_reserved_connections=100 - '-c' - shared_preload_libraries=pg_stat_statements,timescaledb - '-c' diff --git a/tests/scripts/postgres_backup_test.sh b/tests/scripts/postgres_backup_test.sh index 572cbade..4301a007 100644 --- a/tests/scripts/postgres_backup_test.sh +++ b/tests/scripts/postgres_backup_test.sh @@ -27,12 +27,27 @@ setup_stubs() { EOF cat >"$WORK_DIR/bin/pg_dump" <<'EOF' #!/bin/bash +echo "$*" >>"$WORK_DIR/pg-dump-calls" +database="" +file="" while [ $# -gt 0 ]; do - if [ "$1" = "-f" ]; then - echo dump >"$2" - fi + case "$1" in + -d) database="$2" ;; + -f) file="$2" ;; + esac shift done +if [ -f "$WORK_DIR/fail-dump-$database" ]; then + exit 1 +fi +echo "dump of $database" >"$file" +EOF + cat >"$WORK_DIR/bin/psql" <<'EOF' +#!/bin/bash +if [ -f "$WORK_DIR/fail-psql" ]; then + exit 2 +fi +cat "$WORK_DIR/plugin-databases" 2>/dev/null || true EOF cat >"$WORK_DIR/bin/zip" <<'EOF' #!/bin/bash @@ -67,10 +82,17 @@ case "$1 $2" in cat "$WORK_DIR/buckets" ;; "sts get-caller-identity") echo "$FAKE_ACCOUNT_ID" ;; - "s3api list-objects-v2") if [ -f "$WORK_DIR/objects" ]; then cat "$WORK_DIR/objects"; fi ;; + "s3api list-objects-v2") + prefix="$(printf '%s' " $* " | sed -n 's/.* --prefix \([^ ]*\) .*/\1/p')" + listing="$WORK_DIR/objects" + if [ -n "$prefix" ] && [ "$prefix" != "backup-" ]; then + listing="$WORK_DIR/objects-$(printf '%s' "$prefix" | tr '/' '_')" + fi + if [ -f "$listing" ]; then cat "$listing"; fi + ;; esac EOF - chmod +x "$WORK_DIR/bin/apk" "$WORK_DIR/bin/pg_dump" "$WORK_DIR/bin/zip" "$WORK_DIR/bin/aws" + chmod +x "$WORK_DIR/bin/apk" "$WORK_DIR/bin/pg_dump" "$WORK_DIR/bin/psql" "$WORK_DIR/bin/zip" "$WORK_DIR/bin/aws" } buckets() { @@ -243,4 +265,64 @@ test_a_remote_bucket_beside_a_demos_domain_stays_remote() { assert_contains "$(aws_calls)" "list-buckets" } +plugin_databases() { + printf '%s\n' "$@" >"$WORK_DIR/plugin-databases" +} + +test_each_plugin_database_is_its_own_dump_in_its_own_folder_after_the_main_one() { + plugin_databases plugin_arenas plugin_ranks + run_backup "" + assert_succeeded + uploads="$(calls_to "s3 cp ")" + assert_contains "$(echo "$uploads" | sed -n 1p)" "s3://5stack-db-backups/backup-" + assert_contains "$(echo "$uploads" | sed -n 2p)" "s3://5stack-db-backups/plugin-databases/plugin_arenas/backup-" + assert_contains "$(echo "$uploads" | sed -n 3p)" "s3://5stack-db-backups/plugin-databases/plugin_ranks/backup-" + assert_contains "$(cat "$WORK_DIR/pg-dump-calls")" "-d plugin_arenas -F c -Z 0 -f" + assert_not_contains "$(grep -e "-d plugin_arenas" "$WORK_DIR/pg-dump-calls")" "--no-owner" +} + +test_the_main_backups_prune_only_counts_their_own_top_level_keys() { + plugin_databases plugin_arenas + printf 'plugin-databases/plugin_arenas/backup-9.zip\tbackup-8.zip\tbackup-7.zip\tbackup-6.zip\tbackup-5.zip\tbackup-4.zip\tbackup-3.zip\tbackup-2.zip\n' >"$WORK_DIR/objects" + run_backup "" + assert_succeeded + assert_contains "$(calls_to "s3api list-objects-v2 ")" "--prefix backup-" + assert_eq "$(calls_to "s3api delete-object ")" "" +} + +test_each_plugin_database_keeps_its_own_newest_seven() { + plugin_databases plugin_arenas + printf 'plugin-databases/plugin_arenas/backup-8.zip\tplugin-databases/plugin_arenas/backup-7.zip\tplugin-databases/plugin_arenas/backup-6.zip\tplugin-databases/plugin_arenas/backup-5.zip\tplugin-databases/plugin_arenas/backup-4.zip\tplugin-databases/plugin_arenas/backup-3.zip\tplugin-databases/plugin_arenas/backup-2.zip\tplugin-databases/plugin_arenas/backup-1.zip\n' >"$WORK_DIR/objects-plugin-databases_plugin_arenas_" + run_backup "" + assert_succeeded + assert_eq "$(calls_to "s3api delete-object ")" "s3api delete-object --bucket 5stack-db-backups --key plugin-databases/plugin_arenas/backup-1.zip --endpoint-url http://rustfs:9000" +} + +test_a_plugin_database_that_fails_still_backs_up_the_rest_and_fails_the_job() { + plugin_databases plugin_arenas plugin_broken plugin_ranks + touch "$WORK_DIR/fail-dump-plugin_broken" + run_backup "" + [ "$STATUS" -ne 0 ] || fail "backup succeeded with a plugin database that could not be dumped" + uploads="$(calls_to "s3 cp ")" + assert_contains "$uploads" "s3://5stack-db-backups/backup-" + assert_contains "$uploads" "plugin-databases/plugin_arenas/" + assert_contains "$uploads" "plugin-databases/plugin_ranks/" + assert_not_contains "$uploads" "plugin_broken" + assert_contains "$(cat "$WORK_DIR/output")" "the main database was backed up, but these plugin databases were NOT: plugin_broken" +} + +test_a_failed_plugin_listing_fails_the_job_after_the_main_backup() { + touch "$WORK_DIR/fail-psql" + run_backup "" + [ "$STATUS" -ne 0 ] || fail "backup succeeded without listing the plugin databases" + assert_contains "$(calls_to "s3 cp ")" "s3://5stack-db-backups/backup-" + assert_contains "$(cat "$WORK_DIR/output")" "could not list the plugin databases" +} + +test_no_plugin_databases_means_only_the_main_backup() { + run_backup "" + assert_succeeded + assert_eq "$(calls_to "s3 cp " | wc -l | tr -d ' ')" "1" +} + run_tests From 0dd1928863c99a07b64bbbdf9d0aa0bfc95b5a93 Mon Sep 17 00:00:00 2001 From: Luke Policinski Date: Mon, 23 Nov 2026 11:16:29 -0500 Subject: [PATCH 2/5] fix: the pooler's auth lookup lives in the postgres maintenance database, never Hasura's --- base/plugin-db-pooler/configmap.yaml | 5 +++-- base/plugin-db-pooler/deployment.yaml | 10 ++++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/base/plugin-db-pooler/configmap.yaml b/base/plugin-db-pooler/configmap.yaml index 19d57015..24f99c42 100644 --- a/base/plugin-db-pooler/configmap.yaml +++ b/base/plugin-db-pooler/configmap.yaml @@ -13,11 +13,12 @@ data: listen_port = 6432 unix_socket_dir = - ; Only plugin roles get in: the lookup returns nothing for any other name. + ; Only plugin roles get in: the lookup returns nothing for any other name, + ; so the api and Hasura keep going straight to timescaledb. auth_type = scram-sha-256 auth_file = /var/run/plugin-db-pooler/userlist.txt auth_user = pgbouncer_auth - auth_dbname = hasura + auth_dbname = postgres auth_query = SELECT usename, passwd FROM pgbouncer.plugin_user_lookup($1) ; Many game servers share few real connections. Npgsql prepares on the diff --git a/base/plugin-db-pooler/deployment.yaml b/base/plugin-db-pooler/deployment.yaml index 101778b9..83a8cd61 100644 --- a/base/plugin-db-pooler/deployment.yaml +++ b/base/plugin-db-pooler/deployment.yaml @@ -36,8 +36,10 @@ spec: fsGroup: 996 # As the superuser, gives pgbouncer_auth a fresh password that only this # pod knows, so it is stored nowhere, and a lookup that returns the SCRAM - # verifier of plugin roles only. The api's lockdown closes the panel's - # database to PUBLIC and never revisits it, so CONNECT is granted here. + # verifier of plugin roles only. Both live in the postgres maintenance + # database, never the panel's own: pg_authid is shared by every + # database. The api's lockdown closes postgres to PUBLIC and never + # revisits it, so CONNECT is granted here. initContainers: - name: auth image: timescale/timescaledb:2.32.0-pg18@sha256:83952d54cfc74d9aebe4aba6ecf2af829c2bcf1f30058dded4c18ab3720a247a @@ -49,12 +51,12 @@ spec: umask 027 AUTH_PASSWORD="$(head -c 48 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c 40)" export PGPASSWORD="$POSTGRES_PASSWORD" - psql -h timescaledb -U hasura -d hasura -v ON_ERROR_STOP=1 -v auth_password="$AUTH_PASSWORD" <<'SQL' + psql -h timescaledb -U hasura -d postgres -v ON_ERROR_STOP=1 -v auth_password="$AUTH_PASSWORD" <<'SQL' SET pg_stat_statements.track_utility = off; SELECT 'CREATE ROLE pgbouncer_auth' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'pgbouncer_auth')\gexec ALTER ROLE pgbouncer_auth WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION CONNECTION LIMIT 10 PASSWORD :'auth_password'; ALTER ROLE pgbouncer_auth SET fivestack.app_key = ''; - GRANT CONNECT ON DATABASE hasura TO pgbouncer_auth; + GRANT CONNECT ON DATABASE postgres TO pgbouncer_auth; CREATE SCHEMA IF NOT EXISTS pgbouncer; REVOKE ALL ON SCHEMA pgbouncer FROM PUBLIC; GRANT USAGE ON SCHEMA pgbouncer TO pgbouncer_auth; From d7f28e8cb2e1fe4d2bc902f9774c5e533f85c87c Mon Sep 17 00:00:00 2001 From: Luke Policinski Date: Mon, 23 Nov 2026 11:38:56 -0500 Subject: [PATCH 3/5] fix: plugin databases back up in their own CronJob that can never touch the main backups; the pooler rolls on a config change --- base/backups/kustomization.yaml | 1 + .../plugin-databases-backup-cronjob.yaml | 219 ++++++++++++++++++ base/backups/postgres-backup-cronjob.yaml | 92 ++------ base/plugin-db-pooler/configmap.yaml | 36 --- base/plugin-db-pooler/deployment.yaml | 4 +- base/plugin-db-pooler/kustomization.yaml | 8 +- base/plugin-db-pooler/pgbouncer.ini | 29 +++ tests/scripts/postgres_backup_test.sh | 89 +++++-- 8 files changed, 344 insertions(+), 134 deletions(-) create mode 100644 base/backups/plugin-databases-backup-cronjob.yaml delete mode 100644 base/plugin-db-pooler/configmap.yaml create mode 100644 base/plugin-db-pooler/pgbouncer.ini diff --git a/base/backups/kustomization.yaml b/base/backups/kustomization.yaml index 4ff39f8f..35e5c234 100644 --- a/base/backups/kustomization.yaml +++ b/base/backups/kustomization.yaml @@ -3,5 +3,6 @@ kind: Kustomization resources: - postgres-backup-cronjob.yaml + - plugin-databases-backup-cronjob.yaml diff --git a/base/backups/plugin-databases-backup-cronjob.yaml b/base/backups/plugin-databases-backup-cronjob.yaml new file mode 100644 index 00000000..06a04adf --- /dev/null +++ b/base/backups/plugin-databases-backup-cronjob.yaml @@ -0,0 +1,219 @@ +apiVersion: batch/v1 +kind: CronJob +metadata: + name: plugin-databases-backup + namespace: 5stack +spec: + schedule: "30 3 * * *" + # 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" + exit 0 + 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 + + 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 diff --git a/base/backups/postgres-backup-cronjob.yaml b/base/backups/postgres-backup-cronjob.yaml index 289faccb..a2b91be7 100644 --- a/base/backups/postgres-backup-cronjob.yaml +++ b/base/backups/postgres-backup-cronjob.yaml @@ -129,79 +129,25 @@ spec: echo "Backup complete: $ZIP_FILE" - # Keeps the newest 7 keys under a prefix that match the - # pattern; plugin dumps live under plugin-databases/, so the - # main backups only ever count top-level backup-*.zip keys. - prune() { - PREFIX="$1" - PATTERN="$2" - shift 2 - 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 "$PATTERN" | awk 'NR>7' || true) - - if [ -n "$DELETEABLE_KEYS" ]; then - echo "Pruning old backups under ${PREFIX:-the bucket root}, 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 - echo "Pruning complete" - fi - } - - prune "backup-" '^backup-[0-9]+\.zip$' "$@" - - rm -f "$DUMP_FILE" "$ZIP_FILE" - - # Each plugin database is its own dump, in its own folder, - # with its owner and grants kept so a restore hands its - # tables back to the plugin's role. The main backup is - # already uploaded, so a plugin that fails only fails the - # job at the end. - FAILED_PLUGIN_DATABASES="" - 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 - - for PLUGIN_DATABASE in $PLUGIN_DATABASES; do - PLUGIN_DUMP="/tmp/$PLUGIN_DATABASE-$TS.dump" - PLUGIN_ZIP="/tmp/$PLUGIN_DATABASE-$TS.zip" - PLUGIN_KEY="plugin-databases/$PLUGIN_DATABASE/backup-$TS.zip" - - if ! pg_dump -h "$POSTGRES_HOST" -p "$POSTGRES_PORT" -U "$POSTGRES_USER" -d "$PLUGIN_DATABASE" -F c -Z 0 -f "$PLUGIN_DUMP" \ - || [ ! -s "$PLUGIN_DUMP" ]; then - echo "ERROR: could not dump the plugin database $PLUGIN_DATABASE" - FAILED_PLUGIN_DATABASES="$FAILED_PLUGIN_DATABASES $PLUGIN_DATABASE" - rm -f "$PLUGIN_DUMP" - continue - fi - - zip -j "$PLUGIN_ZIP" "$PLUGIN_DUMP" - - echo "Uploading the plugin database $PLUGIN_DATABASE to $S3_DB_BACKUP_BUCKET/$PLUGIN_KEY" - if ! aws s3 cp "$PLUGIN_ZIP" "s3://$S3_DB_BACKUP_BUCKET/$PLUGIN_KEY" --endpoint-url "$ENDPOINT"; then - echo "ERROR: could not upload the plugin database $PLUGIN_DATABASE" - FAILED_PLUGIN_DATABASES="$FAILED_PLUGIN_DATABASES $PLUGIN_DATABASE" - rm -f "$PLUGIN_DUMP" "$PLUGIN_ZIP" - continue - fi - - rm -f "$PLUGIN_DUMP" "$PLUGIN_ZIP" - prune "plugin-databases/$PLUGIN_DATABASE/" '/backup-[0-9]+\.zip$' "$@" - done - - if [ -n "$FAILED_PLUGIN_DATABASES" ]; then - echo "ERROR: the main database was backed up, but these plugin databases were NOT:$FAILED_PLUGIN_DATABASES" - exit 1 + 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) + + # 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" + 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 + echo "Pruning complete" fi envFrom: - secretRef: diff --git a/base/plugin-db-pooler/configmap.yaml b/base/plugin-db-pooler/configmap.yaml deleted file mode 100644 index 24f99c42..00000000 --- a/base/plugin-db-pooler/configmap.yaml +++ /dev/null @@ -1,36 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - name: plugin-db-pooler - namespace: 5stack -data: - pgbouncer.ini: | - [databases] - * = host=timescaledb port=5432 - - [pgbouncer] - listen_addr = 0.0.0.0 - listen_port = 6432 - unix_socket_dir = - - ; Only plugin roles get in: the lookup returns nothing for any other name, - ; so the api and Hasura keep going straight to timescaledb. - auth_type = scram-sha-256 - auth_file = /var/run/plugin-db-pooler/userlist.txt - auth_user = pgbouncer_auth - auth_dbname = postgres - auth_query = SELECT usename, passwd FROM pgbouncer.plugin_user_lookup($1) - - ; Many game servers share few real connections. Npgsql prepares on the - ; protocol level, which transaction pooling needs max_prepared_statements for. - pool_mode = transaction - max_prepared_statements = 200 - default_pool_size = 20 - max_db_connections = 100 - max_client_conn = 2000 - track_extra_parameters = IntervalStyle, search_path - ignore_startup_parameters = extra_float_digits, options - - server_tls_sslmode = prefer - log_connections = 0 - log_disconnections = 0 diff --git a/base/plugin-db-pooler/deployment.yaml b/base/plugin-db-pooler/deployment.yaml index 83a8cd61..41954c16 100644 --- a/base/plugin-db-pooler/deployment.yaml +++ b/base/plugin-db-pooler/deployment.yaml @@ -34,6 +34,8 @@ spec: - 'true' securityContext: fsGroup: 996 + # pgbouncer_auth's limit stays above default_pool_size, so its auth + # pool can't run out after a restart. # As the superuser, gives pgbouncer_auth a fresh password that only this # pod knows, so it is stored nowhere, and a lookup that returns the SCRAM # verifier of plugin roles only. Both live in the postgres maintenance @@ -54,7 +56,7 @@ spec: psql -h timescaledb -U hasura -d postgres -v ON_ERROR_STOP=1 -v auth_password="$AUTH_PASSWORD" <<'SQL' SET pg_stat_statements.track_utility = off; SELECT 'CREATE ROLE pgbouncer_auth' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'pgbouncer_auth')\gexec - ALTER ROLE pgbouncer_auth WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION CONNECTION LIMIT 10 PASSWORD :'auth_password'; + ALTER ROLE pgbouncer_auth WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION CONNECTION LIMIT 30 PASSWORD :'auth_password'; ALTER ROLE pgbouncer_auth SET fivestack.app_key = ''; GRANT CONNECT ON DATABASE postgres TO pgbouncer_auth; CREATE SCHEMA IF NOT EXISTS pgbouncer; diff --git a/base/plugin-db-pooler/kustomization.yaml b/base/plugin-db-pooler/kustomization.yaml index 25a7c2cb..c89355ad 100644 --- a/base/plugin-db-pooler/kustomization.yaml +++ b/base/plugin-db-pooler/kustomization.yaml @@ -2,6 +2,12 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - - configmap.yaml - deployment.yaml - service.yaml + +# Hashed name: a change to pgbouncer.ini rolls the pooler. +configMapGenerator: + - name: plugin-db-pooler + namespace: 5stack + files: + - pgbouncer.ini diff --git a/base/plugin-db-pooler/pgbouncer.ini b/base/plugin-db-pooler/pgbouncer.ini new file mode 100644 index 00000000..0a1b226e --- /dev/null +++ b/base/plugin-db-pooler/pgbouncer.ini @@ -0,0 +1,29 @@ +[databases] +* = host=timescaledb port=5432 + +[pgbouncer] +listen_addr = 0.0.0.0 +listen_port = 6432 +unix_socket_dir = + +; Only plugin roles get in: the lookup returns nothing for any other name, +; so the api and Hasura keep going straight to timescaledb. +auth_type = scram-sha-256 +auth_file = /var/run/plugin-db-pooler/userlist.txt +auth_user = pgbouncer_auth +auth_dbname = postgres +auth_query = SELECT usename, passwd FROM pgbouncer.plugin_user_lookup($1) + +; Many game servers share few real connections. Npgsql prepares on the +; protocol level, which transaction pooling needs max_prepared_statements for. +pool_mode = transaction +max_prepared_statements = 200 +default_pool_size = 20 +max_db_connections = 100 +max_client_conn = 2000 +track_extra_parameters = IntervalStyle, search_path +ignore_startup_parameters = extra_float_digits, options + +server_tls_sslmode = prefer +log_connections = 0 +log_disconnections = 0 diff --git a/tests/scripts/postgres_backup_test.sh b/tests/scripts/postgres_backup_test.sh index 4301a007..358d889b 100644 --- a/tests/scripts/postgres_backup_test.sh +++ b/tests/scripts/postgres_backup_test.sh @@ -17,7 +17,7 @@ backup_script() { if (RLENGTH < indent) { exit } print substr($0, indent + 1) } - ' "$TEST_ROOT/base/backups/postgres-backup-cronjob.yaml" + ' "$TEST_ROOT/base/backups/${1:-postgres-backup-cronjob.yaml}" } setup_stubs() { @@ -88,7 +88,7 @@ case "$1 $2" in if [ -n "$prefix" ] && [ "$prefix" != "backup-" ]; then listing="$WORK_DIR/objects-$(printf '%s' "$prefix" | tr '/' '_')" fi - if [ -f "$listing" ]; then cat "$listing"; fi + if [ -f "$listing" ]; then cat "$listing"; else echo None; fi ;; esac EOF @@ -110,7 +110,7 @@ eight_backups() { run_backup() { setup_stubs - backup_script | sed "s#/tmp/#$WORK_DIR/#g" >"$WORK_DIR/backup.sh" + backup_script "${JOB_FILE:-}" | sed "s#/tmp/#$WORK_DIR/#g" >"$WORK_DIR/backup.sh" PATH="$WORK_DIR/bin:$PATH" \ S3_ENDPOINT="$1" \ DEMOS_DOMAIN="${2:-}" \ @@ -269,20 +269,24 @@ plugin_databases() { printf '%s\n' "$@" >"$WORK_DIR/plugin-databases" } -test_each_plugin_database_is_its_own_dump_in_its_own_folder_after_the_main_one() { - plugin_databases plugin_arenas plugin_ranks +run_plugin_backup() { + JOB_FILE=plugin-databases-backup-cronjob.yaml run_backup "$@" +} + +today() { + date -u +%Y%m%d +} + +test_the_main_backup_never_touches_the_plugin_databases() { + plugin_databases plugin_arenas run_backup "" assert_succeeded - uploads="$(calls_to "s3 cp ")" - assert_contains "$(echo "$uploads" | sed -n 1p)" "s3://5stack-db-backups/backup-" - assert_contains "$(echo "$uploads" | sed -n 2p)" "s3://5stack-db-backups/plugin-databases/plugin_arenas/backup-" - assert_contains "$(echo "$uploads" | sed -n 3p)" "s3://5stack-db-backups/plugin-databases/plugin_ranks/backup-" - assert_contains "$(cat "$WORK_DIR/pg-dump-calls")" "-d plugin_arenas -F c -Z 0 -f" - assert_not_contains "$(grep -e "-d plugin_arenas" "$WORK_DIR/pg-dump-calls")" "--no-owner" + assert_eq "$(calls_to "s3 cp " | wc -l | tr -d ' ')" "1" + assert_eq "$(cat "$WORK_DIR/pg-dump-calls" | wc -l | tr -d ' ')" "1" + assert_not_contains "$(aws_calls)" "plugin-databases" } test_the_main_backups_prune_only_counts_their_own_top_level_keys() { - plugin_databases plugin_arenas printf 'plugin-databases/plugin_arenas/backup-9.zip\tbackup-8.zip\tbackup-7.zip\tbackup-6.zip\tbackup-5.zip\tbackup-4.zip\tbackup-3.zip\tbackup-2.zip\n' >"$WORK_DIR/objects" run_backup "" assert_succeeded @@ -290,39 +294,78 @@ test_the_main_backups_prune_only_counts_their_own_top_level_keys() { assert_eq "$(calls_to "s3api delete-object ")" "" } +test_each_plugin_database_is_its_own_dump_in_its_own_folder() { + plugin_databases plugin_arenas plugin_ranks + run_plugin_backup "" + assert_succeeded + uploads="$(calls_to "s3 cp ")" + assert_contains "$(echo "$uploads" | sed -n 1p)" "s3://5stack-db-backups/plugin-databases/plugin_arenas/backup-" + assert_contains "$(echo "$uploads" | sed -n 2p)" "s3://5stack-db-backups/plugin-databases/plugin_ranks/backup-" + assert_eq "$(echo "$uploads" | wc -l | tr -d ' ')" "2" + dump="$(grep -e "-d plugin_arenas" "$WORK_DIR/pg-dump-calls")" + assert_contains "$dump" "--lock-wait-timeout=300s" + assert_not_contains "$dump" "--no-owner" +} + test_each_plugin_database_keeps_its_own_newest_seven() { plugin_databases plugin_arenas printf 'plugin-databases/plugin_arenas/backup-8.zip\tplugin-databases/plugin_arenas/backup-7.zip\tplugin-databases/plugin_arenas/backup-6.zip\tplugin-databases/plugin_arenas/backup-5.zip\tplugin-databases/plugin_arenas/backup-4.zip\tplugin-databases/plugin_arenas/backup-3.zip\tplugin-databases/plugin_arenas/backup-2.zip\tplugin-databases/plugin_arenas/backup-1.zip\n' >"$WORK_DIR/objects-plugin-databases_plugin_arenas_" - run_backup "" + run_plugin_backup "" assert_succeeded assert_eq "$(calls_to "s3api delete-object ")" "s3api delete-object --bucket 5stack-db-backups --key plugin-databases/plugin_arenas/backup-1.zip --endpoint-url http://rustfs:9000" } -test_a_plugin_database_that_fails_still_backs_up_the_rest_and_fails_the_job() { +test_a_retry_skips_a_plugin_database_already_dumped_today() { + plugin_databases plugin_arenas plugin_ranks + echo "plugin-databases/plugin_arenas/backup-$(today)010203.zip" >"$WORK_DIR/objects-plugin-databases_plugin_arenas_backup-$(today)" + printf 'plugin-databases/plugin_arenas/backup-8.zip\tplugin-databases/plugin_arenas/backup-7.zip\tplugin-databases/plugin_arenas/backup-6.zip\tplugin-databases/plugin_arenas/backup-5.zip\tplugin-databases/plugin_arenas/backup-4.zip\tplugin-databases/plugin_arenas/backup-3.zip\tplugin-databases/plugin_arenas/backup-2.zip\tplugin-databases/plugin_arenas/backup-1.zip\n' >"$WORK_DIR/objects-plugin-databases_plugin_arenas_" + run_plugin_backup "" + assert_succeeded + assert_not_contains "$(cat "$WORK_DIR/pg-dump-calls")" "-d plugin_arenas" + assert_not_contains "$(calls_to "s3 cp ")" "plugin_arenas" + assert_contains "$(calls_to "s3 cp ")" "plugin-databases/plugin_ranks/" + assert_eq "$(calls_to "s3api delete-object ")" "" + assert_contains "$(cat "$WORK_DIR/output")" "plugin_arenas already has today's dump, skipped" +} + +test_a_plugin_database_that_fails_still_backs_up_the_rest_and_never_the_main_one() { plugin_databases plugin_arenas plugin_broken plugin_ranks touch "$WORK_DIR/fail-dump-plugin_broken" - run_backup "" + eight_backups + run_plugin_backup "" [ "$STATUS" -ne 0 ] || fail "backup succeeded with a plugin database that could not be dumped" uploads="$(calls_to "s3 cp ")" - assert_contains "$uploads" "s3://5stack-db-backups/backup-" assert_contains "$uploads" "plugin-databases/plugin_arenas/" assert_contains "$uploads" "plugin-databases/plugin_ranks/" assert_not_contains "$uploads" "plugin_broken" - assert_contains "$(cat "$WORK_DIR/output")" "the main database was backed up, but these plugin databases were NOT: plugin_broken" + assert_not_contains "$uploads" "s3://5stack-db-backups/backup-" + assert_not_contains "$(cat "$WORK_DIR/pg-dump-calls")" "-d hasura" + assert_eq "$(calls_to "s3api delete-object ")" "" + assert_contains "$(cat "$WORK_DIR/output")" "these plugin databases were NOT backed up: plugin_broken" } -test_a_failed_plugin_listing_fails_the_job_after_the_main_backup() { +test_a_failed_plugin_listing_uploads_nothing() { touch "$WORK_DIR/fail-psql" - run_backup "" + run_plugin_backup "" [ "$STATUS" -ne 0 ] || fail "backup succeeded without listing the plugin databases" - assert_contains "$(calls_to "s3 cp ")" "s3://5stack-db-backups/backup-" + assert_eq "$(calls_to "s3 cp ")" "" assert_contains "$(cat "$WORK_DIR/output")" "could not list the plugin databases" } -test_no_plugin_databases_means_only_the_main_backup() { - run_backup "" +test_no_plugin_databases_makes_no_s3_calls() { + run_plugin_backup "" assert_succeeded - assert_eq "$(calls_to "s3 cp " | wc -l | tr -d ' ')" "1" + assert_eq "$(aws_calls)" "" + assert_contains "$(cat "$WORK_DIR/output")" "No plugin databases to back up" +} + +test_the_plugin_job_checks_a_remote_bucket_the_same_way() { + plugin_databases plugin_arenas + deny_bucket_listing + echo 444455556666 >"$WORK_DIR/bucket-owner" + run_plugin_backup "$AWS_ENDPOINT" + [ "$STATUS" -ne 0 ] || fail "plugin backup succeeded into a bucket owned by another account" + assert_eq "$(calls_to "s3 cp ")" "" } run_tests From 13bb49c02efa059e9dd81a7af87462f5b3be8e05 Mon Sep 17 00:00:00 2001 From: Luke Policinski Date: Mon, 23 Nov 2026 11:49:04 -0500 Subject: [PATCH 4/5] fix: the plugin databases backup runs on UTC, the date its retries skip by --- base/backups/plugin-databases-backup-cronjob.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/base/backups/plugin-databases-backup-cronjob.yaml b/base/backups/plugin-databases-backup-cronjob.yaml index 06a04adf..bab55205 100644 --- a/base/backups/plugin-databases-backup-cronjob.yaml +++ b/base/backups/plugin-databases-backup-cronjob.yaml @@ -5,6 +5,8 @@ metadata: 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 From f46fd9a066ba9914d5ca72e3f95016d9f50265af Mon Sep 17 00:00:00 2001 From: Luke Policinski Date: Mon, 23 Nov 2026 11:53:40 -0500 Subject: [PATCH 5/5] fix: a deleted plugin database's dumps age out after a week --- .../plugin-databases-backup-cronjob.yaml | 40 +++++++++++- tests/scripts/postgres_backup_test.sh | 65 ++++++++++++++++++- 2 files changed, 101 insertions(+), 4 deletions(-) diff --git a/base/backups/plugin-databases-backup-cronjob.yaml b/base/backups/plugin-databases-backup-cronjob.yaml index bab55205..a2ad426b 100644 --- a/base/backups/plugin-databases-backup-cronjob.yaml +++ b/base/backups/plugin-databases-backup-cronjob.yaml @@ -52,7 +52,6 @@ spec: if [ -z "$PLUGIN_DATABASES" ]; then echo "No plugin databases to back up" - exit 0 fi ENDPOINT="${S3_ENDPOINT:-rustfs}" @@ -193,6 +192,45 @@ spec: 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 diff --git a/tests/scripts/postgres_backup_test.sh b/tests/scripts/postgres_backup_test.sh index 358d889b..f610e617 100644 --- a/tests/scripts/postgres_backup_test.sh +++ b/tests/scripts/postgres_backup_test.sh @@ -88,11 +88,36 @@ case "$1 $2" in if [ -n "$prefix" ] && [ "$prefix" != "backup-" ]; then listing="$WORK_DIR/objects-$(printf '%s' "$prefix" | tr '/' '_')" fi + case " $* " in + *" --delimiter "*) + if [ -f "$WORK_DIR/fail-folders" ]; then + echo "An error occurred (InternalError) when calling the ListObjectsV2 operation" >&2 + exit 254 + fi + listing="$WORK_DIR/folders" + ;; + *"[Key,LastModified]"*) listing="$WORK_DIR/dated-$(printf '%s' "$prefix" | tr '/' '_')" ;; + esac if [ -f "$listing" ]; then cat "$listing"; else echo None; fi ;; esac EOF - chmod +x "$WORK_DIR/bin/apk" "$WORK_DIR/bin/pg_dump" "$WORK_DIR/bin/psql" "$WORK_DIR/bin/zip" "$WORK_DIR/bin/aws" + # The job's busybox date takes -d @SECONDS; a BSD date spells it -r. + cat >"$WORK_DIR/bin/date" <<'EOF' +#!/bin/bash +args=() +while [ $# -gt 0 ]; do + if [ "$1" = "-d" ] && [ "${2#@}" != "$2" ] && ! /bin/date -d @0 >/dev/null 2>&1; then + args+=(-r "${2#@}") + shift 2 + continue + fi + args+=("$1") + shift +done +exec /bin/date "${args[@]}" +EOF + chmod +x "$WORK_DIR/bin/apk" "$WORK_DIR/bin/pg_dump" "$WORK_DIR/bin/psql" "$WORK_DIR/bin/zip" "$WORK_DIR/bin/aws" "$WORK_DIR/bin/date" } buckets() { @@ -352,13 +377,47 @@ test_a_failed_plugin_listing_uploads_nothing() { assert_contains "$(cat "$WORK_DIR/output")" "could not list the plugin databases" } -test_no_plugin_databases_makes_no_s3_calls() { +test_no_plugin_databases_dumps_nothing() { run_plugin_backup "" assert_succeeded - assert_eq "$(aws_calls)" "" + assert_eq "$(calls_to "s3 cp ")" "" + assert_eq "$(cat "$WORK_DIR/pg-dump-calls" 2>/dev/null)" "" assert_contains "$(cat "$WORK_DIR/output")" "No plugin databases to back up" } +week_old_and_new_dumps_of() { + printf 'plugin-databases/%s/backup-20200101030000.zip\t2020-01-01T03:30:12+00:00\nplugin-databases/%s/backup-%s033000.zip\t%sT03:30:12+00:00\n' \ + "$1" "$1" "$(today)" "$(date -u +%Y-%m-%d)" >"$WORK_DIR/dated-plugin-databases_$1_" +} + +test_a_deleted_plugin_database_keeps_its_last_week_and_loses_older_dumps() { + plugin_databases plugin_arenas + printf 'plugin-databases/plugin_arenas/\tplugin-databases/plugin_gone/\n' >"$WORK_DIR/folders" + week_old_and_new_dumps_of plugin_gone + week_old_and_new_dumps_of plugin_arenas + run_plugin_backup "" + assert_succeeded + assert_eq "$(calls_to "s3api delete-object ")" "s3api delete-object --bucket 5stack-db-backups --key plugin-databases/plugin_gone/backup-20200101030000.zip --endpoint-url http://rustfs:9000" + assert_not_contains "$(aws_calls)" "--prefix plugin-databases/plugin_arenas/ --query Contents[].[Key,LastModified]" +} + +test_the_last_plugin_database_deleted_still_ages_its_dumps_out() { + printf 'plugin-databases/plugin_gone/\n' >"$WORK_DIR/folders" + week_old_and_new_dumps_of plugin_gone + run_plugin_backup "" + assert_succeeded + assert_eq "$(calls_to "s3api delete-object ")" "s3api delete-object --bucket 5stack-db-backups --key plugin-databases/plugin_gone/backup-20200101030000.zip --endpoint-url http://rustfs:9000" +} + +test_a_failed_folder_listing_never_fails_the_dumps() { + plugin_databases plugin_arenas + touch "$WORK_DIR/fail-folders" + run_plugin_backup "" + assert_succeeded + assert_contains "$(calls_to "s3 cp ")" "plugin-databases/plugin_arenas/" + assert_contains "$(cat "$WORK_DIR/output")" "could not list the plugin database folders" +} + test_the_plugin_job_checks_a_remote_bucket_the_same_way() { plugin_databases plugin_arenas deny_bucket_listing