CI: one pipeline that gates the deploy on every check and waits for prod to run it (#55, part 1) #76
No files matched your search
@@ -0,0 +1,255 @@
|
|||||||
|
name: CI
|
||||||
|
|
||||||
|
# One pipeline (gandalf#55): every check must pass before main deploys, the deploy names the
|
||||||
|
# exact commit CI tested, and CI waits until production reports that commit as healthy.
|
||||||
|
# Actions are pinned to full commit SHAs and job images to digests (version in the comment).
|
||||||
|
|
||||||
|
# Pushes build only main (which deploys); branches are built through their pull request,
|
||||||
|
# so nothing runs twice. Monday's run re-checks main against new advisories and rules.
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: ["**"]
|
||||||
|
schedule:
|
||||||
|
- cron: '0 6 * * 1'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||||
|
|
||||||
|
# Python comes from the job image, not actions/setup-python: the runner shares one tool
|
||||||
|
# cache between concurrent jobs, and parallel setup actions overwrote each other in Pulse.
|
||||||
|
# Python 3.13 on Debian 13 (trixie) matches production (CT 157).
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint-python:
|
||||||
|
name: Lint (Python)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 15
|
||||||
|
container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390
|
||||||
|
steps:
|
||||||
|
- name: Node for the checkout action
|
||||||
|
# The runner (act) runs JS actions inside the job container, and the Python image has no Node
|
||||||
|
run: apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends nodejs >/dev/null
|
||||||
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Install pinned tools
|
||||||
|
run: python3 -m pip install -q --root-user-action=ignore -r requirements-dev.txt
|
||||||
|
- name: flake8
|
||||||
|
run: flake8 .
|
||||||
|
- name: No em or en dashes (house style)
|
||||||
|
run: |
|
||||||
|
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||||
|
# Includes the vendored design system: it has been dash-free upstream since web_template#3.
|
||||||
|
if git grep -InP '[\x{2013}\x{2014}]|&[mn]dash;|\\u201[34]|̵[12];|ȁ[34];' \
|
||||||
|
-- . ':!package-lock.json'; then
|
||||||
|
echo "::error::Em or en dashes found (listed above). Use a hyphen, colon, comma or 'to'."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
lint-js:
|
||||||
|
name: Lint (JS)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 15
|
||||||
|
container: node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Install eslint (lockfile only)
|
||||||
|
run: npm ci --no-audit --no-fund
|
||||||
|
- name: eslint
|
||||||
|
run: npx eslint --ext .js static/
|
||||||
|
|
||||||
|
test:
|
||||||
|
name: Test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 20
|
||||||
|
container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390
|
||||||
|
steps:
|
||||||
|
- name: Node for the checkout action
|
||||||
|
# The runner (act) runs JS actions inside the job container, and the Python image has no Node
|
||||||
|
run: apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends nodejs >/dev/null
|
||||||
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Install dependencies and pinned tools
|
||||||
|
run: python3 -m pip install -q --root-user-action=ignore -r requirements.txt -r requirements-dev.txt
|
||||||
|
- name: pytest with coverage
|
||||||
|
run: python3 -m pytest tests/ -q --cov=. --cov-report=term-missing --cov-config=.coveragerc
|
||||||
|
|
||||||
|
security:
|
||||||
|
name: Security
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 15
|
||||||
|
container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390
|
||||||
|
steps:
|
||||||
|
- name: Node for the checkout action
|
||||||
|
# The runner (act) runs JS actions inside the job container, and the Python image has no Node
|
||||||
|
run: apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends nodejs >/dev/null
|
||||||
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Install pinned tools
|
||||||
|
run: python3 -m pip install -q --root-user-action=ignore -r requirements-dev.txt
|
||||||
|
- name: bandit
|
||||||
|
run: bandit -q -r . --exclude ./.git,./node_modules -ll
|
||||||
|
|
||||||
|
scan:
|
||||||
|
name: Scan
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 15
|
||||||
|
container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390
|
||||||
|
steps:
|
||||||
|
- name: Node for the checkout action
|
||||||
|
# The runner (act) runs JS actions inside the job container, and the Python image has no Node
|
||||||
|
run: apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends nodejs >/dev/null
|
||||||
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
fetch-depth: 0 # gitleaks scans the whole history, not just this commit
|
||||||
|
- 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
|
||||||
|
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends shellcheck >/dev/null
|
||||||
|
- name: Secrets in code and history (gitleaks)
|
||||||
|
run: |
|
||||||
|
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||||
|
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 -r shellcheck
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
name: Deploy
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 15
|
||||||
|
needs: [lint-python, lint-js, test, security, scan]
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390
|
||||||
|
# Never run two deploys at once; queue instead of cancelling one mid-way.
|
||||||
|
concurrency:
|
||||||
|
group: deploy-production
|
||||||
|
cancel-in-progress: false
|
||||||
|
permissions:
|
||||||
|
contents: write # deploy tag
|
||||||
|
steps:
|
||||||
|
- name: Trigger the deploy webhook
|
||||||
|
env:
|
||||||
|
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
|
||||||
|
GIT_REF: ${{ github.ref }}
|
||||||
|
GIT_SHA: ${{ github.sha }}
|
||||||
|
run: |
|
||||||
|
# The sha and a timestamp make every signature unique. The server checks them once the
|
||||||
|
# pinned deploy script is installed (gandalf#55 part 2); until then it deploys origin/main.
|
||||||
|
python3 - <<'EOF'
|
||||||
|
import hashlib, hmac, json, os, time, urllib.request
|
||||||
|
body = json.dumps({'ref': os.environ['GIT_REF'], 'sha': os.environ['GIT_SHA'],
|
||||||
|
'ts': int(time.time())}, separators=(',', ':')).encode()
|
||||||
|
sig = hmac.new(os.environ['WEBHOOK_SECRET'].encode(), body, hashlib.sha256).hexdigest()
|
||||||
|
req = urllib.request.Request('http://10.10.10.61:9000/hooks/gandalf-deploy', data=body, method='POST',
|
||||||
|
headers={'Content-Type': 'application/json', 'X-Gitea-Signature': sig})
|
||||||
|
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||||
|
print('Webhook:', resp.status, resp.read().decode()[:200])
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Verify production runs this commit
|
||||||
|
env:
|
||||||
|
GIT_SHA: ${{ github.sha }}
|
||||||
|
run: |
|
||||||
|
# The webhook returns at once; the deploy fetches, installs and restarts both services.
|
||||||
|
# Succeed only when /health reports this commit for the web app and the monitor, with a
|
||||||
|
# working database and a fresh monitor (up to 5 minutes).
|
||||||
|
python3 - <<'EOF'
|
||||||
|
import json, os, sys, time, urllib.request
|
||||||
|
want, last = os.environ['GIT_SHA'], 'no response'
|
||||||
|
for _ in range(60):
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen('http://10.10.10.61/health', timeout=5) as resp:
|
||||||
|
last = resp.read().decode()
|
||||||
|
except Exception as e: # 503 while the monitor catches up, or the restart itself
|
||||||
|
last = getattr(e, 'read', lambda: str(e).encode())().decode()[:300]
|
||||||
|
try:
|
||||||
|
body = json.loads(last)
|
||||||
|
except ValueError:
|
||||||
|
body = {}
|
||||||
|
if body.get('status') == 'ok' and body.get('sha') == want and body.get('monitor_sha') == want:
|
||||||
|
print(f'Production is healthy on {want}: {last}')
|
||||||
|
sys.exit(0)
|
||||||
|
time.sleep(5)
|
||||||
|
print(f'::error::Production never reported {want} as healthy (last /health: {last}). '
|
||||||
|
'See /var/log/gandalf-deploy.log on CT 157.')
|
||||||
|
sys.exit(1)
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Tag the deployed commit
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
RUN_NUMBER: ${{ github.run_number }}
|
||||||
|
GIT_SHA: ${{ github.sha }}
|
||||||
|
REPO: ${{ github.repository }}
|
||||||
|
run: |
|
||||||
|
python3 - <<'EOF'
|
||||||
|
import json, os, sys, time, urllib.error, urllib.request
|
||||||
|
tag = time.strftime('deploy-%Y.%m.%d-', time.gmtime()) + os.environ['RUN_NUMBER']
|
||||||
|
api = f"https://code.lotusguild.org/api/v1/repos/{os.environ['REPO']}/tags"
|
||||||
|
auth = {'Authorization': f"token {os.environ['GITHUB_TOKEN']}", 'Content-Type': 'application/json'}
|
||||||
|
body = json.dumps({'tag_name': tag, 'target': os.environ['GIT_SHA'],
|
||||||
|
'message': 'Deployed to production'}).encode()
|
||||||
|
try:
|
||||||
|
urllib.request.urlopen(urllib.request.Request(api, data=body, headers=auth, method='POST'), timeout=15)
|
||||||
|
print(f"Tagged {os.environ['GIT_SHA']} as {tag}")
|
||||||
|
sys.exit(0)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
code = e.code
|
||||||
|
# A rerun keeps its run number, so the tag can already exist: fine if it is this commit's
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(urllib.request.Request(f'{api}/{tag}', headers=auth), timeout=15) as r:
|
||||||
|
existing = json.load(r).get('commit', {}).get('sha')
|
||||||
|
except Exception:
|
||||||
|
existing = None
|
||||||
|
if existing == os.environ['GIT_SHA']:
|
||||||
|
print(f'{tag} already marks this commit (a rerun)')
|
||||||
|
sys.exit(0)
|
||||||
|
print(f'::error::Could not tag {tag} (HTTP {code}; existing: {existing})')
|
||||||
|
sys.exit(1)
|
||||||
|
EOF
|
||||||
|
|
||||||
|
notify:
|
||||||
|
name: Notify
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 5
|
||||||
|
needs: [lint-python, lint-js, test, security, scan, deploy]
|
||||||
|
# Any failure on main or in the weekly run, and every deploy outcome
|
||||||
|
if: >-
|
||||||
|
always() && (
|
||||||
|
(failure() && (github.ref == 'refs/heads/main' || github.event_name == 'schedule')) ||
|
||||||
|
needs.deploy.result == 'success'
|
||||||
|
)
|
||||||
|
steps:
|
||||||
|
- name: Send Matrix alert
|
||||||
|
env:
|
||||||
|
MATRIX_WEBHOOK_URL: ${{ secrets.MATRIX_WEBHOOK_URL }}
|
||||||
|
REPO: ${{ github.repository }}
|
||||||
|
BRANCH: ${{ github.ref_name }}
|
||||||
|
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||||
|
RESULTS: "lint-python=${{ needs.lint-python.result }} lint-js=${{ needs.lint-js.result }} test=${{ needs.test.result }} security=${{ needs.security.result }} scan=${{ needs.scan.result }} deploy=${{ needs.deploy.result }}"
|
||||||
|
DEPLOYED: ${{ needs.deploy.result == 'success' }}
|
||||||
|
run: |
|
||||||
|
if [ -z "$MATRIX_WEBHOOK_URL" ] || [ "$MATRIX_WEBHOOK_URL" = "CONFIGURE_ME" ]; then exit 0; fi
|
||||||
|
if [ "$DEPLOYED" = "true" ]; then MSG="DEPLOYED: ${REPO} @ ${BRANCH} (${GITHUB_SHA:0:7})"; else MSG="CI FAILED: ${REPO} @ ${BRANCH} [${RESULTS}]"; fi
|
||||||
|
curl -sf -X POST "$MATRIX_WEBHOOK_URL" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "{\"text\":\"${MSG}: ${RUN_URL}\"}"
|
||||||
@@ -1,101 +0,0 @@
|
|||||||
name: Lint
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: ["**"]
|
|
||||||
pull_request:
|
|
||||||
branches: ["**"]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
python-lint:
|
|
||||||
name: Python (flake8)
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Install Python and flake8
|
|
||||||
run: |
|
|
||||||
apt-get update -qq
|
|
||||||
apt-get install -y -qq python3 python3-pip
|
|
||||||
pip3 install --break-system-packages flake8
|
|
||||||
|
|
||||||
- name: Run flake8
|
|
||||||
run: flake8 . --exclude=__pycache__,.git
|
|
||||||
|
|
||||||
js-lint:
|
|
||||||
name: JS (eslint)
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Install ESLint
|
|
||||||
run: npm install --save-dev eslint@8
|
|
||||||
|
|
||||||
- name: Run ESLint
|
|
||||||
run: npx eslint --ext .js static/
|
|
||||||
|
|
||||||
dashes:
|
|
||||||
name: No em or en dashes
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: No em or en dashes (house style)
|
|
||||||
run: |
|
|
||||||
# Includes the vendored design system: it has been dash-free upstream since web_template#3.
|
|
||||||
if git grep -InP '[\x{2013}\x{2014}]|&[mn]dash;|\\u201[34]|̵[12];|ȁ[34];' \
|
|
||||||
-- . ':!package-lock.json'; then
|
|
||||||
echo "::error::Em or en dashes found (listed above). Use a hyphen, colon, comma or 'to'."
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
notify-failure:
|
|
||||||
name: Notify on failure
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [python-lint, js-lint, dashes]
|
|
||||||
if: failure() && github.event_name == 'push'
|
|
||||||
steps:
|
|
||||||
- name: Send Matrix alert
|
|
||||||
env:
|
|
||||||
MATRIX_WEBHOOK_URL: ${{ secrets.MATRIX_WEBHOOK_URL }}
|
|
||||||
REPO: ${{ github.repository }}
|
|
||||||
BRANCH: ${{ github.ref_name }}
|
|
||||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
|
||||||
run: |
|
|
||||||
if [ -z "$MATRIX_WEBHOOK_URL" ] || [ "$MATRIX_WEBHOOK_URL" = "CONFIGURE_ME" ]; then exit 0; fi
|
|
||||||
curl -sf -X POST "$MATRIX_WEBHOOK_URL" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d "{\"text\":\"CI FAILED: ${REPO} @ ${BRANCH}: ${RUN_URL}\"}"
|
|
||||||
|
|
||||||
deploy:
|
|
||||||
name: Deploy
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: [python-lint, js-lint, dashes]
|
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
steps:
|
|
||||||
- name: Trigger webhook
|
|
||||||
env:
|
|
||||||
WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }}
|
|
||||||
GIT_REF: ${{ github.ref }}
|
|
||||||
run: |
|
|
||||||
PAYLOAD="{\"ref\":\"${GIT_REF}\"}"
|
|
||||||
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.61:9000/hooks/gandalf-deploy"
|
|
||||||
|
|
||||||
- name: Tag deployed commit
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
run: |
|
|
||||||
TAG="deploy-$(date -u +%Y.%m.%d)-${{ github.run_number }}"
|
|
||||||
curl -sf -X POST \
|
|
||||||
-H "Authorization: token $GITHUB_TOKEN" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-d "{\"tag_name\":\"${TAG}\",\"target\":\"${{ github.sha }}\",\"message\":\"Deployed to production\"}" \
|
|
||||||
"https://code.lotusguild.org/api/v1/repos/${{ github.repository }}/tags"
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
name: Security
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: ["**"]
|
|
||||||
pull_request:
|
|
||||||
branches: ["**"]
|
|
||||||
schedule:
|
|
||||||
- cron: '0 6 * * 1'
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
bandit:
|
|
||||||
name: Python Security (bandit)
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Install bandit
|
|
||||||
run: |
|
|
||||||
apt-get update -qq
|
|
||||||
apt-get install -y -qq python3 python3-pip
|
|
||||||
pip3 install --break-system-packages bandit
|
|
||||||
|
|
||||||
- name: Run bandit
|
|
||||||
run: bandit -r . --exclude .git,__pycache__,node_modules -ll
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
name: Test
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: ["**"]
|
|
||||||
pull_request:
|
|
||||||
branches: ["**"]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
pytest:
|
|
||||||
name: Python Tests (pytest)
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Install Python and dependencies
|
|
||||||
run: |
|
|
||||||
apt-get update -qq
|
|
||||||
apt-get install -y -qq python3 python3-pip
|
|
||||||
pip3 install --break-system-packages pytest pytest-cov
|
|
||||||
pip3 install --break-system-packages -r requirements.txt --quiet
|
|
||||||
|
|
||||||
- name: Run pytest with coverage
|
|
||||||
run: python3 -m pytest tests/ -v --cov=. --cov-report=term-missing --cov-config=.coveragerc
|
|
||||||
@@ -4,3 +4,4 @@ config.json.*
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
node_modules/
|
node_modules/
|
||||||
|
.coverage
|
||||||
@@ -1,8 +1,6 @@
|
|||||||
# GANDALF (Global Advanced Network Detection And Link Facilitator)
|
# GANDALF (Global Advanced Network Detection And Link Facilitator)
|
||||||
|
|
||||||
[](https://code.lotusguild.org/LotusGuild/gandalf/actions?workflow=lint.yml)
|
[](https://code.lotusguild.org/LotusGuild/gandalf/actions?workflow=ci.yml)
|
||||||
[](https://code.lotusguild.org/LotusGuild/gandalf/actions?workflow=test.yml)
|
|
||||||
[](https://code.lotusguild.org/LotusGuild/gandalf/actions?workflow=security.yml)
|
|
||||||
|
|
||||||
> Because it shall not let problems pass.
|
> Because it shall not let problems pass.
|
||||||
|
|
||||||
@@ -263,6 +261,9 @@ otherwise 503 with the failing check: `{"status": "degraded", "checks": {"db": "
|
|||||||
"monitor_age_s": 742}}`. The monitor counts as stalled after five missed polls (at least 10 minutes),
|
"monitor_age_s": 742}}`. The monitor counts as stalled after five missed polls (at least 10 minutes),
|
||||||
so point an uptime monitor at it to catch a hung `gandalf-monitor`, not just a dead web app.
|
so point an uptime monitor at it to catch a hung `gandalf-monitor`, not just a dead web app.
|
||||||
|
|
||||||
|
It also reports the commit each process runs: `sha` (the web app, read from `.git` at startup by
|
||||||
|
`version.py`) and `monitor_sha` (written by the monitor every cycle). CI's deploy waits for both.
|
||||||
|
|
||||||
### Device pages (`/device/<name>`)
|
### Device pages (`/device/<name>`)
|
||||||
One page per host, switch, router, AP, PDU, or modem. Reach them from the search box on the
|
One page per host, switch, router, AP, PDU, or modem. Reach them from the search box on the
|
||||||
dashboard (`/` focuses it), or from any device name. Search matches hostname, IP, MAC, model, type,
|
dashboard (`/` focuses it), or from any device name. Search matches hostname, IP, MAC, model, type,
|
||||||
@@ -1174,15 +1175,26 @@ Take LED colors from the model's quick start guide. See the comment at the top o
|
|||||||
|
|
||||||
## CI / CD
|
## CI / CD
|
||||||
|
|
||||||
| Workflow | Purpose | Triggers |
|
One pipeline, `.gitea/workflows/ci.yml` (gandalf#55). It runs on every pull request, on pushes to
|
||||||
|---|---|---|
|
`main`, and on Mondays at 06:00 UTC against `main`.
|
||||||
| `lint.yml` (python-lint) | flake8 on all `.py` files | Every push and PR |
|
|
||||||
| `lint.yml` (js-lint) | ESLint on `static/` | Every push and PR |
|
|
||||||
| `test.yml` | pytest: `diagnose.py`, `modem.py`, and `monitor.py` alert logic | Every push and PR |
|
|
||||||
| `security.yml` | bandit `-ll` (medium+ severity) | Every push, PR, and weekly Monday 6am |
|
|
||||||
| `deploy` job in `lint.yml` | Calls the `gandalf-deploy` webhook on CT157 (10.10.10.61) | Push to `main` only, after both lint jobs pass |
|
|
||||||
|
|
||||||
Branch protection is enabled on `main`: both lint jobs must pass before any PR can merge.
|
| Job | Runs |
|
||||||
|
|---|---|
|
||||||
|
| Lint (Python) | flake8, and the house-style check for em and en dashes |
|
||||||
|
| Lint (JS) | ESLint on `static/` (`npm ci` from the lockfile) |
|
||||||
|
| Test | pytest with coverage |
|
||||||
|
| Security | bandit `-ll` (medium and higher) |
|
||||||
|
| Scan | gitleaks over the full history, actionlint (with shellcheck) on the workflow, shellcheck on `*.sh` |
|
||||||
|
| Deploy | `main` only, after every job above passes |
|
||||||
|
| Notify | Matrix message on any failure on `main` or in the weekly run, and on every deploy |
|
||||||
|
|
||||||
|
- **Pinned:** actions to full commit SHAs, job images to digests (Python 3.13 on Debian 13 like CT 157,
|
||||||
|
Node 22 for eslint), Python tools in `requirements-dev.txt`, and the scanner downloads by SHA-256.
|
||||||
|
- **Deploy:** signs `{"ref", "sha", "ts"}` with the webhook secret and calls `gandalf-deploy` on CT 157.
|
||||||
|
It then waits up to 5 minutes for `/health` to report that commit as `sha` and `monitor_sha` with
|
||||||
|
status ok, and only then tags it `deploy-<date>-<run>`. Deploys queue; one is never cancelled mid-way.
|
||||||
|
- **Branch protection on `main`** requires every check job by its context name, e.g.
|
||||||
|
`CI / Lint (Python) (pull_request)`.
|
||||||
|
|
||||||
Tests live in `tests/`:
|
Tests live in `tests/`:
|
||||||
- `test_diagnose.py`: `DiagnosticsRunner` static methods (`build_ssh_command`, `parse_output`,
|
- `test_diagnose.py`: `DiagnosticsRunner` static methods (`build_ssh_command`, `parse_output`,
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import diagnose
|
|||||||
import kuma
|
import kuma
|
||||||
import modem as modem_api
|
import modem as modem_api
|
||||||
import topology
|
import topology
|
||||||
|
import version
|
||||||
from monitor import PulseClient, UnifiClient, pause_smart_power, restore_smart_power
|
from monitor import PulseClient, UnifiClient, pause_smart_power, restore_smart_power
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
@@ -1813,8 +1814,14 @@ def health():
|
|||||||
checks['monitor'] = 'error'
|
checks['monitor'] = 'error'
|
||||||
overall = 'degraded'
|
overall = 'degraded'
|
||||||
|
|
||||||
|
# The commits the web app and the monitor run, so a deploy can wait for both (gandalf#55)
|
||||||
|
try:
|
||||||
|
monitor_sha = db.get_state('monitor_sha', '') or ''
|
||||||
|
except Exception:
|
||||||
|
monitor_sha = ''
|
||||||
status_code = 200 if overall == 'ok' else 503
|
status_code = 200 if overall == 'ok' else 503
|
||||||
return jsonify({'status': overall, 'service': 'gandalf', 'checks': checks}), status_code
|
return jsonify({'status': overall, 'service': 'gandalf', 'checks': checks,
|
||||||
|
'sha': version.SHA, 'monitor_sha': monitor_sha}), status_code
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import modem as modem_api
|
|||||||
import reboots
|
import reboots
|
||||||
import thor as thor_api
|
import thor as thor_api
|
||||||
import ticket_text
|
import ticket_text
|
||||||
|
import version
|
||||||
|
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
@@ -2779,6 +2780,8 @@ class NetworkMonitor:
|
|||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
logger.info('Starting network check cycle')
|
logger.info('Starting network check cycle')
|
||||||
|
# /health reports it, so a deploy can check the monitor restarted on the new commit too
|
||||||
|
db.set_state('monitor_sha', version.SHA)
|
||||||
self._load_unused()
|
self._load_unused()
|
||||||
|
|
||||||
# 1. Fetch interface states once: shared by snapshot and alert processing
|
# 1. Fetch interface states once: shared by snapshot and alert processing
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Pinned tools for CI and local checks (gandalf#55). Runtime dependencies are in requirements.txt.
|
||||||
|
flake8==7.5.0
|
||||||
|
bandit==1.9.4
|
||||||
|
pytest==9.2.0
|
||||||
|
pytest-cov==7.1.0
|
||||||
@@ -473,6 +473,15 @@ class TestHealth:
|
|||||||
assert resp.status_code == 503
|
assert resp.status_code == 503
|
||||||
assert resp.get_json()['checks'] == {'db': 'ok', 'monitor': 'stale', 'monitor_age_s': 660}
|
assert resp.get_json()['checks'] == {'db': 'ok', 'monitor': 'stale', 'monitor_age_s': 660}
|
||||||
|
|
||||||
|
def test_reports_the_running_commits(self, client):
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
stamp = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
|
||||||
|
state = {'last_check': stamp, 'monitor_sha': 'b' * 40}
|
||||||
|
gandalf.db.get_state.side_effect = lambda key, default=None: state.get(key, default)
|
||||||
|
with patch.object(gandalf.version, 'SHA', 'a' * 40):
|
||||||
|
body = client.get('/health').get_json()
|
||||||
|
assert body['sha'] == 'a' * 40 and body['monitor_sha'] == 'b' * 40
|
||||||
|
|
||||||
def test_limit_follows_a_long_poll_interval(self, client):
|
def test_limit_follows_a_long_poll_interval(self, client):
|
||||||
assert self._health(client, 1000, poll=300).status_code == 200
|
assert self._health(client, 1000, poll=300).status_code == 200
|
||||||
assert self._health(client, 1600, poll=300).status_code == 503
|
assert self._health(client, 1600, poll=300).status_code == 503
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""Tests for version.py: the running commit, read from .git without git itself (gandalf#55)."""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
|
|
||||||
|
import version # noqa: E402
|
||||||
|
|
||||||
|
A, B = 'a' * 40, 'b' * 40
|
||||||
|
|
||||||
|
|
||||||
|
def _git(tmp_path, head, loose=None, packed=None):
|
||||||
|
g = tmp_path / '.git'
|
||||||
|
g.mkdir()
|
||||||
|
(g / 'HEAD').write_text(head + '\n')
|
||||||
|
if loose:
|
||||||
|
ref, sha = loose
|
||||||
|
p = g.joinpath(*ref.split('/'))
|
||||||
|
p.parent.mkdir(parents=True)
|
||||||
|
p.write_text(sha + '\n')
|
||||||
|
if packed:
|
||||||
|
(g / 'packed-refs').write_text('# pack-refs with: peeled fully-peeled sorted\n' + packed)
|
||||||
|
return str(tmp_path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_detached_head_is_the_sha(tmp_path):
|
||||||
|
assert version.running_sha(_git(tmp_path, A)) == A
|
||||||
|
|
||||||
|
|
||||||
|
def test_branch_with_a_loose_ref(tmp_path):
|
||||||
|
assert version.running_sha(_git(tmp_path, 'ref: refs/heads/main', loose=('refs/heads/main', B))) == B
|
||||||
|
|
||||||
|
|
||||||
|
def test_branch_in_packed_refs(tmp_path):
|
||||||
|
packed = f'{A} refs/heads/other\n{B} refs/heads/main\n^{A}\n'
|
||||||
|
assert version.running_sha(_git(tmp_path, 'ref: refs/heads/main', packed=packed)) == B
|
||||||
|
|
||||||
|
|
||||||
|
def test_anything_unreadable_is_empty(tmp_path):
|
||||||
|
assert version.running_sha(str(tmp_path)) == '' # no .git
|
||||||
|
assert version.running_sha(_git(tmp_path, 'garbage')) == ''
|
||||||
|
other = tmp_path / 'y'
|
||||||
|
other.mkdir()
|
||||||
|
assert version.running_sha(_git(other, 'ref: refs/heads/gone')) == '' # ref missing
|
||||||
|
|
||||||
|
|
||||||
|
def test_this_checkout_reports_a_sha():
|
||||||
|
assert version.SHA == '' or len(version.SHA) == 40
|
||||||
+39
@@ -0,0 +1,39 @@
|
|||||||
|
"""The git commit this process is running, read once at startup (gandalf#55).
|
||||||
|
|
||||||
|
/health reports it so CI can wait until production runs the commit it tested. Read straight
|
||||||
|
from .git (no subprocess): a detached HEAD holds the sha itself; a branch HEAD points at a
|
||||||
|
loose ref or a line in packed-refs. Anything unreadable gives '' rather than an error.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
_SHA = re.compile(r'^[0-9a-f]{40}$')
|
||||||
|
|
||||||
|
|
||||||
|
def running_sha(root: str = '') -> str:
|
||||||
|
"""The 40-character commit sha checked out in *root* (default: this file's folder), or ''."""
|
||||||
|
git = os.path.join(root or os.path.dirname(os.path.abspath(__file__)), '.git')
|
||||||
|
try:
|
||||||
|
with open(os.path.join(git, 'HEAD')) as f:
|
||||||
|
head = f.read().strip()
|
||||||
|
if _SHA.match(head):
|
||||||
|
return head
|
||||||
|
if not head.startswith('ref: '):
|
||||||
|
return ''
|
||||||
|
ref = head[5:].strip()
|
||||||
|
loose = os.path.join(git, *ref.split('/'))
|
||||||
|
if os.path.isfile(loose):
|
||||||
|
with open(loose) as f:
|
||||||
|
sha = f.read().strip()
|
||||||
|
return sha if _SHA.match(sha) else ''
|
||||||
|
with open(os.path.join(git, 'packed-refs')) as f:
|
||||||
|
for line in f:
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) == 2 and parts[1] == ref and _SHA.match(parts[0]):
|
||||||
|
return parts[0]
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
SHA = running_sha()
|
||||||
Reference in new issue
Block a user