diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..d62f352 --- /dev/null +++ b/.flake8 @@ -0,0 +1,3 @@ +[flake8] +max-line-length = 120 +exclude = .git,__pycache__,.venv diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..73b405c --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -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]|̵[12];|ȁ[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: ` 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8e4f74d --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.venv/ +__pycache__/ +*.pyc +.coverage +.pytest_cache/ diff --git a/README.md b/README.md index 29fc534..9ed1261 100644 --- a/README.md +++ b/README.md @@ -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`. diff --git a/deploy/bootstrap.sh b/deploy/bootstrap.sh new file mode 100644 index 0000000..bcd0f5b --- /dev/null +++ b/deploy/bootstrap.sh @@ -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/. +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)" diff --git a/deploy/nginx/thor b/deploy/nginx/thor new file mode 100644 index 0000000..5481748 --- /dev/null +++ b/deploy/nginx/thor @@ -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; + } +} diff --git a/deploy/systemd/thor-monitor.service b/deploy/systemd/thor-monitor.service new file mode 100644 index 0000000..d45cecf --- /dev/null +++ b/deploy/systemd/thor-monitor.service @@ -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 diff --git a/deploy/systemd/thor.service b/deploy/systemd/thor.service new file mode 100644 index 0000000..3d6f35a --- /dev/null +++ b/deploy/systemd/thor.service @@ -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 diff --git a/deploy/thor.example.json b/deploy/thor.example.json new file mode 100644 index 0000000..4d57bc1 --- /dev/null +++ b/deploy/thor.example.json @@ -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" + } +} diff --git a/deploy/thor_deploy.sh b/deploy/thor_deploy.sh new file mode 100755 index 0000000..a6da021 --- /dev/null +++ b/deploy/thor_deploy.sh @@ -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 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 (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 diff --git a/deploy/webhook/hooks.json.example b/deploy/webhook/hooks.json.example new file mode 100644 index 0000000..c212380 --- /dev/null +++ b/deploy/webhook/hooks.json.example @@ -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"}}} + ] + } + } +] diff --git a/deploy/webhook/sudoers-thor-deploy b/deploy/webhook/sudoers-thor-deploy new file mode 100644 index 0000000..5e5ee41 --- /dev/null +++ b/deploy/webhook/sudoers-thor-deploy @@ -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 diff --git a/deploy/webhook/webhook.service b/deploy/webhook/webhook.service new file mode 100644 index 0000000..f726048 --- /dev/null +++ b/deploy/webhook/webhook.service @@ -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 diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..f14816f --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,5 @@ +pytest>=8 +pytest-cov>=5 +flake8>=7 +bandit>=1.7 +pip-audit>=2.7 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7249e17 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +flask>=3.0 +gunicorn>=22 +pymysql>=1.1 +requests>=2.32 diff --git a/scripts/ci/mariadb.sh b/scripts/ci/mariadb.sh new file mode 100755 index 0000000..ec900c4 --- /dev/null +++ b/scripts/ci/mariadb.sh @@ -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 diff --git a/scripts/ci/python-env.sh b/scripts/ci/python-env.sh new file mode 100755 index 0000000..0b41e3b --- /dev/null +++ b/scripts/ci/python-env.sh @@ -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 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/fakes.py b/tests/fakes.py new file mode 100644 index 0000000..0bef5be --- /dev/null +++ b/tests/fakes.py @@ -0,0 +1,134 @@ +"""Test doubles: an in-memory Store, an HTTP session that serves canned replies, sources.""" +import json +from typing import Any, Dict, List, Optional + +import requests + +from thor.clients import SourceError +from thor.db import DatabaseError + + +class FakeStore: + """Same methods as thor.db.Store, kept in memory. Set ``down = True`` to simulate CT 149 away.""" + + def __init__(self): + self.down = False + self.state: Dict[str, Any] = {} + self.cycles: List[dict] = [] + self.sources: Dict[str, dict] = {} + self.blind: List[dict] = [] + self.calls: List[str] = [] + + def _check(self, name): + self.calls.append(name) + if self.down: + raise DatabaseError('Lost connection to MySQL server') + + def set_state(self, key, value, now): + self._check('set_state') + self.state[key] = json.loads(json.dumps(value, default=str)) + + def get_state(self, key, default=None): + self._check('get_state') + return self.state.get(key, default) + + def record_cycle(self, **kw): + self._check('record_cycle') + self.cycles.append(kw) + return len(self.cycles) + + def prune_cycles(self, older_than): + self._check('prune_cycles') + before = len(self.cycles) + self.cycles = [c for c in self.cycles if c['started'] >= older_than] + return before - len(self.cycles) + + def source_statuses(self): + self._check('source_statuses') + return {k: dict(v) for k, v in self.sources.items()} + + def save_source_status(self, name, up, since, last_ok, last_error, now): + self._check('save_source_status') + self.sources[name] = {'up': up, 'since': since, 'last_ok': last_ok, 'last_error': last_error} + + def open_blind_period(self, source, started, reason): + self._check('open_blind_period') + self.blind.append({'source': source, 'started': started, 'ended': None, 'reason': reason}) + + def close_blind_period(self, source, ended): + self._check('close_blind_period') + for b in self.blind: + if b['source'] == source and b['ended'] is None: + b['ended'] = ended + + def blind_periods(self, since): + self._check('blind_periods') + return [b for b in self.blind if b['ended'] is None or b['ended'] >= since] + + +class FakeResponse: + def __init__(self, status: int = 200, body: Any = None, text: Optional[str] = None): + self.status_code = status + self._body = body + self.text = text if text is not None else json.dumps(body) + + def json(self): + if self._body is None: + raise ValueError('no JSON') + return self._body + + def raise_for_status(self): + if self.status_code >= 400: + raise requests.HTTPError(f'HTTP {self.status_code}') + + +class FakeSession: + """Serves replies in order for each (method, url-prefix). Records every request.""" + + def __init__(self): + self.routes: List[tuple] = [] + self.requests: List[dict] = [] + + def add(self, method: str, url_prefix: str, *replies): + self.routes.append((method.upper(), url_prefix, list(replies))) + return self + + def _serve(self, method, url, **kw): + self.requests.append({'method': method, 'url': url, **kw}) + for m, prefix, replies in self.routes: + if m == method and url.startswith(prefix): + reply = replies[0] if len(replies) == 1 else replies.pop(0) + if isinstance(reply, Exception): + raise reply + return reply + raise requests.ConnectionError(f'no route for {method} {url}') + + def get(self, url, **kw): + return self._serve('GET', url, **kw) + + def post(self, url, **kw): + return self._serve('POST', url, **kw) + + +class FakeSource: + def __init__(self, name: str, up: bool = True, error: str = 'connection refused'): + self.name = name + self.up = up + self.error = error + self.pings = 0 + + def ping(self): + self.pings += 1 + if not self.up: + raise SourceError(self.name, self.error) + + +class Clock: + def __init__(self, t: float = 1_795_575_600.0): # 2026-11-25 03:00:00 UTC + self.t = t + + def __call__(self): + return self.t + + def advance(self, seconds: float): + self.t += seconds diff --git a/tests/test_clients.py b/tests/test_clients.py new file mode 100644 index 0000000..05aacfe --- /dev/null +++ b/tests/test_clients.py @@ -0,0 +1,236 @@ +import pytest +import requests + +from thor.clients import SourceError +from thor.clients.gandalf import GandalfClient +from thor.clients.loki import LokiClient, find_shutdown, quote, shutdown_query +from thor.clients.prometheus import PrometheusClient +from thor.clients.proxmox import ProxmoxClient +from thor.clients.tinker import TinkerClient, backoff_s + +from .fakes import FakeResponse, FakeSession + +PROM = 'http://prom:9090' +LOKI = 'http://loki:3100' + + +# -- Prometheus ---------------------------------------------------------- +def test_prometheus_instant_query_parses_and_skips_bad_values(): + sess = FakeSession().add('GET', f'{PROM}/api/v1/query', FakeResponse(200, { + 'status': 'success', 'data': {'result': [ + {'metric': {'instance': '10.10.10.4:9100'}, 'value': [1795410700.1, '11']}, + {'metric': {}, 'value': [1795410700.1, 'NaN-not']}, + ]}})) + out = PrometheusClient(PROM, session=sess).query('node_vmstat_oom_kill', at=1795410700) + assert out == [{'metric': {'instance': '10.10.10.4:9100'}, 'ts': 1795410700.1, 'value': 11.0}] + assert sess.requests[0]['params']['time'] == '1795410700.000' + + +def test_prometheus_range_query(): + sess = FakeSession().add('GET', f'{PROM}/api/v1/query_range', FakeResponse(200, { + 'status': 'success', 'data': {'result': [{'metric': {'a': 'b'}, 'values': [[1, '2'], [3, 'x']]}]}})) + out = PrometheusClient(PROM, session=sess).query_range('up', 0, 10, 5) + assert out == [{'metric': {'a': 'b'}, 'values': [(1.0, 2.0)]}] + assert sess.requests[0]['params']['step'] == '5' + + +@pytest.mark.parametrize('reply', [ + FakeResponse(500, {'status': 'error'}), + FakeResponse(200, {'status': 'error', 'error': 'bad query'}), + FakeResponse(200, None, text=''), + requests.ConnectionError('refused'), + requests.Timeout('slow'), +]) +def test_prometheus_failures_are_source_errors(reply): + sess = FakeSession().add('GET', PROM, reply) + with pytest.raises(SourceError) as e: + PrometheusClient(PROM, session=sess).ping() + assert e.value.source == 'prometheus' + + +# -- Loki ---------------------------------------------------------------- +def _loki_reply(*streams): + return FakeResponse(200, {'status': 'success', 'data': {'result': [ + {'stream': labels, 'values': values} for labels, values in streams]}}) + + +def test_loki_lines_keep_labels_and_sort(): + sess = FakeSession().add('GET', f'{LOKI}/loki/api/v1/query_range', _loki_reply( + ({'host': 'a'}, [['2000000000', 'old']]), + ({'host': 'b'}, [['3000000000', 'new']]), + )) + out = LokiClient(LOKI, session=sess).lines('{job="journal"}', 0, 10) + assert out == [(3.0, 'new', {'host': 'b'}), (2.0, 'old', {'host': 'a'})] + fwd = LokiClient(LOKI, session=sess).lines('{job="journal"}', 0, 10, direction='forward') + assert [x[1] for x in fwd] == ['old', 'new'] + + +def test_loki_refuses_windows_over_30_days_and_errors(): + with pytest.raises(SourceError): + LokiClient(LOKI, session=FakeSession()).lines('{a="b"}', 0, 31 * 86400) + sess = FakeSession().add('GET', LOKI, FakeResponse(500, {'status': 'error'})) + with pytest.raises(SourceError): + LokiClient(LOKI, session=sess).ping() + + +def test_find_shutdown_matches_logind_line_and_quotes_host(): + line = 'The system will power off now!' + sess = FakeSession().add('GET', LOKI, _loki_reply( + ({'host': 'compute-storage-01'}, [['1795576895000000000', line]]))) + found = find_shutdown(LokiClient(LOKI, session=sess), 'compute-storage-01', before=1795577000) + assert found == {'at': 1795576895.0, 'kind': 'power off', 'line': line} + q = sess.requests[0]['params']['query'] + assert q.startswith('{host="compute-storage-01", job="journal", unit="systemd-logind.service"}') + assert shutdown_query('a"b').startswith('{host="a\\"b"') + assert quote('x\\y') == 'x\\\\y' + + +def test_find_shutdown_none_vs_unknown(): + sess = FakeSession().add('GET', LOKI, _loki_reply()) + assert find_shutdown(LokiClient(LOKI, session=sess), 'storage-01', before=100.0) is None + down = FakeSession().add('GET', LOKI, requests.ConnectionError('x')) + with pytest.raises(SourceError): + find_shutdown(LokiClient(LOKI, session=down), 'storage-01', before=100.0) + + +# -- Proxmox ------------------------------------------------------------- +def test_proxmox_fails_over_between_nodes_and_remembers(): + sess = (FakeSession() + .add('GET', 'https://10.0.0.1:8006', requests.ConnectionError('down')) + .add('GET', 'https://10.0.0.2:8006', FakeResponse(200, {'data': [ + {'name': 'noout', 'value': 1}, {'name': 'pause', 'value': 0}]}))) + px = ProxmoxClient(['10.0.0.1', '10.0.0.2'], 'thor@pve!monitor', 'secret', session=sess) + assert px.ceph_flags() == {'noout': True, 'pause': False} + assert sess.requests[1]['headers']['Authorization'] == 'PVEAPIToken=thor@pve!monitor=secret' + assert sess.requests[1]['verify'] is False + px.ceph_flags() + assert sess.requests[2]['url'].startswith('https://10.0.0.2:8006') # preferred node first now + + +def test_proxmox_token_refusal_does_not_try_other_nodes(): + sess = (FakeSession().add('GET', 'https://10.0.0.1:8006', FakeResponse(401, {})) + .add('GET', 'https://10.0.0.2:8006', FakeResponse(200, {'data': {}}))) + with pytest.raises(SourceError, match='token refused'): + ProxmoxClient(['10.0.0.1', '10.0.0.2'], 'id', 's', session=sess).ping() + assert len(sess.requests) == 1 + + +def test_proxmox_unconfigured_and_all_nodes_down(): + with pytest.raises(SourceError, match='no API token'): + ProxmoxClient(['10.0.0.1'], '', '', session=FakeSession()).ping() + sess = FakeSession().add('GET', 'https://', requests.ConnectionError('x')) + with pytest.raises(SourceError, match='10.0.0.1'): + ProxmoxClient(['10.0.0.1'], 'id', 's', session=sess).cluster_status() + + +def test_proxmox_helpers_pass_params(): + sess = FakeSession().add('GET', 'https://n:8006', FakeResponse(200, {'data': [{'vmid': 154}]})) + px = ProxmoxClient(['n'], 'id', 's', session=sess) + assert px.resources('vm') == [{'vmid': 154}] + assert sess.requests[0]['params'] == {'type': 'vm'} + assert px.ha_status() == [{'vmid': 154}] + + +# -- Gandalf ------------------------------------------------------------- +T2_SUPPRESSION = {'id': 2, 'reason': 'switch update', 'started_at': '2026-11-25T03:11:39Z', + 'ended_at': '2026-11-25T03:41:39Z', 'state': 'expired', 'target_type': 'all'} + + +def test_gandalf_suppressions_with_history(): + sess = FakeSession().add('GET', 'http://g/api/suppressions', + FakeResponse(200, {'since': 'x', 'suppressions': [T2_SUPPRESSION]})) + g = GandalfClient('http://g/', 'key', session=sess) + assert g.suppressions(hours=48) == [T2_SUPPRESSION] + req = sess.requests[0] + assert req['params'] == {'include_ended': '1', 'hours': '48'} + assert req['headers']['Authorization'] == 'Bearer key' + g.suppressions(hours=10_000) + assert sess.requests[1]['params']['hours'] == str(31 * 24) + + +def test_gandalf_errors(): + with pytest.raises(SourceError, match='no API key'): + GandalfClient('http://g', '', session=FakeSession()).ping() + sess = FakeSession().add('GET', 'http://g', FakeResponse(401, {})) + with pytest.raises(SourceError, match='key refused'): + GandalfClient('http://g', 'k', session=sess).status() + bad = FakeSession().add('GET', 'http://g', FakeResponse(200, ['not', 'a', 'dict'])) + with pytest.raises(SourceError): + GandalfClient('http://g', 'k', session=bad).status() + with pytest.raises(SourceError): + GandalfClient('http://g', 'k', session=bad).suppressions() + + +# -- Tinker -------------------------------------------------------------- +TINKER = 'https://t/create_ticket_api.php' + + +def test_tinker_create_sends_dedup_key_and_reads_action(): + sess = FakeSession().add('POST', TINKER, FakeResponse(200, {'success': True, 'ticket_id': '123', 'action': 'new'})) + t = TinkerClient(TINKER, 'k', session=sess) + r = t.create(title='[h][auto][thor][software] x', description='d', priority=3, category='Software', + ticket_type='Issue', dedup_key='host:h:oom') + assert (r.ticket_id, r.action, r.ok) == ('123', 'new', True) + body = sess.requests[0]['json'] + assert body['dedup_key'] == 'host:h:oom' and body['priority'] == '3' and body['status'] == 'Open' + + +def test_tinker_create_failures(): + assert not TinkerClient('', '').create(title='t', description='', priority=3, category='c', + ticket_type='Issue', dedup_key='k').ok + sess = FakeSession().add('POST', TINKER, FakeResponse(403, {})) + t = TinkerClient(TINKER, 'k', session=sess) + r = t.create(title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k') + assert r.error == 'HTTP 403' + assert t.writes_denied + assert t.comment('1', 'x') is False + dup = FakeSession().add('POST', TINKER, FakeResponse(200, {'existing_ticket_id': 77})) + r = TinkerClient(TINKER, 'k', session=dup).create( + title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k') + assert (r.ticket_id, r.action) == ('77', 'deduplicated') + odd = FakeSession().add('POST', TINKER, FakeResponse(200, {'success': False})) + assert 'unexpected' in TinkerClient(TINKER, 'k', session=odd).create( + title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k').error + + +def test_tinker_comment_and_reads(): + sess = (FakeSession() + .add('POST', 'https://t/api/ticket_comment_api.php', FakeResponse(200, {'success': True}), + FakeResponse(404, {}), requests.ConnectionError('x')) + .add('GET', 'https://t/api/tickets_api.php', + FakeResponse(200, {'success': True, 'pages': 2, + 'tickets': [{'ticket_id': 1, 'title': 'a', 'status': 'Open'}]}), + FakeResponse(200, {'success': True, 'pages': 2, + 'tickets': [{'ticket_id': 2, 'title': 'b', 'status': 'Pending'}]}), + FakeResponse(200, {'success': True, 'ticket': {'ticket_id': '693930698'}}))) + t = TinkerClient(TINKER, 'k', session=sess) + assert t.comment('1', 'hi') is True + assert t.comment('1', 'hi') is True # deleted ticket: done + assert t.comment('1', 'hi') is False # network error: retry later + assert set(t.open_tickets()) == {'1', '2'} + assert t.ticket('693930698') == {'ticket_id': '693930698'} + assert TinkerClient('', '').open_tickets() is None + + +def test_backoff(): + assert backoff_s(1) == 120 + assert backoff_s(3) == 480 + assert backoff_s(50) == 3600 + + +def test_tinker_network_errors_and_unknown_reads(): + down = FakeSession().add('POST', TINKER, requests.ConnectionError('x')).add( + 'GET', 'https://t/api/tickets_api.php', requests.ConnectionError('x')) + t = TinkerClient(TINKER, 'k', session=down) + r = t.create(title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k') + assert not r.ok and r.ticket_id is None and 'x' in r.error + assert t.open_tickets() is None + assert t.ticket('1') is None + assert 'TicketResult' in repr(r) + refused = FakeSession().add('POST', 'https://t/api/ticket_comment_api.php', FakeResponse(401, {})) + assert TinkerClient(TINKER, 'k', session=refused).comment('1', 'x') is False + missing = FakeSession().add('GET', 'https://t/api/tickets_api.php', FakeResponse(404, {}), + FakeResponse(200, {'success': False})) + tm = TinkerClient(TINKER, 'k', session=missing) + assert tm.ticket('1') is None + assert tm.open_tickets() is None diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..8ae1f9e --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,41 @@ +import json + +from thor import config + + +def test_parse_env_file_handles_comments_quotes_and_junk(): + text = '# comment\n\nA=1\nB = "two words"\nC=\'x=y\'\nnot a line\n=nokey\n' + assert config.parse_env_file(text) == {'A': '1', 'B': 'two words', 'C': 'x=y'} + + +def test_defaults_without_any_files(tmp_path): + s = config.load(str(tmp_path / 'missing.json'), str(tmp_path / 'nodir'), environ={}) + assert s.prometheus_url == 'http://10.10.10.48:9090' + assert s.cycle_seconds == 120 + assert s.catchup_hours == 24 + assert s.stale_after_s == 360 + assert not s.database.configured + assert s.proxmox_nodes[0] == '10.10.10.11' + + +def test_json_and_env_files_and_environment_layer_in_order(tmp_path): + (tmp_path / 'thor.json').write_text(json.dumps({ + 'prometheus_url': 'http://prom:9090/', 'cycle_seconds': 60, 'checks': {'memory': 'live', 'x': 'bogus'}, + 'proxmox_nodes': ['10.0.0.1'], 'proxmox_verify_tls': 'yes'})) + env = tmp_path / 'env' + env.mkdir() + (env / 'db.env').write_text('DB_HOST=10.10.10.50\nDB_PASSWORD=from-file\n') + (env / 'pve.env').write_text('PVE_TOKEN_ID=thor@pve!monitor\nPVE_TOKEN_SECRET=s3cret\n') + (env / 'ignored.txt').write_text('DB_HOST=wrong\n') + s = config.load(str(tmp_path / 'thor.json'), str(env), environ={'DB_PASSWORD': 'from-env', 'lower': 'x'}) + assert s.prometheus_url == 'http://prom:9090' + assert s.cycle_seconds == 60 + assert s.proxmox_nodes == ['10.0.0.1'] + assert s.proxmox_verify_tls is True + assert s.database.host == '10.10.10.50' + assert s.database.password == 'from-env' + assert s.database.configured + assert s.proxmox_token_id == 'thor@pve!monitor' + assert s.check_mode('memory') == 'live' + assert s.check_mode('x') == 'shadow' # unknown mode falls back to shadow + assert s.check_mode('never-set') == 'shadow' # every check starts in shadow diff --git a/tests/test_db_mariadb.py b/tests/test_db_mariadb.py new file mode 100644 index 0000000..d038991 --- /dev/null +++ b/tests/test_db_mariadb.py @@ -0,0 +1,63 @@ +"""Runs against a real MariaDB when THOR_TEST_DB_HOST is set (the CI integration job).""" +import os + +import pytest + +from thor.config import DatabaseSettings +from thor.db import MIGRATIONS, Database, DatabaseError, Store, from_dt, to_dt + +pytestmark = pytest.mark.skipif(not os.environ.get('THOR_TEST_DB_HOST'), reason='needs THOR_TEST_DB_HOST') + + +@pytest.fixture +def db(): + d = Database(DatabaseSettings( + host=os.environ['THOR_TEST_DB_HOST'], port=int(os.environ.get('THOR_TEST_DB_PORT', '3306')), + name=os.environ.get('THOR_TEST_DB_NAME', 'thor'), user=os.environ.get('THOR_TEST_DB_USER', 'thor'), + password=os.environ.get('THOR_TEST_DB_PASSWORD', ''))) + for t in ('state', 'cycles', 'source_status', 'blind_periods', 'schema_version'): + d.execute(f'DROP TABLE IF EXISTS {t}') # nosec B608 - fixed table names + return d + + +def test_migrate_is_idempotent(db): + assert db.migrate() == len(MIGRATIONS) + assert db.migrate() == len(MIGRATIONS) + assert len(db.query('SELECT * FROM schema_version')) == len(MIGRATIONS) + + +def test_store_round_trips(db): + db.migrate() + s = Store(db) + t = 1795575600.123 + s.set_state('last_cycle', {'blind': ['loki'], 'ok': True}, t) + s.set_state('last_cycle', {'blind': [], 'ok': True}, t + 1) + assert s.get_state('last_cycle') == {'blind': [], 'ok': True} + assert s.get_state('missing', 'dflt') == 'dflt' + s.record_cycle(started=t, finished=t + 2, window_start=t - 120, window_end=t, ok=True, blind=['loki']) + s.record_cycle(started=t - 100000, finished=t, window_start=t, window_end=t, ok=False, blind=[], error='x') + assert s.prune_cycles(t - 1) == 1 + s.save_source_status('loki', False, t, None, 'HTTP 500', t) + s.save_source_status('loki', True, t + 5, t + 5, '', t + 5) + loki = s.source_statuses()['loki'] + assert loki == {'up': True, 'since': pytest.approx(t + 5, abs=0.001), + 'last_ok': pytest.approx(t + 5, abs=0.001), 'last_error': ''} + s.open_blind_period('loki', t, 'HTTP 500') + assert s.blind_periods(t - 10)[0]['ended'] is None + s.close_blind_period('loki', t + 60) + periods = s.blind_periods(t - 10) + assert periods[0]['ended'] == pytest.approx(t + 60, abs=0.001) + assert s.blind_periods(t + 61) == [] + + +def test_time_conversion_is_utc(): + t = 1795575600.5 + assert from_dt(to_dt(t)) == t + assert to_dt(t).isoformat() == '2026-11-25T03:00:00.500000' + assert to_dt(None) is None and from_dt(None) is None + + +def test_unreachable_database_raises_database_error(): + d = Database(DatabaseSettings(host='127.0.0.1', port=1, user='x', password='y')) + with pytest.raises(DatabaseError): + d.query('SELECT 1') diff --git a/tests/test_db_unit.py b/tests/test_db_unit.py new file mode 100644 index 0000000..1a2e8a1 --- /dev/null +++ b/tests/test_db_unit.py @@ -0,0 +1,135 @@ +"""Database connection handling and migrations, with a fake PyMySQL connection.""" +import pymysql +import pytest + +from thor.config import DatabaseSettings +from thor.db import MIGRATIONS, Database, DatabaseError, Store, _statements + + +class FakeCursor: + def __init__(self, conn): + self.conn = conn + self.lastrowid = 0 + self.rowcount = 0 + self._rows = [] + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def execute(self, sql, params=()): + if self.conn.fail_execute: + raise pymysql.err.OperationalError(2013, 'Lost connection') + self.conn.executed.append((' '.join(sql.split()), params)) + if 'MAX(version)' in sql: + self._rows = [{'v': self.conn.version}] + elif sql.startswith('SELECT v FROM state'): + self._rows = [{'v': self.conn.state_value}] if self.conn.state_value is not None else [] + else: + self._rows = [] + self.rowcount = 1 + self.lastrowid = 7 if sql.lstrip().startswith('INSERT') else 0 + + def fetchall(self): + return self._rows + + +class FakeConn: + def __init__(self): + self.executed = [] + self.fail_execute = False + self.fail_ping = False + self.closed = False + self.version = 0 + self.state_value = None + + def cursor(self): + return FakeCursor(self) + + def ping(self, reconnect=False): + assert reconnect is False # deprecated in PyMySQL 1.2 + if self.fail_ping: + raise pymysql.err.OperationalError(2006, 'gone away') + + def close(self): + self.closed = True + + +def make_db(): + conns = [] + + def connect(): + c = FakeConn() + conns.append(c) + return c + return Database(DatabaseSettings(host='h', password='p'), connect=connect), conns + + +def test_reuses_connection_and_reconnects_after_failed_ping(): + db, conns = make_db() + db.execute('SELECT 1') + db.execute('SELECT 2') + assert len(conns) == 1 + conns[0].fail_ping = True + db.execute('SELECT 3') + assert len(conns) == 2 and conns[0].closed + assert conns[1].executed == [('SELECT 3', ())] + + +def test_mysql_errors_become_database_errors_and_drop_the_connection(): + db, conns = make_db() + db.execute('SELECT 1') + conns[0].fail_execute = True + with pytest.raises(DatabaseError, match='Lost connection'): + db.query('SELECT 1') + db.execute('SELECT 2') + assert len(conns) == 2 + + +def test_connect_failure_is_database_error(): + def connect(): + raise pymysql.err.OperationalError(2003, "Can't connect") + with pytest.raises(DatabaseError): + Database(DatabaseSettings(), connect=connect).query('SELECT 1') + + +def test_migrate_applies_pending_migrations_once(): + db, conns = make_db() + assert db.migrate() == len(MIGRATIONS) + executed = [sql for sql, _ in conns[0].executed] + creates = [s for s in executed if s.startswith('CREATE TABLE IF NOT EXISTS') and 'schema_version' not in s] + assert len(creates) == sum(len(list(_statements(m))) for m in MIGRATIONS) + assert any(s.startswith('INSERT INTO schema_version') for s in executed) + conns[0].executed.clear() + conns[0].version = len(MIGRATIONS) + assert db.migrate() == len(MIGRATIONS) + assert not any(s.startswith('INSERT INTO schema_version') for s in (x for x, _ in conns[0].executed)) + + +def test_store_state_json_and_bad_json(): + db, conns = make_db() + store = Store(db) + store.set_state('k', {'a': 1}, 1795575600.0) + sql, params = conns[0].executed[-1] + assert sql.startswith('INSERT INTO state') and params[1] == '{"a": 1}' + conns[0].state_value = '{"a": 1}' + assert store.get_state('k') == {'a': 1} + conns[0].state_value = 'not json' + assert store.get_state('k', 'dflt') == 'dflt' + conns[0].state_value = None + assert store.get_state('k', 'dflt') == 'dflt' + + +def test_store_writes_pass_utc_datetimes_and_truncate(): + db, conns = make_db() + store = Store(db) + assert store.record_cycle(started=1795575600.0, finished=1795575602.0, window_start=1795575480.0, + window_end=1795575600.0, ok=True, blind=['loki', 'gandalf']) == 7 + _sql, params = conns[0].executed[-1] + assert params[0].isoformat() == '2026-11-25T03:00:00' + assert params[5] == 'gandalf,loki' + assert params[6] is None + store.open_blind_period('loki', 1795575600.0, 'x' * 5000) + assert len(conns[0].executed[-1][1][2]) == 2000 diff --git a/tests/test_deploy_script.py b/tests/test_deploy_script.py new file mode 100644 index 0000000..e21c257 --- /dev/null +++ b/tests/test_deploy_script.py @@ -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' diff --git a/tests/test_monitor.py b/tests/test_monitor.py new file mode 100644 index 0000000..79cd654 --- /dev/null +++ b/tests/test_monitor.py @@ -0,0 +1,196 @@ +from thor.config import Settings +from thor.monitor import MAX_PENDING_WRITES, Monitor + +from .fakes import Clock, FakeSource, FakeStore + + +def make(store=None, sources=None, checks=None, clock=None, prepare=None): + settings = Settings() + clock = clock or Clock() + sources = sources if sources is not None else {n: FakeSource(n) for n in ('prometheus', 'loki')} + return Monitor(settings, store or FakeStore(), sources, checks=checks, clock=clock, prepare=prepare), clock + + +def test_first_cycle_covers_one_cycle_and_records_heartbeat(): + store = FakeStore() + m, clock = make(store) + r = m.cycle() + assert r.ok and not r.blind and not r.catching_up + assert r.window == (clock.t - 120, clock.t) + assert store.state['last_good_window_end'] == clock.t + assert store.state['last_good_cycle'] == clock.t + assert store.cycles[0]['ok'] is True + assert store.sources['prometheus']['up'] is True + assert store.blind == [] + + +def test_next_cycle_starts_where_the_last_good_one_ended(): + m, clock = make() + first = m.cycle() + clock.advance(120) + second = m.cycle() + assert second.window[0] == first.window[1] + assert not second.catching_up + + +def test_restart_resumes_from_stored_window_and_catches_up(): + """T2 shape: Thor goes dark with the rack, comes back 22 minutes later, reviews the gap.""" + store = FakeStore() + m, clock = make(store) + m.cycle() + gone_at = clock.t + clock.advance(22 * 60) + m2, _ = make(store, clock=clock) # new process + r = m2.cycle() + assert r.window == (gone_at, clock.t) + assert r.catching_up + + +def test_catch_up_is_capped_at_24_hours(): + store = FakeStore() + m, clock = make(store) + m.cycle() + clock.advance(3 * 86400) + r = make(store, clock=clock)[0].cycle() + assert r.window == (clock.t - 24 * 3600, clock.t) + assert r.catching_up + + +def test_blind_source_opens_and_closes_a_blind_period(): + store = FakeStore() + loki = FakeSource('loki', up=False, error='HTTP 500') + m, clock = make(store, {'prometheus': FakeSource('prometheus'), 'loki': loki}) + r = m.cycle() + assert r.ok and r.blind == ['loki'] # blind is recorded, it doesn't fail the cycle + assert store.blind == [{'source': 'loki', 'started': clock.t, 'ended': None, 'reason': 'HTTP 500'}] + assert store.state['last_cycle']['blind'] == ['loki'] + clock.advance(120) + m.cycle() # still down: no second period + assert len(store.blind) == 1 + loki.up = True + clock.advance(120) + m.cycle() + assert store.blind[0]['ended'] == clock.t + assert store.sources['loki']['up'] is True + + +def test_known_down_source_from_previous_process_is_not_reopened(): + store = FakeStore() + store.sources['loki'] = {'up': False, 'since': 10.0, 'last_ok': None, 'last_error': 'x'} + store.blind.append({'source': 'loki', 'started': 10.0, 'ended': None, 'reason': 'x'}) + m, _ = make(store, {'loki': FakeSource('loki', up=False)}) + m.cycle() + assert len(store.blind) == 1 + assert store.sources['loki']['since'] == 10.0 + + +def test_database_away_buffers_writes_and_flushes_later(): + """T1 shape: CT 149 freezes with Ceph; Thor keeps cycling and writes when it's back.""" + store = FakeStore() + store.down = True + m, clock = make(store) + r1 = m.cycle() + assert r1.ok + assert m.pending # nothing written yet + clock.advance(120) + r2 = m.cycle() + assert r2.window[0] == r1.window[1] # the window still advances in memory + store.down = False + clock.advance(120) + m.cycle() + assert not m.pending + assert len(store.cycles) == 3 + assert store.state['last_good_window_end'] == clock.t + + +def test_pending_writes_are_bounded(): + store = FakeStore() + store.down = True + m, _ = make(store) + for i in range(MAX_PENDING_WRITES + 10): + m._write('set_state', 'k', i, 0) + assert len(m.pending) == MAX_PENDING_WRITES + assert m.pending[-1][1][1] == MAX_PENDING_WRITES + 9 + + +def test_failing_check_keeps_the_window_for_next_cycle_and_others_still_run(): + ran = [] + + class Boom: + name = 'boom' + + def run(self, ctx): + raise RuntimeError('bug') + + class Fine: + name = 'fine' + + def run(self, ctx): + ran.append((ctx.window_start, ctx.window_end, dict(ctx.up))) + return [{'x': 1}] + + store = FakeStore() + m, clock = make(store, checks=[Boom(), Fine()]) + r = m.cycle() + assert not r.ok and 'boom: RuntimeError: bug' in r.error + assert r.findings == 1 and ran + assert 'last_good_window_end' not in store.state + assert 'last_good_cycle' not in store.state + + +def test_source_that_raises_unexpectedly_counts_as_blind(): + class Broken: + name = 'proxmox' + + def ping(self): + raise KeyError('bug') + + m, _ = make(sources={'proxmox': Broken()}) + r = m.cycle() + assert r.blind == ['proxmox'] + + +def test_prepare_runs_once_and_is_retried_until_db_answers(): + store = FakeStore() + store.down = True + calls = [] + + def prepare(): + calls.append(1) + if store.down: + from thor.db import DatabaseError + raise DatabaseError('down') + + m, clock = make(store, prepare=prepare) + m.cycle() + store.down = False + clock.advance(120) + m.cycle() + clock.advance(120) + m.cycle() + assert len(calls) == 2 + + +def test_stop_ends_run_forever(): + m, clock = make() + m.settings.cycle_seconds = 1 + m.stop() + m.run_forever() # returns at once + + +def test_restart_while_db_away_still_catches_up_once_db_answers(): + """T2 order: the rack comes back, Thor starts before CT 149 does.""" + store = FakeStore() + m, clock = make(store) + m.cycle() + went_dark = clock.t + clock.advance(22 * 60) + store.down = True + m2, _ = make(store, clock=clock) + first = m2.cycle() + assert first.window == (clock.t - 120, clock.t) # nothing known yet + clock.advance(120) + store.down = False + second = m2.cycle() + # The stored end wins, so the whole time Thor was away is reviewed, not just the last cycle. + assert second.window == (went_dark, clock.t) and second.catching_up diff --git a/tests/test_web.py b/tests/test_web.py new file mode 100644 index 0000000..648e846 --- /dev/null +++ b/tests/test_web.py @@ -0,0 +1,59 @@ +from thor.config import Settings +from thor.web.app import create_app, detect_version + +from .fakes import Clock, FakeStore + + +def client(store, clock=None): + app = create_app(Settings(), store, 'abc123', clock=clock or Clock()) + return app.test_client() + + +def test_health_ok_when_monitor_fresh(): + clock = Clock() + store = FakeStore() + store.state['last_good_cycle'] = clock.t - 30 + store.state['last_cycle'] = {'blind': ['loki']} + r = client(store, clock).get('/health') + assert r.status_code == 200 + body = r.get_json() + assert body == {'status': 'ok', 'sha': 'abc123', 'db': True, 'monitor': 'ok', 'monitor_age_s': 30, + 'blind': ['loki']} + assert r.headers['X-Frame-Options'] == 'DENY' + + +def test_health_503_when_stale_never_ran_or_no_db(): + clock = Clock() + store = FakeStore() + r = client(store, clock).get('/health') + assert r.status_code == 503 and r.get_json()['monitor'] == 'no good cycle yet' + store.state['last_good_cycle'] = clock.t - 361 + r = client(store, clock).get('/health') + assert r.status_code == 503 and r.get_json()['monitor'] == 'stale' + store.down = True + r = client(store, clock).get('/health') + assert r.status_code == 503 and r.get_json()['db'] is False + + +def test_metrics(): + clock = Clock() + store = FakeStore() + store.state['last_good_cycle'] = 1795575600.0 + store.state['last_cycle'] = {'started': 10.0, 'finished': 12.5} + store.sources = {'loki': {'up': False}, 'prometheus': {'up': True}} + text = client(store, clock).get('/metrics').get_data(as_text=True) + assert 'thor_build_info{sha="abc123"} 1' in text + assert 'thor_database_up 1' in text + assert 'thor_last_good_cycle_timestamp_seconds 1795575600.000' in text + assert 'thor_cycle_duration_seconds 2.500' in text + assert 'thor_source_up{source="loki"} 0' in text + store.down = True + text = client(store, clock).get('/metrics').get_data(as_text=True) + assert 'thor_database_up 0' in text and 'thor_source_up' not in text + + +def test_detect_version(monkeypatch, tmp_path): + monkeypatch.setenv('THOR_SHA', 'deadbeef') + assert detect_version() == 'deadbeef' + monkeypatch.delenv('THOR_SHA') + assert detect_version(str(tmp_path)) == 'unknown' # not a git checkout diff --git a/thor/__init__.py b/thor/__init__.py new file mode 100644 index 0000000..204a48c --- /dev/null +++ b/thor/__init__.py @@ -0,0 +1,3 @@ +"""Thor: out-of-band host and cluster health for the LotusGuild cluster (thor#1).""" + +APP_NAME = 'thor' diff --git a/thor/clients/__init__.py b/thor/clients/__init__.py new file mode 100644 index 0000000..56a0f20 --- /dev/null +++ b/thor/clients/__init__.py @@ -0,0 +1,15 @@ +"""Read-only clients for the sources Thor watches through, plus the Tinker ticket client. + +Every client raises :class:`SourceError` when its source can't answer. Callers must treat +that as "unknown" (Thor is blind to that source), never as "nothing found" (thor#1, +Area 1 rule 3; same principle as Gandalf's ``reboots.LokiError``). +""" + + +class SourceError(Exception): + """A source could not answer: unreachable, timed out, HTTP error or a malformed reply.""" + + def __init__(self, source: str, message: str): + super().__init__(f'{source}: {message}') + self.source = source + self.message = message diff --git a/thor/clients/gandalf.py b/thor/clients/gandalf.py new file mode 100644 index 0000000..1327943 --- /dev/null +++ b/thor/clients/gandalf.py @@ -0,0 +1,63 @@ +"""Read-only client for Gandalf's API (machine key, gandalf#66 / gandalf#68). + +Thor uses Gandalf's reachability data instead of probing hosts itself, and Gandalf's +suppressions (with their start and end times) as the record of planned maintenance. +""" +from typing import Dict, List, Optional + +import requests + +from . import SourceError + +# Gandalf serves at most 31 days of suppression history. +MAX_SUPPRESSION_HOURS = 31 * 24 + + +class GandalfClient: + name = 'gandalf' + + def __init__(self, url: str, api_key: str, timeout: float = 10.0, + session: Optional[requests.Session] = None): + self.url = url.rstrip('/') + self.api_key = api_key + self.timeout = timeout + self.session = session or requests.Session() + + @property + def configured(self) -> bool: + return bool(self.url and self.api_key) + + def _get(self, path: str, params: Optional[dict] = None): + if not self.configured: + raise SourceError(self.name, 'no API key configured') + try: + resp = self.session.get(f'{self.url}{path}', params=params, timeout=self.timeout, + headers={'Authorization': f'Bearer {self.api_key}'}) + if resp.status_code in (401, 403): + raise SourceError(self.name, f'key refused (HTTP {resp.status_code})') + resp.raise_for_status() + return resp.json() + except SourceError: + raise + except (requests.RequestException, ValueError) as e: + raise SourceError(self.name, str(e)) from e + + def suppressions(self, hours: int = 24, include_ended: bool = True) -> List[Dict]: + """Every suppression in force in the last ``hours``, with started_at, ended_at, state.""" + hours = max(1, min(int(hours), MAX_SUPPRESSION_HOURS)) + params = {'include_ended': '1', 'hours': str(hours)} if include_ended else None + data = self._get('/api/suppressions', params) + if isinstance(data, dict): + data = data.get('suppressions') + if not isinstance(data, list) or not all(isinstance(s, dict) for s in data): + raise SourceError(self.name, 'unexpected suppressions reply') + return data + + def status(self) -> Dict: + data = self._get('/api/status') + if not isinstance(data, dict): + raise SourceError(self.name, 'unexpected status reply') + return data + + def ping(self) -> None: + self.status() diff --git a/thor/clients/loki.py b/thor/clients/loki.py new file mode 100644 index 0000000..9aad770 --- /dev/null +++ b/thor/clients/loki.py @@ -0,0 +1,89 @@ +"""Loki client and the planned-shutdown lookup. + +Lifted from Gandalf's ``reboots.py`` (gandalf#65, at LotusGuild/gandalf@1c250d6), which was +written to move here unchanged. Changes: lines keep their stream labels (Thor needs the +``host``), errors are :class:`SourceError`, and windows longer than Loki's 30 day limit are +refused up front. +""" +import re +import time +from typing import Dict, List, Optional, Tuple + +import requests + +from . import SourceError + +# What systemd-logind logs when a shutdown is requested (reboot, poweroff, halt, kexec). +SHUTDOWN_RE = re.compile(r'The system will (reboot|power off|halt|suspend|kexec) now') +LOGQL_SHUTDOWN_FILTER = 'will (reboot|power off|halt|kexec) now' +# How far before a host went missing to look for its shutdown line. +SHUTDOWN_LOOKBACK_S = 600 +# Loki rejects queries spanning more than 30 days. +MAX_WINDOW_S = 30 * 24 * 3600 + +Line = Tuple[float, str, Dict[str, str]] + + +def quote(value: str) -> str: + """Quote a value for use inside a LogQL label matcher.""" + return value.replace('\\', '\\\\').replace('"', '\\"') + + +class LokiClient: + name = 'loki' + + def __init__(self, url: str, timeout: float = 10.0, session: Optional[requests.Session] = None): + self.url = url.rstrip('/') + self.timeout = timeout + self.session = session or requests.Session() + + def lines(self, logql: str, start: float, end: float, limit: int = 100, + direction: str = 'backward') -> List[Line]: + """[(unix seconds, line, labels)], newest first unless direction='forward'.""" + if end - start > MAX_WINDOW_S: + raise SourceError(self.name, 'window longer than 30 days') + try: + resp = self.session.get( + f'{self.url}/loki/api/v1/query_range', + params={'query': logql, 'start': f'{int(start * 1e9)}', 'end': f'{int(end * 1e9)}', + 'limit': limit, 'direction': direction}, + timeout=self.timeout, + ) + resp.raise_for_status() + data = resp.json() + except (requests.RequestException, ValueError) as e: + raise SourceError(self.name, str(e)) from e + if not isinstance(data, dict) or data.get('status') != 'success': + raise SourceError(self.name, f'unsuccessful reply: {str(data)[:200]}') + out: List[Line] = [] + for stream in (data.get('data') or {}).get('result') or []: + labels = stream.get('stream') or {} + for ts, line in stream.get('values') or []: + out.append((int(ts) / 1e9, line, labels)) + out.sort(key=lambda x: x[0], reverse=(direction != 'forward')) + return out + + def ping(self) -> None: + """Loki's /ready can return 503 while queries still work, so test with a query.""" + now = time.time() + self.lines('{job="journal"} |= "thor-ping-never-matches"', now - 60, now, limit=1) + + +def shutdown_query(host: str) -> str: + return (f'{{host="{quote(host)}", job="journal", unit="systemd-logind.service"}} ' + f'|~ "{LOGQL_SHUTDOWN_FILTER}"') + + +def find_shutdown(loki: LokiClient, host: str, before: float, + lookback_s: float = SHUTDOWN_LOOKBACK_S) -> Optional[dict]: + """The shutdown request a host logged in the lookback window before ``before``, or None. + + Raises SourceError when Loki can't answer, so "no line" is never confused with "no data". + A missing line is still not proof of a crash: the journal may have stopped reaching Loki + before the host went down (thor#4, 2026-11-25). + """ + for ts, line, _labels in loki.lines(shutdown_query(host), before - lookback_s, before, limit=20): + m = SHUTDOWN_RE.search(line) + if m: + return {'at': ts, 'kind': m.group(1), 'line': line.strip()} + return None diff --git a/thor/clients/prometheus.py b/thor/clients/prometheus.py new file mode 100644 index 0000000..c6889f2 --- /dev/null +++ b/thor/clients/prometheus.py @@ -0,0 +1,62 @@ +"""Prometheus HTTP API client (instant and range queries).""" +from typing import Dict, List, Optional, Tuple + +import requests + +from . import SourceError + +Sample = Tuple[float, float] + + +class PrometheusClient: + name = 'prometheus' + + def __init__(self, url: str, timeout: float = 10.0, session: Optional[requests.Session] = None): + self.url = url.rstrip('/') + self.timeout = timeout + self.session = session or requests.Session() + + def _get(self, path: str, params: dict) -> dict: + try: + resp = self.session.get(f'{self.url}{path}', params=params, timeout=self.timeout) + resp.raise_for_status() + data = resp.json() + except (requests.RequestException, ValueError) as e: + raise SourceError(self.name, str(e)) from e + if not isinstance(data, dict) or data.get('status') != 'success': + raise SourceError(self.name, f'unsuccessful reply: {str(data)[:200]}') + return data.get('data') or {} + + def query(self, expr: str, at: Optional[float] = None) -> List[Dict]: + """Instant query. Returns [{'metric': {...}, 'ts': float, 'value': float}].""" + params = {'query': expr} + if at is not None: + params['time'] = f'{at:.3f}' + data = self._get('/api/v1/query', params) + out = [] + for r in data.get('result') or []: + ts, val = r.get('value', (None, None)) + try: + out.append({'metric': r.get('metric') or {}, 'ts': float(ts), 'value': float(val)}) + except (TypeError, ValueError): + continue + return out + + def query_range(self, expr: str, start: float, end: float, step: float) -> List[Dict]: + """Range query. Returns [{'metric': {...}, 'values': [(ts, value), ...]}].""" + data = self._get('/api/v1/query_range', { + 'query': expr, 'start': f'{start:.3f}', 'end': f'{end:.3f}', 'step': f'{step:g}'}) + out = [] + for r in data.get('result') or []: + values: List[Sample] = [] + for ts, val in r.get('values') or []: + try: + values.append((float(ts), float(val))) + except (TypeError, ValueError): + continue + out.append({'metric': r.get('metric') or {}, 'values': values}) + return out + + def ping(self) -> None: + """Raises SourceError unless Prometheus answers a trivial query.""" + self.query('vector(1)') diff --git a/thor/clients/proxmox.py b/thor/clients/proxmox.py new file mode 100644 index 0000000..71fdd19 --- /dev/null +++ b/thor/clients/proxmox.py @@ -0,0 +1,73 @@ +"""Read-only Proxmox VE API client, authenticated with an API token (thor@pve, PVEAuditor). + +Any node answers for the whole cluster, so each call tries the configured nodes in order +and remembers the last one that answered. +""" +from typing import Dict, List, Optional + +import requests +import urllib3 + +from . import SourceError + + +class ProxmoxClient: + name = 'proxmox' + + def __init__(self, nodes: List[str], token_id: str, token_secret: str, verify_tls: bool = False, + timeout: float = 10.0, session: Optional[requests.Session] = None): + self.nodes = list(nodes) + self.token_id = token_id + self.token_secret = token_secret + self.verify_tls = verify_tls + self.timeout = timeout + self.session = session or requests.Session() + self._preferred = 0 + if not verify_tls: + urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + + @property + def configured(self) -> bool: + return bool(self.nodes and self.token_id and self.token_secret) + + def get(self, path: str, params: Optional[dict] = None): + if not self.configured: + raise SourceError(self.name, 'no API token configured') + headers = {'Authorization': f'PVEAPIToken={self.token_id}={self.token_secret}'} + errors = [] + order = self.nodes[self._preferred:] + self.nodes[:self._preferred] + for node in order: + try: + resp = self.session.get(f'https://{node}:8006/api2/json{path}', params=params, + headers=headers, timeout=self.timeout, + verify=self.verify_tls) # nosec B501 - cluster CA is self-signed + if resp.status_code in (401, 403): + # The token is cluster-wide, so another node won't accept it either. + raise SourceError(self.name, f'token refused (HTTP {resp.status_code})') + resp.raise_for_status() + data = resp.json() + except SourceError: + raise + except (requests.RequestException, ValueError) as e: + errors.append(f'{node}: {e}') + continue + self._preferred = self.nodes.index(node) + return data.get('data') if isinstance(data, dict) else None + raise SourceError(self.name, '; '.join(errors) or 'no nodes configured') + + def cluster_status(self) -> List[Dict]: + """Cluster and node entries: name, ip, online, nodeid, quorate.""" + return self.get('/cluster/status') or [] + + def ceph_flags(self) -> Dict[str, bool]: + """{flag: set?} including pause, which the Prometheus exporter doesn't export.""" + return {f['name']: bool(f.get('value')) for f in (self.get('/cluster/ceph/flags') or [])} + + def ha_status(self) -> List[Dict]: + return self.get('/cluster/ha/status/current') or [] + + def resources(self, kind: Optional[str] = None) -> List[Dict]: + return self.get('/cluster/resources', params={'type': kind} if kind else None) or [] + + def ping(self) -> None: + self.get('/version') diff --git a/thor/clients/tinker.py b/thor/clients/tinker.py new file mode 100644 index 0000000..1f653c6 --- /dev/null +++ b/thor/clients/tinker.py @@ -0,0 +1,145 @@ +"""Tinker Tickets Bearer API client. + +Adapted from Gandalf's ``TicketClient`` (LotusGuild/gandalf@1c250d6, monitor.py). Changes: +every create carries a ``dedup_key`` (tinker_tickets#123; older Tinker ignores the field), +errors don't raise, and nothing here decides whether a ticket should be sent. Shadow mode is +enforced by the caller, which never reaches this client for a check that isn't live. +""" +import logging +from typing import Dict, Optional +from urllib.parse import urljoin + +import requests + +logger = logging.getLogger('thor.tinker') + + +class TicketResult: + """What Tinker did with a create: its ticket id and action (created, deduplicated, ...).""" + + def __init__(self, ticket_id: Optional[str], action: str = '', ok: bool = False, error: str = ''): + self.ticket_id = ticket_id + self.action = action + self.ok = ok + self.error = error + + def __repr__(self): + return f'TicketResult({self.ticket_id!r}, {self.action!r}, ok={self.ok})' + + +class TinkerClient: + name = 'tinker' + OPEN_STATUSES = 'Open,Pending,In Progress' + _OPEN_TICKETS_MAX_PAGES = 20 + + def __init__(self, url: str, api_key: str, timeout: float = 15.0, + session: Optional[requests.Session] = None): + self.url = url + self.api_key = api_key + self.timeout = timeout + self.session = session or requests.Session() + # Tinker serves its other API scripts under api/ beside create_ticket_api.php + self.comment_url = urljoin(url, 'api/ticket_comment_api.php') if url else '' + self.read_url = urljoin(url, 'api/tickets_api.php') if url else '' + self.writes_denied = False + + @property + def configured(self) -> bool: + return bool(self.url and self.api_key) + + def _headers(self) -> Dict[str, str]: + return {'Authorization': f'Bearer {self.api_key}'} + + def create(self, *, title: str, description: str, priority: int, category: str, + ticket_type: str, dedup_key: str) -> TicketResult: + if not self.configured: + return TicketResult(None, error='not configured') + if self.writes_denied: + return TicketResult(None, error='key lacks write scope') + payload = { + 'title': title, 'description': description, 'status': 'Open', + 'priority': str(int(priority)), 'category': category, 'type': ticket_type, + 'dedup_key': dedup_key, + } + try: + resp = self.session.post(self.url, json=payload, headers=self._headers(), timeout=self.timeout) + if resp.status_code in (401, 403): + self.writes_denied = True + logger.error('Tinker refused a create (HTTP %s); ticket writes are off until restart', + resp.status_code) + return TicketResult(None, error=f'HTTP {resp.status_code}') + resp.raise_for_status() + data = resp.json() + except (requests.RequestException, ValueError) as e: + return TicketResult(None, error=str(e)) + if data.get('success') and data.get('ticket_id'): + return TicketResult(str(data['ticket_id']), data.get('action') or 'created', ok=True) + if data.get('existing_ticket_id'): + return TicketResult(str(data['existing_ticket_id']), 'deduplicated', ok=True) + return TicketResult(None, error=f'unexpected reply: {str(data)[:200]}') + + def comment(self, ticket_id: str, text: str) -> bool: + """Add a Markdown comment. False means try again later; a deleted ticket counts as done.""" + if not self.configured or self.writes_denied: + return False + try: + resp = self.session.post( + self.comment_url, headers=self._headers(), timeout=self.timeout, + json={'ticket_id': str(ticket_id), 'comment_text': text, 'markdown_enabled': True}) + if resp.status_code in (401, 403): + self.writes_denied = True + logger.error('Tinker refused a comment on #%s (HTTP %s)', ticket_id, resp.status_code) + return False + if resp.status_code == 404: + logger.warning('Ticket #%s no longer exists; dropping the comment', ticket_id) + return True + resp.raise_for_status() + return bool(resp.json().get('success')) + except (requests.RequestException, ValueError) as e: + logger.error('Comment on #%s failed: %s', ticket_id, e) + return False + + def open_tickets(self) -> Optional[Dict[str, Dict]]: + """{ticket_id: {title, status, priority}} for every ticket not closed, or None if unknown.""" + if not self.configured: + return None + found: Dict[str, Dict] = {} + try: + for page in range(1, self._OPEN_TICKETS_MAX_PAGES + 1): + resp = self.session.get(self.read_url, headers=self._headers(), timeout=self.timeout, + params={'status': self.OPEN_STATUSES, 'limit': 100, 'page': page}) + resp.raise_for_status() + data = resp.json() + if not data.get('success'): + return None + for t in data.get('tickets') or []: + found[str(t.get('ticket_id'))] = { + 'title': t.get('title') or '', 'status': t.get('status') or '', + 'priority': t.get('priority')} + if page >= int(data.get('pages') or 1): + return found + logger.warning('Open ticket list is longer than expected; using the first pages only') + return found + except (requests.RequestException, ValueError) as e: + logger.error('Reading open tickets failed: %s', e) + return None + + def ticket(self, ticket_id: str) -> Optional[Dict]: + """One ticket with its comments, or None if Tinker can't say.""" + if not self.configured: + return None + try: + resp = self.session.get(self.read_url, headers=self._headers(), timeout=self.timeout, + params={'ticket_id': str(ticket_id)}) + if resp.status_code == 404: + return None + resp.raise_for_status() + data = resp.json() + except (requests.RequestException, ValueError): + return None + return data.get('ticket') if data.get('success') else None + + +def backoff_s(attempts: int, base: float = 120.0, cap: float = 3600.0) -> float: + """Delay before retrying an outbox item that has failed ``attempts`` times.""" + return min(cap, base * (2 ** max(0, attempts - 1))) diff --git a/thor/config.py b/thor/config.py new file mode 100644 index 0000000..2af777a --- /dev/null +++ b/thor/config.py @@ -0,0 +1,152 @@ +"""Settings for Thor. + +Two sources, read in this order (later wins): + +1. ``/etc/thor/thor.json``: non-secret settings (URLs, cadence, check modes). Optional; + every key has a default. ``deploy/thor.example.json`` documents them. +2. ``/etc/thor/*.env``: one ``KEY=VALUE`` per line, holding secrets (Proxmox token, + database password, Gandalf and Tinker keys). Readable by root and the ``thor`` group + only, never in the repo. +3. The process environment, for tests and one-off runs. + +Nothing here talks to the network; a missing secret just leaves that source unconfigured, +and the monitor reports it as unavailable instead of failing to start. +""" +import json +import os +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List, Mapping, Optional + +DEFAULT_CONFIG_PATH = '/etc/thor/thor.json' +DEFAULT_ENV_DIR = '/etc/thor' + +# Every check starts in shadow: it is evaluated and shown in Thor, and what it would have +# opened is logged, but nothing is sent to Tinker (thor#1, Area 5). +CHECK_MODES = ('off', 'shadow', 'live') + + +@dataclass +class DatabaseSettings: + host: str = '' + port: int = 3306 + name: str = 'thor' + user: str = 'thor' + password: str = '' + + @property + def configured(self) -> bool: + return bool(self.host and self.user and self.password) + + +@dataclass +class Settings: + prometheus_url: str = 'http://10.10.10.48:9090' + loki_url: str = 'http://10.10.10.69:3100' + # Any node answers for the whole cluster; Thor tries them in this order. + proxmox_nodes: List[str] = field(default_factory=lambda: [ + '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_token_id: str = '' + proxmox_token_secret: str = '' + # Proxmox nodes use their self-signed cluster CA. + proxmox_verify_tls: bool = False + gandalf_url: str = 'http://10.10.10.61' + gandalf_api_key: str = '' + tinker_url: str = 'https://t.lotusguild.org/create_ticket_api.php' + tinker_api_key: str = '' + public_url: str = 'https://thor.lotusguild.org' + cycle_seconds: int = 120 + catchup_hours: int = 24 + # How many missed cycles before /health reports the monitor as stale. + stale_after_cycles: int = 3 + http_timeout_s: float = 10.0 + checks: Dict[str, str] = field(default_factory=dict) + database: DatabaseSettings = field(default_factory=DatabaseSettings) + + def check_mode(self, name: str) -> str: + mode = self.checks.get(name, 'shadow') + return mode if mode in CHECK_MODES else 'shadow' + + @property + def stale_after_s(self) -> int: + return self.cycle_seconds * self.stale_after_cycles + + +def parse_env_file(text: str) -> Dict[str, str]: + """KEY=VALUE lines; blank lines and # comments ignored; optional surrounding quotes.""" + out = {} + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith('#') or '=' not in line: + continue + key, value = line.split('=', 1) + key, value = key.strip(), value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in '"\'': + value = value[1:-1] + if key: + out[key] = value + return out + + +def read_env_dir(env_dir: str) -> Dict[str, str]: + values: Dict[str, str] = {} + path = Path(env_dir) + if not path.is_dir(): + return values + for f in sorted(path.glob('*.env')): + try: + values.update(parse_env_file(f.read_text())) + except OSError: + continue + return values + + +def _as_bool(value) -> bool: + if isinstance(value, bool): + return value + return str(value).strip().lower() in ('1', 'true', 'yes', 'on') + + +def load(config_path: Optional[str] = None, env_dir: Optional[str] = None, + environ: Optional[Mapping[str, str]] = None) -> Settings: + config_path = config_path or os.environ.get('THOR_CONFIG', DEFAULT_CONFIG_PATH) + env_dir = env_dir or os.environ.get('THOR_ENV_DIR', DEFAULT_ENV_DIR) + environ = os.environ if environ is None else environ + + s = Settings() + try: + with open(config_path) as f: + data = json.load(f) + except FileNotFoundError: + data = {} + for key in ('prometheus_url', 'loki_url', 'gandalf_url', 'tinker_url', 'public_url'): + if data.get(key): + setattr(s, key, str(data[key]).rstrip('/') if key != 'tinker_url' else str(data[key])) + for key in ('cycle_seconds', 'catchup_hours', 'stale_after_cycles'): + if key in data: + setattr(s, key, int(data[key])) + if 'http_timeout_s' in data: + s.http_timeout_s = float(data['http_timeout_s']) + if data.get('proxmox_nodes'): + s.proxmox_nodes = [str(n) for n in data['proxmox_nodes']] + if 'proxmox_verify_tls' in data: + s.proxmox_verify_tls = _as_bool(data['proxmox_verify_tls']) + if isinstance(data.get('checks'), dict): + s.checks = {str(k): str(v) for k, v in data['checks'].items()} + + env = read_env_dir(env_dir) + env.update({k: v for k, v in environ.items() if k.isupper()}) + + s.proxmox_token_id = env.get('PVE_TOKEN_ID', s.proxmox_token_id) + s.proxmox_token_secret = env.get('PVE_TOKEN_SECRET', s.proxmox_token_secret) + s.gandalf_url = env.get('GANDALF_URL', s.gandalf_url).rstrip('/') + s.gandalf_api_key = env.get('GANDALF_API_KEY', s.gandalf_api_key) + s.tinker_url = env.get('TINKER_URL', s.tinker_url) + s.tinker_api_key = env.get('TINKER_API_KEY', s.tinker_api_key) + db = s.database + db.host = env.get('DB_HOST', db.host) + db.port = int(env.get('DB_PORT', db.port)) + db.name = env.get('DB_NAME', db.name) + db.user = env.get('DB_USER', db.user) + db.password = env.get('DB_PASSWORD', db.password) + return s diff --git a/thor/db.py b/thor/db.py new file mode 100644 index 0000000..932948d --- /dev/null +++ b/thor/db.py @@ -0,0 +1,221 @@ +"""MariaDB access: connection handling, versioned migrations, and the queries Thor uses. + +Thor shares MariaDB CT 149 with Gandalf and Tinker (thor#1). That database freezes when +Ceph stalls, so every caller must survive :class:`DatabaseError`: the monitor keeps what it +saw in memory and writes it on the next cycle that has a database. + +All times are stored as naive UTC ``DATETIME(3)``; this module converts to and from unix +seconds so the rest of Thor only deals in floats. +""" +import json +import logging +import threading +from contextlib import contextmanager +from datetime import datetime, timezone +from typing import Any, Dict, Iterator, List, Optional + +import pymysql +import pymysql.cursors + +from .config import DatabaseSettings + +logger = logging.getLogger('thor.db') + + +class DatabaseError(Exception): + """The database could not be reached or refused a statement.""" + + +def to_dt(ts: Optional[float]) -> Optional[datetime]: + if ts is None: + return None + return datetime.fromtimestamp(ts, tz=timezone.utc).replace(tzinfo=None) + + +def from_dt(dt: Optional[datetime]) -> Optional[float]: + if dt is None: + return None + return dt.replace(tzinfo=timezone.utc).timestamp() + + +# Each migration runs once, in order, and is recorded in schema_version. Never edit one +# that has shipped; add a new one. +MIGRATIONS: List[str] = [ + # 1: monitor bookkeeping + """ + CREATE TABLE IF NOT EXISTS state ( + k VARCHAR(64) NOT NULL PRIMARY KEY, + v MEDIUMTEXT NOT NULL, + updated_at DATETIME(3) NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + CREATE TABLE IF NOT EXISTS cycles ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + started_at DATETIME(3) NOT NULL, + finished_at DATETIME(3) NULL, + window_start DATETIME(3) NOT NULL, + window_end DATETIME(3) NOT NULL, + ok TINYINT(1) NOT NULL DEFAULT 0, + blind_sources VARCHAR(255) NOT NULL DEFAULT '', + error TEXT NULL, + KEY idx_cycles_started (started_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + CREATE TABLE IF NOT EXISTS source_status ( + name VARCHAR(32) NOT NULL PRIMARY KEY, + up TINYINT(1) NOT NULL, + since DATETIME(3) NOT NULL, + last_ok DATETIME(3) NULL, + last_error TEXT NULL, + updated_at DATETIME(3) NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + CREATE TABLE IF NOT EXISTS blind_periods ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + source VARCHAR(32) NOT NULL, + started_at DATETIME(3) NOT NULL, + ended_at DATETIME(3) NULL, + reason TEXT NULL, + KEY idx_blind_source (source, started_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + """, +] + + +def _statements(sql: str) -> Iterator[str]: + for part in sql.split(';'): + if part.strip(): + yield part.strip() + + +class Database: + def __init__(self, settings: DatabaseSettings, connect=None): + self.settings = settings + self._connect = connect or self._default_connect + self._local = threading.local() + + def _default_connect(self): + s = self.settings + return pymysql.connect( + host=s.host, port=s.port, user=s.user, password=s.password, database=s.name, + autocommit=True, cursorclass=pymysql.cursors.DictCursor, connect_timeout=10, + read_timeout=30, write_timeout=30, charset='utf8mb4', + init_command="SET time_zone='+00:00'", + ) + + @contextmanager + def cursor(self): + """A cursor on a per-thread connection, reconnecting as needed. Raises DatabaseError.""" + try: + conn = getattr(self._local, 'conn', None) + if conn is None: + conn = self._connect() + self._local.conn = conn + else: + try: + conn.ping(reconnect=False) + except pymysql.MySQLError: + try: + conn.close() + except pymysql.MySQLError: + pass + self._local.conn = None + conn = self._connect() + self._local.conn = conn + with conn.cursor() as cur: + yield cur + except pymysql.MySQLError as e: + self._local.conn = None + raise DatabaseError(str(e)) from e + + def execute(self, sql: str, params: tuple = ()) -> int: + with self.cursor() as cur: + cur.execute(sql, params) + return cur.lastrowid or cur.rowcount + + def query(self, sql: str, params: tuple = ()) -> List[Dict[str, Any]]: + with self.cursor() as cur: + cur.execute(sql, params) + return list(cur.fetchall()) + + def migrate(self) -> int: + """Apply pending migrations. Returns the schema version now in place.""" + self.execute("""CREATE TABLE IF NOT EXISTS schema_version ( + version INT NOT NULL PRIMARY KEY, applied_at DATETIME(3) NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4""") + rows = self.query('SELECT COALESCE(MAX(version), 0) AS v FROM schema_version') + current = int(rows[0]['v']) if rows else 0 + for version, sql in enumerate(MIGRATIONS, start=1): + if version <= current: + continue + for stmt in _statements(sql): + self.execute(stmt) + self.execute('INSERT INTO schema_version (version, applied_at) VALUES (%s, UTC_TIMESTAMP(3))', + (version,)) + logger.info('Applied schema migration %d', version) + current = version + return current + + +class Store: + """The queries the monitor and web app use. Every method may raise DatabaseError.""" + + def __init__(self, db: Database): + self.db = db + + # -- key/value state -------------------------------------------------- + def set_state(self, key: str, value: Any, now: float) -> None: + self.db.execute( + """INSERT INTO state (k, v, updated_at) VALUES (%s, %s, %s) + ON DUPLICATE KEY UPDATE v=VALUES(v), updated_at=VALUES(updated_at)""", + (key, json.dumps(value, default=str), to_dt(now))) + + def get_state(self, key: str, default: Any = None) -> Any: + rows = self.db.query('SELECT v FROM state WHERE k=%s', (key,)) + if not rows: + return default + try: + return json.loads(rows[0]['v']) + except ValueError: + return default + + # -- cycles ----------------------------------------------------------- + def record_cycle(self, *, started: float, finished: float, window_start: float, window_end: float, + ok: bool, blind: List[str], error: str = '') -> int: + return self.db.execute( + """INSERT INTO cycles (started_at, finished_at, window_start, window_end, ok, blind_sources, error) + VALUES (%s, %s, %s, %s, %s, %s, %s)""", + (to_dt(started), to_dt(finished), to_dt(window_start), to_dt(window_end), int(ok), + ','.join(sorted(blind))[:255], error or None)) + + def prune_cycles(self, older_than: float) -> int: + return self.db.execute('DELETE FROM cycles WHERE started_at < %s', (to_dt(older_than),)) + + # -- sources ---------------------------------------------------------- + def source_statuses(self) -> Dict[str, Dict[str, Any]]: + out = {} + for r in self.db.query('SELECT name, up, since, last_ok, last_error FROM source_status'): + out[r['name']] = {'up': bool(r['up']), 'since': from_dt(r['since']), + 'last_ok': from_dt(r['last_ok']), 'last_error': r['last_error'] or ''} + return out + + def save_source_status(self, name: str, up: bool, since: float, last_ok: Optional[float], + last_error: str, now: float) -> None: + self.db.execute( + """INSERT INTO source_status (name, up, since, last_ok, last_error, updated_at) + VALUES (%s, %s, %s, %s, %s, %s) + ON DUPLICATE KEY UPDATE up=VALUES(up), since=VALUES(since), last_ok=VALUES(last_ok), + last_error=VALUES(last_error), updated_at=VALUES(updated_at)""", + (name, int(up), to_dt(since), to_dt(last_ok), last_error or None, to_dt(now))) + + def open_blind_period(self, source: str, started: float, reason: str) -> None: + self.db.execute('INSERT INTO blind_periods (source, started_at, reason) VALUES (%s, %s, %s)', + (source, to_dt(started), reason[:2000])) + + def close_blind_period(self, source: str, ended: float) -> None: + self.db.execute('UPDATE blind_periods SET ended_at=%s WHERE source=%s AND ended_at IS NULL', + (to_dt(ended), source)) + + def blind_periods(self, since: float) -> List[Dict[str, Any]]: + rows = self.db.query( + """SELECT source, started_at, ended_at, reason FROM blind_periods + WHERE ended_at IS NULL OR ended_at >= %s ORDER BY started_at""", (to_dt(since),)) + return [{'source': r['source'], 'started': from_dt(r['started_at']), + 'ended': from_dt(r['ended_at']), 'reason': r['reason'] or ''} for r in rows] diff --git a/thor/monitor.py b/thor/monitor.py new file mode 100644 index 0000000..d38f02a --- /dev/null +++ b/thor/monitor.py @@ -0,0 +1,251 @@ +"""Thor's monitor loop (``thor-monitor.service``). + +Design rules from thor#1, Area 1, because Thor runs on the cluster it watches: + +* **Decide from history, not live edges.** Each cycle reviews the window since the last good + one. If Thor was frozen or down, the next cycle covers the gap, up to ``catchup_hours``. +* **Blind is its own state.** A source that can't answer opens a blind period; nothing it + would have said is ever read as "all clear" or as "host down". +* **Survive the database.** CT 149 freezes when Ceph stalls. Writes are buffered in memory and + flushed on the next cycle that has a database; the loop itself never stops for it. +""" +import logging +import signal +import threading +import time +from dataclasses import dataclass, field +from typing import Callable, Dict, List, Optional, Protocol, Tuple + +from . import config as config_mod +from .clients import SourceError +from .clients.gandalf import GandalfClient +from .clients.loki import LokiClient +from .clients.prometheus import PrometheusClient +from .clients.proxmox import ProxmoxClient +from .db import Database, DatabaseError, Store + +logger = logging.getLogger('thor.monitor') + +# Writes kept while the database is away. A cycle produces a handful, so this is days. +MAX_PENDING_WRITES = 5000 + + +class Source(Protocol): + name: str + + def ping(self) -> None: ... + + +@dataclass +class SourceState: + up: bool = True + since: float = 0.0 + last_ok: Optional[float] = None + last_error: str = '' + known: bool = False # False until the first check of this process or a value loaded from the DB + + +@dataclass +class CycleContext: + """What a check gets each cycle.""" + window_start: float + window_end: float + catching_up: bool + sources: Dict[str, Source] + up: Dict[str, bool] + + +class Check(Protocol): + name: str + + def run(self, ctx: CycleContext) -> List[dict]: ... + + +@dataclass +class CycleResult: + started: float + finished: float + window: Tuple[float, float] + ok: bool + blind: List[str] = field(default_factory=list) + catching_up: bool = False + findings: int = 0 + error: str = '' + + +class Monitor: + def __init__(self, settings: config_mod.Settings, store: Store, sources: Dict[str, Source], + checks: Optional[List[Check]] = None, clock: Callable[[], float] = time.time, + prepare: Optional[Callable[[], object]] = None): + self.settings = settings + self.prepare = prepare + self.store = store + self.sources = sources + self.checks = checks or [] + self.clock = clock + self.source_state: Dict[str, SourceState] = {name: SourceState() for name in sources} + self.pending: List[Tuple[str, tuple, dict]] = [] + self.last_good_end: Optional[float] = None + self._loaded = False + self._stop = threading.Event() + + # -- persistence that tolerates a missing database ---------------------- + def _write(self, method: str, *args, **kwargs) -> None: + self.pending.append((method, args, kwargs)) + if len(self.pending) > MAX_PENDING_WRITES: + dropped = len(self.pending) - MAX_PENDING_WRITES + del self.pending[:dropped] + logger.error('Database away too long: dropped %d oldest buffered writes', dropped) + + def flush(self) -> bool: + """Write everything buffered, oldest first. False if the database is still away.""" + while self.pending: + method, args, kwargs = self.pending[0] + try: + getattr(self.store, method)(*args, **kwargs) + except DatabaseError as e: + logger.warning('Database unavailable, %d writes buffered: %s', len(self.pending), e) + return False + self.pending.pop(0) + return True + + def _load(self) -> None: + """Restore where the last process left off. Retried each cycle until the DB answers.""" + if self._loaded: + return + try: + if self.prepare: + self.prepare() # schema migrations + end = self.store.get_state('last_good_window_end') + statuses = self.store.source_statuses() + except DatabaseError as e: + logger.warning('Could not load previous state yet: %s', e) + return + # The stored end is at or before anything this process reviewed while the database + # was away, so it wins: the next window then covers the whole time Thor was gone. + if isinstance(end, (int, float)): + self.last_good_end = float(end) + for name, st in statuses.items(): + if name in self.source_state: + self.source_state[name] = SourceState(up=st['up'], since=st['since'] or 0.0, + last_ok=st['last_ok'], last_error=st['last_error'], + known=True) + self._loaded = True + + # -- sources ------------------------------------------------------------ + def check_sources(self, now: float) -> Dict[str, bool]: + up = {} + for name, src in self.sources.items(): + st = self.source_state[name] + try: + src.ping() + ok, err = True, '' + except SourceError as e: + ok, err = False, e.message + except Exception as e: # a client bug must not stop the loop + logger.exception('Source %s raised unexpectedly', name) + ok, err = False, f'{type(e).__name__}: {e}' + changed = (not st.known) or st.up != ok + if changed: + if st.known or not ok: + logger.log(logging.INFO if ok else logging.WARNING, 'Source %s is %s%s', name, + 'back' if ok else 'unavailable', '' if ok else f': {err}') + if not ok: + self._write('open_blind_period', name, now, err) + elif st.known: + self._write('close_blind_period', name, now) + st.up, st.since, st.known = ok, now, True + if ok: + st.last_ok = now + st.last_error = err + self._write('save_source_status', name, ok, st.since, st.last_ok, err, now) + up[name] = ok + return up + + # -- the cycle ------------------------------------------------------------ + def window(self, now: float) -> Tuple[float, float, bool]: + """(start, end, catching_up) for this cycle.""" + cycle = self.settings.cycle_seconds + if self.last_good_end is None: + return now - cycle, now, False + start = self.last_good_end + earliest = now - self.settings.catchup_hours * 3600 + if start < earliest: + logger.warning('Thor was away %.1f h; catching up on the last %d h only', + (now - start) / 3600, self.settings.catchup_hours) + start = earliest + return start, now, (now - start) > 2 * cycle + + def cycle(self) -> CycleResult: + started = self.clock() + self._load() + start, end, catching_up = self.window(started) + up = self.check_sources(started) + blind = [n for n, ok in up.items() if not ok] + ctx = CycleContext(start, end, catching_up, self.sources, up) + findings, errors = 0, [] + for check in self.checks: + try: + findings += len(check.run(ctx) or []) + except Exception as e: + logger.exception('Check %s failed', check.name) + errors.append(f'{check.name}: {type(e).__name__}: {e}') + finished = self.clock() + # A cycle is good when it ran; blind sources don't make it bad (they're recorded). + # A failing check does, so its window is reviewed again next cycle. + ok = not errors + result = CycleResult(started, finished, (start, end), ok, blind, catching_up, findings, + '; '.join(errors)) + self._write('record_cycle', started=started, finished=finished, window_start=start, + window_end=end, ok=ok, blind=blind, error=result.error) + heartbeat = {'started': started, 'finished': finished, 'ok': ok, 'blind': blind, + 'window_start': start, 'window_end': end, 'catching_up': catching_up} + self._write('set_state', 'last_cycle', heartbeat, finished) + if ok: + self.last_good_end = end + self._write('set_state', 'last_good_window_end', end, finished) + self._write('set_state', 'last_good_cycle', finished, finished) + self.flush() + return result + + def run_forever(self) -> None: + logger.info('Thor monitor starting: %d s cycle, %d sources, %d checks', + self.settings.cycle_seconds, len(self.sources), len(self.checks)) + while not self._stop.is_set(): + began = self.clock() + try: + r = self.cycle() + logger.info('Cycle %s in %.1f s: window %.0f s%s%s', 'ok' if r.ok else 'FAILED', + r.finished - r.started, r.window[1] - r.window[0], + f', blind: {",".join(r.blind)}' if r.blind else '', + ' (catching up)' if r.catching_up else '') + except Exception: + logger.exception('Cycle crashed') + self._stop.wait(max(1.0, self.settings.cycle_seconds - (self.clock() - began))) + + def stop(self, *_args) -> None: + self._stop.set() + + +def build_sources(s: config_mod.Settings) -> Dict[str, Source]: + return { + 'prometheus': PrometheusClient(s.prometheus_url, timeout=s.http_timeout_s), + 'loki': LokiClient(s.loki_url, timeout=s.http_timeout_s), + 'proxmox': ProxmoxClient(s.proxmox_nodes, s.proxmox_token_id, s.proxmox_token_secret, + verify_tls=s.proxmox_verify_tls, timeout=s.http_timeout_s), + 'gandalf': GandalfClient(s.gandalf_url, s.gandalf_api_key, timeout=s.http_timeout_s), + } + + +def main() -> None: # pragma: no cover - process entry point + logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s: %(message)s') + settings = config_mod.load() + db = Database(settings.database) + monitor = Monitor(settings, Store(db), build_sources(settings), prepare=db.migrate) + signal.signal(signal.SIGTERM, monitor.stop) + signal.signal(signal.SIGINT, monitor.stop) + monitor.run_forever() + + +if __name__ == '__main__': # pragma: no cover + main() diff --git a/thor/web/__init__.py b/thor/web/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/thor/web/app.py b/thor/web/app.py new file mode 100644 index 0000000..941237b --- /dev/null +++ b/thor/web/app.py @@ -0,0 +1,111 @@ +"""Thor's web process (``thor.service``): health, metrics, and later the UI, API and MCP. + +``/health`` is what Kuma probes and what the deploy script waits on: 200 only when the +database answers and the monitor loop finished a good cycle recently (like Gandalf's +``health()``), and it reports the commit it runs so a deploy can confirm itself. +""" +import os +import subprocess # nosec B404 - fixed git command, no user input +import time +from typing import Callable, Optional + +from flask import Flask, Response, jsonify + +from .. import config as config_mod +from ..db import Database, DatabaseError, Store + + +def detect_version(root: Optional[str] = None) -> str: + """The deployed commit: THOR_SHA if set, else ``git rev-parse HEAD``, else 'unknown'.""" + sha = os.environ.get('THOR_SHA', '').strip() + if sha: + return sha + root = root or os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + try: + out = subprocess.run(['git', '-C', root, 'rev-parse', 'HEAD'], capture_output=True, # nosec B603 B607 + text=True, timeout=5, check=True) + return out.stdout.strip() or 'unknown' + except (OSError, subprocess.SubprocessError): + return 'unknown' + + +def _metric_escape(value: str) -> str: + return value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n') + + +def create_app(settings: config_mod.Settings, store: Store, version: str, + clock: Callable[[], float] = time.time) -> Flask: + app = Flask(__name__) + app.config['JSON_SORT_KEYS'] = False + + @app.after_request + def security_headers(resp): + resp.headers.setdefault('X-Content-Type-Options', 'nosniff') + resp.headers.setdefault('X-Frame-Options', 'DENY') + resp.headers.setdefault('Referrer-Policy', 'same-origin') + return resp + + @app.route('/health') + def health(): + body = {'status': 'ok', 'sha': version, 'db': False, 'monitor': 'unknown'} + code = 200 + try: + last_good = store.get_state('last_good_cycle') + last = store.get_state('last_cycle') or {} + body['db'] = True + except DatabaseError: + body.update(status='degraded', monitor='unknown (no database)') + return jsonify(body), 503 + now = clock() + if not isinstance(last_good, (int, float)): + body.update(monitor='no good cycle yet', status='degraded') + code = 503 + else: + age = now - float(last_good) + body['monitor_age_s'] = int(age) + if age > settings.stale_after_s: + body.update(monitor='stale', status='degraded') + code = 503 + else: + body['monitor'] = 'ok' + if isinstance(last, dict) and last.get('blind'): + body['blind'] = sorted(last['blind']) + return jsonify(body), code + + @app.route('/metrics') + def metrics(): + lines = [ + '# HELP thor_build_info The commit Thor runs.', + '# TYPE thor_build_info gauge', + f'thor_build_info{{sha="{_metric_escape(version)}"}} 1', + ] + try: + last_good = store.get_state('last_good_cycle') + last = store.get_state('last_cycle') or {} + sources = store.source_statuses() + db_up = 1 + except DatabaseError: + last_good, last, sources, db_up = None, {}, {}, 0 + lines += ['# HELP thor_database_up Whether the web process can read Thor\'s database.', + '# TYPE thor_database_up gauge', f'thor_database_up {db_up}'] + if isinstance(last_good, (int, float)): + lines += ['# HELP thor_last_good_cycle_timestamp_seconds When the monitor last finished a good cycle.', + '# TYPE thor_last_good_cycle_timestamp_seconds gauge', + f'thor_last_good_cycle_timestamp_seconds {float(last_good):.3f}'] + if isinstance(last, dict) and 'started' in last and 'finished' in last: + lines += ['# HELP thor_cycle_duration_seconds How long the last monitor cycle took.', + '# TYPE thor_cycle_duration_seconds gauge', + f'thor_cycle_duration_seconds {float(last["finished"]) - float(last["started"]):.3f}'] + if sources: + lines += ['# HELP thor_source_up Whether a source Thor reads answered on the last check.', + '# TYPE thor_source_up gauge'] + lines += [f'thor_source_up{{source="{_metric_escape(n)}"}} {int(st["up"])}' + for n, st in sorted(sources.items())] + return Response('\n'.join(lines) + '\n', mimetype='text/plain; version=0.0.4') + + return app + + +def build_app() -> Flask: # pragma: no cover - gunicorn entry point + settings = config_mod.load() + return create_app(settings, Store(Database(settings.database)), detect_version()) diff --git a/thor/web/wsgi.py b/thor/web/wsgi.py new file mode 100644 index 0000000..60bf691 --- /dev/null +++ b/thor/web/wsgi.py @@ -0,0 +1,4 @@ +"""gunicorn entry point: ``gunicorn thor.web.wsgi:app``.""" +from .app import build_app + +app = build_app()