Files
thor/tests/fakes.py
T
jaredandClaude Opus 5.5 e70dee0ad8
CI / Lint (flake8, house style) (pull_request) Successful in 54s
CI / Test (pytest) (pull_request) Successful in 55s
CI / Security (bandit, pip-audit) (pull_request) Successful in 56s
CI / Integration (MariaDB) (pull_request) Successful in 2m2s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Successful in 1m30s
CI / Deploy (pull_request) Skipped
Reboots, fencing and partitions, maintenance from Gandalf, known conditions; T2/T3/T4/DIMM replays
- checks/reboots.py (thor#4): boot-time changes classified as planned (logind line),
  unexpected, or unknown (journal went quiet first); several together are one event.
- checks/cluster.py: HA fence lines, watchdog self-fences, corosync quorum loss: one host is
  'lost its cluster link and was fenced' (P2), two or more a cluster partition (P1).
- checks/maintenance.py: Gandalf suppressions (with ended ones) as a cause that never
  opens a ticket; everything under it goes on the timeline.
- Engine: higher causes first, lower causes they explain become symptoms; a higher cause
  found later absorbs pending ones and comments 'Root cause' on opened ones; host-scoped
  causes never explain another host's cause; incidents stay active while an attached host
  is still down; silent state changes are saved; notes join timeline-only incidents.
- Known conditions (migration 3, seeded): compute-storage-02 reboots and Ceph noout ->
  693930698, the old UPS battery. A match sends a note to that ticket instead of a new one.
- Replays: T2 0 tickets; T3 one P2 (fenced, cleared when the host is back); T4 one P1
  partition (storage-01's later fence and all reboots fold in); DIMM one note on 693930698.

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

196 lines
6.8 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 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