Files

198 lines
8.2 KiB
Bash
Raw Permalink Normal View History

#!/usr/bin/env bash
set -Eeuo pipefail
project="heimdall-migration-$(date -u +%Y%m%d%H%M%S)-$(openssl rand -hex 4)"
temp_dir="$(mktemp -d "${TMPDIR:-/tmp}/${project}.XXXXXX")"
env_file="$temp_dir/acceptance.env"
compose_override="$temp_dir/compose.override.yml"
failure_override="$temp_dir/compose.failure.yml"
recovery_override="$temp_dir/compose.recovery.yml"
compose_file="$(git rev-parse --show-toplevel)/docker/docker-compose.yml"
local_image_tags=("heimdall:${project}-central")
web_port="$(python3 - <<'PY'
import socket
s = socket.socket()
s.bind(('127.0.0.1', 0))
print(s.getsockname()[1])
s.close()
PY
)"
db_name="${project//-/_}"
db_user="migration_owner_${project//-/_}"
db_password="$(openssl rand -hex 24)"
probe_password="$(openssl rand -hex 24)"
jwt_key="$(openssl rand -base64 48 | tr -d '\n')"
jwt_refresh_key="$(openssl rand -base64 48 | tr -d '\n')"
cat > "$env_file" <<EOF
POSTGRES_DB=$db_name
POSTGRES_USER=$db_user
POSTGRES_PASSWORD=$db_password
DATABASE_URL=Host=postgresql;Port=5432;Database=$db_name;Username=$db_user;Password=$db_password
JWT__KEY=$jwt_key
JWT__REFRESHKEY=$jwt_refresh_key
JWT__ISSUER=$project
JWT__AUDIENCE=$project
ASPNETCORE_ENVIRONMENT=Development
Sentry__Dsn=
SENTRY_DSN=
WEB_PORT=$web_port
HEIMDALL_NETWORK_NAME=${project}_net
ACCEPTANCE_PROJECT=$project
MIGRATION_PROBE_PASSWORD=$probe_password
EOF
chmod 600 "$env_file"
cat > "$compose_override" <<'EOF'
services:
postgresql:
ports: !override []
heimdall:
image: heimdall:${ACCEPTANCE_PROJECT}-central
ports: !override
- "127.0.0.1:${WEB_PORT}:8080"
EOF
cat > "$failure_override" <<'EOF'
services:
heimdall:
environment:
DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD}
restart: "no"
EOF
cat > "$recovery_override" <<'EOF'
services:
heimdall:
environment:
DATABASE_URL: Host=postgresql;Port=5432;Database=${POSTGRES_DB};Username=migration_probe;Password=${MIGRATION_PROBE_PASSWORD}
restart: "no"
EOF
cleanup() {
status=$?
trap - EXIT
cleanup_failed=0
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" down --volumes --remove-orphans || cleanup_failed=1
containers="$(docker ps -aq --filter "label=com.docker.compose.project=$project")" || cleanup_failed=1
volumes="$(docker volume ls -q --filter "label=com.docker.compose.project=$project")" || cleanup_failed=1
networks="$(docker network ls -q --filter "label=com.docker.compose.project=$project")" || cleanup_failed=1
[[ -z "$containers" && -z "$volumes" && -z "$networks" ]] || cleanup_failed=1
for tag in "${local_image_tags[@]}"; do
docker image rm "$tag" >/dev/null 2>&1 || true
docker image inspect "$tag" >/dev/null 2>&1 && cleanup_failed=1
done
python3 - "$env_file" "$compose_override" "$failure_override" "$recovery_override" <<'PY' || cleanup_failed=1
import pathlib
import sys
for name in sys.argv[1:]:
pathlib.Path(name).unlink(missing_ok=True)
PY
rmdir -- "$temp_dir" || cleanup_failed=1
if (( cleanup_failed )); then
printf 'Disposable migration recipe cleanup failed for project %s\n' "$project" >&2
status=1
else
printf 'Cleanup verified: project containers/volumes/network and exact tag absent (%s).\n' "${local_image_tags[*]}"
fi
exit "$status"
}
trap cleanup EXIT
for tag in "${local_image_tags[@]}"; do
if docker image inspect "$tag" >/dev/null 2>&1; then
printf 'Unique acceptance image tag already exists: %s\n' "$tag" >&2
exit 1
fi
done
compose() {
docker compose -p "$project" --env-file "$env_file" -f "$compose_file" -f "$compose_override" "$@"
}
compose config --quiet
compose up -d --build
base_url="http://127.0.0.1:$web_port"
wait_healthy() {
for attempt in $(seq 1 120); do
if curl --fail --silent "$base_url/healthz" -o /dev/null; then return 0; fi
sleep 2
done
return 1
}
wait_healthy || { echo 'Central did not become healthy after first migration.' >&2; exit 1; }
echo 'First boot: PostgreSQL fresh schema migrated; Central healthz returned HTTP 200.'
compose restart heimdall
wait_healthy || { echo 'Central did not recover against the migrated database.' >&2; exit 1; }
echo 'Restart: Central healthz returned HTTP 200 on the migrated schema.'
postgres_container="$(compose ps -q postgresql)"
[[ -n "$postgres_container" ]] || { echo 'PostgreSQL container was not found.' >&2; exit 1; }
docker exec -i "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \
-v probe_password="$probe_password" <<'SQL'
CREATE ROLE migration_probe LOGIN PASSWORD :'probe_password';
SELECT format('GRANT CONNECT ON DATABASE %I TO migration_probe', current_database()) \gexec
GRANT USAGE ON SCHEMA public TO migration_probe;
GRANT CREATE ON SCHEMA public TO migration_probe;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO migration_probe;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO migration_probe;
GRANT USAGE, CREATE ON SCHEMA hangfire TO migration_probe;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA hangfire TO migration_probe;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA hangfire TO migration_probe;
REVOKE SELECT ON TABLE public."__EFMigrationsHistory" FROM migration_probe;
SQL
compose -f "$failure_override" up -d --force-recreate heimdall
web_container="$(compose -f "$failure_override" ps -q heimdall)"
[[ -n "$web_container" ]] || { echo 'Central failure-test container was not found.' >&2; exit 1; }
failure_state=""
for attempt in $(seq 1 90); do
failure_state="$(docker inspect -f '{{.State.Status}}' "$web_container" 2>/dev/null || true)"
[[ "$failure_state" == exited ]] && break
sleep 1
done
[[ "$failure_state" == exited ]] || { echo 'Central did not exit on a permanent migration permission failure.' >&2; exit 1; }
failure_exit_code="$(docker inspect -f '{{.State.ExitCode}}' "$web_container")"
[[ "$failure_exit_code" != 0 ]] || { echo 'Central exited successfully despite the permanent migration failure.' >&2; exit 1; }
failure_logs="$(docker logs "$web_container" 2>&1)"
application_logs="$(grep -E 'Applying database migrations \(attempt|Database migration attempt .* failed|Failed to apply database migrations after 5 attempts|Database migrations applied successfully|permission denied' <<<"$failure_logs" | grep -v 'HttpTransport: Envelope')"
attempt_count="$(grep -c 'Applying database migrations (attempt' <<<"$application_logs" || true)"
retry_count="$(grep -c 'Database migration attempt .* failed' <<<"$application_logs" || true)"
terminal_count="$(grep -c 'Failed to apply database migrations after 5 attempts' <<<"$application_logs" || true)"
success_count="$(grep -c 'Database migrations applied successfully' <<<"$application_logs" || true)"
[[ "$attempt_count" -eq 5 && "$retry_count" -eq 4 && "$terminal_count" -eq 1 && "$success_count" -eq 0 ]] || {
printf 'Retry log counts: attempts=%s retries=%s terminal=%s successes=%s\n' \
"$attempt_count" "$retry_count" "$terminal_count" "$success_count" >&2
grep -E 'Applying database migrations \(attempt|Database migration attempt|Failed to apply database migrations|Database migrations applied successfully' \
<<<"$application_logs" | cut -c1-240 >&2 || true
echo 'Permanent failure did not show five attempts, four retries, one terminal failure, and zero success logs.' >&2
exit 1
}
grep -qi 'permission denied' <<<"$application_logs" || {
echo 'The synthetic failure did not report the expected history-table permission denial.' >&2
exit 1
}
echo 'Permanent failure: permission denied on migration history; five attempts, four retries, final Critical error, nonzero exit, no migration-success log.'
docker exec "$postgres_container" psql -v ON_ERROR_STOP=1 -U "$db_user" -d "$db_name" \
-c 'GRANT SELECT ON TABLE public."__EFMigrationsHistory" TO migration_probe;' >/dev/null
compose -f "$recovery_override" up -d --force-recreate heimdall
wait_healthy || {
echo 'Central did not recover after granting migration-history access.' >&2
docker logs "$(compose -f "$recovery_override" ps -q heimdall)" 2>&1 \
| grep -Ei 'failed|error|permission denied|database migration|migration.*success' \
| grep -v 'HttpTransport: Envelope' | cut -c1-240 | tail -n 20 >&2 || true
exit 1
}
echo 'Recovery: granting history-table SELECT allowed startup; Central healthz returned HTTP 200.'