CI modelled on Pulse, deploy script with rollback, bootstrap, README

- .gitea/workflows/ci.yml: flake8 + dash check, pytest (90% coverage floor), MariaDB
  integration tests, bandit, pip-audit, gitleaks, actionlint, shellcheck, zizmor, semgrep;
  main deploys through a signed webhook and waits for /health to report the commit.
- deploy/thor_deploy.sh: deploys an exact sha, installs units and nginx site when changed,
  rolls back unless /health reports the sha with a working database. Sandbox-tested.
- deploy/bootstrap.sh: idempotent first install on CT 173.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-25 22:35:28 -05:00
1 parent eecb24297a
commit 379570bbdc
14 files changed
+689

No files matched your search

+191
View File
@@ -0,0 +1,191 @@
name: CI
# One pipeline, modelled on Pulse's: lint, unit tests, integration tests against MariaDB,
# security checks and scans must all pass before main deploys. Actions are pinned to full
# commit SHAs and the job image to a digest (version in the trailing comment).
# Pushes build only main (which deploys); branches are built through their pull request.
on:
push:
branches: [main]
pull_request:
branches: ["**"]
schedule:
- cron: '0 6 * * 1' # weekly dependency audit against new advisories
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
# node:22-trixie: Node for the checkout action, Debian trixie for Python 3.13 (production).
jobs:
lint:
name: Lint (flake8, house style)
runs-on: ubuntu-latest
timeout-minutes: 15
container: node:22-trixie@sha256:f92a4668ece057eff6b83ed531b5f6277892b5c8fa8c1df4ea4ef470bf92b91e
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
- name: Python environment
run: scripts/ci/python-env.sh
- name: flake8
run: /tmp/venv/bin/flake8 .
- name: No em or en dashes (house style)
run: |
if git grep -nP '[\x{2013}\x{2014}]|&[mn]dash;|\\u201[34]|&#821[12];|&#x201[34];' -- .; then
echo "::error::Em or en dashes found (listed above). Use a hyphen, colon, comma or 'to'."
exit 1
fi
test:
name: Test (pytest)
runs-on: ubuntu-latest
timeout-minutes: 15
container: node:22-trixie@sha256:f92a4668ece057eff6b83ed531b5f6277892b5c8fa8c1df4ea4ef470bf92b91e
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
- name: Python environment
run: scripts/ci/python-env.sh
- name: pytest with coverage
run: /tmp/venv/bin/python -m pytest -W error::DeprecationWarning --cov=thor --cov-report=term-missing --cov-fail-under=90
integration:
name: Integration (MariaDB)
runs-on: ubuntu-latest
timeout-minutes: 20
container: node:22-trixie@sha256:f92a4668ece057eff6b83ed531b5f6277892b5c8fa8c1df4ea4ef470bf92b91e
env:
DB_NAME: thor
DB_USER: thor
DB_PASSWORD: ci-only # throwaway database inside the job container
THOR_TEST_DB_HOST: 127.0.0.1
THOR_TEST_DB_PASSWORD: ci-only
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
- name: Python environment
run: scripts/ci/python-env.sh
- name: Start MariaDB
run: scripts/ci/mariadb.sh
- name: Database tests
run: /tmp/venv/bin/python -m pytest -W error::DeprecationWarning tests/test_db_mariadb.py -v
security:
name: Security (bandit, pip-audit)
runs-on: ubuntu-latest
timeout-minutes: 15
container: node:22-trixie@sha256:f92a4668ece057eff6b83ed531b5f6277892b5c8fa8c1df4ea4ef470bf92b91e
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
- name: Python environment
run: scripts/ci/python-env.sh
- name: bandit
run: /tmp/venv/bin/bandit -q -r thor -ll
- name: pip-audit (runtime dependencies)
run: /tmp/venv/bin/pip-audit -r requirements.txt --progress-spinner off
scan:
name: Scan (secrets, workflows, shell, patterns)
runs-on: ubuntu-latest
timeout-minutes: 20
container: node:22-trixie@sha256:f92a4668ece057eff6b83ed531b5f6277892b5c8fa8c1df4ea4ef470bf92b91e
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
fetch-depth: 0 # gitleaks scans the whole history
- name: Install scanners (pinned versions, verified checksums)
run: |
cd /tmp
curl -fsSLo gitleaks.tgz https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz
echo "551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb gitleaks.tgz" | sha256sum -c
curl -fsSLo actionlint.tgz https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz
echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 actionlint.tgz" | sha256sum -c
tar -xzf gitleaks.tgz -C /usr/local/bin gitleaks
tar -xzf actionlint.tgz -C /usr/local/bin actionlint
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends shellcheck python3-venv >/dev/null
- name: Secrets in code and history (gitleaks)
run: gitleaks git --no-banner --redact --exit-code 1 .
- name: Workflow files (actionlint, with shellcheck on run scripts)
run: actionlint .gitea/workflows/*.yml
- name: Shell scripts (shellcheck)
run: git ls-files -z '*.sh' | xargs -0 shellcheck
- name: Workflow security (zizmor)
run: |
python3 -m venv /tmp/zizmor && /tmp/zizmor/bin/pip install -q zizmor==1.32.0
/tmp/zizmor/bin/zizmor --offline --format plain .gitea/workflows/*.yml
- name: Code patterns (semgrep)
# Rule packs come from the semgrep registry. Fix new findings, or suppress one line
# with `nosemgrep: <rule id>` and a reason.
run: |
python3 -m venv /tmp/semgrep && /tmp/semgrep/bin/pip install -q semgrep==1.184.0
/tmp/semgrep/bin/semgrep scan --metrics=off --error \
--config p/python --config p/flask --config p/secrets --config p/security-audit \
--exclude tests
deploy:
name: Deploy
runs-on: ubuntu-latest
timeout-minutes: 15
needs: [lint, test, integration, security, scan]
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
concurrency:
group: deploy-production
cancel-in-progress: false
permissions:
contents: write # deploy tag
steps:
- name: Trigger webhook
env:
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
GIT_REF: ${{ github.ref }}
GIT_SHA: ${{ github.sha }}
run: |
PAYLOAD="{\"ref\":\"${GIT_REF}\",\"sha\":\"${GIT_SHA}\",\"ts\":$(date +%s)}"
SIG=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | awk '{print $2}')
curl -sf --connect-timeout 10 -X POST \
-H "Content-Type: application/json" \
-H "X-Gitea-Signature: ${SIG}" \
-d "$PAYLOAD" \
"http://10.10.10.86:9000/hooks/thor-deploy"
- name: Verify production runs this commit
env:
GIT_SHA: ${{ github.sha }}
run: |
# thor_deploy.sh checks out this sha, installs dependencies, restarts, and rolls
# back if /health never reports it with a working database.
for _ in $(seq 1 48); do
body=$(curl -sS --connect-timeout 5 --max-time 5 http://10.10.10.86/health || true)
if echo "$body" | grep -Eq "\"sha\": ?\"${GIT_SHA}\"" && echo "$body" | grep -Eq '"db": ?true'; then
echo "Production runs ${GIT_SHA}: ${body}"
exit 0
fi
sleep 5
done
echo "::error::Production never reported ${GIT_SHA} (last /health: ${body:-no response}). See /var/log/thor-deploy.log on CT 173."
exit 1
- name: Tag deployed commit
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RUN_NUMBER: ${{ github.run_number }}
GIT_SHA: ${{ github.sha }}
REPO: ${{ github.repository }}
run: |
TAG="deploy-$(date -u +%Y.%m.%d)-${RUN_NUMBER}"
code=$(curl -s -o /tmp/tag.json -w '%{http_code}' -X POST \
-H "Authorization: token $GITHUB_TOKEN" -H "Content-Type: application/json" \
-d "{\"tag_name\":\"${TAG}\",\"target\":\"${GIT_SHA}\",\"message\":\"Deployed to production\"}" \
"https://code.lotusguild.org/api/v1/repos/${REPO}/tags")
if [ "$code" = 201 ] || [ "$code" = 409 ]; then echo "Tag ${TAG}: HTTP ${code}"; exit 0; fi
cat /tmp/tag.json; exit 1
+35
View File
@@ -39,3 +39,38 @@ A monitor that runs on a failing host is least reliable exactly when it's needed
- hwmonDaemon#39: interim OOM check, which moves here later.
- hwmonDaemon#40: the boundary, and which checks move here.
- gandalf#57: Gandalf stops calling non-network faults "network".
## Code layout
- `thor/config.py`: settings from `/etc/thor/thor.json` (non-secret) and `/etc/thor/*.env` (secrets).
- `thor/clients/`: read-only clients for Prometheus, Loki, Proxmox and Gandalf, and the Tinker ticket client. A source that can't answer raises `SourceError`, which means "unknown", never "nothing found".
- `thor/db.py`: MariaDB (CT 149, schema `thor`), versioned migrations, and the queries.
- `thor/monitor.py`: the 120 s loop (`thor-monitor.service`): review window since the last good cycle with 24 h catch-up, blind periods per source, writes buffered while the database is away.
- `thor/web/`: `thor.service`: `/health` (database + monitor freshness + deployed commit) and `/metrics`.
The decisions behind all of this are in the plan on thor#1.
## Development
```bash
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt -r requirements-dev.txt
.venv/bin/python -m pytest # unit tests
.venv/bin/flake8 . && .venv/bin/bandit -q -r thor -ll
# Database tests need a throwaway MariaDB:
THOR_TEST_DB_HOST=127.0.0.1 THOR_TEST_DB_PASSWORD=... .venv/bin/python -m pytest tests/test_db_mariadb.py
```
CI (`.gitea/workflows/ci.yml`, modelled on Pulse's) runs lint, the dash check, tests with coverage, the MariaDB tests, bandit, pip-audit, gitleaks, actionlint, shellcheck, zizmor and semgrep on every pull request, and deploys `main`.
## Deploy
Thor runs on **CT 173** (`thor`, 10.10.10.86, DHCP reservation), in the HA rule `EMERGENCY needed`.
| Path | What |
|---|---|
| `/opt/thor/app` | checkout of this repo (detached at the deployed commit) |
| `/opt/thor/venv` | Python virtualenv |
| `/opt/thor/revision.env` | `THOR_SHA`, the commit `/health` reports |
| `/etc/thor/thor.json` | non-secret settings (`deploy/thor.example.json`) |
| `/etc/thor/*.env` | secrets: `pve.env`, `db.env`, `gandalf.env`, `tinker.env` (root:thor 0640, never in git) |
| `/etc/webhook/hooks.json` | deploy hook and its HMAC secret (also the repo secret `WEBHOOK_SECRET`) |
- **First install:** `bash deploy/bootstrap.sh` inside the CT (idempotent).
- **Every merge to main:** CI signs `{ref, sha, ts}` and calls the webhook on `:9000`. `/usr/local/bin/thor_deploy.sh` (installed from `deploy/thor_deploy.sh`; reinstall it by hand when it changes) checks out exactly that commit, installs dependencies, units and the nginx site, restarts `thor` and `thor-monitor`, and rolls back unless `/health` reports the commit with a working database. CI then waits for production to report the commit. Log: `/var/log/thor-deploy.log`.
- **After a deploy:** prod HEAD, `systemctl is-active thor thor-monitor`, `curl http://10.10.10.86/health`, and no tracebacks in `journalctl -u thor -u thor-monitor`.
+55
View File
@@ -0,0 +1,55 @@
#!/bin/bash
# One-time (idempotent) setup of Thor's LXC, run as root inside it from a checkout of this
# repo: `bash deploy/bootstrap.sh`. Later deploys go through thor_deploy.sh.
#
# Expects the base packages (python3-venv, git, nginx, webhook, sudo, curl), the `thor`
# user and the secrets in /etc/thor/*.env to exist already (see README, "Deploy").
set -euo pipefail
SRC=$(cd "$(dirname "$0")/.." && pwd)
REPO_URL=${THOR_REPO_URL:-https://code.lotusguild.org/LotusGuild/thor.git}
id thor >/dev/null 2>&1 || useradd --system --home /var/lib/thor --create-home --shell /usr/sbin/nologin thor
install -d -m 0755 /opt/thor
install -d -m 0750 -o root -g thor /etc/thor
if [ ! -d /opt/thor/app/.git ]; then
git clone --quiet "$REPO_URL" /opt/thor/app
fi
# Only for the very first install, before main has code: THOR_BOOTSTRAP_REF=origin/<branch>.
if [ -n "${THOR_BOOTSTRAP_REF:-}" ]; then
git -C /opt/thor/app fetch --quiet origin
git -C /opt/thor/app checkout --quiet --detach "$THOR_BOOTSTRAP_REF"
fi
[ -x /opt/thor/venv/bin/python ] || python3 -m venv /opt/thor/venv
/opt/thor/venv/bin/pip install --quiet --disable-pip-version-check -r /opt/thor/app/requirements.txt
[ -f /etc/thor/thor.json ] || install -m 0640 -o root -g thor "$SRC/deploy/thor.example.json" /etc/thor/thor.json
printf 'THOR_SHA=%s\n' "$(git -C /opt/thor/app rev-parse HEAD)" > /opt/thor/revision.env
install -m 0644 "$SRC/deploy/systemd/thor.service" /etc/systemd/system/thor.service
install -m 0644 "$SRC/deploy/systemd/thor-monitor.service" /etc/systemd/system/thor-monitor.service
install -m 0644 "$SRC/deploy/nginx/thor" /etc/nginx/sites-enabled/thor
rm -f /etc/nginx/sites-enabled/default
nginx -t
# Deploy webhook: its own unprivileged user, allowed to run only the deploy script.
id webhook >/dev/null 2>&1 || useradd --system --no-create-home --shell /usr/sbin/nologin webhook
install -m 0755 -o root -g root "$SRC/deploy/thor_deploy.sh" /usr/local/bin/thor_deploy.sh
install -m 0440 -o root -g root "$SRC/deploy/webhook/sudoers-thor-deploy" /etc/sudoers.d/thor-deploy
visudo -cf /etc/sudoers.d/thor-deploy
install -d -m 0750 -o root -g webhook /etc/webhook
if [ ! -f /etc/webhook/hooks.json ]; then
secret=$(python3 -c 'import secrets; print(secrets.token_hex(32))')
sed "s/REPLACE_WITH_WEBHOOK_SECRET/${secret}/" "$SRC/deploy/webhook/hooks.json.example" > /etc/webhook/hooks.json
chown root:webhook /etc/webhook/hooks.json
chmod 0640 /etc/webhook/hooks.json
echo "Generated a new webhook secret in /etc/webhook/hooks.json: copy it to the repo's WEBHOOK_SECRET."
fi
install -m 0644 "$SRC/deploy/webhook/webhook.service" /etc/systemd/system/webhook.service
systemctl daemon-reload
systemctl enable --quiet --now webhook thor thor-monitor
systemctl reload nginx
systemctl restart thor thor-monitor
echo "Thor bootstrapped at $(git -C /opt/thor/app rev-parse --short HEAD)"
+17
View File
@@ -0,0 +1,17 @@
# Thor on CT 173. NPM (thor.lotusguild.org) forwards here behind Authelia; Kuma and
# Prometheus reach /health and /metrics directly on 10.10.10.86.
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
client_max_body_size 1m;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 60s;
}
}
+26
View File
@@ -0,0 +1,26 @@
[Unit]
Description=Thor monitor loop (out-of-band host and cluster health)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=thor
Group=thor
WorkingDirectory=/opt/thor/app
EnvironmentFile=-/opt/thor/revision.env
ExecStart=/opt/thor/venv/bin/python -m thor.monitor
Restart=always
RestartSec=10
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectControlGroups=true
RestrictSUIDSGID=true
LockPersonality=true
[Install]
WantedBy=multi-user.target
+27
View File
@@ -0,0 +1,27 @@
[Unit]
Description=Thor web (health, metrics, UI, API, MCP)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=thor
Group=thor
WorkingDirectory=/opt/thor/app
# THOR_SHA, written by thor_deploy.sh: the commit /health reports.
EnvironmentFile=-/opt/thor/revision.env
ExecStart=/opt/thor/venv/bin/gunicorn --workers 2 --bind 127.0.0.1:8000 --access-logfile - thor.web.wsgi:app
Restart=always
RestartSec=5
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectControlGroups=true
RestrictSUIDSGID=true
LockPersonality=true
[Install]
WantedBy=multi-user.target
+16
View File
@@ -0,0 +1,16 @@
{
"prometheus_url": "http://10.10.10.48:9090",
"loki_url": "http://10.10.10.69:3100",
"gandalf_url": "http://10.10.10.61",
"tinker_url": "https://t.lotusguild.org/create_ticket_api.php",
"public_url": "https://thor.lotusguild.org",
"proxmox_nodes": ["10.10.10.11", "10.10.10.10", "10.10.10.4", "10.10.10.2", "10.10.10.8", "10.10.10.9"],
"proxmox_verify_tls": false,
"cycle_seconds": 120,
"catchup_hours": 24,
"stale_after_cycles": 3,
"http_timeout_s": 10,
"checks": {
"memory": "shadow"
}
}
+128
View File
@@ -0,0 +1,128 @@
#!/bin/bash
# Thor production deploy, run by the webhook listener on CT 173 (through sudo).
#
# Source of truth: deploy/thor_deploy.sh in the Thor repo.
# Installed copy: /usr/local/bin/thor_deploy.sh (root:root 0755; reinstall it by hand
# when this file changes, like Pulse's deploy script).
#
# Usage: thor_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. The timestamp makes every signature
# unique, so stale or replayed requests are refused.
#
# Deploys exactly <sha> (code, Python dependencies, systemd units, nginx site), then waits
# for /health to report that sha with a working database. Otherwise it rolls back.
set -euo pipefail
# Overridable only so tests can run the script in a sandbox.
APP_ROOT=${THOR_DEPLOY_APP_ROOT:-/opt/thor/app}
VENV=${THOR_DEPLOY_VENV:-/opt/thor/venv}
REVISION_FILE=${THOR_DEPLOY_REVISION_FILE:-/opt/thor/revision.env}
STATE_DIR=${THOR_DEPLOY_STATE_DIR:-/var/lib/thor-deploy}
LOG=${THOR_DEPLOY_LOG:-/var/log/thor-deploy.log}
LOCK=${THOR_DEPLOY_LOCK:-/run/thor-deploy.lock}
HEALTH_URL=${THOR_DEPLOY_HEALTH_URL:-http://127.0.0.1:8000/health}
SYSTEMD_DIR=${THOR_DEPLOY_SYSTEMD_DIR:-/etc/systemd/system}
NGINX_SITE=${THOR_DEPLOY_NGINX_SITE:-/etc/nginx/sites-enabled/thor}
BRANCH=main
MAX_AGE_S=300
HEALTH_TRIES=${THOR_DEPLOY_HEALTH_TRIES:-45}
log() { echo "$(date '+%F %T') [thor-deploy] $*" | tee -a "$LOG"; }
fail() { log "REFUSED: $*"; exit 1; }
SHA="${1:-}"
TS="${2:-}"
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)"
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)
# Copy a tracked file into place only when it differs. Prints 1 when it changed.
place() {
local src="$1" dst="$2"
if [ -f "$dst" ] && cmp -s "$src" "$dst"; then echo 0; return; fi
install -m 0644 -o root -g root "$src" "$dst"
echo 1
}
deploy_to() {
local sha="$1" units=0 site=0
git checkout --quiet --force --detach "$sha" || { log "checkout of $sha failed"; return 1; }
"$VENV/bin/pip" install --quiet --disable-pip-version-check -r requirements.txt >>"$LOG" 2>&1 \
|| { log "pip install failed for $sha"; return 1; }
for unit in thor.service thor-monitor.service; do
units=$(( units + $(place "deploy/systemd/$unit" "$SYSTEMD_DIR/$unit") ))
done
site=$(place deploy/nginx/thor "$NGINX_SITE")
if (( units > 0 )); then systemctl daemon-reload; fi
if (( site > 0 )); then
nginx -t >>"$LOG" 2>&1 || { log "nginx config invalid for $sha"; return 1; }
systemctl reload nginx
fi
printf 'THOR_SHA=%s\n' "$sha" > "$REVISION_FILE"
chmod 0644 "$REVISION_FILE"
systemctl restart thor thor-monitor || { log "restart failed for $sha"; return 1; }
}
# Healthy means: /health answers with this sha and a working database. The monitor may
# still be on its first cycle (503 "no good cycle yet"), which is fine for a deploy.
healthy() {
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:
d = json.loads(sys.stdin.read())
except ValueError:
sys.exit(1)
sys.exit(0 if d.get("sha") == os.environ["WANT"] and d.get("db") is True else 1)' <<<"$body" \
&& systemctl is-active --quiet thor-monitor; then
return 0
fi
sleep "${THOR_DEPLOY_HEALTH_SLEEP:-2}"
done
log "last /health reply: ${body:-none}"
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 thor -u thor-monitor"
fi
exit 1
+21
View File
@@ -0,0 +1,21 @@
[
{
"id": "thor-deploy",
"execute-command": "/usr/bin/sudo",
"pass-arguments-to-command": [
{"source": "string", "name": "/usr/local/bin/thor_deploy.sh"},
{"source": "payload", "name": "sha"},
{"source": "payload", "name": "ts"}
],
"command-working-directory": "/",
"include-command-output-in-response": false,
"trigger-rule": {
"and": [
{"match": {"type": "payload-hmac-sha256", "secret": "REPLACE_WITH_WEBHOOK_SECRET",
"parameter": {"source": "header", "name": "X-Gitea-Signature"}}},
{"match": {"type": "value", "value": "refs/heads/main",
"parameter": {"source": "payload", "name": "ref"}}}
]
}
}
]
+2
View File
@@ -0,0 +1,2 @@
# /etc/sudoers.d/thor-deploy (mode 0440): the webhook user may run the deploy script only.
webhook ALL=(root) NOPASSWD: /usr/local/bin/thor_deploy.sh
+14
View File
@@ -0,0 +1,14 @@
[Unit]
Description=Webhook listener for Thor deploys
After=network-online.target
Wants=network-online.target
[Service]
User=webhook
Group=webhook
ExecStart=/usr/bin/webhook -hooks /etc/webhook/hooks.json -port 9000 -verbose
Restart=always
# No NoNewPrivileges here: the hook runs the deploy script through sudo.
[Install]
WantedBy=multi-user.target
+25
View File
@@ -0,0 +1,25 @@
#!/bin/bash
# Installs and starts a throwaway MariaDB inside a CI job container (as root) and creates
# the database and user from DB_NAME, DB_USER and DB_PASSWORD. Same approach as Pulse's
# scripts/ci/mariadb.sh: the Gitea runner can't reach service containers by name.
set -euo pipefail
: "${DB_NAME:?}" "${DB_USER:?}" "${DB_PASSWORD:?}"
for attempt in 1 2 3; do
if apt-get -o Acquire::Retries=3 update -qq \
&& DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 install -y -qq --no-install-recommends \
mariadb-server >/dev/null; then
break
fi
[ "$attempt" = 3 ] && { echo "::error::could not install mariadb-server"; exit 1; }
echo "apt failed (attempt $attempt); retrying in 10s"
sleep 10
done
mkdir -p /run/mysqld && chown mysql:mysql /run/mysqld
if ! mariadb-admin ping --silent 2>/dev/null; then
(mariadbd --user=mysql --bind-address=127.0.0.1 --port=3306 >/tmp/mariadb.log 2>&1 &)
fi
for _ in $(seq 1 30); do mariadb-admin ping --silent 2>/dev/null && break; sleep 1; done
mariadb -e "CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\`;
CREATE USER IF NOT EXISTS '${DB_USER}'@'127.0.0.1' IDENTIFIED BY '${DB_PASSWORD}';
GRANT ALL ON \`${DB_NAME}\`.* TO '${DB_USER}'@'127.0.0.1';"
mariadb --version
+17
View File
@@ -0,0 +1,17 @@
#!/bin/bash
# Creates /tmp/venv with Thor's runtime and dev dependencies inside a CI job container
# (Debian trixie: Python 3.13, the same as production on CT 173).
set -euo pipefail
for attempt in 1 2 3; do
if apt-get -o Acquire::Retries=3 update -qq \
&& DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=3 install -y -qq --no-install-recommends \
python3 python3-venv python3-pip >/dev/null; then
break
fi
[ "$attempt" = 3 ] && { echo "::error::could not install python3"; exit 1; }
echo "apt failed (attempt $attempt); retrying in 10s"
sleep 10
done
python3 -m venv /tmp/venv
/tmp/venv/bin/pip install --quiet --disable-pip-version-check -r requirements.txt -r requirements-dev.txt
/tmp/venv/bin/python --version
+115
View File
@@ -0,0 +1,115 @@
"""Runs deploy/thor_deploy.sh in a sandbox: a real git origin, fake systemctl/nginx/pip/curl."""
import os
import shutil
import stat
import subprocess # nosec B404 - test runs our own script
import time
from pathlib import Path
import pytest
SCRIPT = Path(__file__).resolve().parent.parent / 'deploy' / 'thor_deploy.sh'
pytestmark = pytest.mark.skipif(shutil.which('git') is None or shutil.which('flock') is None,
reason='needs git and flock')
def sh(*args, cwd=None):
return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout.strip() # nosec
def shim(path: Path, body: str):
path.write_text('#!/bin/bash\n' + body + '\n')
path.chmod(path.stat().st_mode | stat.S_IEXEC)
@pytest.fixture
def sandbox(tmp_path):
origin = tmp_path / 'origin'
origin.mkdir()
sh('git', 'init', '-q', '-b', 'main', cwd=origin)
sh('git', 'config', 'user.email', 't@t', cwd=origin)
sh('git', 'config', 'user.name', 't', cwd=origin)
(origin / 'deploy' / 'systemd').mkdir(parents=True)
(origin / 'deploy' / 'nginx').mkdir()
for f in ('thor.service', 'thor-monitor.service'):
(origin / 'deploy' / 'systemd' / f).write_text(f'[Unit]\nDescription={f}\n')
(origin / 'deploy' / 'nginx' / 'thor').write_text('server {}\n')
(origin / 'requirements.txt').write_text('flask\n')
sh('git', 'add', '-A', cwd=origin)
sh('git', 'commit', '-q', '-m', 'one', cwd=origin)
first = sh('git', 'rev-parse', 'HEAD', cwd=origin)
(origin / 'requirements.txt').write_text('flask\nrequests\n')
sh('git', 'commit', '-qam', 'two', cwd=origin)
second = sh('git', 'rev-parse', 'HEAD', cwd=origin)
app = tmp_path / 'app'
sh('git', 'clone', '-q', str(origin), str(app))
sh('git', 'checkout', '-q', '--detach', first, cwd=app)
bin_dir = tmp_path / 'bin'
bin_dir.mkdir()
calls = tmp_path / 'calls.log'
shim(bin_dir / 'systemctl', f'echo "systemctl $*" >> {calls}; exit 0')
shim(bin_dir / 'nginx', f'echo "nginx $*" >> {calls}; exit 0')
# /health reports whatever revision file says, unless HEALTH_BROKEN is set.
revision = tmp_path / 'revision.env'
shim(bin_dir / 'curl', f'[ -n "$HEALTH_BROKEN" ] && exit 7; . {revision} 2>/dev/null; '
'echo "{\\"sha\\": \\"$THOR_SHA\\", \\"db\\": true}"')
shim(bin_dir / 'install', 'src="${@: -2:1}"; dst="${@: -1}"; cp "$src" "$dst"')
venv = tmp_path / 'venv'
(venv / 'bin').mkdir(parents=True)
shim(venv / 'bin' / 'pip', f'echo "pip $*" >> {calls}')
(tmp_path / 'systemd').mkdir()
(tmp_path / 'nginx').mkdir()
env = dict(os.environ)
env.update({
'PATH': f'{bin_dir}:{env["PATH"]}',
'THOR_DEPLOY_APP_ROOT': str(app), 'THOR_DEPLOY_VENV': str(venv),
'THOR_DEPLOY_REVISION_FILE': str(revision), 'THOR_DEPLOY_STATE_DIR': str(tmp_path / 'state'),
'THOR_DEPLOY_LOG': str(tmp_path / 'deploy.log'), 'THOR_DEPLOY_LOCK': str(tmp_path / 'lock'),
'THOR_DEPLOY_SYSTEMD_DIR': str(tmp_path / 'systemd'),
'THOR_DEPLOY_NGINX_SITE': str(tmp_path / 'nginx' / 'thor'),
'THOR_DEPLOY_HEALTH_TRIES': '2', 'THOR_DEPLOY_HEALTH_SLEEP': '0',
})
return {'env': env, 'app': app, 'first': first, 'second': second, 'calls': calls,
'revision': revision, 'tmp': tmp_path}
def run(sb, sha, ts=None, **extra):
env = dict(sb['env'], **extra)
return subprocess.run(['bash', str(SCRIPT), sha, str(ts or int(time.time()))], env=env, # nosec
capture_output=True, text=True)
def test_deploys_exact_sha_installs_files_and_restarts(sandbox):
r = run(sandbox, sandbox['second'])
assert r.returncode == 0, r.stdout + r.stderr
assert sh('git', 'rev-parse', 'HEAD', cwd=sandbox['app']) == sandbox['second']
assert sandbox['revision'].read_text() == f'THOR_SHA={sandbox["second"]}\n'
calls = sandbox['calls'].read_text()
assert 'pip install' in calls and 'systemctl daemon-reload' in calls
assert 'nginx -t' in calls and 'systemctl restart thor thor-monitor' in calls
assert (sandbox['tmp'] / 'systemd' / 'thor.service').exists()
def test_refuses_bad_input_old_and_replayed_requests(sandbox):
assert run(sandbox, 'not-a-sha').returncode == 1
assert run(sandbox, sandbox['second'], ts=int(time.time()) - 3600).returncode == 1
ts = int(time.time())
assert run(sandbox, sandbox['second'], ts=ts).returncode == 0
replay = run(sandbox, sandbox['second'], ts=ts)
assert replay.returncode == 1 and 'not newer' in replay.stdout
def test_refuses_commit_not_on_main(sandbox):
r = run(sandbox, 'f' * 40)
assert r.returncode == 1 and 'not found' in r.stdout
def test_rolls_back_when_never_healthy(sandbox):
r = run(sandbox, sandbox['second'], HEALTH_BROKEN='1')
assert r.returncode == 1
assert 'rolling back' in r.stdout
assert sh('git', 'rev-parse', 'HEAD', cwd=sandbox['app']) == sandbox['first']
assert sandbox['revision'].read_text() == f'THOR_SHA={sandbox["first"]}\n'