Files
thor/thor/web/views.py
T
jaredandClaude Opus 5.5 ab4b20d15f
CI / Lint (flake8, house style) (pull_request) Successful in 56s
CI / Test (pytest) (pull_request) Successful in 53s
CI / Security (bandit, pip-audit) (pull_request) Successful in 1m8s
CI / Integration (MariaDB) (pull_request) Successful in 1m49s
CI / UI (screenshots) (pull_request) Failing after 1m7s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Successful in 1m58s
CI / Deploy (pull_request) Skipped
UI and API: Needs attention, incident pages, known conditions, /covering for Gandalf and hwmonDaemon
- thor/web/api.py: /api/incidents/covering (thor#1 pre-check), /api/incidents, /api/incident/<key>,
  machine keys by SHA-256 with optional source CIDRs, like Gandalf's (gandalf#68); 503 when the
  database is away so callers fail open. covered=true only when there is a ticket to comment on;
  shadow incidents are listed but never cover.
- thor/web/ui.py + templates: Needs attention (incidents, Thor itself, timeline-only, known
  conditions seen again, unexplained symptoms), incident page (what happened, also seen, what
  Thor sent or would have sent, ticket text), known conditions. Read-only; CSP with nonces;
  Authelia identity shown only when it comes from NPM. Mobile nav drawer.
- web_template v1.2 (8286bb2) vendored and checked against upstream in CI.
- docs/contract.md: the /covering contract for the Gandalf and hwmonDaemon sessions.
- scripts/ui_demo.py + scripts/screenshots.py, and a CI job that renders every page with replay
  data (desktop, mobile, dark, light) and uploads the screenshots.
- Fix: systemd-escaped cpusets (system-ceph\x2dosd.slice) were not recognised as Ceph; four of
  the 11-23 kills came from the OSD slice. Found while reviewing the screenshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:23:43 -05:00

123 lines
6.6 KiB
Python

"""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)}