228 lines
10 KiB
Bash
Executable File
228 lines
10 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
# Releases Peppa itself (PEP-18) from its own release directory, apart from the development
|
|
# checkout:
|
|
# ~/peppa/repo.git bare clone of $GITEA_PLATFORM_REPO (peppa/peppa)
|
|
# ~/peppa/releases/<sha> git worktree at the commit (.env → ~/peppa/shared/.env)
|
|
# ~/peppa/current symlink to the release the services run (launchd, ~/.local/bin)
|
|
#
|
|
# Usage:
|
|
# peppa-release.sh <sha> release that commit: install → build → DB backup →
|
|
# migrate → switch current → kickstart → health; rollback
|
|
# to the previous release if it is not healthy
|
|
# peppa-release.sh --queue requests from ~/.peppa/release-queue (the PM's button;
|
|
# launchd agent quest.telecom.peppa.release)
|
|
# peppa-release.sh <sha> --no-restart everything up to the switch, no kickstart, no health
|
|
# and no reports (the first move of prod to ~/peppa)
|
|
# peppa-release.sh --check health of the current release (exit code)
|
|
# Every step is reported with `peppa release report` → releases table → PM messages.
|
|
set -uo pipefail
|
|
|
|
RELEASES="${PEPPA_RELEASES_DIR:-$HOME/peppa}"
|
|
PEPPA_HOME="${PEPPA_HOME:-$HOME/.peppa}"
|
|
QUEUE="${PEPPA_RELEASE_QUEUE:-$PEPPA_HOME/release-queue}"
|
|
REMOTE="${PEPPA_RELEASE_REMOTE:-${GITEA_URL:-https://git.telecom.quest}/${GITEA_PLATFORM_REPO:-peppa/peppa}.git}"
|
|
KEY="${PEPPA_PLATFORM_KEY:-PEP}"
|
|
HEALTH_URL="${PEPPA_RELEASE_HEALTH_URL:-http://127.0.0.1:3100/api/health}"
|
|
HEALTH_TIMEOUT="${PEPPA_RELEASE_HEALTH_TIMEOUT:-120}"
|
|
HEALTH_INTERVAL="${PEPPA_RELEASE_HEALTH_INTERVAL:-3}"
|
|
SERVICES="${PEPPA_RELEASE_SERVICES:-web bot watchdog}"
|
|
KEEP="${PEPPA_RELEASE_KEEP:-5}"
|
|
NODE="${PEPPA_NODE:-node}"
|
|
CURRENT="$RELEASES/current"
|
|
mkdir -p "$RELEASES/releases" "$RELEASES/logs" "$RELEASES/requests" "$PEPPA_HOME/backups"
|
|
|
|
say() { echo "[$(date '+%F %T')] $*" | tee -a "${LOG:-/dev/null}"; }
|
|
run() { "$@" >>"$LOG" 2>&1; }
|
|
git_repo() { git -C "$RELEASES/repo.git" "$@"; }
|
|
current_sha() { [ -L "$CURRENT" ] && basename "$(readlink "$CURRENT")" || true; }
|
|
|
|
# The CLI that reports: the release being built once its deps are in, else the current one.
|
|
cli() {
|
|
local bin="${PEPPA_RELEASE_CLI:-}"
|
|
if [ -z "$bin" ]; then
|
|
if [ -n "${REL:-}" ] && [ -d "$REL/node_modules" ]; then bin="$REL/packages/cli/bin/peppa"
|
|
elif [ -e "$CURRENT/packages/cli/bin/peppa" ]; then bin="$CURRENT/packages/cli/bin/peppa"
|
|
else say "no peppa CLI to run: peppa $*"; return 1; fi
|
|
fi
|
|
(cd "$RELEASES" && "$bin" "$@")
|
|
}
|
|
|
|
report() { # status [reason]
|
|
[ -n "${NO_RESTART:-}" ] && return 0
|
|
local args=(release report "$KEY" --sha "$SHA" -s "$1")
|
|
[ -n "${PREV:-}" ] && args+=(--previous "$PREV")
|
|
[ -n "${2:-}" ] && args+=(--reason "$2")
|
|
[ "$1" != deploying ] && [ "$1" != healthy ] && args+=(--log-file "$LOG")
|
|
[ -s "${COMMITS:-}" ] && args+=(--commits-file "$COMMITS")
|
|
cli "${args[@]}" >>"$LOG" 2>&1 || say "report $1 failed (see log)"
|
|
}
|
|
|
|
kickstart() {
|
|
local s ok=0
|
|
for s in $SERVICES; do
|
|
say "kickstart quest.telecom.peppa.$s"
|
|
run launchctl kickstart -k "gui/$(id -u)/quest.telecom.peppa.$s" || ok=1
|
|
done
|
|
return $ok
|
|
}
|
|
|
|
# Healthy: /api/health answers 200 with this commit, the bot and the watchdog beat after `since`.
|
|
health() { # sha since-ms
|
|
local deadline=$(( $(date +%s) + HEALTH_TIMEOUT )) body why=""
|
|
while :; do
|
|
if body=$(curl -fsS --max-time 5 "$HEALTH_URL" 2>&1); then
|
|
why=$(printf '%s' "$body" | SHA="$1" SINCE="$2" WANT="$SERVICES" "$NODE" -e '
|
|
let s = ""; process.stdin.on("data", (c) => (s += c)).on("end", () => {
|
|
const h = JSON.parse(s), sha = process.env.SHA, since = Number(process.env.SINCE);
|
|
const want = process.env.WANT.split(/\s+/).filter((x) => x === "bot" || x === "watchdog");
|
|
if (!h.ok) return console.log("health: ok=false");
|
|
if (!h.commit || !sha.startsWith(h.commit)) return console.log(`веб отдаёт коммит ${h.commit ?? "—"}`);
|
|
for (const w of want) {
|
|
const sv = (h.services ?? []).find((x) => x.service === w);
|
|
if (!sv?.lastHeartbeat || Date.parse(sv.lastHeartbeat) < since) return console.log(`${w}: нет свежего heartbeat`);
|
|
}
|
|
});' 2>&1)
|
|
[ -z "$why" ] && return 0
|
|
else
|
|
why="веб не отвечает: ${body##*$'\n'}"
|
|
fi
|
|
[ "$(date +%s)" -ge "$deadline" ] && { HEALTH_WHY="$why"; return 1; }
|
|
sleep "$HEALTH_INTERVAL"
|
|
done
|
|
}
|
|
|
|
now_ms() { "$NODE" -e 'console.log(Date.now())'; }
|
|
|
|
switch_to() { # release dir
|
|
ln -sfn "$1" "$CURRENT" && [ "$(readlink "$CURRENT")" = "$1" ]
|
|
}
|
|
|
|
# Not healthy after the switch: back to the previous release and restart it.
|
|
rollback() { # reason
|
|
local reason="$1"
|
|
if [ -z "$PREV" ] || [ ! -d "$RELEASES/releases/$PREV" ]; then
|
|
FINISHED=1; report failed "$reason; предыдущего релиза нет — откатывать некуда"; exit 1
|
|
fi
|
|
say "rollback to $PREV: $reason"
|
|
switch_to "$RELEASES/releases/$PREV"
|
|
local since; since=$(now_ms)
|
|
kickstart
|
|
if health "$PREV" "$since"; then
|
|
FINISHED=1; report rolled_back "$reason (схема БД не откатывается; бэкап: ${BACKUP:-нет})"; exit 1
|
|
fi
|
|
FINISHED=1; report failed "$reason; откат на ${PREV:0:7} тоже нездоров: $HEALTH_WHY"; exit 1
|
|
}
|
|
|
|
fail() { # reason — before the switch: prod untouched
|
|
say "failed: $1"
|
|
FINISHED=1; report failed "$1"; exit 1
|
|
}
|
|
|
|
on_exit() {
|
|
local code=$?
|
|
[ -n "${LOCKED:-}" ] && rm -rf "$RELEASES/.lock"
|
|
[ -z "${FINISHED:-}" ] && [ -n "${STARTED:-}" ] && report failed "скрипт релиза прервался (код $code)"
|
|
}
|
|
|
|
lock() {
|
|
local waited=0
|
|
until mkdir "$RELEASES/.lock" 2>/dev/null; do
|
|
local pid; pid=$(cat "$RELEASES/.lock/pid" 2>/dev/null || true)
|
|
if [ -n "$pid" ] && ! kill -0 "$pid" 2>/dev/null; then rm -rf "$RELEASES/.lock"; continue; fi
|
|
[ "$waited" -ge 3600 ] && { echo "another release holds $RELEASES/.lock" >&2; exit 1; }
|
|
sleep 5; waited=$((waited + 5))
|
|
done
|
|
echo $$ > "$RELEASES/.lock/pid"
|
|
LOCKED=1
|
|
}
|
|
|
|
prune() {
|
|
local keep_dirs=("$REL" "$RELEASES/releases/${PREV:-none}") d n=0
|
|
for d in $(ls -1td "$RELEASES"/releases/*/ 2>/dev/null); do
|
|
d="${d%/}"; n=$((n + 1))
|
|
[[ " ${keep_dirs[*]} " == *" $d "* ]] && continue
|
|
[ "$n" -le "$KEEP" ] && continue
|
|
say "prune $(basename "$d")"
|
|
git_repo worktree remove --force "$d" >>"$LOG" 2>&1 || rm -rf "$d"
|
|
done
|
|
git_repo worktree prune >>"$LOG" 2>&1
|
|
ls -1t "$PEPPA_HOME"/backups/release-*.db 2>/dev/null | tail -n +$((KEEP + 1)) | while read -r f; do rm -f "$f"; done
|
|
}
|
|
|
|
release() { # sha
|
|
trap on_exit EXIT
|
|
lock
|
|
[[ "$1" =~ ^[0-9a-f]{7,40}$ ]] || { echo "not a commit sha: $1" >&2; exit 2; }
|
|
LOG="$RELEASES/logs/${1:0:12}-$(date +%Y%m%d%H%M%S).log"
|
|
if [ ! -d "$RELEASES/repo.git" ]; then
|
|
say "clone $REMOTE"
|
|
# Gitea over https: peppa-bot's token through git-credential-peppa, set in repo.git only.
|
|
local cred=(); [[ "$REMOTE" == http* ]] && cred=(-c credential.helper=peppa)
|
|
git ${cred[@]+"${cred[@]}"} clone -q --bare "$REMOTE" "$RELEASES/repo.git" >>"$LOG" 2>&1 || { echo "clone failed, see $LOG" >&2; exit 1; }
|
|
[[ "$REMOTE" == http* ]] && git_repo config credential.helper peppa
|
|
fi
|
|
git_repo fetch -q origin '+refs/heads/*:refs/heads/*' >>"$LOG" 2>&1 || say "fetch failed (using known commits)"
|
|
SHA=$(git_repo rev-parse --verify -q "$1^{commit}") || { say "commit $1 not found in $REMOTE"; exit 2; }
|
|
PREV=$(current_sha)
|
|
REL="$RELEASES/releases/$SHA"
|
|
COMMITS="$RELEASES/logs/${SHA:0:12}.commits"
|
|
if [ -n "$PREV" ] && git_repo cat-file -e "$PREV^{commit}" 2>/dev/null; then
|
|
git_repo log --format=%s "$PREV..$SHA" > "$COMMITS"
|
|
else
|
|
git_repo log -1 --format=%s "$SHA" > "$COMMITS"
|
|
fi
|
|
if [ "$PREV" = "$SHA" ]; then say "$SHA is already current"; FINISHED=1; exit 0; fi
|
|
STARTED=1
|
|
say "release ${SHA:0:7} (current: ${PREV:-none}) log: $LOG"
|
|
report deploying
|
|
|
|
if [ ! -d "$REL" ]; then
|
|
run git_repo worktree add -q --detach "$REL" "$SHA" || fail "git worktree не создан"
|
|
fi
|
|
[ -f "$RELEASES/shared/.env" ] || fail "нет $RELEASES/shared/.env"
|
|
ln -sfn "$RELEASES/shared/.env" "$REL/.env"
|
|
say "pnpm install"
|
|
(cd "$REL" && run pnpm install --frozen-lockfile) || fail "pnpm install упал"
|
|
say "build web"
|
|
(cd "$REL" && run pnpm --filter @peppa/web build) || fail "сборка веба (next build) упала"
|
|
BACKUP="$PEPPA_HOME/backups/release-$(date +%Y%m%d%H%M%S)-${SHA:0:7}.db"
|
|
say "backup → $BACKUP"
|
|
cli db backup "$BACKUP" >>"$LOG" 2>&1 || fail "бэкап БД не сделан — миграции не применялись"
|
|
say "migrate"
|
|
cli db migrate >>"$LOG" 2>&1 || fail "миграция БД упала (бэкап: $BACKUP)"
|
|
|
|
say "switch current → ${SHA:0:7}"
|
|
switch_to "$REL" || fail "симлинк current не переключился"
|
|
if [ -n "${NO_RESTART:-}" ]; then say "switched without restart"; FINISHED=1; exit 0; fi
|
|
local since; since=$(now_ms)
|
|
kickstart || rollback "launchctl kickstart не прошёл"
|
|
say "health (${HEALTH_TIMEOUT}s)"
|
|
health "$SHA" "$since" || rollback "релиз нездоров: $HEALTH_WHY"
|
|
cli status >>"$LOG" 2>&1 || true
|
|
FINISHED=1
|
|
report healthy
|
|
say "healthy ${SHA:0:7}"
|
|
prune
|
|
}
|
|
|
|
case "${1:-}" in
|
|
--queue)
|
|
# launchd starts this while the queue has files; each request is moved out before it runs.
|
|
for f in "$QUEUE"/*.json; do
|
|
[ -e "$f" ] || continue
|
|
done_f="$RELEASES/requests/$(date +%Y%m%d%H%M%S)-$(basename "$f")"
|
|
mv "$f" "$done_f" || continue
|
|
sha=$("$NODE" -e 'try { const r = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); if (/^[0-9a-f]{7,40}$/.test(r.sha)) console.log(r.sha) } catch {}' "$done_f")
|
|
if [ -z "$sha" ]; then echo "[$(date '+%F %T')] bad request $(basename "$f") — skipped"; continue; fi
|
|
echo "[$(date '+%F %T')] request $(basename "$f"): $sha"
|
|
( release "$sha" ) || echo "[$(date '+%F %T')] release $sha failed"
|
|
done ;;
|
|
--check)
|
|
SHA=$(current_sha); [ -n "$SHA" ] || { echo "no $CURRENT" >&2; exit 1; }
|
|
if health "$SHA" 0; then echo "healthy ${SHA:0:7}"; else echo "unhealthy ${SHA:0:7}: $HEALTH_WHY"; exit 1; fi ;;
|
|
""|-h|--help) sed -n '2,17p' "$0" | sed 's/^# \{0,1\}//'; [ -n "${1:-}" ] ;;
|
|
*)
|
|
[ "${2:-}" = "--no-restart" ] && NO_RESTART=1
|
|
( release "$1" ) ;;
|
|
esac
|