#!/usr/bin/env bash # Deploy the companion: serving tiers first, then code, then restart. # # There was no script for this, only a host in somebody's shell history and two # helper scripts loose on the server, and the gap showed. The deployed checkout # had drifted fourteen commits behind, and start-herbarium.sh still named # explorer:app after a3e6f4c had turned explorer/ into apps/companion/ -- so the # next restart would have failed with the old process already killed. The # restart script lives in the repo now (scripts/restart_server.sh) so the WSGI # target cannot drift from the module again, and this checks the app imports # before it stops anything. # # scripts/deploy.sh # tiers, then code # scripts/deploy.sh --dry-run # say what would happen, touch nothing # scripts/deploy.sh --no-data # code only, leave the tiers alone # # Everything is overridable, so this is not welded to one machine: # DEPLOY_HOST=root@1.2.3.4 DEPLOY_DIR=/srv/app scripts/deploy.sh set -euo pipefail # As deploy, never root. Nothing here needs privilege: the ports are above # 1024, every file the app reads or writes is deploy-owned, and the service is # a systemd USER unit, so the restart needs no sudoers rule either. Running the # app as root meant any bug that got code execution got it as root on a box # that fronts other things. HOST=${DEPLOY_HOST:-deploy@178.156.219.133} KEY=${DEPLOY_KEY:-$HOME/.ssh/proteus-softworks-github-deploy} DIR=${DEPLOY_DIR:-/home/deploy/herbarium} BRANCH=${DEPLOY_BRANCH:-main} HEALTH=${DEPLOY_HEALTH:-http://127.0.0.1:8000/} UV=${DEPLOY_UV:-/home/deploy/.local/bin/uv} WAIT=${DEPLOY_WAIT:-45} # seconds to give the app to answer # The serving tiers are not in git -- scripts/build_tiers.py makes them and they # are what the app actually reads. They go up with the code because they are one # release: the trait explorer is a query against a plant_traits table that only # exists in a tier built after it, and shipping either half alone gives you a # page that renders empty rather than one that fails. TIERS=${DEPLOY_TIERS:-data/tiers} TIER_DIR=${DEPLOY_TIER_DIR:-/home/deploy/herbarium-data/tiers} DRY=0 DATA=1 for arg in "$@"; do case "$arg" in --dry-run) DRY=1 ;; --no-data) DATA=0 ;; *) echo "unknown flag: $arg" >&2; exit 2 ;; esac done SSH=(ssh -o BatchMode=yes) [ -f "$KEY" ] && SSH+=(-i "$KEY") say() { printf '\033[1m==>\033[0m %s\n' "$*"; } die() { printf '\033[31mdeploy failed:\033[0m %s\n' "$*" >&2; exit 1; } # --- deploy what is pushed, not what is lying around ------------------------ # The server pulls from the git remote, so anything not on the remote is not # going to be deployed however good it looks locally. [ -n "$(git status --porcelain)" ] && die "working tree is dirty; commit or stash first" git fetch --quiet origin "$BRANCH" || die "cannot reach the git remote" head=$(git rev-parse HEAD) remote_head=$(git rev-parse "origin/$BRANCH") [ "$head" = "$remote_head" ] || die "HEAD is not origin/$BRANCH -- push first (local ${head:0:7}, remote ${remote_head:0:7})" say "deploying ${remote_head:0:7} to $HOST:$DIR" was=$("${SSH[@]}" "$HOST" "cd $DIR && git rev-parse HEAD") || die "cannot read the deployed commit" if [ "$was" = "$remote_head" ]; then say "code already at ${was:0:7}" else say "code is at ${was:0:7}, $(git rev-list --count "$was..$remote_head" 2>/dev/null || echo '?') commits behind" fi # --- the tiers -------------------------------------------------------------- # Only *.sqlite, so a local build artefact like cells.parquet does not go up. # No --delete, because the destination holds .prev files from earlier deploys # and this is not the thing that should decide to remove them. # # --backup --suffix=.prev keeps the file being replaced, matching the # cell.sqlite.prev already on the box; the disk is 38G against 727M of tiers. # # NOT --inplace, and that is the whole reason this is safe to run against a # live server: rsync writes a temp file and renames it, so gunicorn keeps # reading the inode it already has open until the restart below swaps it. # # --no-owner --no-group: plain -a over ssh preserves the LOCAL owner, which as # root landed every tier owned by uid 501 -- my laptop account, which is nobody # on that box. As deploy it cannot chown at all, so dropping the flags is both # the fix and the only thing that works; files come out owned by deploy because # that is who wrote them. RSYNC_FLAGS=(-a --no-owner --no-group --info=progress2 --human-readable --include='*.sqlite' --exclude='*' --backup --suffix=.prev) if [ "$DATA" = 1 ]; then [ -d "$TIERS" ] || die "no local tiers at $TIERS -- run scripts/build_tiers.py" if [ "$DRY" = 1 ]; then say "tiers that would be copied ($TIERS -> $HOST:$TIER_DIR):" rsync -n --itemize-changes -e "${SSH[*]}" "${RSYNC_FLAGS[@]}" \ "$TIERS/" "$HOST:$TIER_DIR/" | sed 's/^/ /' else say "copying tiers to $HOST:$TIER_DIR" rsync -e "${SSH[*]}" "${RSYNC_FLAGS[@]}" "$TIERS/" "$HOST:$TIER_DIR/" || die "tier copy failed -- nothing restarted, the server is still serving the old ones" fi else say "skipping tiers (--no-data)" fi if [ "$DRY" = 1 ]; then [ "$was" = "$remote_head" ] || git log --oneline "$was..$remote_head" 2>/dev/null | sed 's/^/ /' say "dry run -- stopping here" exit 0 fi # --- pull, prove it loads, restart, prove it answers ------------------------ # One ssh, because a rollback has to happen on the box: splitting this across # several would leave a half-deployed checkout if the connection dropped. "${SSH[@]}" "$HOST" "bash -euo pipefail -s" </dev/null || true ./scripts/restart_server.sh echo "--- code rolled back. Tiers were NOT reverted: the .prev files beside" echo " them are the previous ones if you want them back." } # Plain git: we ARE the user that owns the checkout now, so there is nothing to # sudo to and nothing left behind for the next deploy to trip on. git fetch --quiet origin "$BRANCH" git reset --hard "origin/$BRANCH" --quiet echo "--- now at \$(git rev-parse --short HEAD) \$(git log -1 --format=%s)" # Dependencies before the import check, or a new one reads as broken code. if [ -x "$UV" ]; then "$UV" sync --frozen --quiet || { roll_back; exit 1; } fi # The check that would have caught the explorer:app trap. Ask Python whether # the target still resolves while the old process is still up and serving, # rather than finding out from gunicorn once it is dead. # Read out of restart_server.sh rather than repeated here, so the name this # checks and the name that gets served cannot disagree -- which is the exact # failure being guarded against. target=\$(grep -oE 'APP_MODULE:-[^}]+' ./scripts/restart_server.sh | head -1 | cut -d- -f2-) [ -n "\$target" ] || { echo "cannot read APP_MODULE from scripts/restart_server.sh"; roll_back; exit 1; } echo "--- entrypoint: \$target" .venv/bin/python -c " import sys mod, _, attr = sys.argv[1].partition(':') getattr(__import__(mod, fromlist=[attr]), attr) print('--- imports clean') " "\$target" || { echo "!!! \$target does not import -- not restarting"; roll_back; exit 1; } # And that the tiers we just copied are readable SQLite, not half a file. .venv/bin/python -c " import glob, sqlite3, sys for path in sorted(glob.glob(sys.argv[1] + '/*.sqlite')): sqlite3.connect('file:%s?mode=ro' % path, uri=True).execute('pragma schema_version').fetchone() print('--- tiers open cleanly') " "$TIER_DIR" || { echo "!!! a tier will not open"; roll_back; exit 1; } chmod +x ./scripts/restart_server.sh ./scripts/restart_server.sh # Up, or put the old one back. A restart that returns without the app # answering is the failure this is here to catch. for i in \$(seq 1 $WAIT); do code=\$(curl -s -o /dev/null -w '%{http_code}' --max-time 3 "$HEALTH" || true) if [ "\$code" = "200" ]; then echo "--- healthy after \${i}s (HTTP 200)"; exit 0; fi sleep 1 done echo "!!! no 200 from $HEALTH after ${WAIT}s" tail -20 /home/deploy/herbarium.log 2>/dev/null || true roll_back exit 1 REMOTE say "deployed ${remote_head:0:7}"