Files
photoreport/infra/deploy/deploy.sh
spark c9c994e0a0
ci / rust (pull_request) Successful in 5m13s
ci / typescript (pull_request) Successful in 8m55s
fix(boot): retry a hung PM2 start so a reboot cannot leave the API down
pm2 startOrReload hung on pr-api after the 2026-11-18 reboot. systemd killed
photoreport-boot and the process list stayed empty, so nothing could report
the outage. Bound the call, reset the daemon once, and retry the unit.
2026-11-19 00:11:50 +00:00

218 lines
8.8 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
}
# pm2 startOrReload has hung forever against a half-spawned daemon (pr-api, 2026-11-18).
# Bound it; if it does not return, kill that daemon and try once more.
pm2_reload() {
local sha="$1"
local config="$2"
if timeout 90s env APP_VERSION="$sha" pm2 startOrReload "$config" --update-env; then
return 0
fi
log "pm2 startOrReload did not finish; resetting the daemon and retrying once"
pm2 kill >/dev/null 2>&1 || true
sleep 2
timeout 90s env APP_VERSION="$sha" pm2 startOrReload "$config" --update-env
}
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"
# Archive videos need ffmpeg on the worker. Without it they wait (FAILED "ffprobe_missing") until it is there.
ensure_ffmpeg || log "WARNING: no ffmpeg: archive videos wait for it"
# 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
pm2_reload "$sha" infra/pm2/api.config.cjs
)
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
}
# ffmpeg and ffprobe for archive videos: the system's when installed (apt install ffmpeg), else a static build in
# the deploy user's home (no root), checked against its published md5, where the worker looks for it.
ensure_ffmpeg() {
command -v ffmpeg >/dev/null 2>&1 && command -v ffprobe >/dev/null 2>&1 && return 0
local dir="$HOME/.local/ffmpeg"
[[ -x "$dir/ffmpeg" && -x "$dir/ffprobe" ]] && return 0
local arch
case "$(uname -m)" in x86_64) arch=amd64 ;; aarch64) arch=arm64 ;; *) return 1 ;; esac
local name="ffmpeg-release-${arch}-static.tar.xz" tmp
tmp="$(mktemp -d)"
log "installing a static ffmpeg (once) in $dir"
(
cd "$tmp" &&
curl -fsSL --max-time 600 -o "$name" "https://johnvansickle.com/ffmpeg/releases/$name" &&
curl -fsSL --max-time 60 -o "$name.md5" "https://johnvansickle.com/ffmpeg/releases/$name.md5" &&
md5sum -c --quiet "$name.md5" &&
mkdir x && tar -xJf "$name" -C x --strip-components=1 &&
mkdir -p "$dir" && cp x/ffmpeg x/ffprobe "$dir/" && chmod 755 "$dir/ffmpeg" "$dir/ffprobe"
)
local ok=$?
rm -rf "$tmp"
return $ok
}
# 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
pm2_reload "$sha" infra/pm2/site.config.cjs
)
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