Deploys: exact sha, replay protection, health check and automatic rollback
CI / Test (jest) (push) Successful in 47s
CI / Lint (eslint) (push) Successful in 52s
CI / Security (npm audit) (push) Successful in 17s
CI / Deploy (push) Skipped
CI / Notify (push) Skipped
CI / Test (jest) (pull_request) Failing after 12s
CI / Lint (eslint) (pull_request) Successful in 14s
CI / Security (npm audit) (pull_request) Successful in 11s
CI / Deploy (pull_request) Skipped
CI / Notify (pull_request) Skipped
CI / Test (jest) (push) Successful in 47s
CI / Lint (eslint) (push) Successful in 52s
CI / Security (npm audit) (push) Successful in 17s
CI / Deploy (push) Skipped
CI / Notify (push) Skipped
CI / Test (jest) (pull_request) Failing after 12s
CI / Lint (eslint) (pull_request) Successful in 14s
CI / Security (npm audit) (pull_request) Successful in 11s
CI / Deploy (pull_request) Skipped
CI / Notify (pull_request) Skipped
#45 phase 2. - GET /healthz (unauthenticated): running git sha, version, database reachability, connected workers, uptime. 503 when the database is down. - deploy/pulse_deploy.sh, versioned for the first time (it only existed as a hand-edited file on CT 122). It takes <sha> <ts> from the signed webhook payload and: - refuses requests older than 5 minutes, or not newer than the last accepted one (replays); - refuses commits that aren't on main; - checks out exactly that sha (before, it deployed whatever main was); - runs npm ci --omit=dev (before, npm install --production) and restarts; - waits for /healthz to report the sha with a working database, and otherwise rolls back to the previous commit. - tests/deploy-script.test.js runs the script in a sandbox (temporary git origin, fake systemctl/npm/curl): exact-sha deploy with .env kept, replay, stale request, off-main commit, malformed input, and rollback of an unhealthy build. - CI's deploy job now succeeds only once production reports the tested sha as healthy, before tagging. Before, it only checked that the server answered. - README: CI/CD and deploy documentation, including installing the script and the hooks.json arguments. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b10ea154dd
commit
cb12fec28c
5 files changed
+311
-17
No files matched your search
+14
-9
@@ -98,18 +98,23 @@ jobs:
|
||||
-d "$PAYLOAD" \
|
||||
"http://10.10.10.65:9000/hooks/pulse-deploy"
|
||||
|
||||
- name: Wait for Pulse to come back
|
||||
- name: Verify production runs this commit
|
||||
env:
|
||||
GIT_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
# Liveness only: the webhook returns before the restart finishes, so this
|
||||
# can't prove the new commit is running. /healthz with the git SHA
|
||||
# replaces it in #45 phase 2. The unauthenticated root answers 401 when up.
|
||||
sleep 30
|
||||
for i in $(seq 1 24); do
|
||||
code=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 http://10.10.10.65:8080/ || true)
|
||||
if [ "$code" = "401" ]; then echo "Pulse is serving (HTTP $code)"; exit 0; fi
|
||||
# The webhook returns at once; the server-side deploy script checks out
|
||||
# this exact sha, runs npm ci and restarts, and rolls back if /healthz
|
||||
# never reports it. Succeed only when production reports this sha with
|
||||
# a working database (up to 4 minutes, covering npm ci).
|
||||
for i in $(seq 1 48); do
|
||||
body=$(curl -fsS --connect-timeout 5 --max-time 5 http://10.10.10.65:8080/healthz || true)
|
||||
if echo "$body" | grep -q "\"sha\":\"${GIT_SHA}\"" && echo "$body" | grep -q '"db":true'; then
|
||||
echo "Production is healthy on ${GIT_SHA}: ${body}"
|
||||
exit 0
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
echo "::error::Pulse did not come back within 2 minutes after deploy"
|
||||
echo "::error::Production never reported ${GIT_SHA} as healthy (last /healthz: ${body:-no response}). The server rolls back automatically; see /var/log/pulse-deploy.log on CT 122."
|
||||
exit 1
|
||||
|
||||
- name: Tag deployed commit
|
||||
|
||||
@@ -582,17 +582,49 @@ MIT License - See LICENSE file for details
|
||||
|
||||
## CI / CD
|
||||
|
||||
| Workflow | Purpose | Triggers |
|
||||
Everything runs from `.gitea/workflows/ci.yml`:
|
||||
|
||||
| Job | What it does | When |
|
||||
|---|---|---|
|
||||
| `lint.yml` | ESLint on all `.js` files | Every push and PR |
|
||||
| `test.yml` | Jest unit tests (`lib/utils.js`) | Every push and PR |
|
||||
| `security.yml` | `npm audit --audit-level=high` | Every push, PR, and weekly Monday 6am |
|
||||
| `deploy` job in `lint.yml` | Calls the `pulse-deploy` webhook on CT122 (10.10.10.65) to pull + restart | Push to `main` only, after lint passes |
|
||||
| `Lint (eslint)` | `npm run lint`, plus a check that fails on em or en dashes in Pulse-owned files | Every push and PR |
|
||||
| `Test (jest)` | `npm test`: unit tests for `lib/` and the deploy-script sandbox tests | Every push and PR |
|
||||
| `Security (npm audit)` | `npm audit --audit-level=high` | Every push and PR, and weekly (Monday 06:00) |
|
||||
| `Deploy` | Calls the `pulse-deploy` webhook on CT 122, waits until `/healthz` reports the tested commit, then tags it `deploy-*` | Push to `main`, only after all three checks pass |
|
||||
| `Notify` | Matrix alert on any failure on `main` or in the weekly audit, and on every deploy | As needed |
|
||||
|
||||
All CI lives in `.gitea/workflows/ci.yml`. Branch protection on `main` requires its `Lint (eslint)`, `Test (jest)` and `Security (npm audit)` checks, and the `Deploy` job only runs after all three pass on a push to `main`.
|
||||
Branch protection on `main` requires `CI / Lint (eslint) (push)`, `CI / Test (jest) (push)` and
|
||||
`CI / Security (npm audit) (push)`. Actions are pinned to commit SHAs and builds use `npm ci`.
|
||||
The plan for the rest of the pipeline is tracked in #45.
|
||||
|
||||
Tests live in `tests/utils.test.js` and cover the pure utility functions in `lib/utils.js`:
|
||||
`validateWebhookUrl`, `applyParams`, `evalCondition`, `calculateNextRun`.
|
||||
### Deploys
|
||||
|
||||
CI sends an HMAC-signed payload `{"ref", "sha", "ts"}` to the webhook on CT 122. The webhook runs
|
||||
`deploy/pulse_deploy.sh <sha> <ts>`, which:
|
||||
|
||||
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, runs `npm ci --omit=dev` and restarts `pulse`;
|
||||
4. waits for `GET /healthz` to report that commit with a working database, and otherwise
|
||||
**rolls back** to the previous commit.
|
||||
|
||||
It logs to `/var/log/pulse-deploy.log`. `GET /healthz` (unauthenticated) returns
|
||||
`{status, version, sha, db, workers, uptime_s}` with 200, or 503 when the database is unreachable.
|
||||
|
||||
**Installing or updating the deploy script** (on CT 122, 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 /opt/pulse-server/deploy/pulse_deploy.sh /usr/local/bin/pulse_deploy.sh
|
||||
```
|
||||
|
||||
The `pulse-deploy` hook in `/etc/webhook/hooks.json` passes the signed values as arguments:
|
||||
|
||||
```json
|
||||
"pass-arguments-to-command": [
|
||||
{ "source": "payload", "name": "sha" },
|
||||
{ "source": "payload", "name": "ts" }
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
Executable
+96
@@ -0,0 +1,96 @@
|
||||
#!/bin/bash
|
||||
# Pulse production deploy (#45 phase 2), run by the webhook listener on CT 122.
|
||||
#
|
||||
# Source of truth: deploy/pulse_deploy.sh in the Pulse repo.
|
||||
# Installed copy: /usr/local/bin/pulse_deploy.sh (install it from the repo; see README "Deploys").
|
||||
#
|
||||
# Usage: pulse_deploy.sh <sha> <ts>
|
||||
# sha full 40-char 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 <sha>, then waits for /healthz to report that sha with a working
|
||||
# database. Otherwise it rolls back to the previous commit.
|
||||
set -euo pipefail
|
||||
|
||||
# Overridable only so tests can run the script in a sandbox.
|
||||
APP_ROOT=${PULSE_DEPLOY_APP_ROOT:-/opt/pulse-server}
|
||||
BRANCH=main
|
||||
STATE_DIR=${PULSE_DEPLOY_STATE_DIR:-/var/lib/pulse-deploy}
|
||||
LOG=${PULSE_DEPLOY_LOG:-/var/log/pulse-deploy.log}
|
||||
LOCK=${PULSE_DEPLOY_LOCK:-/run/pulse-deploy.lock}
|
||||
HEALTH_URL=${PULSE_DEPLOY_HEALTH_URL:-http://127.0.0.1:8080/healthz}
|
||||
MAX_AGE_S=300 # refuse requests signed more than 5 minutes ago
|
||||
HEALTH_TRIES=${PULSE_DEPLOY_HEALTH_TRIES:-45} # x 2 s = 90 s for the new process to report healthy
|
||||
|
||||
log() { echo "$(date '+%F %T') [pulse-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() {
|
||||
# .env and node_modules are untracked, so a forced checkout leaves .env 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; }
|
||||
npm ci --omit=dev --no-audit --no-fund >>"$LOG" 2>&1 || { log "npm ci failed for $1"; return 1; }
|
||||
systemctl restart pulse || { log "restart failed for $1"; return 1; }
|
||||
}
|
||||
|
||||
healthy() {
|
||||
local want="$1" body
|
||||
for _ in $(seq 1 "$HEALTH_TRIES"); do
|
||||
if body=$(curl -fsS --max-time 3 "$HEALTH_URL" 2>/dev/null) \
|
||||
&& grep -q "\"sha\":\"$want\"" <<<"$body" \
|
||||
&& grep -q '"db":true' <<<"$body"; then
|
||||
return 0
|
||||
fi
|
||||
sleep "${PULSE_DEPLOY_HEALTH_SLEEP:-2}"
|
||||
done
|
||||
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 pulse"
|
||||
fi
|
||||
exit 1
|
||||
@@ -1321,6 +1321,40 @@ async function waitForCommandResult(executionId, commandId, timeout) {
|
||||
|
||||
|
||||
|
||||
// Health check for deploys and monitoring (#45 phase 2). Unauthenticated on purpose,
|
||||
// so CI and the deploy script can reach it; it reveals only the running commit,
|
||||
// whether the database answers and how many workers are connected.
|
||||
const GIT_SHA = (() => {
|
||||
try {
|
||||
return require('child_process')
|
||||
.execFileSync('git', ['rev-parse', 'HEAD'], { cwd: __dirname, timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] })
|
||||
.toString().trim();
|
||||
} catch {
|
||||
return 'unknown';
|
||||
}
|
||||
})();
|
||||
|
||||
app.get('/healthz', async (req, res) => {
|
||||
let db = false;
|
||||
try {
|
||||
await Promise.race([
|
||||
pool.query('SELECT 1'),
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 3000))
|
||||
]);
|
||||
db = true;
|
||||
} catch { /* reported as db: false */ }
|
||||
const connectedWorkers = new Set([...workers.values()].map(w => w.dbWorkerId).filter(Boolean)).size;
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.status(db ? 200 : 503).json({
|
||||
status: db ? 'ok' : 'degraded',
|
||||
version: SERVER_VERSION,
|
||||
sha: GIT_SHA,
|
||||
db,
|
||||
workers: connectedWorkers,
|
||||
uptime_s: Math.round(process.uptime())
|
||||
});
|
||||
});
|
||||
|
||||
// HTML page routes (registered before the API routes)
|
||||
const authenticatePage = makeAuthenticatePage(pool);
|
||||
PAGES.forEach((p) => {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
'use strict';
|
||||
|
||||
// Runs deploy/pulse_deploy.sh in a sandbox: a throwaway git origin and checkout,
|
||||
// with fake systemctl/npm/curl on PATH. "Production" health is simulated by the
|
||||
// fake curl, which reports whatever commit the fake systemctl last started; a
|
||||
// commit containing a BROKEN file reports db:false (an unhealthy build).
|
||||
|
||||
const { execFileSync, spawnSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
const path = require('path');
|
||||
|
||||
const SCRIPT = path.join(__dirname, '..', 'deploy', 'pulse_deploy.sh');
|
||||
let root, app, bin, env, commits;
|
||||
|
||||
function sh(cwd, ...args) {
|
||||
return execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim();
|
||||
}
|
||||
|
||||
function commit(repo, name, files) {
|
||||
for (const [f, c] of Object.entries(files)) fs.writeFileSync(path.join(repo, f), c);
|
||||
sh(repo, 'add', '-A');
|
||||
sh(repo, '-c', 'user.name=t', '-c', 'user.email=t@example.invalid', 'commit', '-qm', name);
|
||||
return sh(repo, 'rev-parse', 'HEAD');
|
||||
}
|
||||
|
||||
function deploy(sha, ts = Math.floor(Date.now() / 1000)) {
|
||||
const r = spawnSync('bash', [SCRIPT, sha, String(ts)], { env, encoding: 'utf8' });
|
||||
return { code: r.status, out: r.stdout + r.stderr };
|
||||
}
|
||||
const head = () => sh(app, 'rev-parse', 'HEAD');
|
||||
const running = () => fs.readFileSync(path.join(root, 'running'), 'utf8').trim();
|
||||
|
||||
beforeAll(() => {
|
||||
root = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-deploy-'));
|
||||
const work = path.join(root, 'work');
|
||||
const origin = path.join(root, 'origin.git');
|
||||
app = path.join(root, 'app');
|
||||
bin = path.join(root, 'bin');
|
||||
fs.mkdirSync(work); fs.mkdirSync(bin);
|
||||
|
||||
sh(root, 'init', '-q', '--bare', '-b', 'main', origin);
|
||||
sh(root, 'init', '-q', '-b', 'main', work);
|
||||
commits = {};
|
||||
commits.a = commit(work, 'a', { 'server.js': 'a' });
|
||||
sh(work, 'remote', 'add', 'origin', origin);
|
||||
sh(work, 'push', '-q', 'origin', 'main');
|
||||
sh(root, 'clone', '-q', origin, app);
|
||||
fs.writeFileSync(path.join(app, '.env'), 'SECRET=keep-me\n'); // untracked, must survive
|
||||
|
||||
commits.b = commit(work, 'b', { 'server.js': 'b' });
|
||||
commits.broken = commit(work, 'broken', { 'server.js': 'c', BROKEN: '1' });
|
||||
commits.fixed = commit(work, 'fixed', { 'server.js': 'd' });
|
||||
fs.unlinkSync(path.join(work, 'BROKEN'));
|
||||
commits.fixed = commit(work, 'fixed2', { 'server.js': 'e' });
|
||||
sh(work, 'push', '-q', 'origin', 'main');
|
||||
sh(work, 'checkout', '-q', '-b', 'side', commits.a);
|
||||
commits.side = commit(work, 'side', { 'server.js': 'side' });
|
||||
sh(work, 'push', '-q', 'origin', 'side');
|
||||
|
||||
const fake = (name, body) => fs.writeFileSync(path.join(bin, name), `#!/bin/bash\n${body}\n`, { mode: 0o755 });
|
||||
fake('npm', 'exit 0');
|
||||
fake('systemctl', `git -C "${app}" rev-parse HEAD > "${root}/running"`);
|
||||
fake('curl', `s=$(cat "${root}/running" 2>/dev/null) || exit 7
|
||||
if [ -e "${app}/BROKEN" ]; then db=false; else db=true; fi
|
||||
echo "{\\"status\\":\\"ok\\",\\"sha\\":\\"$s\\",\\"db\\":$db}"`);
|
||||
fs.writeFileSync(path.join(root, 'running'), commits.a);
|
||||
|
||||
env = {
|
||||
...process.env,
|
||||
PATH: `${bin}:${process.env.PATH}`,
|
||||
PULSE_DEPLOY_APP_ROOT: app,
|
||||
PULSE_DEPLOY_STATE_DIR: path.join(root, 'state'),
|
||||
PULSE_DEPLOY_LOG: path.join(root, 'deploy.log'),
|
||||
PULSE_DEPLOY_LOCK: path.join(root, 'lock'),
|
||||
PULSE_DEPLOY_HEALTH_TRIES: '3',
|
||||
PULSE_DEPLOY_HEALTH_SLEEP: '0'
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
|
||||
// Order matters: each test builds on the state the previous one left.
|
||||
test('deploys exactly the requested commit, not just the tip of main', () => {
|
||||
const r = deploy(commits.b);
|
||||
expect(r.code).toBe(0);
|
||||
expect(head()).toBe(commits.b);
|
||||
expect(running()).toBe(commits.b);
|
||||
expect(fs.readFileSync(path.join(app, '.env'), 'utf8')).toBe('SECRET=keep-me\n');
|
||||
});
|
||||
|
||||
test('a replayed request (same or older timestamp) is refused', () => {
|
||||
const ts = Math.floor(Date.now() / 1000) + 5;
|
||||
expect(deploy(commits.fixed, ts).code).toBe(0);
|
||||
const r = deploy(commits.b, ts);
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toMatch(/replay or out of order/);
|
||||
expect(head()).toBe(commits.fixed);
|
||||
});
|
||||
|
||||
test('a stale request is refused', () => {
|
||||
const r = deploy(commits.b, Math.floor(Date.now() / 1000) - 3600);
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toMatch(/old \(limit 300s\)/);
|
||||
});
|
||||
|
||||
test('a commit that is not on main is refused', () => {
|
||||
const r = deploy(commits.side, Math.floor(Date.now() / 1000) + 10);
|
||||
expect(r.code).toBe(1);
|
||||
// Only main is fetched, so a commit from another branch is unknown or not an ancestor.
|
||||
expect(r.out).toMatch(/is not on main|not found after fetch/);
|
||||
expect(head()).toBe(commits.fixed);
|
||||
});
|
||||
|
||||
test('malformed input is refused', () => {
|
||||
expect(deploy('abc', Math.floor(Date.now() / 1000) + 11).out).toMatch(/invalid sha/);
|
||||
expect(deploy(commits.b, 'x').out).toMatch(/invalid timestamp/);
|
||||
});
|
||||
|
||||
test('an unhealthy build is rolled back to the previous commit', () => {
|
||||
const r = deploy(commits.broken, Math.floor(Date.now() / 1000) + 20);
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.out).toMatch(/rolling back/);
|
||||
expect(r.out).toMatch(/rolled back to .*healthy/);
|
||||
expect(head()).toBe(commits.fixed);
|
||||
expect(running()).toBe(commits.fixed);
|
||||
});
|
||||
Reference in new issue
Block a user