#!/bin/bash # Thor production deploy, run by the webhook listener on CT 173 (through sudo). # # Source of truth: deploy/thor_deploy.sh in the Thor repo. # Installed copy: /usr/local/bin/thor_deploy.sh (root:root 0755; reinstall it by hand # when this file changes, like Pulse's deploy script). # # Usage: thor_deploy.sh # sha full 40-char commit CI tested; must be on origin/main # ts unix time CI signed the request at # Both come from the HMAC-signed webhook payload. The timestamp makes every signature # unique, so stale or replayed requests are refused. # # Deploys exactly (code, Python dependencies, systemd units, nginx site), then waits # for /health to report that sha with a working database. Otherwise it rolls back. set -euo pipefail # Overridable only so tests can run the script in a sandbox. APP_ROOT=${THOR_DEPLOY_APP_ROOT:-/opt/thor/app} VENV=${THOR_DEPLOY_VENV:-/opt/thor/venv} REVISION_FILE=${THOR_DEPLOY_REVISION_FILE:-/opt/thor/revision.env} STATE_DIR=${THOR_DEPLOY_STATE_DIR:-/var/lib/thor-deploy} LOG=${THOR_DEPLOY_LOG:-/var/log/thor-deploy.log} LOCK=${THOR_DEPLOY_LOCK:-/run/thor-deploy.lock} HEALTH_URL=${THOR_DEPLOY_HEALTH_URL:-http://127.0.0.1:8000/health} SYSTEMD_DIR=${THOR_DEPLOY_SYSTEMD_DIR:-/etc/systemd/system} NGINX_SITE=${THOR_DEPLOY_NGINX_SITE:-/etc/nginx/sites-enabled/thor} BRANCH=main MAX_AGE_S=300 HEALTH_TRIES=${THOR_DEPLOY_HEALTH_TRIES:-45} log() { echo "$(date '+%F %T') [thor-deploy] $*" | tee -a "$LOG"; } fail() { log "REFUSED: $*"; exit 1; } SHA="${1:-}" TS="${2:-}" 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)" 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) # Copy a tracked file into place only when it differs. Prints 1 when it changed. place() { local src="$1" dst="$2" if [ -f "$dst" ] && cmp -s "$src" "$dst"; then echo 0; return; fi install -m 0644 -o root -g root "$src" "$dst" echo 1 } deploy_to() { local sha="$1" units=0 site=0 git checkout --quiet --force --detach "$sha" || { log "checkout of $sha failed"; return 1; } "$VENV/bin/pip" install --quiet --disable-pip-version-check -r requirements.txt >>"$LOG" 2>&1 \ || { log "pip install failed for $sha"; return 1; } for unit in thor.service thor-monitor.service; do units=$(( units + $(place "deploy/systemd/$unit" "$SYSTEMD_DIR/$unit") )) done site=$(place deploy/nginx/thor "$NGINX_SITE") if (( units > 0 )); then systemctl daemon-reload; fi if (( site > 0 )); then nginx -t >>"$LOG" 2>&1 || { log "nginx config invalid for $sha"; return 1; } systemctl reload nginx fi printf 'THOR_SHA=%s\n' "$sha" > "$REVISION_FILE" chmod 0644 "$REVISION_FILE" systemctl restart thor thor-monitor || { log "restart failed for $sha"; return 1; } } # Healthy means: /health answers with this sha and a working database. The monitor may # still be on its first cycle (503 "no good cycle yet"), which is fine for a deploy. healthy() { 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: d = json.loads(sys.stdin.read()) except ValueError: sys.exit(1) sys.exit(0 if d.get("sha") == os.environ["WANT"] and d.get("db") is True else 1)' <<<"$body" \ && systemctl is-active --quiet thor-monitor; then return 0 fi sleep "${THOR_DEPLOY_HEALTH_SLEEP:-2}" done log "last /health reply: ${body:-none}" 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 thor -u thor-monitor" fi exit 1