UI and API: Needs attention, incident pages, known conditions, /covering for Gandalf and hwmonDaemon
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

- 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>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-25 23:23:43 -05:00
1 parent 6c2328c2b1
commit ab4b20d15f
23 files changed
+9946 -9

No files matched your search

+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:
hosts = query_regex(names)
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(','):
if '=' in part:
k, v = part.split('=', 1)
fields[k] = v
fields[k] = unescape(v)
else:
flags.add(part)
memcg = fields.get('task_memcg', '')
@@ -195,11 +203,16 @@ class MemoryCheck:
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.'
return 1
stalled = {s['subject'] for s in inc.symptoms.values()
if s.get('cluster_effect') and s['subject'] not in (inc.subject,)}
if stalled:
inc.facts['escalation_reason'] = ('While this host is out of memory, the cluster is stalling: '
+ ', '.join(sorted(stalled)) + '.')
effects = [s for s in inc.symptoms.values() if s.get('cluster_effect') and s['subject'] != inc.subject]
stalled = sorted({s['subject'] for s in effects if s['subject'] != 'cluster'})
ceph = any(s['subject'] == 'cluster' for s in effects)
if stalled or ceph:
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
times = sorted(e['at'] for e in inc.events)
for i in range(len(times)):
+10
View File
@@ -62,6 +62,12 @@ class Settings:
http_timeout_s: float = 10.0
checks: Dict[str, str] = field(default_factory=dict)
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:
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']]
if 'proxmox_verify_tls' in data:
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):
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:
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))
# -- 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,
clock: Callable[[], float] = time.time) -> Flask:
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
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)}