Phase 1, PR 4: UI (Needs attention, incidents, known conditions) and the /covering API #8

Merged
jared merged 2 commits from ui into main 2026-11-26 13:47:14 -05:00
23 changed files with 9954 additions and 9 deletions

No files matched your search

+39 -1
View File
@@ -125,6 +125,8 @@ jobs:
run: | run: |
python3 -m venv /tmp/zizmor && /tmp/zizmor/bin/pip install -q zizmor==1.32.0 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 /tmp/zizmor/bin/zizmor --offline --format plain .gitea/workflows/*.yml
- name: Vendored design system matches upstream
run: scripts/ci/check-web-template.sh
- name: Code patterns (semgrep) - name: Code patterns (semgrep)
# Rule packs come from the semgrep registry. Fix new findings, or suppress one line # Rule packs come from the semgrep registry. Fix new findings, or suppress one line
# with `nosemgrep: <rule id>` and a reason. # with `nosemgrep: <rule id>` and a reason.
@@ -134,11 +136,47 @@ jobs:
--config p/python --config p/flask --config p/secrets --config p/security-audit \ --config p/python --config p/flask --config p/secrets --config p/security-audit \
--exclude tests --exclude tests
ui:
name: UI (screenshots)
runs-on: ubuntu-latest
timeout-minutes: 20
# Node (for the checkout action), Chromium and its system libraries. The browser build must
# match the playwright pip pin below; Python is added in the first step.
container: mcr.microsoft.com/playwright:v1.49.1-noble@sha256:70e367e0cbf60340a5b5fd562f6247a34eb3196efab9f88a3dd56482d9fe09d2
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false
- name: Python and dependencies
run: |
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends python3 python3-venv >/dev/null
python3 -m venv /tmp/venv
/tmp/venv/bin/pip install --quiet --disable-pip-version-check -r requirements.txt playwright==1.49.1
- name: Every page renders with replay data (desktop and mobile, dark and light)
run: |
/tmp/venv/bin/python scripts/ui_demo.py 8811 > /tmp/ui-demo.log 2>&1 &
for _ in $(seq 1 60); do
/tmp/venv/bin/python -c 'import urllib.request; urllib.request.urlopen("http://127.0.0.1:8811/", timeout=2)' 2>/dev/null && break
sleep 1
done
/tmp/venv/bin/python scripts/screenshots.py http://127.0.0.1:8811 ui-screenshots
- name: Demo server log
if: always()
run: tail -n 100 /tmp/ui-demo.log || true
- name: Upload screenshots
if: github.event_name == 'pull_request'
uses: actions/upload-artifact@c6a3b2bd78b3985e4b2f15397fec357f0fd808de # v3.2.2-node20 (v4 is unsupported on Gitea)
with:
name: ui-screenshots
path: ui-screenshots/
retention-days: 30
deploy: deploy:
name: Deploy name: Deploy
runs-on: ubuntu-latest runs-on: ubuntu-latest
timeout-minutes: 15 timeout-minutes: 15
needs: [lint, test, integration, security, scan] needs: [lint, test, integration, security, scan, ui]
if: github.event_name == 'push' && github.ref == 'refs/heads/main' if: github.event_name == 'push' && github.ref == 'refs/heads/main'
concurrency: concurrency:
group: deploy-production group: deploy-production
+76
View File
@@ -0,0 +1,76 @@
# Thor's side of the ticket contract
How Gandalf and hwmonDaemon ask Thor whether something is already covered, before they open
a host-, cluster- or source-level ticket. The contract itself is in the plan on
[thor#1](https://code.lotusguild.org/LotusGuild/thor/issues/1); the callers' side is gandalf#66
and hwmonDaemon#42.
## The rules in short
- Each app tickets only its own evidence domain. The root cause owns the ticket, whichever app
found it; symptoms are "Also seen" comments. Thor is the only correlator.
- Before opening a host-, cluster- or source-level ticket, ask Thor. If Thor says **covered**,
comment on the ticket it names instead. If Thor doesn't answer, answers an error, or is slow
(use a short timeout, 3 to 5 s), **open your ticket as normal**. Fail open: never lose a ticket.
- Nobody closes tickets automatically.
## Request
```
GET http://10.10.10.86/api/incidents/covering?host=<host>
GET http://10.10.10.86/api/incidents/covering?scope=cluster
GET http://10.10.10.86/api/incidents/covering?scope=source:prometheus
Authorization: Bearer <your app's key>
```
- Call the CT directly (10.10.10.86), not `thor.lotusguild.org`, which is behind Authelia.
- `host` accepts current names and old ones (`large1`, `micro1`).
- Keys: give Thor's operator the SHA-256 of your key. It goes in `/etc/thor/thor.json`:
`"api_keys": [{"name": "gandalf", "sha256": "<hex>", "scopes": ["read"], "sources": ["10.10.10.61/32"]}]`.
A wrong or unknown key is a 401, even with identity headers. Only `GET` is allowed.
## Response
```json
{
"covered": true,
"ticket_id": "987654321",
"host": "compute-storage-02",
"scope": null,
"incidents": [
{"key": "cluster:corosync:partition", "kind": "partition", "subject": "cluster", "state": "open",
"priority": 1, "summary": "Cluster partition: ...", "mode": "live", "ticket_id": "987654321",
"first_seen": 1793825481.9, "last_seen": 1793825662.0,
"url": "https://thor.lotusguild.org/incident/cluster:corosync:partition"}
],
"known_conditions": [
{"kind": "reboot", "subject": "compute-storage-02", "ticket_id": "693930698",
"reason": "compute-storage-02 reboots every 2 to 3 days from a failing DIMM ..."}
]
}
```
- **`covered`** is true only when there is a ticket you can comment on: an incident with a live
ticket, or a known condition with a tracking ticket. **`ticket_id`** is that ticket.
- While a Thor check runs in **shadow** (all of phase 1), its incidents are listed with
`"mode": "shadow"` and `"ticket_id": null`, and they do **not** make `covered` true: there is
nothing in Tinker to comment on, so open your own ticket. Logging the shadow incident's key
next to your ticket helps the comparison before Thor goes live.
- Timeline-only incidents (planned maintenance from Gandalf) never appear here.
- Times are unix seconds (UTC).
- Errors: `400` (no `host` or `scope`), `401` (key), `503` (Thor can't read its database).
Treat every error as "not covered".
## What counts as covering what
| Ask | Matches |
|---|---|
| `host=X` | active incidents about X, and active cluster-wide incidents |
| `scope=cluster` | active cluster-wide incidents, and incidents on hosts that run Ceph OSDs |
| `scope=source:prometheus` | an active "monitoring source down" incident for that source |
## Incident keys (`dedup_key` in Tinker, tinker_tickets#123)
`scope:subject:kind`, chosen by the app that owns the ticket. Thor's:
| Key | Meaning |
|---|---|
| `host:<host>:oom` | host out of memory (global OOM kills) |
| `host:<host>:reboot` | unexpected reboot (thor#4) |
| `host:<host>:fenced` | host lost its cluster link and was fenced |
| `cluster:corosync:partition` | two or more nodes fenced or out of quorum |
| `cluster:reboots:<n>` | several hosts rebooted together with nothing else explaining it |
| `maintenance:gandalf:<id>` | a Gandalf maintenance (timeline only, never a ticket) |
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# Fails if thor/web/static/web_template/{base.css,base.js} differ from LotusGuild/web_template at
# the commit recorded in thor/web/static/web_template/VERSION. Change the design system upstream,
# then vendor it with a new download (see thor/web/static/web_template/VERSION); never edit the copies here.
set -euo pipefail
ROOT=$(cd "$(dirname "$0")/../.." && pwd)
DEST="$ROOT/thor/web/static/web_template"
UPSTREAM=${WEB_TEMPLATE_RAW_URL:-https://code.lotusguild.org/LotusGuild/web_template/raw/commit}
sha=$(awk '{print $2}' "$DEST/VERSION")
[[ "$sha" =~ ^[0-9a-f]{7,40}$ ]] || { echo "::error::thor/web/static/web_template/VERSION has no commit sha"; exit 1; }
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
status=0
for f in base.css base.js; do
curl -fsS --retry 2 --max-time 30 -o "$tmp/$f" "$UPSTREAM/$sha/$f"
if cmp -s "$tmp/$f" "$DEST/$f"; then
echo "$f matches web_template@$sha"
else
echo "::error::thor/web/static/web_template/$f differs from web_template@$sha. Change it upstream and resync with a new download (see thor/web/static/web_template/VERSION)."
diff -u "$tmp/$f" "$DEST/$f" | head -40 || true
status=1
fi
done
exit $status
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Screenshot Thor's pages (desktop and mobile) for UI review in pull requests.
Usage: python scripts/screenshots.py <base-url> <out-dir>
Needs Playwright with Chromium (pip install playwright; playwright install chromium).
Pair it with scripts/ui_demo.py to show the pages with replay data.
"""
import sys
from pathlib import Path
from playwright.sync_api import sync_playwright
PAGES = {
'needs-attention': '/',
'incident-oom-t1': '/incident/host:compute-storage-01:oom',
'incident-partition-t4': '/incident/cluster:corosync:partition',
'incident-maintenance-t2': '/incident/maintenance:gandalf:2',
'known-conditions': '/known',
}
VIEWPORTS = {'desktop': {'width': 1440, 'height': 900}, 'mobile': {'width': 390, 'height': 844}}
# The design system follows the browser's preference; the terminal look is the dark one.
SCHEMES = ('dark', 'light')
def main(base: str, out: str) -> None:
out_dir = Path(out)
out_dir.mkdir(parents=True, exist_ok=True)
with sync_playwright() as p:
browser = p.chromium.launch()
count = 0
for scheme in SCHEMES:
for vp_name, vp in VIEWPORTS.items():
if scheme == 'light' and vp_name == 'mobile':
continue
page = browser.new_page(viewport=vp, color_scheme=scheme)
for name, path in PAGES.items():
resp = page.goto(base.rstrip('/') + path, wait_until='networkidle')
if resp is None or resp.status >= 400:
raise SystemExit(f'{path} answered {resp.status if resp else "nothing"}')
page.screenshot(path=str(out_dir / f'{name}-{vp_name}-{scheme}.png'), full_page=True)
count += 1
page.close()
browser.close()
print(f'wrote {count} screenshots to {out_dir}')
if __name__ == '__main__':
main(sys.argv[1], sys.argv[2])
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Serve Thor's UI with data from the replays, for screenshots and design review.
Usage: .venv/bin/python scripts/ui_demo.py [port] (default 8811, binds 127.0.0.1)
The store holds T1 stopped mid-incident (05:40, an open P1), the T2 maintenance timeline,
the DIMM known-condition note, and the T4 partition, all from tests/fixtures. The clock is
frozen at T1 05:40 so "ago" texts read as they would have that night.
"""
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from tests.fakes import FakeStore # noqa: E402
from tests.replay import Replay # noqa: E402
from thor.config import Settings # noqa: E402
from thor.web.app import create_app # noqa: E402
T1_0540 = 1795412400.0
def demo_store() -> FakeStore:
merged = FakeStore()
runs = [Replay('t4').run(), Replay('dimm').run(), Replay('t2').run(), Replay('t1').run(until=T1_0540)]
for r in runs:
merged.incidents.update(r.store.incidents)
offset = len(merged.actions)
for a in r.store.actions:
merged.actions.append(dict(a, id=a['id'] + offset))
merged.observations.update(r.store.observations)
t1 = runs[-1].store
merged.state.update(t1.state)
merged.sources = t1.sources
merged.blind = t1.blind
# Show T2's maintenance as still active, as it was mid-window.
m = merged.incidents['maintenance:gandalf:2']
m.update(state='open', cleared_at=None, last_seen=T1_0540 - 600)
return merged
def build():
settings = Settings()
settings.public_url = ''
return create_app(settings, demo_store(), 'demo0000', clock=lambda: T1_0540)
if __name__ == '__main__':
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8811
build().run(host='127.0.0.1', port=port)
+17
View File
@@ -118,6 +118,23 @@ class FakeStore:
self._check('delete_incident') self._check('delete_incident')
self.incidents.pop(key, None) self.incidents.pop(key, None)
def get_incident(self, key):
self._check('get_incident')
return self.incidents.get(key)
def actions_for(self, key):
self._check('actions_for')
return [a for a in self.actions if a['incident_key'] == key]
def recent_actions(self, since, limit=200):
self._check('recent_actions')
return [a for a in reversed(self.actions) if a['created'] >= since][:limit]
def recent_observations(self, since):
self._check('recent_observations')
return [dict(o, first_seen=o['start'], last_seen=o['end'], k=o['key'])
for o in self.observations.values() if o['end'] >= since]
def known_conditions(self): def known_conditions(self):
self._check('known_conditions') self._check('known_conditions')
return [dict(k) for k in self.known if not k.get('ended')] return [dict(k) for k in self.known if not k.get('ended')]
+11 -1
View File
@@ -27,6 +27,13 @@ def test_query_regex_escapes_for_promql_strings():
assert kernel_query(['compute-storage-01']).startswith('{job="journal", host=~"compute\\\\-storage\\\\-01"') assert kernel_query(['compute-storage-01']).startswith('{job="journal", host=~"compute\\\\-storage\\\\-01"')
def test_systemd_escaped_cpuset_is_recognised_as_ceph():
line = GLOBAL.replace('cpuset=ceph-osd@3.service', 'cpuset=system-ceph\\x2dosd.slice')
kill = parse_kills([(10.0, line, {})])[0]
assert kill['cpuset'] == 'system-ceph-osd.slice'
assert MemoryCheck._event('h', kill, {})['ceph'] is True
def test_parse_kills_pairs_lines_and_reads_everything(): def test_parse_kills_pairs_lines_and_reads_everything():
kills = parse_kills([(10.0, GLOBAL, {}), (10.1, KILLED, {}), (20.0, MEMCG, {}), kills = parse_kills([(10.0, GLOBAL, {}), (10.1, KILLED, {}), (20.0, MEMCG, {}),
(30.0, 'Out of memory: Killed process 99 (x) anon-rss:1kB', {})]) (30.0, 'Out of memory: Killed process 99 (x) anon-rss:1kB', {})])
@@ -115,8 +122,11 @@ def test_memory_rules_summary_and_priority():
assert m.priority(inc) == 3 assert m.priority(inc) == 3
inc.events += [{'at': 600, 'guest': '154'}, {'at': 1200, 'guest': '154'}] inc.events += [{'at': 600, 'guest': '154'}, {'at': 1200, 'guest': '154'}]
assert m.priority(inc) == 2 assert m.priority(inc) == 2
inc.symptoms = {'s': {'subject': 'storage-01', 'cluster_effect': True}} inc.symptoms = {'s': {'subject': 'storage-01', 'cluster_effect': True},
'c': {'subject': 'cluster', 'cluster_effect': True}}
assert m.priority(inc) == 1 assert m.priority(inc) == 1
assert inc.facts['escalation_reason'] == ('While this host is out of memory, other hosts are stalling '
'(storage-01) and Ceph raised new alerts.')
inc.symptoms = {} inc.symptoms = {}
inc.events.append({'at': 1300, 'guest': '155', 'ceph': True}) inc.events.append({'at': 1300, 'guest': '155', 'ceph': True})
assert m.priority(inc) == 1 assert m.priority(inc) == 1
+182
View File
@@ -0,0 +1,182 @@
import hashlib
import pytest
from thor.config import Settings
from thor.web import views
from thor.web.api import check_key
from thor.web.app import create_app
from .fakes import Clock, FakeStore
KEY = 'gandalf-test-key'
T = 1_795_412_400.0
def settings(**kw):
s = Settings()
s.public_url = 'https://thor.example'
s.api_keys = [{'name': 'gandalf', 'sha256': hashlib.sha256(KEY.encode()).hexdigest(), 'scopes': ['read'],
'sources': ['10.10.10.61/32']}]
for k, v in kw.items():
setattr(s, k, v)
return s
def inc(key, subject, state='open', mode='shadow', ticket=True, kind='oom', priority=1, **kw):
d = {'key': key, 'kind': kind, 'subject': subject, 'state': state, 'priority': priority, 'mode': mode,
'ticket': ticket, 'summary': f'{subject} {kind}', 'first_seen': T - 600, 'last_seen': T - 60,
'symptoms': {}, 'events': [{'at': T - 600, 'text': 'kill'}], 'facts': {}}
d.update(kw)
return d
@pytest.fixture
def store():
s = FakeStore()
s.incidents = {
'host:compute-storage-01:oom': inc('host:compute-storage-01:oom', 'compute-storage-01'),
'cluster:corosync:partition': inc('cluster:corosync:partition', 'cluster', mode='live', kind='partition'),
'maintenance:gandalf:2': inc('maintenance:gandalf:2', 'cluster', ticket=False, kind='maintenance'),
'host:storage-01:oom': inc('host:storage-01:oom', 'storage-01', state='cleared', cleared_at=T - 30),
}
s.add_action({'incident_key': 'cluster:corosync:partition', 'kind': 'open', 'created': T - 500, 'mode': 'live',
'payload': {'title': 't', 'description': 'd', 'priority': 1}})
s.mark_action_sent(1, '987654321', T - 499)
s.state['last_good_cycle'] = T - 30
s.state['last_cycle'] = {'started': T - 31, 'finished': T - 30, 'blind': [], 'catching_up': False}
s.sources = {'loki': {'up': False, 'since': T - 120, 'last_ok': None, 'last_error': 'HTTP 500'},
'prometheus': {'up': True, 'since': T - 9000, 'last_ok': T - 30, 'last_error': ''}}
s.observations['host:monitor-01:scrape'] = {
'key': 'host:monitor-01:scrape', 'kind': 'scrape', 'role': 'symptom', 'subject': 'monitor-01',
'start': T - 100, 'end': T - 90, 'summary': 'monitor-01 slow'}
return s
def client(store, **kw):
return create_app(settings(**kw), store, 'abc1234def', clock=Clock(T)).test_client()
def get(c, path, key=KEY, ip='10.10.10.61'):
headers = {'X-Forwarded-For': ip}
if key:
headers['Authorization'] = f'Bearer {key}'
return c.get(path, headers=headers)
# -- API keys ------------------------------------------------------------------
def test_api_needs_a_valid_key_from_an_allowed_address(store):
c = client(store)
assert get(c, '/api/incidents', key=None).status_code == 401
assert get(c, '/api/incidents', key='wrong').status_code == 401
assert get(c, '/api/incidents', ip='10.10.10.99').status_code == 401
assert get(c, '/api/incidents').status_code == 200
assert c.post('/api/incidents', headers={'Authorization': f'Bearer {KEY}'}).status_code == 405
# Identity headers never stand in for a key.
spoof = {'Remote-User': 'jared', 'X-Forwarded-For': '10.10.10.27'}
assert c.get('/api/incidents', headers=spoof).status_code == 401
def test_check_key_edge_cases():
s = settings()
s.api_keys.append({'name': 'noread', 'sha256': hashlib.sha256(b'k2').hexdigest(), 'scopes': ['write']})
s.api_keys.append({'name': 'any', 'sha256': hashlib.sha256(b'k3').hexdigest()})
assert check_key(s, 'Bearer k2', '1.2.3.4') is None
assert check_key(s, 'Bearer k3', 'not-an-ip')['name'] == 'any'
assert check_key(s, f'Bearer {KEY}', 'garbage') is None
assert check_key(s, 'Basic x', '10.10.10.61') is None
# -- /covering (thor#1 contract, docs/contract.md) ---------------------------------
def test_covering_shadow_incident_is_listed_but_does_not_cover(store):
store.incidents.pop('cluster:corosync:partition')
body = get(client(store), '/api/incidents/covering?host=compute-storage-01').get_json()
assert body['covered'] is False and body['ticket_id'] is None
assert [i['key'] for i in body['incidents']] == ['host:compute-storage-01:oom']
assert body['incidents'][0]['mode'] == 'shadow'
def test_covering_live_ticket_covers_and_cluster_incidents_cover_every_host(store):
body = get(client(store), '/api/incidents/covering?host=monitor-01').get_json()
assert body['covered'] is True and body['ticket_id'] == '987654321'
assert [i['key'] for i in body['incidents']] == ['cluster:corosync:partition']
# Timeline-only maintenance is never offered as something to comment on.
assert all(i['key'] != 'maintenance:gandalf:2' for i in body['incidents'])
def test_covering_known_condition_and_old_names(store):
store.incidents = {}
body = get(client(store), '/api/incidents/covering?host=large1').get_json()
assert body['host'] == 'compute-storage-02'
assert body['covered'] is True and body['ticket_id'] == '693930698'
assert body['known_conditions'][0]['kind'] == 'reboot'
def test_covering_scopes_and_errors(store):
c = client(store)
cluster = get(c, '/api/incidents/covering?scope=cluster').get_json()
assert {i['key'] for i in cluster['incidents']} == {'host:compute-storage-01:oom', 'cluster:corosync:partition'}
source = get(c, '/api/incidents/covering?scope=source:prometheus').get_json()
assert source['covered'] is False and source['incidents'] == []
assert get(c, '/api/incidents/covering').status_code == 400
store.down = True
assert get(c, '/api/incidents/covering?host=monitor-01').status_code == 503 # callers fail open
def test_incident_api(store):
c = client(store)
assert get(c, '/api/incident/host:compute-storage-01:oom').get_json()['incident']['summary'] == \
'compute-storage-01 oom'
assert get(c, '/api/incident/none').status_code == 404
listing = get(c, '/api/incidents').get_json()
assert {i['key'] for i in listing['active']} == {'cluster:corosync:partition', 'host:compute-storage-01:oom',
'maintenance:gandalf:2'}
assert [i['key'] for i in listing['recent']] == ['host:storage-01:oom']
# -- pages -----------------------------------------------------------------------
def test_needs_attention_page(store):
r = client(store).get('/')
html = r.get_data(as_text=True)
assert r.status_code == 200
assert 'nonce-' in r.headers['Content-Security-Policy']
assert 'compute-storage-01 oom' in html and 'shadow (not sent)' in html
assert 'ticket #987654321' in html
assert 'Loki: <strong>blind</strong>' in html and 'HTTP 500' in html
assert 'On the timeline only' in html and 'monitor-01 slow' in html # unexplained symptom
assert 'Last 7 days' in html and 'storage-01 oom' in html
def test_incident_and_known_pages(store):
c = client(store)
r = c.get('/incident/cluster:corosync:partition')
assert r.status_code == 200 and '#987654321' in r.get_data(as_text=True)
assert 'timeline only' in c.get('/incident/maintenance:gandalf:2').get_data(as_text=True)
assert c.get('/incident/nope').status_code == 404
known = c.get('/known').get_data(as_text=True)
assert '693930698' in known and 'compute-storage-02' in known
def test_user_shown_only_from_the_proxy(store):
c = client(store)
headers = {'Remote-User': 'jared', 'Remote-Name': 'Jared', 'Remote-Groups': 'admin,employee'}
via_npm = c.get('/', headers=dict(headers, **{'X-Forwarded-For': '10.10.10.27'})).get_data(as_text=True)
assert 'Jared' in via_npm and 'lt-badge-admin' in via_npm
direct = c.get('/', headers=dict(headers, **{'X-Forwarded-For': '10.10.10.99'})).get_data(as_text=True)
assert 'Jared' not in direct
def test_explained_symptoms_are_not_listed_as_unexplained(store):
store.incidents['host:compute-storage-01:oom']['symptoms'] = {'host:monitor-01:scrape': {'first': T}}
data = views.needs_attention(store, settings(), T)
assert data['loose'] == []
def test_filters():
from thor.web.ui import ago, hm, pclass, utc
app = create_app(settings(), FakeStore(), 'x', clock=Clock(T))
with app.test_request_context('/'):
assert utc(None) == 'unknown' and hm(None) == '?' and ago(None) == 'never'
assert ago(T - 30) == '30 s ago' and ago(T - 600) == '10 min ago'
assert ago(T - 7200) == '2 h ago' and ago(T - 3 * 86400) == '3 d ago'
assert pclass(1) == 'bad' and pclass(3) == 'warn' and pclass(9) == 'info'
+19 -6
View File
@@ -39,6 +39,14 @@ OOM_CHECKS = [
] ]
ESCAPE_RE = re.compile(r'\\x([0-9a-fA-F]{2})')
def unescape(value: str) -> str:
"""Undo systemd's unit-name escaping: ``system-ceph\\x2dosd.slice`` is ``system-ceph-osd.slice``."""
return ESCAPE_RE.sub(lambda m: chr(int(m.group(1), 16)), value)
def kernel_query(names: List[str]) -> str: def kernel_query(names: List[str]) -> str:
hosts = query_regex(names) hosts = query_regex(names)
return (f'{{job="journal", host=~"{hosts}", transport="kernel"}} ' return (f'{{job="journal", host=~"{hosts}", transport="kernel"}} '
@@ -57,7 +65,7 @@ def parse_kills(lines) -> List[Dict]:
for part in m.group(1).split(','): for part in m.group(1).split(','):
if '=' in part: if '=' in part:
k, v = part.split('=', 1) k, v = part.split('=', 1)
fields[k] = v fields[k] = unescape(v)
else: else:
flags.add(part) flags.add(part)
memcg = fields.get('task_memcg', '') memcg = fields.get('task_memcg', '')
@@ -195,11 +203,16 @@ class MemoryCheck:
if any(e.get('ceph') for e in inc.events): if any(e.get('ceph') for e in inc.events):
inc.facts['escalation_reason'] = 'An OOM kill was triggered from a Ceph OSD: storage is affected.' inc.facts['escalation_reason'] = 'An OOM kill was triggered from a Ceph OSD: storage is affected.'
return 1 return 1
stalled = {s['subject'] for s in inc.symptoms.values() effects = [s for s in inc.symptoms.values() if s.get('cluster_effect') and s['subject'] != inc.subject]
if s.get('cluster_effect') and s['subject'] not in (inc.subject,)} stalled = sorted({s['subject'] for s in effects if s['subject'] != 'cluster'})
if stalled: ceph = any(s['subject'] == 'cluster' for s in effects)
inc.facts['escalation_reason'] = ('While this host is out of memory, the cluster is stalling: ' if stalled or ceph:
+ ', '.join(sorted(stalled)) + '.') parts = []
if stalled:
parts.append('other hosts are stalling (' + ', '.join(stalled) + ')')
if ceph:
parts.append('Ceph raised new alerts')
inc.facts['escalation_reason'] = 'While this host is out of memory, ' + ' and '.join(parts) + '.'
return 1 return 1
times = sorted(e['at'] for e in inc.events) times = sorted(e['at'] for e in inc.events)
for i in range(len(times)): for i in range(len(times)):
+10
View File
@@ -62,6 +62,12 @@ class Settings:
http_timeout_s: float = 10.0 http_timeout_s: float = 10.0
checks: Dict[str, str] = field(default_factory=dict) checks: Dict[str, str] = field(default_factory=dict)
database: DatabaseSettings = field(default_factory=DatabaseSettings) database: DatabaseSettings = field(default_factory=DatabaseSettings)
# Machine keys for Thor's API (Gandalf's and hwmonDaemon's /covering pre-check): only the
# SHA-256 of each key is kept, like Gandalf's api_keys (gandalf#68).
api_keys: List[Dict] = field(default_factory=list)
# Requests through NPM carry Authelia's Remote-* headers. They are only displayed (the UI is
# read-only), and only believed from this proxy address.
trusted_proxy: str = '10.10.10.27'
def check_mode(self, name: str) -> str: def check_mode(self, name: str) -> str:
mode = self.checks.get(name, 'shadow') mode = self.checks.get(name, 'shadow')
@@ -131,6 +137,10 @@ def load(config_path: Optional[str] = None, env_dir: Optional[str] = None,
s.proxmox_nodes = [str(n) for n in data['proxmox_nodes']] s.proxmox_nodes = [str(n) for n in data['proxmox_nodes']]
if 'proxmox_verify_tls' in data: if 'proxmox_verify_tls' in data:
s.proxmox_verify_tls = _as_bool(data['proxmox_verify_tls']) s.proxmox_verify_tls = _as_bool(data['proxmox_verify_tls'])
if isinstance(data.get('api_keys'), list):
s.api_keys = [k for k in data['api_keys'] if isinstance(k, dict) and k.get('sha256')]
if data.get('trusted_proxy'):
s.trusted_proxy = str(data['trusted_proxy'])
if isinstance(data.get('checks'), dict): if isinstance(data.get('checks'), dict):
s.checks = {str(k): str(v) for k, v in data['checks'].items()} s.checks = {str(k): str(v) for k, v in data['checks'].items()}
+13
View File
@@ -398,3 +398,16 @@ class Store:
def end_known_condition(self, condition_id: int, ended_by: str, now: float) -> int: def end_known_condition(self, condition_id: int, ended_by: str, now: float) -> int:
return self.db.execute("""UPDATE known_conditions SET ended_at=%s, ended_by=%s return self.db.execute("""UPDATE known_conditions SET ended_at=%s, ended_by=%s
WHERE id=%s AND ended_at IS NULL""", (to_dt(now), ended_by, condition_id)) WHERE id=%s AND ended_at IS NULL""", (to_dt(now), ended_by, condition_id))
# -- reads for the web UI and API -------------------------------------------
def get_incident(self, key: str) -> Optional[Dict[str, Any]]:
rows = self.db.query('SELECT data FROM incidents WHERE k=%s', (key,))
return json.loads(rows[0]['data']) if rows else None
def actions_for(self, key: str) -> List[Dict[str, Any]]:
rows = self.db.query("""SELECT id, kind, mode, status, created_at, sent_at, ticket_id, error, payload
FROM actions WHERE incident_key=%s ORDER BY id""", (key,))
for r in rows:
r['created_at'], r['sent_at'] = from_dt(r['created_at']), from_dt(r['sent_at'])
r['payload'] = json.loads(r['payload'] or '{}')
return rows
+100
View File
@@ -0,0 +1,100 @@
"""Thor's JSON API.
``/api/incidents/covering`` is the pre-check Gandalf and hwmonDaemon call before opening a host,
cluster or source ticket (thor#1 contract; docs/contract.md). Callers use a machine key, sent
straight to the CT (``http://10.10.10.86``), like Thor's own key for Gandalf (gandalf#68):
only the key's SHA-256 is configured, a key can be limited to source addresses, and a wrong
key is refused even if identity headers are present.
"""
import hashlib
import hmac
import ipaddress
import time
from typing import Callable, Optional
from flask import Blueprint, abort, current_app, g, jsonify, request
from ..db import DatabaseError
from ..hosts import HostRegistry
from . import views
bp = Blueprint('api', __name__, url_prefix='/api')
def _client_ip() -> str:
# gunicorn sits behind the CT's own nginx; the address nginx saw is the first hop.
fwd = request.headers.get('X-Forwarded-For', '')
return (fwd.split(',')[-1].strip() if fwd else '') or (request.remote_addr or '')
def check_key(settings, header: str, client_ip: str) -> Optional[dict]:
"""The configured key matching ``Authorization: Bearer <key>``, or None."""
if not header.startswith('Bearer '):
return None
digest = hashlib.sha256(header[7:].strip().encode()).hexdigest()
for k in settings.api_keys:
if not hmac.compare_digest(digest, str(k.get('sha256', '')).lower()):
continue
if 'read' not in (k.get('scopes') or ['read']):
return None
sources = k.get('sources') or []
if sources:
try:
ip = ipaddress.ip_address(client_ip)
except ValueError:
return None
if not any(ip in ipaddress.ip_network(s, strict=False) for s in sources):
return None
return k
return None
@bp.before_request
def require_key():
settings = current_app.config['THOR_SETTINGS']
if request.method != 'GET':
abort(405)
key = check_key(settings, request.headers.get('Authorization', ''), _client_ip())
if key is None:
return jsonify({'error': 'a valid API key is required'}), 401
g.api_client = key.get('name', 'unknown')
def _store():
return current_app.config['THOR_STORE']
def _now() -> float:
clock: Callable[[], float] = current_app.config.get('THOR_CLOCK', time.time)
return clock()
@bp.errorhandler(DatabaseError)
def db_down(_e):
return jsonify({'error': 'Thor cannot read its database right now; fail open'}), 503
@bp.route('/incidents/covering')
def covering():
host = (request.args.get('host') or '').strip() or None
scope = (request.args.get('scope') or '').strip() or None
if not host and not scope:
return jsonify({'error': 'give host=<name> or scope=cluster|source:<name>'}), 400
hosts = current_app.config.get('THOR_HOSTS') or HostRegistry()
settings = current_app.config['THOR_SETTINGS']
return jsonify(views.covering(_store(), hosts, host, scope, settings.public_url))
@bp.route('/incidents')
def incidents():
settings = current_app.config['THOR_SETTINGS']
return jsonify(views.incidents(_store(), _now(), settings.public_url))
@bp.route('/incident/<path:key>')
def incident(key):
settings = current_app.config['THOR_SETTINGS']
detail = views.incident_detail(_store(), key, settings.public_url)
if detail is None:
return jsonify({'error': 'no such incident'}), 404
return jsonify(detail)
+4 -1
View File
@@ -37,7 +37,10 @@ def _metric_escape(value: str) -> str:
def create_app(settings: config_mod.Settings, store: Store, version: str, def create_app(settings: config_mod.Settings, store: Store, version: str,
clock: Callable[[], float] = time.time) -> Flask: clock: Callable[[], float] = time.time) -> Flask:
app = Flask(__name__) app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False app.config.update(THOR_SETTINGS=settings, THOR_STORE=store, THOR_VERSION=version, THOR_CLOCK=clock)
from . import api, ui
app.register_blueprint(api.bp)
app.register_blueprint(ui.bp)
@app.after_request @app.after_request
def security_headers(resp): def security_headers(resp):
+59
View File
@@ -0,0 +1,59 @@
/* Thor's own styles, on top of the LotusGuild design system (web_template/base.css).
The "Needs attention" groups follow Gandalf's dashboard so the two apps read alike. */
.t-section { margin: 0 0 var(--space-xl); }
.t-section-header { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-md);
border-bottom: 1px solid var(--border-dim); margin-bottom: var(--space-md); padding-bottom: var(--space-xs); }
.t-section-title { font-size: 1.05rem; letter-spacing: .06em; text-transform: uppercase; margin: 0;
color: var(--text-accent); display: flex; align-items: center; gap: var(--space-sm); }
.t-section-meta { color: var(--text-muted); font-size: .82em; }
.t-columns { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-lg); }
.t-note { color: var(--text-secondary); font-size: .88em; max-width: 70ch; }
.t-err { color: var(--accent-red); }
/* Needs attention (same shape as Gandalf's) */
.attention-groups { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.attention-group { border: 1px solid var(--border-dim); background: var(--bg-card); padding: 12px 14px; }
.attention-group-title { font-size: .82rem; letter-spacing: .08em; text-transform: uppercase; margin: 0 0 8px;
color: var(--text-secondary); display: flex; align-items: center; gap: 8px; }
.attention-group-broken .attention-group-title { color: var(--accent-red); }
.attention-count { font-size: .78em; padding: 0 6px; border: 1px solid var(--border-color); color: var(--text-secondary); }
.attention-list { list-style: none; margin: 0; padding: 0; }
.attention-item { position: relative; padding: 7px 0 7px 14px; border-top: 1px solid var(--border-dim); font-size: .9em; }
.attention-item:first-child { border-top: 0; }
.attention-item::before { content: ''; position: absolute; left: 0; top: 13px; width: 6px; height: 6px; }
.attention-bad::before { background: var(--accent-red); }
.attention-warn::before { background: var(--accent-amber); }
.attention-info::before { background: var(--accent-cyan); }
.attention-link { color: var(--text-primary); text-decoration: none; }
.attention-link:hover, .attention-link:focus-visible { color: var(--accent-cyan); text-decoration: underline; }
.attention-detail { color: var(--text-muted); font-size: .86em; margin: 2px 0 0; }
.attention-clear { color: var(--accent-green); font-size: .86em; margin: 0; }
.attention-empty { color: var(--text-muted); font-size: .86em; margin: 0; }
/* Priority chips */
.t-prio { display: inline-block; font-size: .75em; font-weight: 700; padding: 0 5px; margin-right: 6px;
border: 1px solid currentColor; vertical-align: 1px; }
.t-prio-bad { color: var(--accent-red); }
.t-prio-warn { color: var(--accent-amber); }
.t-prio-info { color: var(--accent-cyan); }
/* Incident page */
.t-facts { display: grid; grid-template-columns: max-content 1fr; gap: 4px 18px; margin: 0; font-size: .9em; }
.t-facts dt { color: var(--text-muted); }
.t-facts dd { margin: 0; }
.t-timeline { list-style: none; margin: 0; padding: 0; font-size: .88em; }
.t-timeline li { padding: 5px 0; border-top: 1px solid var(--border-dim); }
.t-timeline li:first-child { border-top: 0; }
.t-timeline time { color: var(--accent-cyan); margin-right: 8px; font-variant-numeric: tabular-nums; }
.t-preview-title { font-size: .85em; }
.t-preview { white-space: pre-wrap; font-size: .82em; background: var(--bg-terminal); border: 1px solid var(--border-dim);
padding: 12px; max-height: 520px; overflow: auto; color: var(--text-secondary); }
.t-footer { display: flex; flex-wrap: wrap; gap: 6px 22px; padding: 14px var(--space-lg); color: var(--text-muted);
font-size: .78em; border-top: 1px solid var(--border-dim); }
.t-footer a { color: var(--text-muted); }
@media (max-width: 900px) {
.attention-groups, .t-columns { grid-template-columns: 1fr; }
}
+1
View File
@@ -0,0 +1 @@
v1.2 8286bb23f3cff3ab9242a29d12184dfd03a3d8a4 2026-11-23T00:21:08Z
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+71
View File
@@ -0,0 +1,71 @@
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="theme-color" content="#030508">
<meta name="robots" content="noindex, nofollow">
<meta name="description" content="THOR: out-of-band host and cluster health for the LotusGuild cluster">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='3' fill='%23030508'/%3E%3Cpath d='M3 3h10v4H9v6H7V7H3z' fill='%23FF6B00'/%3E%3C/svg%3E">
<title>{% block title %}Needs attention{% endblock %} | THOR</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,400;0,600;0,700;1,400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='web_template/base.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<script nonce="{{ nonce }}" src="{{ url_for('static', filename='web_template/base.js') }}"></script>
</head>
<body>
<a class="lt-skip-link" href="#main-content">Skip to main content</a>
<div id="lt-nav-drawer" class="lt-nav-drawer" aria-hidden="true" role="dialog" aria-modal="true" aria-label="Navigation menu">
<div class="lt-nav-drawer-header">
<span class="lt-brand-title">THOR</span>
<button type="button" class="lt-nav-drawer-close" id="lt-nav-drawer-close" aria-label="Close navigation">&#x2715;</button>
</div>
<nav class="lt-nav-drawer-links" aria-label="Mobile navigation">
<a href="{{ url_for('ui.index') }}" class="lt-nav-drawer-link{% if active_nav == 'index' %} active{% endif %}">Needs attention</a>
<a href="{{ url_for('ui.known') }}" class="lt-nav-drawer-link{% if active_nav == 'known' %} active{% endif %}">Known conditions</a>
</nav>
</div>
<div id="lt-nav-overlay" class="lt-nav-drawer-overlay"></div>
<header class="lt-header" role="banner">
<div class="lt-header-left">
<button type="button" class="lt-menu-btn" id="lt-menu-btn" aria-label="Open navigation menu"
aria-expanded="false" aria-controls="lt-nav-drawer">
<span class="lt-menu-btn-bar"></span><span class="lt-menu-btn-bar"></span><span class="lt-menu-btn-bar"></span>
</button>
<div class="lt-brand">
<a href="{{ url_for('ui.index') }}" class="lt-brand-title" title="Total Hardware Operations Resolver">THOR</a>
<span class="lt-brand-subtitle">Host and cluster health, seen from outside</span>
</div>
<nav class="lt-nav" aria-label="Main navigation">
<a href="{{ url_for('ui.index') }}" class="lt-nav-link{% if active_nav == 'index' %} active{% endif %}"
{% if active_nav == 'index' %}aria-current="page"{% endif %}>Needs attention</a>
<a href="{{ url_for('ui.known') }}" class="lt-nav-link{% if active_nav == 'known' %} active{% endif %}"
{% if active_nav == 'known' %}aria-current="page"{% endif %}>Known conditions</a>
</nav>
</div>
<div class="lt-header-right">
{% if user.name %}<span class="lt-header-user">{{ user.name }}</span>{% endif %}
{% if 'admin' in user.groups %}<span class="lt-badge-admin">admin</span>{% endif %}
</div>
</header>
<main class="lt-main lt-container" id="main-content">
{% block content %}{% endblock %}
</main>
<footer class="t-footer">
<span>THOR {{ version }}</span>
<span>Shadow mode: Thor records what it would send and sends nothing to Tinker until a check goes live.</span>
<a href="https://code.lotusguild.org/LotusGuild/thor/issues/1">thor#1</a>
</footer>
<script nonce="{{ nonce }}">
document.addEventListener('DOMContentLoaded', function () { lt.init({ skipBoot: true }); });
</script>
{% block scripts %}{% endblock %}
</body>
</html>
+79
View File
@@ -0,0 +1,79 @@
{% extends "base.html" %}
{% set i = d.incident %}
{% block title %}{{ i.summary }}{% endblock %}
{% block content %}
<section class="t-section" aria-labelledby="inc-title">
<div class="t-section-header">
<h1 class="t-section-title" id="inc-title">
{% if i.ticket %}<span class="t-prio t-prio-{{ i.priority | pclass }}">P{{ i.priority }}</span>{% endif %}
{{ i.summary }}
</h1>
</div>
<dl class="t-facts">
<dt>State</dt><dd>{{ i.state }}{% if not i.ticket %} (timeline only, no ticket by design){% endif %}</dd>
<dt>Ticket</dt><dd>
{% if i.known_ticket %}known condition: notes go to #{{ i.known_ticket }}{% if d.known_reason %} ({{ d.known_reason }}){% endif %}
{% elif i.ticket_id %}<a href="https://t.lotusguild.org/ticket/{{ i.ticket_id }}">#{{ i.ticket_id }}</a>
{% elif i.mode != 'live' %}shadow: recorded below, not sent{% else %}not sent yet{% endif %}</dd>
<dt>Key</dt><dd><code>{{ i.key }}</code></dd>
<dt>First seen</dt><dd>{{ i.first_seen | utc }}</dd>
<dt>Last seen</dt><dd>{{ i.last_seen | utc }}</dd>
{% if i.cleared_at %}<dt>Cleared</dt><dd>{{ i.cleared_at | utc }}</dd>{% endif %}
{% for k, v in (d.facts.display or {}).items() %}<dt>{{ k }}</dt><dd>{{ v }}</dd>{% endfor %}
{% if d.facts.escalation_reason and i.priority and i.priority < 3 %}<dt>Why this priority</dt><dd>{{ d.facts.escalation_reason }}</dd>{% endif %}
</dl>
{% if d.seen_after_the_fact %}<p class="t-note">Seen after the fact: Thor was away or blind while this happened and found it when it caught up.</p>{% endif %}
</section>
<div class="t-columns">
<section class="t-section" aria-labelledby="ev-title">
<div class="t-section-header"><h2 class="t-section-title" id="ev-title">What happened</h2></div>
{% if d.events %}
<ol class="t-timeline">
{% for e in d.events %}<li><time>{{ e.at | hm }}</time> {{ e.text }}</li>{% endfor %}
</ol>
{% else %}<p class="attention-empty">No events recorded.</p>{% endif %}
</section>
<section class="t-section" aria-labelledby="sym-title">
<div class="t-section-header"><h2 class="t-section-title" id="sym-title">Also seen <span class="attention-count">{{ d.symptoms | length }}</span></h2></div>
{% if d.symptoms %}
<ol class="t-timeline">
{% for s in d.symptoms %}
<li><time>{{ s.first | hm }}{% if s.last and s.last - s.first >= 60 %} to {{ s.last | hm }}{% endif %}</time> {{ s.summary }}</li>
{% endfor %}
</ol>
{% else %}<p class="attention-empty">Nothing attached.</p>{% endif %}
</section>
</div>
<section class="t-section" aria-labelledby="act-title">
<div class="t-section-header"><h2 class="t-section-title" id="act-title">What Thor sent, or would have sent</h2></div>
{% if d.actions %}
<div class="lt-table-wrap">
<table class="lt-table">
<thead><tr><th>When</th><th>Action</th><th>Mode</th><th>Status</th><th>Detail</th></tr></thead>
<tbody>
{% for a in d.actions %}
<tr>
<td>{{ a.created_at | utc('%m-%d %H:%M:%S') if a.created_at else (a.created | utc('%m-%d %H:%M:%S')) }}</td>
<td>{{ a.kind | replace('_', ' ') }}</td>
<td>{{ a.mode }}</td>
<td>{{ a.status }}{% if a.ticket_id %} #{{ a.ticket_id }}{% endif %}</td>
<td>{% if a.payload.priority %}P{{ a.payload.priority }} {% endif %}{{ a.payload.title or a.payload.symptoms | join(', ') if a.payload.symptoms else a.payload.title or '' }}{% if a.error %} <span class="t-err">{{ a.error }}</span>{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}<p class="attention-empty">Nothing yet.</p>{% endif %}
</section>
{% if d.preview %}
<section class="t-section" aria-labelledby="prev-title">
<div class="t-section-header"><h2 class="t-section-title" id="prev-title">Ticket text</h2></div>
<p class="t-preview-title"><code>{{ d.preview.title }}</code></p>
<pre class="t-preview">{{ d.preview.description }}</pre>
</section>
{% endif %}
{% endblock %}
+117
View File
@@ -0,0 +1,117 @@
{% extends "base.html" %}
{% block title %}Needs attention{% endblock %}
{% block content %}
{% set thor = d.thor %}
<section class="t-section" aria-labelledby="attention-title">
<div class="t-section-header">
<h1 class="t-section-title" id="attention-title">Needs attention</h1>
<span class="t-section-meta">
{% if thor.last_cycle and thor.last_cycle.finished %}last cycle {{ thor.last_cycle.finished | ago }}{% else %}no cycle yet{% endif %}
</span>
</div>
<div class="attention-groups">
<div class="attention-group{% if d.incidents %} attention-group-broken{% endif %}">
<h2 class="attention-group-title">Incidents <span class="attention-count">{{ d.incidents | length }}</span></h2>
{% if d.incidents %}
<ul class="attention-list">
{% for i in d.incidents %}
<li class="attention-item attention-{{ i.priority | pclass }}">
<span class="t-prio t-prio-{{ i.priority | pclass }}">P{{ i.priority }}</span>
<a class="attention-link" href="{{ url_for('ui.incident', key=i.key) }}">{{ i.summary }}</a>
<p class="attention-detail">
{{ i.state }}{% if i.mode != 'live' %}, shadow (not sent){% elif i.ticket_id %}, ticket #{{ i.ticket_id }}{% endif %}
&middot; first seen {{ i.first_seen | ago }}
{% if i.symptoms %}&middot; {{ i.symptoms }} also seen{% endif %}
</p>
</li>
{% endfor %}
</ul>
{% else %}
<p class="attention-clear">No open incidents.</p>
{% endif %}
</div>
<div class="attention-group{% if thor.blind or thor.stale %} attention-group-broken{% endif %}">
<h2 class="attention-group-title">Thor itself</h2>
<ul class="attention-list">
{% if thor.stale %}
<li class="attention-item attention-bad">The monitor loop has not finished a good cycle recently.</li>
{% endif %}
{% for s in thor.sources %}
<li class="attention-item attention-{% if s.up %}info{% else %}bad{% endif %}">
{{ s.label }}: {% if s.up %}answering{% else %}<strong>blind</strong> since {{ s.since | hm }}{% endif %}
{% if not s.up and s.last_error %}<p class="attention-detail">{{ s.last_error }}</p>{% endif %}
</li>
{% endfor %}
{% if thor.last_cycle.catching_up %}
<li class="attention-item attention-warn">Catching up after being away: reviewing from {{ thor.last_cycle.window_start | hm }}.</li>
{% endif %}
</ul>
</div>
{% if d.timeline %}
<div class="attention-group">
<h2 class="attention-group-title">On the timeline only <span class="attention-count">{{ d.timeline | length }}</span></h2>
<ul class="attention-list">
{% for i in d.timeline %}
<li class="attention-item attention-info">
<a class="attention-link" href="{{ url_for('ui.incident', key=i.key) }}">{{ i.summary }}</a>
<p class="attention-detail">no ticket by design &middot; {{ i.symptoms }} thing(s) filed under it</p>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if d.known_hits %}
<div class="attention-group">
<h2 class="attention-group-title">Known conditions seen again</h2>
<ul class="attention-list">
{% for i in d.known_hits %}
<li class="attention-item attention-info">
<a class="attention-link" href="{{ url_for('ui.incident', key=i.key) }}">{{ i.summary }}</a>
<p class="attention-detail">note on #{{ i.known_ticket }} &middot; {{ i.first_seen | ago }}</p>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
{% if d.loose %}
<div class="attention-group">
<h2 class="attention-group-title">Unexplained in the last hour <span class="attention-count">{{ d.loose | length }}</span></h2>
<ul class="attention-list">
{% for o in d.loose %}
<li class="attention-item attention-warn">{{ o.summary }}
<p class="attention-detail">{{ o.first_seen | hm }} to {{ o.last_seen | hm }} &middot; nothing explains it yet; no ticket</p>
</li>
{% endfor %}
</ul>
</div>
{% endif %}
</div>
</section>
{% if d.recent %}
<section class="t-section" aria-labelledby="recent-title">
<div class="t-section-header"><h2 class="t-section-title" id="recent-title">Last 7 days</h2></div>
<div class="lt-table-wrap">
<table class="lt-table">
<thead><tr><th>Priority</th><th>Incident</th><th>First seen</th><th>Cleared</th><th>Ticket</th></tr></thead>
<tbody>
{% for i in d.recent %}
<tr>
<td><span class="t-prio t-prio-{{ i.priority | pclass }}">P{{ i.priority }}</span></td>
<td><a href="{{ url_for('ui.incident', key=i.key) }}">{{ i.summary }}</a></td>
<td>{{ i.first_seen | utc('%m-%d %H:%M') }}</td>
<td>{{ i.cleared_at | utc('%m-%d %H:%M') if i.cleared_at else '' }}</td>
<td>{% if i.ticket_id %}#{{ i.ticket_id }}{% elif i.mode != 'live' %}shadow{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</section>
{% endif %}
{% endblock %}
+29
View File
@@ -0,0 +1,29 @@
{% extends "base.html" %}
{% block title %}Known conditions{% endblock %}
{% block content %}
<section class="t-section" aria-labelledby="known-title">
<div class="t-section-header">
<h1 class="t-section-title" id="known-title">Known conditions <span class="attention-count">{{ known | length }}</span></h1>
</div>
<p class="t-note">When something matches a known condition, Thor adds a note to its tracking ticket instead of opening
a new one. A condition ends when its ticket is closed. Add or end one with Thor's MCP tools.</p>
{% if known %}
<div class="lt-table-wrap">
<table class="lt-table">
<thead><tr><th>What</th><th>Subject</th><th>Ticket</th><th>Why</th><th>Added</th></tr></thead>
<tbody>
{% for k in known %}
<tr>
<td>{{ k.kind | replace('_', ' ') }}</td>
<td>{{ k.subject }}</td>
<td>{% if k.ticket_id %}<a href="https://t.lotusguild.org/ticket/{{ k.ticket_id }}">#{{ k.ticket_id }}</a>{% else %}none{% endif %}</td>
<td>{{ k.reason }}</td>
<td>{{ k.created_by }}{% if k.created_at %}, {{ k.created_at | utc('%Y-%m-%d') }}{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}<p class="attention-empty">No known conditions.</p>{% endif %}
</section>
{% endblock %}
+110
View File
@@ -0,0 +1,110 @@
"""Thor's pages. Read-only: changes (known conditions, attaching tickets) go through the MCP tools.
The operator's rule for every LotusGuild UI: avoid overload, fold problems into one "Needs
attention" list instead of adding sections.
"""
import base64
import os
import time
from datetime import datetime, timezone
from typing import Callable
from flask import Blueprint, abort, current_app, g, render_template, request
from . import views
bp = Blueprint('ui', __name__)
PRIORITY_CLASS = {1: 'bad', 2: 'bad', 3: 'warn', 4: 'info', 5: 'info'}
def _now() -> float:
clock: Callable[[], float] = current_app.config.get('THOR_CLOCK', time.time)
return clock()
def _user():
"""Who NPM/Authelia says is looking. Display only, and only believed from the proxy."""
settings = current_app.config['THOR_SETTINGS']
fwd = request.headers.get('X-Forwarded-For', '')
hop = (fwd.split(',')[-1].strip() if fwd else '') or (request.remote_addr or '')
if hop != settings.trusted_proxy:
return {'name': '', 'groups': []}
return {'name': request.headers.get('Remote-Name') or request.headers.get('Remote-User') or '',
'groups': [x.strip() for x in request.headers.get('Remote-Groups', '').split(',') if x.strip()]}
@bp.before_app_request
def nonce():
g.nonce = base64.b64encode(os.urandom(16)).decode()
@bp.after_app_request
def csp(resp):
if resp.mimetype == 'text/html' and getattr(g, 'nonce', None):
resp.headers['Content-Security-Policy'] = (
f"default-src 'self'; script-src 'self' 'nonce-{g.nonce}'; style-src 'self' 'unsafe-inline' "
"https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:; "
"frame-ancestors 'none'; base-uri 'self'; form-action 'self'")
return resp
@bp.app_context_processor
def inject():
return {'nonce': getattr(g, 'nonce', ''), 'user': _user(), 'now': _now(),
'version': current_app.config.get('THOR_VERSION', '')[:7]}
@bp.app_template_filter('utc')
def utc(ts, fmt='%Y-%m-%d %H:%M:%S'):
if ts is None:
return 'unknown'
return datetime.fromtimestamp(float(ts), tz=timezone.utc).strftime(fmt) + ' UTC'
@bp.app_template_filter('hm')
def hm(ts):
if ts is None:
return '?'
return datetime.fromtimestamp(float(ts), tz=timezone.utc).strftime('%H:%M:%S')
@bp.app_template_filter('ago')
def ago(ts):
if ts is None:
return 'never'
s = max(0, int(_now() - float(ts)))
if s < 90:
return f'{s} s ago'
if s < 5400:
return f'{s // 60} min ago'
if s < 172800:
return f'{s // 3600} h ago'
return f'{s // 86400} d ago'
@bp.app_template_filter('pclass')
def pclass(p):
return PRIORITY_CLASS.get(p, 'info')
@bp.route('/')
def index():
settings = current_app.config['THOR_SETTINGS']
data = views.needs_attention(current_app.config['THOR_STORE'], settings, _now())
return render_template('index.html', d=data, active_nav='index')
@bp.route('/incident/<path:key>')
def incident(key):
settings = current_app.config['THOR_SETTINGS']
detail = views.incident_detail(current_app.config['THOR_STORE'], key, settings.public_url)
if detail is None:
abort(404)
return render_template('incident.html', d=detail, active_nav='index')
@bp.route('/known')
def known():
store = current_app.config['THOR_STORE']
return render_template('known.html', known=store.known_conditions(), active_nav='known')
+122
View File
@@ -0,0 +1,122 @@
"""What the UI, the API and the MCP tools show, built from the database in one place."""
from typing import Any, Dict, List, Optional
from ..hosts import HostRegistry
ACTIVE = ('pending', 'open')
HISTORY_S = 7 * 86400
SOURCE_LABELS = {'prometheus': 'Prometheus', 'loki': 'Loki', 'proxmox': 'Proxmox API', 'gandalf': 'Gandalf'}
def incident_brief(inc: Dict[str, Any], public_url: str = '') -> Dict[str, Any]:
return {
'key': inc['key'], 'kind': inc.get('kind'), 'subject': inc.get('subject'), 'state': inc.get('state'),
'priority': inc.get('priority'), 'summary': inc.get('summary'), 'mode': inc.get('mode'),
'ticket': bool(inc.get('ticket', True)), 'ticket_id': inc.get('ticket_id') or inc.get('known_ticket'),
'known_ticket': inc.get('known_ticket'), 'first_seen': inc.get('first_seen'),
'last_seen': inc.get('last_seen'), 'opened_at': inc.get('opened_at'), 'cleared_at': inc.get('cleared_at'),
'symptoms': len(inc.get('symptoms') or {}), 'events': len(inc.get('events') or []),
'url': f'{public_url}/incident/{inc["key"]}' if public_url else f'/incident/{inc["key"]}',
}
def incidents(store, now: float, public_url: str = '') -> Dict[str, List[Dict[str, Any]]]:
rows = store.load_incidents(now - HISTORY_S)
for r in rows:
if r.get('ticket_id') is None:
r['ticket_id'] = store.incident_ticket(r['key'])
active = [incident_brief(r, public_url) for r in rows if r.get('state') in ACTIVE]
recent = [incident_brief(r, public_url) for r in rows if r.get('state') not in ACTIVE]
active.sort(key=lambda i: (i['priority'] or 9, -(i['last_seen'] or 0)))
recent.sort(key=lambda i: -(i['last_seen'] or 0))
return {'active': active, 'recent': recent}
def _known_for(known: List[dict], host: Optional[str]) -> List[dict]:
if not host:
return []
return [k for k in known if k.get('subject') in (host, '*')]
def covering(store, hosts: HostRegistry, host: Optional[str], scope: Optional[str],
public_url: str = '') -> Dict[str, Any]:
"""Thor's answer to Gandalf's and hwmonDaemon's pre-check (thor#1 contract, docs/contract.md).
``covered`` is true only when there is a ticket the caller can comment on instead of opening
its own: an incident with a live ticket, or a known condition with a tracking ticket. A
shadow incident has no ticket yet, so it is listed but doesn't count: callers then open
their own ticket as before (fail open).
"""
canonical = hosts.canonical(host) if host else None
rows = [r for r in store.load_incidents(0) if r.get('state') in ACTIVE and r.get('ticket', True)]
matched = []
for r in rows:
subject = r.get('subject')
if canonical and subject in (canonical, 'cluster'):
matched.append(r)
elif scope == 'cluster' and (subject == 'cluster' or (hosts.get(subject) and hosts.get(subject).ceph_osds)):
matched.append(r)
elif scope and scope.startswith('source:') and r.get('kind') == 'source_down' \
and subject == scope.split(':', 1)[1]:
matched.append(r)
briefs = []
for r in sorted(matched, key=lambda r: (r.get('priority') or 9, -(r.get('last_seen') or 0))):
b = incident_brief(r, public_url)
if r.get('mode') == 'live' and not r.get('known_ticket'):
b['ticket_id'] = store.incident_ticket(r['key'])
elif not r.get('known_ticket'):
b['ticket_id'] = None # shadow: nothing in Tinker to comment on
briefs.append(b)
known = [{'kind': k['kind'], 'subject': k['subject'], 'ticket_id': k.get('ticket_id'),
'reason': k.get('reason', '')} for k in _known_for(store.known_conditions(), canonical)]
covered = any(b['ticket_id'] for b in briefs) or any(k['ticket_id'] for k in known)
ticket = next((b['ticket_id'] for b in briefs if b['ticket_id']), None) or \
next((k['ticket_id'] for k in known if k['ticket_id']), None)
return {'covered': bool(covered), 'ticket_id': ticket, 'host': canonical or host, 'scope': scope,
'incidents': briefs, 'known_conditions': known}
def thor_status(store, settings, now: float) -> Dict[str, Any]:
last = store.get_state('last_cycle') or {}
last_good = store.get_state('last_good_cycle')
sources = store.source_statuses()
return {
'last_cycle': last, 'last_good_cycle': last_good,
'stale': not isinstance(last_good, (int, float)) or now - float(last_good) > settings.stale_after_s,
'sources': [{'name': n, 'label': SOURCE_LABELS.get(n, n), **st} for n, st in sorted(sources.items())],
'blind': [n for n, st in sorted(sources.items()) if not st['up']],
'blind_periods': store.blind_periods(now - 86400),
}
def needs_attention(store, settings, now: float) -> Dict[str, Any]:
inc = incidents(store, now, settings.public_url)
ticketed = [i for i in inc['active'] if i['ticket'] and not i['known_ticket']]
timeline = [i for i in inc['active'] if not i['ticket']]
known_hits = [i for i in inc['active'] + inc['recent'] if i['known_ticket']]
explained = set()
for row in store.load_incidents(now - 3600):
explained.update((row.get('symptoms') or {}).keys())
loose = [o for o in store.recent_observations(now - 3600)
if o.get('role') == 'symptom' and o.get('k') not in explained]
return {'incidents': ticketed, 'timeline': timeline, 'known_hits': known_hits[:10],
'recent': [i for i in inc['recent'] if i['ticket'] and not i['known_ticket']][:15],
'loose': loose[:20], 'thor': thor_status(store, settings, now),
'known': store.known_conditions()}
def incident_detail(store, key: str, public_url: str = '') -> Optional[Dict[str, Any]]:
inc = store.get_incident(key)
if not inc:
return None
actions = store.actions_for(key)
brief = incident_brief(inc, public_url)
brief['ticket_id'] = next((a['ticket_id'] for a in reversed(actions) if a.get('ticket_id')), None) \
or inc.get('known_ticket')
symptoms = sorted((inc.get('symptoms') or {}).values(), key=lambda s: s.get('first', 0))
events = sorted(inc.get('events') or [], key=lambda e: e.get('at', 0))
preview = next((a['payload'] for a in reversed(actions)
if a['kind'] in ('open', 'escalate', 'refresh') and a['payload'].get('description')), None)
return {'incident': brief, 'facts': inc.get('facts') or {}, 'events': events, 'symptoms': symptoms,
'actions': actions, 'preview': preview, 'known_reason': inc.get('known_reason', ''),
'seen_after_the_fact': inc.get('seen_after_the_fact', False)}