Files
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

213 lines
7.5 KiB
Python

"""Test doubles: an in-memory Store, an HTTP session that serves canned replies, sources."""
import json
from typing import Any, Dict, List, Optional
import requests
from thor.clients import SourceError
from thor.db import DatabaseError
class FakeStore:
"""Same methods as thor.db.Store, kept in memory. Set ``down = True`` to simulate CT 149 away."""
def __init__(self):
self.down = False
self.state: Dict[str, Any] = {}
self.cycles: List[dict] = []
self.sources: Dict[str, dict] = {}
self.blind: List[dict] = []
self.calls: List[str] = []
self.incidents: Dict[str, dict] = {}
self.actions: List[dict] = []
self.observations: Dict[str, dict] = {}
self.known: List[dict] = [
{'id': 1, 'kind': 'reboot', 'subject': 'compute-storage-02', 'ticket_id': '693930698',
'reason': 'compute-storage-02 reboots every 2 to 3 days from a failing DIMM.'},
]
def _check(self, name):
self.calls.append(name)
if self.down:
raise DatabaseError('Lost connection to MySQL server')
def set_state(self, key, value, now):
self._check('set_state')
self.state[key] = json.loads(json.dumps(value, default=str))
def get_state(self, key, default=None):
self._check('get_state')
return self.state.get(key, default)
def record_cycle(self, **kw):
self._check('record_cycle')
self.cycles.append(kw)
return len(self.cycles)
def prune_cycles(self, older_than):
self._check('prune_cycles')
before = len(self.cycles)
self.cycles = [c for c in self.cycles if c['started'] >= older_than]
return before - len(self.cycles)
def source_statuses(self):
self._check('source_statuses')
return {k: dict(v) for k, v in self.sources.items()}
def save_source_status(self, name, up, since, last_ok, last_error, now):
self._check('save_source_status')
self.sources[name] = {'up': up, 'since': since, 'last_ok': last_ok, 'last_error': last_error}
def open_blind_period(self, source, started, reason):
self._check('open_blind_period')
self.blind.append({'source': source, 'started': started, 'ended': None, 'reason': reason})
def close_blind_period(self, source, ended):
self._check('close_blind_period')
for b in self.blind:
if b['source'] == source and b['ended'] is None:
b['ended'] = ended
def save_incident(self, inc, now):
self._check('save_incident')
self.incidents[inc['key']] = json.loads(json.dumps(inc, default=str))
def load_incidents(self, since):
self._check('load_incidents')
return [dict(i) for i in self.incidents.values()
if i['state'] in ('pending', 'open') or i['last_seen'] >= since]
def add_action(self, action):
self._check('add_action')
a = json.loads(json.dumps(action, default=str))
a.update(id=len(self.actions) + 1, status='pending' if a['mode'] == 'live' else 'shadow',
attempts=0, next_attempt_at=a['created'] if a['mode'] == 'live' else None, ticket_id=None)
self.actions.append(a)
return a['id']
def due_actions(self, now, limit=20):
self._check('due_actions')
return [a for a in self.actions if a['status'] == 'pending' and a['next_attempt_at'] <= now][:limit]
def mark_action_sent(self, action_id, ticket_id, now):
self._check('mark_action_sent')
a = self.actions[action_id - 1]
a.update(status='sent', ticket_id=ticket_id, sent_at=now)
def mark_action_failed(self, action_id, error, attempts, retry_at):
self._check('mark_action_failed')
a = self.actions[action_id - 1]
a.update(status='pending' if retry_at is not None else 'failed', attempts=attempts,
next_attempt_at=retry_at, error=error)
def incident_ticket(self, key):
self._check('incident_ticket')
ids = [a['ticket_id'] for a in self.actions if a['incident_key'] == key and a.get('ticket_id')]
return ids[-1] if ids else None
def save_observation(self, f, now):
self._check('save_observation')
o = self.observations.get(f['key'])
if o:
o['start'], o['end'] = min(o['start'], f['start']), max(o['end'], f['end'])
o['summary'], o['role'] = f['summary'], f['role']
else:
self.observations[f['key']] = json.loads(json.dumps(f, default=str))
def delete_incident(self, key):
self._check('delete_incident')
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):
self._check('known_conditions')
return [dict(k) for k in self.known if not k.get('ended')]
def blind_periods(self, since):
self._check('blind_periods')
return [b for b in self.blind if b['ended'] is None or b['ended'] >= since]
class FakeResponse:
def __init__(self, status: int = 200, body: Any = None, text: Optional[str] = None):
self.status_code = status
self._body = body
self.text = text if text is not None else json.dumps(body)
def json(self):
if self._body is None:
raise ValueError('no JSON')
return self._body
def raise_for_status(self):
if self.status_code >= 400:
raise requests.HTTPError(f'HTTP {self.status_code}')
class FakeSession:
"""Serves replies in order for each (method, url-prefix). Records every request."""
def __init__(self):
self.routes: List[tuple] = []
self.requests: List[dict] = []
def add(self, method: str, url_prefix: str, *replies):
self.routes.append((method.upper(), url_prefix, list(replies)))
return self
def _serve(self, method, url, **kw):
self.requests.append({'method': method, 'url': url, **kw})
for m, prefix, replies in self.routes:
if m == method and url.startswith(prefix):
reply = replies[0] if len(replies) == 1 else replies.pop(0)
if isinstance(reply, Exception):
raise reply
return reply
raise requests.ConnectionError(f'no route for {method} {url}')
def get(self, url, **kw):
return self._serve('GET', url, **kw)
def post(self, url, **kw):
return self._serve('POST', url, **kw)
class FakeSource:
def __init__(self, name: str, up: bool = True, error: str = 'connection refused'):
self.name = name
self.up = up
self.error = error
self.pings = 0
def ping(self):
self.pings += 1
if not self.up:
raise SourceError(self.name, self.error)
class Clock:
def __init__(self, t: float = 1_795_575_600.0): # 2026-11-25 03:00:00 UTC
self.t = t
def __call__(self):
return self.t
def advance(self, seconds: float):
self.t += seconds