diff --git a/README.md b/README.md index 6421243..b96fc7e 100644 --- a/README.md +++ b/README.md @@ -1196,6 +1196,40 @@ One pipeline, `.gitea/workflows/ci.yml` (gandalf#55). It runs on every pull requ - **Branch protection on `main`** requires every check job by its context name, e.g. `CI / Lint (Python) (pull_request)`. +### Deploys + +CI sends an HMAC-signed payload `{"ref", "sha", "ts"}` to the `gandalf-deploy` webhook on CT 157, +which runs `deploy/gandalf_deploy.sh ` (installed as `/usr/local/bin/gandalf_app_deploy.sh`). +The script: + +1. refuses requests signed more than 5 minutes ago, or not newer than the last accepted one (replays); +2. refuses commits that aren't on `main`; +3. checks out exactly that commit (detached), installs `requirements.txt` and restarts `gandalf` and + `gandalf-monitor`; +4. waits for `/health` to report that commit as `sha` and `monitor_sha` with status ok, and otherwise + **rolls back** to the previous commit. + +It logs to `/var/log/gandalf-app-deploy.log`. `tests/test_deploy_script.py` runs it in a sandbox +(replays, stale and off-main requests, rollback). Service files and the nginx site still come from +pve-infra (`containers/157-gandalf`), whose own hook no longer touches the app code. + +**Installing or updating the deploy script** (on CT 157, as root). The webhook runs the installed copy, +not the one in the checkout, so a bad commit can't replace the code that rolls it back: + +```bash +install -m 755 /var/www/html/prod/deploy/gandalf_deploy.sh /usr/local/bin/gandalf_app_deploy.sh +``` + +The `gandalf-deploy` hook in `/etc/webhook/hooks.json` runs it with the signed values as arguments: + +```json +"execute-command": "/usr/local/bin/gandalf_app_deploy.sh", +"pass-arguments-to-command": [ + { "source": "payload", "name": "sha" }, + { "source": "payload", "name": "ts" } +] +``` + Tests live in `tests/`: - `test_diagnose.py`: `DiagnosticsRunner` static methods (`build_ssh_command`, `parse_output`, `parse_sysfs_stats`, `parse_ethtool`, and variants) diff --git a/deploy/gandalf_deploy.sh b/deploy/gandalf_deploy.sh new file mode 100755 index 0000000..330d67b --- /dev/null +++ b/deploy/gandalf_deploy.sh @@ -0,0 +1,107 @@ +#!/bin/bash +# Gandalf production deploy (gandalf#55 part 2), run by the webhook listener on CT 157. +# +# Source of truth: deploy/gandalf_deploy.sh in the Gandalf repo. +# Installed copy: /usr/local/bin/gandalf_app_deploy.sh (see README "Deploys"). The webhook +# runs the installed copy, so a bad commit can't replace the code that rolls it back. +# +# Usage: gandalf_app_deploy.sh +# sha full 40-character commit CI tested; must be on origin/main +# ts unix time CI signed the request at +# Both come from the HMAC-signed webhook payload, so they can't be altered. The timestamp +# makes every signature unique: stale or replayed requests are refused. +# +# Deploys exactly , then waits for /health to report that sha for the web app and the +# monitor with status ok. Otherwise it rolls back to the previous commit. +set -euo pipefail + +# Overridable only so tests can run the script in a sandbox. +APP_ROOT=${GANDALF_DEPLOY_APP_ROOT:-/var/www/html/prod} +BRANCH=main +STATE_DIR=${GANDALF_DEPLOY_STATE_DIR:-/var/lib/gandalf-deploy} +LOG=${GANDALF_DEPLOY_LOG:-/var/log/gandalf-app-deploy.log} +LOCK=${GANDALF_DEPLOY_LOCK:-/run/gandalf-deploy.lock} +HEALTH_URL=${GANDALF_DEPLOY_HEALTH_URL:-http://127.0.0.1:8000/health} +MAX_AGE_S=300 # refuse requests signed more than 5 minutes ago +HEALTH_TRIES=${GANDALF_DEPLOY_HEALTH_TRIES:-60} # x 2 s = 2 minutes for both services to report + +log() { echo "$(date '+%F %T') [gandalf-deploy] $*" | tee -a "$LOG"; } +fail() { log "REFUSED: $*"; exit 1; } + +SHA="${1:-}" +TS="${2:-}" + +# One deploy at a time (CI also queues deploys; this covers manual runs). +exec 9>"$LOCK" +flock -w 600 9 || fail "timed out waiting for another deploy" + +[[ "$SHA" =~ ^[0-9a-f]{40}$ ]] || fail "missing or invalid sha" +[[ "$TS" =~ ^[0-9]+$ ]] || fail "missing or invalid timestamp" + +now=$(date +%s) +age=$(( now - TS )) +(( age >= -60 && age <= MAX_AGE_S )) || fail "request is ${age}s old (limit ${MAX_AGE_S}s)" + +mkdir -p "$STATE_DIR" +chmod 700 "$STATE_DIR" +last_ts=$(cat "$STATE_DIR/last_ts" 2>/dev/null || echo 0) +(( TS > last_ts )) || fail "timestamp $TS is not newer than the last accepted request ($last_ts): replay or out of order" +echo "$TS" > "$STATE_DIR/last_ts" + +cd "$APP_ROOT" +git fetch --quiet origin "$BRANCH" +git cat-file -e "${SHA}^{commit}" 2>/dev/null || fail "commit $SHA not found after fetch" +git merge-base --is-ancestor "$SHA" "origin/$BRANCH" || fail "commit $SHA is not on $BRANCH" + +PREV=$(git rev-parse HEAD) + +deploy_to() { + # config.json and the logs are untracked, so a forced checkout leaves them alone. + # Explicit returns: `set -e` does not apply inside a function used in an `if`. + git checkout --quiet --force --detach "$1" || { log "checkout of $1 failed"; return 1; } + pip3 install -r requirements.txt --break-system-packages --quiet >>"$LOG" 2>&1 \ + || { log "pip install failed for $1"; return 1; } + systemctl restart gandalf gandalf-monitor || { log "restart failed for $1"; return 1; } +} + +healthy() { + # /health answers 503 until the monitor has checked in, so read the body whatever the code. + local want="$1" body + for _ in $(seq 1 "$HEALTH_TRIES"); do + body=$(curl -sS --max-time 3 "$HEALTH_URL" 2>/dev/null || true) + if WANT="$want" python3 -c ' +import json, os, sys +try: + b = json.loads(sys.stdin.read()) +except ValueError: + sys.exit(1) +w = os.environ["WANT"] +sys.exit(0 if b.get("status") == "ok" and b.get("sha") == w and b.get("monitor_sha") == w else 1) +' <<<"$body"; then + return 0 + fi + sleep "${GANDALF_DEPLOY_HEALTH_SLEEP:-2}" + done + log "last /health: ${body:-no response}" + return 1 +} + +if [ "$PREV" = "$SHA" ] && healthy "$SHA"; then + log "already running $SHA and healthy; nothing to do" + exit 0 +fi + +log "deploying $SHA (previous $PREV)" +if deploy_to "$SHA" && healthy "$SHA"; then + echo "$SHA" > "$STATE_DIR/current" + log "deployed $SHA: healthy" + exit 0 +fi + +log "FAILED: $SHA did not become healthy; rolling back to $PREV" +if deploy_to "$PREV" && healthy "$PREV"; then + log "rolled back to $PREV: healthy" +else + log "ROLLBACK FAILED: check journalctl -u gandalf -u gandalf-monitor" +fi +exit 1 diff --git a/tests/test_deploy_script.py b/tests/test_deploy_script.py new file mode 100644 index 0000000..b0c236d --- /dev/null +++ b/tests/test_deploy_script.py @@ -0,0 +1,144 @@ +"""Runs deploy/gandalf_deploy.sh in a sandbox (gandalf#55 part 2). + +A throwaway git origin and checkout, with fake systemctl, pip3 and curl on PATH. "Production" +health is simulated by the fake curl: it reports whatever commit the fake systemctl last +started, for both the web app and the monitor, and a commit containing a BROKEN file reports +status "degraded" (an unhealthy build). Each test builds on the state the previous one left. +""" +import os +import shutil +import subprocess # nosec B404: runs the deploy script and git in a temporary sandbox +import time + +import pytest + +SCRIPT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'deploy', 'gandalf_deploy.sh') + +pytestmark = pytest.mark.skipif(not (shutil.which('bash') and shutil.which('git') and shutil.which('flock')), + reason='needs bash, git and flock') + + +def _git(cwd, *args): + return subprocess.run(['git', *args], cwd=cwd, check=True, capture_output=True, # nosec B603 B607 + text=True).stdout.strip() + + +def _commit(repo, name, files, remove=()): + for f, content in files.items(): + with open(os.path.join(repo, f), 'w') as fh: + fh.write(content) + for f in remove: + os.unlink(os.path.join(repo, f)) + _git(repo, 'add', '-A') + _git(repo, '-c', 'user.name=t', '-c', 'user.email=t@example.invalid', 'commit', '-qm', name) + return _git(repo, 'rev-parse', 'HEAD') + + +@pytest.fixture(scope='module') +def sandbox(tmp_path_factory): + root = str(tmp_path_factory.mktemp('gandalf-deploy')) + work, origin, app, bin_dir = (os.path.join(root, d) for d in ('work', 'origin.git', 'app', 'bin')) + os.makedirs(work) + os.makedirs(bin_dir) + _git(root, 'init', '-q', '--bare', '-b', 'main', origin) + _git(root, 'init', '-q', '-b', 'main', work) + c = {'a': _commit(work, 'a', {'app.py': 'a', 'requirements.txt': ''})} + _git(work, 'remote', 'add', 'origin', origin) + _git(work, 'push', '-q', 'origin', 'main') + _git(root, 'clone', '-q', origin, app) + with open(os.path.join(app, 'config.json'), 'w') as fh: + fh.write('{"secret": "keep-me"}') # untracked, must survive every checkout + + c['b'] = _commit(work, 'b', {'app.py': 'b'}) + c['broken'] = _commit(work, 'broken', {'app.py': 'c', 'BROKEN': '1'}) + c['fixed'] = _commit(work, 'fixed', {'app.py': 'd'}, remove=['BROKEN']) + _git(work, 'push', '-q', 'origin', 'main') + _git(work, 'checkout', '-q', '-b', 'side', c['a']) + c['side'] = _commit(work, 'side', {'app.py': 'side'}) + _git(work, 'push', '-q', 'origin', 'side') + + running = os.path.join(root, 'running') + + def fake(name, body): + p = os.path.join(bin_dir, name) + with open(p, 'w') as fh: + fh.write('#!/bin/bash\n' + body + '\n') + os.chmod(p, 0o755) # nosec B103: a test stub in a temporary directory + + fake('pip3', 'exit 0') + fake('systemctl', f'git -C "{app}" rev-parse HEAD > "{running}"') + fake('curl', f'''s=$(cat "{running}" 2>/dev/null) || exit 7 +if [ -e "{app}/BROKEN" ]; then st=degraded; else st=ok; fi +echo "{{\\"status\\":\\"$st\\",\\"sha\\":\\"$s\\",\\"monitor_sha\\":\\"$s\\"}}"''') + with open(running, 'w') as fh: + fh.write(c['a']) + + env = dict(os.environ, PATH=f'{bin_dir}:{os.environ["PATH"]}', + GANDALF_DEPLOY_APP_ROOT=app, GANDALF_DEPLOY_STATE_DIR=os.path.join(root, 'state'), + GANDALF_DEPLOY_LOG=os.path.join(root, 'deploy.log'), GANDALF_DEPLOY_LOCK=os.path.join(root, 'lock'), + GANDALF_DEPLOY_HEALTH_TRIES='3', GANDALF_DEPLOY_HEALTH_SLEEP='0') + + def deploy(sha, ts=None): + ts = int(time.time()) if ts is None else ts + r = subprocess.run(['bash', SCRIPT, sha, str(ts)], env=env, # nosec B603 B607 + capture_output=True, text=True) + return r.returncode, r.stdout + r.stderr + + def head(): + return _git(app, 'rev-parse', 'HEAD') + + def runs(): + with open(running) as fh: + return fh.read().strip() + + return {'c': c, 'deploy': deploy, 'head': head, 'running': runs, 'app': app} + + +def test_deploys_exactly_the_requested_commit(sandbox): + s = sandbox + code, out = s['deploy'](s['c']['b']) + assert code == 0, out + assert s['head']() == s['c']['b'] and s['running']() == s['c']['b'] + with open(os.path.join(s['app'], 'config.json')) as fh: + assert fh.read() == '{"secret": "keep-me"}' + + +def test_a_replayed_request_is_refused(sandbox): + s = sandbox + ts = int(time.time()) + 5 + assert s['deploy'](s['c']['fixed'], ts)[0] == 0 + code, out = s['deploy'](s['c']['b'], ts) + assert code == 1 and 'replay or out of order' in out + assert s['head']() == s['c']['fixed'] + + +def test_a_stale_request_is_refused(sandbox): + code, out = sandbox['deploy'](sandbox['c']['b'], int(time.time()) - 3600) + assert code == 1 and 'old (limit 300s)' in out + + +def test_a_commit_not_on_main_is_refused(sandbox): + s = sandbox + code, out = s['deploy'](s['c']['side'], int(time.time()) + 10) + assert code == 1 and ('is not on main' in out or 'not found after fetch' in out) + assert s['head']() == s['c']['fixed'] + + +def test_malformed_input_is_refused(sandbox): + s = sandbox + assert 'invalid sha' in s['deploy']('abc', int(time.time()) + 11)[1] + assert 'invalid timestamp' in s['deploy'](s['c']['b'], 'x')[1] + + +def test_an_unhealthy_build_is_rolled_back(sandbox): + s = sandbox + code, out = s['deploy'](s['c']['broken'], int(time.time()) + 20) + assert code == 1 + assert 'rolling back' in out and 'healthy' in out.split('rolled back to', 1)[1] + assert s['head']() == s['c']['fixed'] and s['running']() == s['c']['fixed'] + + +def test_the_running_commit_is_a_no_op(sandbox): + s = sandbox + code, out = s['deploy'](s['c']['fixed'], int(time.time()) + 30) + assert code == 0 and 'nothing to do' in out