Files
spark 4eac0e6f95
ci / rust (push) Successful in 3m51s
ci / typescript (push) Successful in 7m22s
fix(infra): serialize pm2 startOrReload between boot.sh and deploy.sh
Live incident 2026-10-19: node09 rebooted and photoreport-boot.service ran
twice concurrently against a freshly-spawned, still-empty PM2 daemon. Both
invocations saw "not running" and launched photoreport-api, creating a
duplicate that crash-looped forever on EADDRINUSE (1700+ restarts by the
time it was caught, silently -- the original instance kept serving so
/health never flagged it). Deleted the ghost process and re-saved live.

Wrap the pm2 startOrReload calls in both scripts with the same flock so a
boot racing a webhook-triggered deploy (or a double-invoked boot unit)
serializes instead of racing the "is it running" check.

Paperclip-Issue: BIT-31073
Paperclip-Run: 9c6946f6-df0c-4544-97ac-6b00a2de8bd1
2026-10-19 10:05:23 +01:00

178 lines
7.1 KiB
Bash
Executable File

#!/usr/bin/env bash
# Deploys one PhotoReport service at a given commit, on the container that runs it.
# Called by the deploy receiver: deploy.sh <service> <sha>
# Rules (docs/DEPLOY.md): never touch .env files or data; migrations only move forward;
# a failed health check rolls the code back to the previous commit and reloads it.
set -Eeuo pipefail
SERVICE="${1:?usage: deploy.sh <api|app|site|workers|ml> <sha>}"
SHA="${2:?usage: deploy.sh <service> <sha>}"
REPO_DIR="${DEPLOY_REPO_DIR:-/srv/photoreport}"
BRANCH="${DEPLOY_BRANCH:-main}"
API_PORT="${API_PORT:-3000}"
WEB_ROOT="${DEPLOY_WEB_ROOT:-/var/www/photoreport-app}"
HEALTH_TRIES="${DEPLOY_HEALTH_TRIES:-30}"
log() { printf '[%s] %s\n' "$(date -u +%FT%TZ)" "$*"; }
die() { log "ERROR: $*"; exit 1; }
[[ "$SHA" =~ ^[0-9a-f]{40}$ ]] || die "invalid sha: $SHA"
# pnpm needs $TMPDIR to exist; on these containers it is under /tmp, which a reboot empties.
[[ -n "${TMPDIR:-}" ]] && mkdir -p "$TMPDIR" && chmod 700 "$TMPDIR"
cd "$REPO_DIR"
# Keep a copy of every .env before touching anything (norm BIT-25005). Deploys never write them.
backup_env() {
while IFS= read -r -d '' f; do cp -p "$f" "$f.bak.deploy"; done \
< <(find . -name .env -not -path './node_modules/*' -print0)
}
checkout() {
local target="$1"
git fetch --quiet origin "$BRANCH"
git merge-base --is-ancestor "$target" "origin/$BRANCH" || die "$target is not on origin/$BRANCH"
git reset --quiet --hard "$target"
}
node_install() { pnpm install --frozen-lockfile --prefer-offline; }
wait_for_version() {
local url="$1" want="$2" i
for ((i = 1; i <= HEALTH_TRIES; i++)); do
if curl -fsS --max-time 3 "$url" 2>/dev/null | grep -q "\"version\":\"$want\""; then return 0; fi
sleep 2
done
return 1
}
deploy_api() {
local sha="$1"
node_install
pnpm --filter "@photoreport/api..." build
# prisma.config.ts reads DATABASE_URL from process.env with no fallback .env loading,
# unlike the app itself (started with `node --env-file=.env`), so the CLI needs it sourced.
(cd apps/api && set -a && . ./.env && set +a && pnpm exec prisma migrate deploy)
# The background worker's Rust engines (faces, render) and the face models. The worker finds them by itself
# (target/release, <data>/models) when apps/api/.env doesn't name them. Failures warn; the API still deploys.
if ensure_rust; then
cargo build --release --locked -p photoreport-faces -p photoreport-render || log "WARNING: face/render engines failed to build"
else
log "WARNING: no Rust toolchain: face analysis and edited renders stay off"
fi
bash infra/faces/download-models.sh "${MODELS_DIR:-/srv/photoreport-data/models}" || log "WARNING: face models could not be downloaded"
# Same lock as boot.sh: a reboot racing this deploy's pm2 call against a freshly-spawned, still-empty PM2
# daemon duplicated photoreport-api on 2026-10-19 (crash-looped on EADDRINUSE forever). Serialize instead.
( exec 9>/run/photoreport-pm2.lock; flock 9
APP_VERSION="$sha" pm2 startOrReload infra/pm2/api.config.cjs --update-env
)
wait_for_version "http://127.0.0.1:${API_PORT}/health" "$sha"
# The process list PM2 restores after a reboot follows every deploy (photoreport-boot.service starts it too).
pm2 save --force >/dev/null
}
# Rust in the deploy user's home (no root): installed the first time, then only put on PATH (systemd's PATH
# doesn't include ~/.cargo/bin).
ensure_rust() {
export PATH="$HOME/.cargo/bin:$PATH"
command -v cargo >/dev/null 2>&1 && return 0
log "installing the Rust toolchain (once)"
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --no-modify-path >/dev/null
}
# Rust + wasm32 target + the wasm-bindgen CLI the engine pins, in the deploy user's home (no root, no system
# packages). Idempotent: after the first run it only checks versions.
ensure_wasm_toolchain() {
ensure_rust || return 1
rustup target list --installed 2>/dev/null | grep -qx wasm32-unknown-unknown || rustup target add wasm32-unknown-unknown || return 1
local want have
want="$(sed -n 's/^wasm-bindgen = "=\(.*\)"/\1/p' engine/wasm/Cargo.toml)"
have="$(wasm-bindgen --version 2>/dev/null | awk '{print $2}')"
if [[ "$have" != "$want" ]]; then
log "installing wasm-bindgen-cli $want (once)"
cargo install wasm-bindgen-cli --version "$want" --locked >/dev/null || return 1
fi
}
deploy_app() {
local sha="$1" release="$WEB_ROOT/releases/$1"
node_install
rm -rf apps/app/dist # never publish a stale build
# The develop module's engine (WASM). The toolchain installs itself the first time (a few minutes, once). If that
# fails, the app still deploys and Revelar says the engine is missing.
if ensure_wasm_toolchain; then
infra/engine/build-wasm.sh || log "WARNING: the develop engine did not build"
else
log "WARNING: no Rust/wasm toolchain (needs curl and a C compiler): the develop engine is not built"
fi
VITE_APP_VERSION="$sha" pnpm --filter "@photoreport/app..." build
mkdir -p "$release"
cp -a apps/app/dist/. "$release/"
# The web server runs as another user: everything published must be world-readable (the engine too).
chmod -R a+rX "$release"
ln -sfn "$release" "$WEB_ROOT/current.tmp" && mv -Tf "$WEB_ROOT/current.tmp" "$WEB_ROOT/current"
[[ -f "$WEB_ROOT/current/index.html" ]]
# Keep the last 5 releases.
ls -1dt "$WEB_ROOT"/releases/* 2>/dev/null | tail -n +6 | xargs -r rm -rf
}
deploy_site() {
local sha="$1"
node_install
rm -rf apps/site/.next
pnpm --filter "@photoreport/site..." build
# site.config.cjs reads API_URL from process.env at the moment this script calls pm2, not
# from apps/site/.env (that's Next's own, separate env loading) — source it here, same gap
# class as the prisma CLI fix above, so a host's API_URL override actually reaches pm2.
if [[ -f apps/site/.env ]]; then set -a; source apps/site/.env; set +a; fi
( exec 9>/run/photoreport-pm2.lock; flock 9
APP_VERSION="$sha" pm2 startOrReload infra/pm2/site.config.cjs --update-env
)
local i
for ((i = 1; i <= HEALTH_TRIES; i++)); do
if curl -fsS --max-time 3 -o /dev/null "http://127.0.0.1:${SITE_PORT:-3100}/"; then pm2 save --force >/dev/null; return 0; fi
sleep 2
done
return 1
}
deploy_pending() { log "service $SERVICE has no deployable build yet; nothing to do"; }
run_service() {
case "$SERVICE" in
api) deploy_api "$1" ;;
app) deploy_app "$1" ;;
site) deploy_site "$1" ;;
workers | ml) deploy_pending ;;
*) die "unknown service: $SERVICE" ;;
esac
}
PREVIOUS="$(git rev-parse HEAD)"
log "deploying $SERVICE: $PREVIOUS -> $SHA"
backup_env
checkout "$SHA"
# Bash ignores `set -e` in anything called from `if`, `&&` or `||` (including subshells), so each attempt
# runs as a plain statement in a subshell and its exit code is read afterwards.
set +e
(set -e; run_service "$SHA")
rc=$?
set -e
if [[ $rc -eq 0 ]]; then
log "deploy of $SERVICE at $SHA succeeded"
exit 0
fi
log "deploy failed (exit $rc); rolling back to $PREVIOUS"
checkout "$PREVIOUS"
set +e
(set -e; run_service "$PREVIOUS")
rc=$?
set -e
if [[ $rc -eq 0 ]]; then
log "rolled back to $PREVIOUS"
else
log "rollback to $PREVIOUS also failed (exit $rc); service needs attention"
fi
exit 1