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

+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