#!/usr/bin/env bash # ─── Heimdall — PostgreSQL Restore from Backup ─────────────────── # Downloads a backup from RustFS/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="${RUSTFS_ENDPOINT:-${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}}" S3_ACCESS_KEY="${RUSTFS_ACCESS_KEY:-${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}}" S3_SECRET_KEY="${RUSTFS_SECRET_KEY:-${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}}" S3_BUCKET="${RUSTFS_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 </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" # Validate the backup before confirming or changing the target database. if pg_restore --list "$FILE" >/dev/null 2>&1; then RESTORE_FORMAT="custom" else gzip -t "$FILE" >/dev/null 2>&1 || die "Backup is not a valid PostgreSQL custom dump or gzip-compressed SQL file" SQL_HEADER="$(gunzip -c "$FILE" | sed -n '1,5p')" grep -qE '^(-- PostgreSQL|SET |CREATE |SELECT )' <<<"$SQL_HEADER" \ || die "Backup is not a valid PostgreSQL custom dump or gzip-compressed SQL file" RESTORE_FORMAT="plain" fi # ── 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 ─────────────────────── if [[ "$IS_DRY_RUN" != "1" ]]; then 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)" fi # ── 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 if [[ "$RESTORE_FORMAT" == "custom" ]]; 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 else 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 ✓"