#!/bin/bash # Gandalf production deploy (gandalf#55 part 2), run by the webhook listener on CT 157. # # Source of truth: deploy/gandalf_deploy.sh in the Gandalf repo. # Installed copy: /usr/local/bin/gandalf_app_deploy.sh (see README "Deploys"). The webhook # runs the installed copy, so a bad commit can't replace the code that rolls it back. # # Usage: gandalf_app_deploy.sh # sha full 40-character commit CI tested; must be on origin/main # ts unix time CI signed the request at # Both come from the HMAC-signed webhook payload, so they can't be altered. The timestamp # makes every signature unique: stale or replayed requests are refused. # # Deploys exactly , then waits for /health to report that sha for the web app and the # monitor with status ok. Otherwise it rolls back to the previous commit. set -euo pipefail # Overridable only so tests can run the script in a sandbox. APP_ROOT=${GANDALF_DEPLOY_APP_ROOT:-/var/www/html/prod} BRANCH=main STATE_DIR=${GANDALF_DEPLOY_STATE_DIR:-/var/lib/gandalf-deploy} LOG=${GANDALF_DEPLOY_LOG:-/var/log/gandalf-app-deploy.log} LOCK=${GANDALF_DEPLOY_LOCK:-/run/gandalf-deploy.lock} HEALTH_URL=${GANDALF_DEPLOY_HEALTH_URL:-http://127.0.0.1:8000/health} MAX_AGE_S=300 # refuse requests signed more than 5 minutes ago HEALTH_TRIES=${GANDALF_DEPLOY_HEALTH_TRIES:-60} # x 2 s = 2 minutes for both services to report log() { echo "$(date '+%F %T') [gandalf-deploy] $*" | tee -a "$LOG"; } fail() { log "REFUSED: $*"; exit 1; } SHA="${1:-}" TS="${2:-}" # One deploy at a time (CI also queues deploys; this covers manual runs). exec 9>"$LOCK" flock -w 600 9 || fail "timed out waiting for another deploy" [[ "$SHA" =~ ^[0-9a-f]{40}$ ]] || fail "missing or invalid sha" [[ "$TS" =~ ^[0-9]+$ ]] || fail "missing or invalid timestamp" now=$(date +%s) age=$(( now - TS )) (( age >= -60 && age <= MAX_AGE_S )) || fail "request is ${age}s old (limit ${MAX_AGE_S}s)" mkdir -p "$STATE_DIR" chmod 700 "$STATE_DIR" last_ts=$(cat "$STATE_DIR/last_ts" 2>/dev/null || echo 0) (( TS > last_ts )) || fail "timestamp $TS is not newer than the last accepted request ($last_ts): replay or out of order" echo "$TS" > "$STATE_DIR/last_ts" cd "$APP_ROOT" git fetch --quiet origin "$BRANCH" git cat-file -e "${SHA}^{commit}" 2>/dev/null || fail "commit $SHA not found after fetch" git merge-base --is-ancestor "$SHA" "origin/$BRANCH" || fail "commit $SHA is not on $BRANCH" PREV=$(git rev-parse HEAD) deploy_to() { # config.json and the logs are untracked, so a forced checkout leaves them alone. # Explicit returns: `set -e` does not apply inside a function used in an `if`. git checkout --quiet --force --detach "$1" || { log "checkout of $1 failed"; return 1; } pip3 install -r requirements.txt --break-system-packages --quiet >>"$LOG" 2>&1 \ || { log "pip install failed for $1"; return 1; } systemctl restart gandalf gandalf-monitor || { log "restart failed for $1"; return 1; } } healthy() { # /health answers 503 until the monitor has checked in, so read the body whatever the code. local want="$1" body for _ in $(seq 1 "$HEALTH_TRIES"); do body=$(curl -sS --max-time 3 "$HEALTH_URL" 2>/dev/null || true) if WANT="$want" python3 -c ' import json, os, sys try: b = json.loads(sys.stdin.read()) except ValueError: sys.exit(1) w = os.environ["WANT"] sys.exit(0 if b.get("status") == "ok" and b.get("sha") == w and b.get("monitor_sha") == w else 1) ' <<<"$body"; then return 0 fi sleep "${GANDALF_DEPLOY_HEALTH_SLEEP:-2}" done log "last /health: ${body:-no response}" return 1 } if [ "$PREV" = "$SHA" ] && healthy "$SHA"; then log "already running $SHA and healthy; nothing to do" exit 0 fi log "deploying $SHA (previous $PREV)" if deploy_to "$SHA" && healthy "$SHA"; then echo "$SHA" > "$STATE_DIR/current" log "deployed $SHA: healthy" exit 0 fi log "FAILED: $SHA did not become healthy; rolling back to $PREV" if deploy_to "$PREV" && healthy "$PREV"; then log "rolled back to $PREV: healthy" else log "ROLLBACK FAILED: check journalctl -u gandalf -u gandalf-monitor" fi exit 1