ci: split test-db en 2 jobs parallèles (Infra + Integration) (#162)

This commit is contained in:
Arnaud Dartois authored and Arnaud Dartois committed 2026-08-27 00:11:14 +02:00
1 parent 91bf33f794
commit 2eebc1d779
12 files changed
+916 -26

No files matched your search

+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env bash
# ─── Heimdall — Alarik/S3 Mirror Backup (weekly) ────────────────
# Mirrors the heimdall bucket to a backup prefix with versioning.
# This captures snapshots, recordings, and other S3-stored data.
#
# Usage:
# ./backup-alarik.sh # defaults from env / .env
# ./backup-alarik.sh --dry-run # show what would be done
# BACKUP_RETENTION_WEEKS=8 ./backup-alarik.sh
#
# Required env vars:
# ALARIK_ENDPOINT (or S3_ENDPOINT), ALARIK_ACCESS_KEY (or S3_ACCESS_KEY),
# ALARIK_SECRET_KEY (or S3_SECRET_KEY), ALARIK_BUCKET (default: heimdall)
#
# Optional:
# BACKUP_RETENTION_WEEKS (default: 12)
# DRY_RUN (set to 1 for dry-run)
# ──────────────────────────────────────────────────────────────────
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
# ── Load .env if present ────────────────────────────────────────
ENV_FILE="${PROJECT_DIR}/docker/.env"
if [[ -f "$ENV_FILE" ]]; then
set -a
# shellcheck disable=SC1091
source "$ENV_FILE"
set +a
fi
# ── Configuration ───────────────────────────────────────────────
S3_ENDPOINT="${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}"
S3_ACCESS_KEY="${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}"
S3_SECRET_KEY="${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}"
S3_BUCKET="${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}"
BACKUP_PREFIX="backup/alarik"
RETENTION_WEEKS="${BACKUP_RETENTION_WEEKS:-12}"
TIMESTAMP="$(date -u +%Y-%m-%dT%H-%M-%SZ)"
WEEK_TAG="$(date -u +%Y-W%V)"
IS_DRY_RUN="${DRY_RUN:-0}"
# ── Helpers ─────────────────────────────────────────────────────
log() { echo "[alarik-backup] $(date -u +%H:%M:%S) $*"; }
warn() { log "WARN: $*"; }
die() { log "FATAL: $*"; exit 1; }
# ── Preflight ───────────────────────────────────────────────────
[[ -z "$S3_ENDPOINT" ]] && die "S3_ENDPOINT not set — cannot mirror Alarik"
if command -v mc >/dev/null 2>&1; then
CLIENT="mc"
mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 2>/dev/null
elif command -v aws >/dev/null 2>&1; then
CLIENT="aws"
else
die "Neither 'mc' (MinIO client) nor 'aws' CLI found"
fi
# ── Step 1: Mirror bucket to backup prefix ──────────────────────
log "Mirroring s3://${S3_BUCKET} → s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}/"
if [[ "$IS_DRY_RUN" == "1" ]]; then
log "[DRY-RUN] Would mirror all objects from ${S3_BUCKET} to ${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}/"
else
if [[ "$CLIENT" == "mc" ]]; then
# mc mirror: copies new/changed objects, skips unchanged
# --overwrite: always copy (we want a point-in-time snapshot)
# --exclude "backup/*": don't mirror our own backups (avoid recursion)
mc mirror \
"heimdall-backup/${S3_BUCKET}" \
"heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}" \
--overwrite \
--exclude "backup/*" \
2>&1 | tail -10
else
# AWS CLI: sync with exclusion
aws --endpoint-url "$S3_ENDPOINT" s3 sync \
"s3://${S3_BUCKET}" \
"s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}" \
--exclude "backup/*" \
2>&1 | tail -10
fi
log "Mirror complete"
fi
# ── Step 2: Prune old weekly backups ────────────────────────────
CUTOFF_WEEK=$(date -u -d "${RETENTION_WEEKS} weeks ago" +%Y-W%V 2>/dev/null || \
date -u -v-"${RETENTION_WEEKS}"w +%Y-W%V 2>/dev/null || echo "")
if [[ -n "$CUTOFF_WEEK" ]]; then
log "Pruning weekly backups older than ${RETENTION_WEEKS} weeks (cutoff: ${CUTOFF_WEEK})..."
if [[ "$IS_DRY_RUN" != "1" ]]; then
if [[ "$CLIENT" == "mc" ]]; then
mc ls "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/" 2>/dev/null | \
awk '{print $NF}' | \
tr -d '/' | \
while read -r week; do
if [[ -n "$week" && "$week" < "$CUTOFF_WEEK" ]]; then
log " Deleting: ${BACKUP_PREFIX}/${week}/"
mc rm --recursive --force "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" 2>/dev/null || true
fi
done
fi
fi
fi
# ── Step 3: Create manifest ────────────────────────────────────
MANIFEST_KEY="${BACKUP_PREFIX}/${WEEK_TAG}/MANIFEST.txt"
if [[ "$IS_DRY_RUN" != "1" ]]; then
log "Creating manifest..."
OBJECT_COUNT=0
TOTAL_SIZE=0
if [[ "$CLIENT" == "mc" ]]; then
STATS=$(mc ls "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}/" --recursive --summarize 2>/dev/null | tail -2)
OBJECT_COUNT=$(echo "$STATATS" | grep -oP 'Objects: \K\d+' || echo "0")
TOTAL_SIZE=$(echo "$STATATS" | grep -oP 'Size: \K\d+' || echo "0")
fi
MANIFEST="Heimdall Alarik Backup Manifest
================================
Week: ${WEEK_TAG}
Created: ${TIMESTAMP}
Bucket: ${S3_BUCKET}
Objects: ${OBJECT_COUNT}
Total: ${TOTAL_SIZE} bytes
"
if [[ "$CLIENT" == "mc" ]]; then
echo "$MANIFEST" | mc pipe "heimdall-backup/${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null
else
echo "$MANIFEST" | aws --endpoint-url "$S3_ENDPOINT" s3 cp - "s3://${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null
fi
log "Manifest written: ${MANIFEST_KEY}"
fi
log "Alarik backup complete ✓"
log " Location: s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}/"
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env bash
# ─── Heimdall — PostgreSQL Daily Backup ──────────────────────────
# Runs pg_dump inside the PostgreSQL container, compresses, uploads
# to Alarik/S3 under backup/postgresql/YYYY-MM-DD/, and prunes
# backups older than RETENTION_DAYS.
#
# Usage:
# ./backup.sh # defaults from env / .env
# ./backup.sh --dry-run # show what would be done
# BACKUP_RETENTION_DAYS=14 ./backup.sh
#
# Required env vars (set in .env or export):
# POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD
# ALARIK_ENDPOINT (or S3_ENDPOINT), ALARIK_ACCESS_KEY (or S3_ACCESS_KEY),
# ALARIK_SECRET_KEY (or S3_SECRET_KEY), ALARIK_BUCKET (default: heimdall)
#
# Optional:
# BACKUP_RETENTION_DAYS (default: 30)
# BACKUP_LOCAL_DIR (default: /var/lib/heimdall/backups)
# DRY_RUN (set to 1 for dry-run)
# ──────────────────────────────────────────────────────────────────
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
# ── Load .env if present ────────────────────────────────────────
ENV_FILE="${PROJECT_DIR}/docker/.env"
if [[ -f "$ENV_FILE" ]]; then
set -a
# shellcheck disable=SC1091
source "$ENV_FILE"
set +a
fi
# ── Configuration ───────────────────────────────────────────────
PG_HOST="${POSTGRES_HOST:-localhost}"
PG_PORT="${POSTGRES_PORT:-5432}"
PG_DB="${POSTGRES_DB:-heimdall}"
PG_USER="${POSTGRES_USER:-heimdall}"
PG_PASSWORD="${POSTGRES_PASSWORD:-heimdall}"
S3_ENDPOINT="${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}"
S3_ACCESS_KEY="${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}"
S3_SECRET_KEY="${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}"
S3_BUCKET="${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}"
S3_PREFIX="backup/postgresql"
RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-30}"
LOCAL_DIR="${BACKUP_LOCAL_DIR:-/var/lib/heimdall/backups}"
TIMESTAMP="$(date -u +%Y-%m-%dT%H-%M-%SZ)"
DATE_TAG="$(date -u +%Y-%m-%d)"
DUMP_FILE="${LOCAL_DIR}/postgresql/heimdall-${TIMESTAMP}.sql.gz"
IS_DRY_RUN="${DRY_RUN:-0}"
# ── Helpers ─────────────────────────────────────────────────────
log() { echo "[backup] $(date -u +%H:%M:%S) $*"; }
warn() { log "WARN: $*"; }
die() { log "FATAL: $*"; exit 1; }
# ── Preflight ───────────────────────────────────────────────────
command -v pg_dump >/dev/null 2>&1 || die "pg_dump not found — install postgresql-client"
command -v mc >/dev/null 2>&1 || command -v aws >/dev/null 2>&1 || die "Neither 'mc' (MinIO client) nor 'aws' CLI found"
if [[ -z "$S3_ENDPOINT" ]]; then
warn "S3_ENDPOINT not set — backup will be local only (no upload)"
fi
mkdir -p "${LOCAL_DIR}/postgresql"
# ── Step 1: pg_dump ─────────────────────────────────────────────
log "Starting PostgreSQL backup: ${PG_DB}@${PG_HOST}:${PG_PORT}"
if [[ "$IS_DRY_RUN" == "1" ]]; then
log "[DRY-RUN] Would run: pg_dump -h $PG_HOST -p $PG_PORT -U $PG_USER -d $PG_DB | gzip > $DUMP_FILE"
else
PGPASSWORD="$PG_PASSWORD" pg_dump \
-h "$PG_HOST" \
-p "$PG_PORT" \
-U "$PG_USER" \
-d "$PG_DB" \
--format=custom \
--compress=9 \
--verbose \
-f "$DUMP_FILE" \
2>&1 | tail -5
log "Dump created: $(du -h "$DUMP_FILE" | cut -f1) → $DUMP_FILE"
fi
# ── Step 2: Upload to Alarik/S3 ────────────────────────────────
S3_KEY="${S3_PREFIX}/${DATE_TAG}/heimdall-${TIMESTAMP}.sql.gz"
S3_LATEST_KEY="${S3_PREFIX}/latest.sql.gz"
if [[ -n "$S3_ENDPOINT" ]]; then
log "Uploading to S3: s3://${S3_BUCKET}/${S3_KEY}"
if [[ "$IS_DRY_RUN" == "1" ]]; then
log "[DRY-RUN] Would upload to s3://${S3_BUCKET}/${S3_KEY}"
else
# Try mc first, fallback to aws
if command -v mc >/dev/null 2>&1; then
mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 2>/dev/null
mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3
mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3
else
aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3
aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3
fi
log "Upload complete"
fi
else
warn "Skipping S3 upload (no endpoint configured)"
fi
# ── Step 3: Prune old local backups ─────────────────────────────
log "Pruning local backups older than ${RETENTION_DAYS} days..."
PRUNED=$(find "${LOCAL_DIR}/postgresql" -name "*.sql.gz" -mtime +"$RETENTION_DAYS" -print -delete 2>/dev/null | wc -l)
log "Pruned ${PRUNED} local backup(s)"
# ── Step 4: Prune old S3 backups ────────────────────────────────
if [[ -n "$S3_ENDPOINT" && "$IS_DRY_RUN" != "1" ]]; then
log "Pruning S3 backups older than ${RETENTION_DAYS} days..."
CUTOFF_DATE=$(date -u -d "${RETENTION_DAYS} days ago" +%Y-%m-%d 2>/dev/null || date -u -v-"${RETENTION_DAYS}"d +%Y-%m-%d 2>/dev/null || echo "")
if [[ -n "$CUTOFF_DATE" ]]; then
if command -v mc >/dev/null 2>&1; then
# List and delete old daily backups
mc ls "heimdall-backup/${S3_BUCKET}/${S3_PREFIX}/" --recursive 2>/dev/null | \
awk '{print $NF}' | \
grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}/' | \
while read -r key; do
# Extract date from key: backup/postgresql/YYYY-MM-DD/...
key_date=$(echo "$key" | grep -oP '\d{4}-\d{2}-\d{2}' | head -1)
if [[ -n "$key_date" && "$key_date" < "$CUTOFF_DATE" ]]; then
log " Deleting: $key"
mc rm "heimdall-backup/${S3_BUCKET}/${key}" 2>/dev/null || true
fi
done
fi
fi
fi
log "Backup complete ✓"
log " Local: ${DUMP_FILE}"
[[ -n "$S3_ENDPOINT" ]] && log " S3: s3://${S3_BUCKET}/${S3_KEY}"
+193
View File
@@ -0,0 +1,193 @@
#!/usr/bin/env bash
# ─── Heimdall — PostgreSQL Restore from Backup ───────────────────
# Downloads a backup from Alarik/S3 (or uses a local file) and
# restores it to the PostgreSQL database.
#
# Usage:
# ./restore.sh --file /path/to/backup.sql.gz # local file
# ./restore.sh --s3-key backup/postgresql/latest.sql.gz # from S3
# ./restore.sh --latest # most recent from S3
#
# ⚠️ This DROPS and RECREATES the target database.
# A confirmation prompt is shown unless --yes is passed.
#
# Required env vars (set in .env or export):
# POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD
# (S3 vars only needed for --s3-key or --latest)
# ──────────────────────────────────────────────────────────────────
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
# ── Load .env if present ────────────────────────────────────────
ENV_FILE="${PROJECT_DIR}/docker/.env"
if [[ -f "$ENV_FILE" ]]; then
set -a
# shellcheck disable=SC1091
source "$ENV_FILE"
set +a
fi
# ── Configuration ───────────────────────────────────────────────
PG_HOST="${POSTGRES_HOST:-localhost}"
PG_PORT="${POSTGRES_PORT:-5432}"
PG_DB="${POSTGRES_DB:-heimdall}"
PG_USER="${POSTGRES_USER:-heimdall}"
PG_PASSWORD="${POSTGRES_PASSWORD:-heimdall}"
S3_ENDPOINT="${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}"
S3_ACCESS_KEY="${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}"
S3_SECRET_KEY="${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}"
S3_BUCKET="${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}"
LOCAL_DIR="${BACKUP_LOCAL_DIR:-/var/lib/heimdall/backups}"
RESTORE_TMP="${LOCAL_DIR}/.restore-tmp"
AUTO_YES=0
# ── Helpers ─────────────────────────────────────────────────────
log() { echo "[restore] $(date -u +%H:%M:%S) $*"; }
warn() { log "WARN: $*"; }
die() { log "FATAL: $*"; exit 1; }
usage() {
cat <<EOF
Usage: $(basename "$0") [OPTIONS]
Options:
--file PATH Restore from a local .sql.gz file
--s3-key KEY Restore from S3 (specific key)
--latest Restore the latest backup from S3
--yes Skip confirmation prompt
--dry-run Show what would be done
-h, --help Show this help
EOF
exit 0
}
# ── Parse arguments ─────────────────────────────────────────────
FILE=""
S3_KEY=""
USE_LATEST=0
IS_DRY_RUN=0
while [[ $# -gt 0 ]]; do
case "$1" in
--file) FILE="$2"; shift 2 ;;
--s3-key) S3_KEY="$2"; shift 2 ;;
--latest) USE_LATEST=1; shift ;;
--yes) AUTO_YES=1; shift ;;
--dry-run) IS_DRY_RUN=1; shift ;;
-h|--help) usage ;;
*) die "Unknown option: $1" ;;
esac
done
[[ -z "$FILE" && -z "$S3_KEY" && "$USE_LATEST" != "1" ]] && die "Specify --file, --s3-key, or --latest"
# ── Preflight ───────────────────────────────────────────────────
command -v pg_restore >/dev/null 2>&1 || command -v psql >/dev/null 2>&1 || \
die "pg_restore or psql not found — install postgresql-client"
if [[ "$USE_LATEST" == "1" || -n "$S3_KEY" ]]; then
[[ -z "$S3_ENDPOINT" ]] && die "S3_ENDPOINT not set — required for S3 restore"
command -v mc >/dev/null 2>&1 || command -v aws >/dev/null 2>&1 || \
die "Neither 'mc' (MinIO client) nor 'aws' CLI found"
fi
mkdir -p "$RESTORE_TMP"
# ── Step 1: Get the backup file ─────────────────────────────────
if [[ "$USE_LATEST" == "1" ]]; then
S3_KEY="backup/postgresql/latest.sql.gz"
fi
if [[ -n "$S3_KEY" ]]; then
log "Downloading from S3: s3://${S3_BUCKET}/${S3_KEY}"
FILE="${RESTORE_TMP}/restore-$(date -u +%Y%m%d%H%M%S).sql.gz"
if [[ "$IS_DRY_RUN" == "1" ]]; then
log "[DRY-RUN] Would download s3://${S3_BUCKET}/${S3_KEY} → $FILE"
log "[DRY-RUN] Would restore to ${PG_DB}@${PG_HOST}:${PG_PORT}"
exit 0
fi
if command -v mc >/dev/null 2>&1; then
mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 2>/dev/null
mc cp "heimdall-backup/${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3
else
aws --endpoint-url "$S3_ENDPOINT" s3 cp "s3://${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3
fi
log "Downloaded: $(du -h "$FILE" | cut -f1)"
fi
[[ ! -f "$FILE" ]] && die "Backup file not found: $FILE"
# ── Step 2: Confirm ─────────────────────────────────────────────
if [[ "$AUTO_YES" != "1" && "$IS_DRY_RUN" != "1" ]]; then
echo ""
echo "⚠️ WARNING: This will DROP and RESTORE the database '${PG_DB}'."
echo " Backup file: ${FILE}"
echo " Target: ${PG_USER}@${PG_HOST}:${PG_PORT}/${PG_DB}"
echo ""
read -rp "Type 'RESTORE' to confirm: " CONFIRM
[[ "$CONFIRM" != "RESTORE" ]] && { log "Aborted."; exit 1; }
fi
# ── Step 3: Terminate existing connections ───────────────────────
log "Terminating existing connections to ${PG_DB}..."
PGPASSWORD="$PG_PASSWORD" psql \
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d postgres \
-c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${PG_DB}' AND pid <> pg_backend_pid();" \
2>/dev/null || warn "Could not terminate connections (may be first restore)"
# ── Step 4: Drop and recreate database ──────────────────────────
log "Dropping and recreating database ${PG_DB}..."
if [[ "$IS_DRY_RUN" != "1" ]]; then
PGPASSWORD="$PG_PASSWORD" psql \
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d postgres \
-c "DROP DATABASE IF EXISTS ${PG_DB};" \
-c "CREATE DATABASE ${PG_DB} OWNER ${PG_USER};" \
2>&1 | tail -5
fi
# ── Step 5: Restore ─────────────────────────────────────────────
log "Restoring from backup..."
if [[ "$IS_DRY_RUN" != "1" ]]; then
# Try pg_restore first (for custom format dumps)
if pg_restore --version 2>/dev/null | grep -q "."; then
PGPASSWORD="$PG_PASSWORD" pg_restore \
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" \
-d "$PG_DB" \
--no-owner \
--no-privileges \
--verbose \
"$FILE" 2>&1 | tail -10 || true
else
# Fallback: psql for plain SQL dumps
gunzip -c "$FILE" | PGPASSWORD="$PG_PASSWORD" psql \
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d "$PG_DB" \
--quiet 2>&1 | tail -10
fi
fi
# ── Step 6: Verify ──────────────────────────────────────────────
log "Verifying restore..."
if [[ "$IS_DRY_RUN" != "1" ]]; then
TABLE_COUNT=$(PGPASSWORD="$PG_PASSWORD" psql \
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d "$PG_DB" \
-t -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';" \
2>/dev/null | tr -d ' ')
ROW_COUNT=$(PGPASSWORD="$PG_PASSWORD" psql \
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d "$PG_DB" \
-t -c "SELECT SUM(n_live_tup) FROM pg_stat_user_tables;" \
2>/dev/null | tr -d ' ' || echo "0")
log " Tables: ${TABLE_COUNT:-0}"
log " Rows: ${ROW_COUNT:-0}"
fi
# ── Cleanup ─────────────────────────────────────────────────────
rm -f "${RESTORE_TMP}"/*.sql.gz 2>/dev/null
rmdir "$RESTORE_TMP" 2>/dev/null || true
log "Restore complete ✓"
+235
View File
@@ -0,0 +1,235 @@
#!/usr/bin/env bash
# ─── Heimdall — Backup/Restore E2E Test ─────────────────────────
# Creates a test backup, restores it into a temporary database,
# and verifies data integrity. Uses Docker to run PostgreSQL
# independently from the main stack. All DB operations go through
# docker exec (no host psql required).
#
# Usage:
# ./test-backup-restore.sh # runs the full test
# ./test-backup-restore.sh --no-cleanup # leave test containers running
#
# Requirements:
# - Docker
# - gzip, tar (standard on Linux)
# ──────────────────────────────────────────────────────────────────
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
TEST_DB="heimdall_backup_test"
TEST_PORT=15432
TEST_USER="testbackup"
TEST_PASS="testbackup123"
CONTAINER_NAME="heimdall-pg-backup-test"
CLEANUP=1
# ── Helpers ─────────────────────────────────────────────────────
log() { echo "[backup-test] $(date -u +%H:%M:%S) $*"; }
pass() { log "✅ PASS: $*"; }
fail() { log "❌ FAIL: $*"; FAILURES=$((FAILURES + 1)); }
die() { log "FATAL: $*"; exit 1; }
# Run psql inside the test container — connect to target DB.
# After DROP/CREATE the DB name is reused so psql -d $TEST_DB reconnects.
run_sql() {
docker exec "$CONTAINER_NAME" psql -U "$TEST_USER" -d "$TEST_DB" -t -A -c "$1" 2>/dev/null
}
run_sql_raw() {
local sql_file
sql_file=$(mktemp /tmp/heimdall-test-XXXXXX.sql)
echo "$1" > "$sql_file"
docker cp "$sql_file" "${CONTAINER_NAME}:/tmp/test-query.sql"
docker exec "$CONTAINER_NAME" psql -U "$TEST_USER" -d "$TEST_DB" -f /tmp/test-query.sql 2>/dev/null
rm -f "$sql_file"
}
# Drop DB helper — connects to 'postgres' to avoid dangling session
drop_and_recreate_db() {
local sql_file
sql_file=$(mktemp /tmp/heimdall-test-XXXXXX.sql)
cat > "$sql_file" <<SQLEOF
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${TEST_DB}' AND pid <> pg_backend_pid();
DROP DATABASE IF EXISTS ${TEST_DB};
CREATE DATABASE ${TEST_DB} OWNER ${TEST_USER};
SQLEOF
docker cp "$sql_file" "${CONTAINER_NAME}:/tmp/drop-recreate.sql"
docker exec "$CONTAINER_NAME" psql -U "$TEST_USER" -d postgres -f /tmp/drop-recreate.sql >/dev/null 2>&1
rm -f "$sql_file"
}
FAILURES=0
TESTS=0
run_test() {
local name="$1"
shift
TESTS=$((TESTS + 1))
log "TEST ${TESTS}: ${name}"
if "$@"; then
pass "$name"
else
fail "$name"
fi
}
# ── Parse arguments ─────────────────────────────────────────────
for arg in "$@"; do
case "$arg" in
--no-cleanup) CLEANUP=0 ;;
esac
done
# ── Cleanup on exit ─────────────────────────────────────────────
cleanup() {
if [[ "$CLEANUP" == "1" ]]; then
log "Cleaning up test environment..."
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
docker network rm heimdall-backup-test-net 2>/dev/null || true
rm -rf "${SCRIPT_DIR}/.test-backup-tmp" 2>/dev/null
fi
}
trap cleanup EXIT
# ── Setup: Start isolated PostgreSQL ─────────────────────────────
log "Setting up isolated PostgreSQL for backup test..."
docker network create heimdall-backup-test-net 2>/dev/null || true
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
docker run -d \
--name "$CONTAINER_NAME" \
--network heimdall-backup-test-net \
-e POSTGRES_DB="$TEST_DB" \
-e POSTGRES_USER="$TEST_USER" \
-e POSTGRES_PASSWORD="$TEST_PASS" \
-p "${TEST_PORT}:5432" \
postgres:17-alpine
log "Waiting for PostgreSQL to be ready..."
for i in $(seq 1 30); do
if docker exec "$CONTAINER_NAME" pg_isready -U "$TEST_USER" >/dev/null 2>&1; then
log "PostgreSQL ready after ${i}s"
break
fi
[[ $i -eq 30 ]] && die "PostgreSQL did not start in time"
sleep 1
done
# ── Step 1: Seed test data ──────────────────────────────────────
log "Seeding test data..."
run_sql_raw "
CREATE TABLE IF NOT EXISTS sites (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS cameras (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
site_id UUID REFERENCES sites(id),
name TEXT NOT NULL,
rtsp_url TEXT,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS camera_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
camera_id UUID REFERENCES cameras(id),
event_type TEXT NOT NULL,
snapshot_url TEXT,
created_at TIMESTAMPTZ DEFAULT now()
);
INSERT INTO sites (id, name) VALUES
('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'Maison Principale'),
('b0eebc99-9c0b-4ef8-bb6d-6bb9bd380a22', 'Garage');
INSERT INTO cameras (id, site_id, name, rtsp_url) VALUES
('c0eebc99-9c0b-4ef8-bb6d-6bb9bd380a33', 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'Entrée', 'rtsp://192.168.1.100:554/stream1'),
('d0eebc99-9c0b-4ef8-bb6d-6bb9bd380a44', 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', 'Jardin', 'rtsp://192.168.1.100:554/stream2'),
('e0eebc99-9c0b-4ef8-bb6d-6bb9bd380a55', 'b0eebc99-9c0b-4ef8-bb6d-6bb9bd380a22', 'Garage Intérieur', 'rtsp://192.168.1.101:554/stream1');
INSERT INTO camera_events (camera_id, event_type, snapshot_url) VALUES
('c0eebc99-9c0b-4ef8-bb6d-6bb9bd380a33', 'motion', 'https://alarik.local/snapshots/s1.jpg'),
('c0eebc99-9c0b-4ef8-bb6d-6bb9bd380a33', 'person', 'https://alarik.local/snapshots/s2.jpg'),
('d0eebc99-9c0b-4ef8-bb6d-6bb9bd380a44', 'vehicle', 'https://alarik.local/snapshots/s3.jpg'),
('e0eebc99-9c0b-4ef8-bb6d-6bb9bd380a55', 'motion', 'https://alarik.local/snapshots/s4.jpg');
"
log "Test data seeded"
# ── Capture pre-backup counts ───────────────────────────────────
PRE_SITES=$(run_sql "SELECT COUNT(*) FROM sites;")
PRE_CAMERAS=$(run_sql "SELECT COUNT(*) FROM cameras;")
PRE_EVENTS=$(run_sql "SELECT COUNT(*) FROM camera_events;")
log "Pre-backup: ${PRE_SITES} sites, ${PRE_CAMERAS} cameras, ${PRE_EVENTS} events"
# ── Step 2: Create backup using pg_dump ─────────────────────────
TEST_BACKUP_DIR="${SCRIPT_DIR}/.test-backup-tmp"
mkdir -p "$TEST_BACKUP_DIR"
DUMP_FILE="${TEST_BACKUP_DIR}/test-backup.sql.gz"
log "Creating backup with pg_dump..."
docker exec "$CONTAINER_NAME" pg_dump \
-U "$TEST_USER" -d "$TEST_DB" \
--format=custom --compress=9 \
-f "/tmp/test-backup.sql.gz"
docker cp "${CONTAINER_NAME}:/tmp/test-backup.sql.gz" "$DUMP_FILE"
docker exec "$CONTAINER_NAME" rm -f /tmp/test-backup.sql.gz
[[ -f "$DUMP_FILE" ]] || die "Backup file not created"
DUMP_SIZE=$(du -h "$DUMP_FILE" | cut -f1)
log "Backup created: ${DUMP_SIZE}"
run_test "Backup file exists and is non-empty" test -s "$DUMP_FILE"
# ── Step 3: Drop and recreate database ──────────────────────────
log "Dropping and recreating test database..."
drop_and_recreate_db
# Verify empty
EMPTY_TABLES=$(run_sql "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';")
run_test "Database is empty after drop" test "$EMPTY_TABLES" -eq 0
# ── Step 4: Restore from backup ─────────────────────────────────
log "Restoring from backup..."
docker cp "$DUMP_FILE" "${CONTAINER_NAME}:/tmp/restore-dump.sql.gz"
docker exec "$CONTAINER_NAME" pg_restore \
-U "$TEST_USER" -d "$TEST_DB" \
--no-owner --no-privileges \
/tmp/restore-dump.sql.gz 2>&1 | tail -5 || true
docker exec "$CONTAINER_NAME" rm -f /tmp/restore-dump.sql.gz
# ── Step 5: Verify restored data ────────────────────────────────
POST_SITES=$(run_sql "SELECT COUNT(*) FROM sites;")
POST_CAMERAS=$(run_sql "SELECT COUNT(*) FROM cameras;")
POST_EVENTS=$(run_sql "SELECT COUNT(*) FROM camera_events;")
log "Post-restore: ${POST_SITES} sites, ${POST_CAMERAS} cameras, ${POST_EVENTS} events"
run_test "Site count matches" test "$POST_SITES" -eq "$PRE_SITES"
run_test "Camera count matches" test "$POST_CAMERAS" -eq "$PRE_CAMERAS"
run_test "Event count matches" test "$POST_EVENTS" -eq "$PRE_EVENTS"
# ── Step 6: Verify specific data integrity ──────────────────────
SITE_NAME=$(run_sql "SELECT name FROM sites WHERE id = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11';")
run_test "Site name preserved" test "$SITE_NAME" = "Maison Principale"
CAMERA_RTSP=$(run_sql "SELECT rtsp_url FROM cameras WHERE name = 'Entrée';")
run_test "Camera RTSP URL preserved" test "$CAMERA_RTSP" = "rtsp://192.168.1.100:554/stream1"
FK_VIOLATIONS=$(run_sql "
SELECT COUNT(*) FROM camera_events e
WHERE NOT EXISTS (SELECT 1 FROM cameras c WHERE c.id = e.camera_id);
")
run_test "No FK violations in restored data" test "$FK_VIOLATIONS" -eq 0
# ── Summary ─────────────────────────────────────────────────────
echo ""
log "═══════════════════════════════════════════"
log " Test Results: $((TESTS - FAILURES))/${TESTS} passed"
log "═══════════════════════════════════════════"
if [[ $FAILURES -gt 0 ]]; then
log "Some tests FAILED ❌"
exit 1
else
log "All tests PASSED ✅"
exit 0
fi