Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189#!/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.shset -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=0DATA=1for arg in "$@"; do case "$arg" in --dry-run) DRY=1 ;; --no-data) DATA=0 ;; *) echo "unknown flag: $arg" >&2; exit 2 ;; esacdone
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" fielse 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 0fi
# --- 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" <<REMOTE || die "see the output above"set -euo pipefailcd "$DIR"
roll_back() { echo "--- rolling back code to ${was:0:7}" git reset --hard "$was" --quiet "$UV" sync --frozen --quiet 2>/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" --quietecho "--- 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 sysmod, _, 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, sysfor 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 1doneecho "!!! no 200 from $HEALTH after ${WAIT}s"tail -20 /home/deploy/herbarium.log 2>/dev/null || trueroll_backexit 1REMOTE
say "deployed ${remote_head:0:7}"