2026-11-25 20:32:07 -05:00
|
|
|
"""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] = []
|
2026-11-25 23:02:10 -05:00
|
|
|
self.incidents: Dict[str, dict] = {}
|
|
|
|
|
self.actions: List[dict] = []
|
|
|
|
|
self.observations: Dict[str, dict] = {}
|
2026-11-25 23:13:59 -05:00
|
|
|
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.'},
|
|
|
|
|
]
|
2026-11-25 20:32:07 -05:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
2026-11-25 23:02:10 -05:00
|
|
|
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))
|
|
|
|
|
|
2026-11-25 23:13:59 -05:00
|
|
|
def delete_incident(self, key):
|
|
|
|
|
self._check('delete_incident')
|
|
|
|
|
self.incidents.pop(key, None)
|
|
|
|
|
|
2026-11-25 23:23:43 -05:00
|
|
|
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]
|
|
|
|
|
|
2026-11-25 23:13:59 -05:00
|
|
|
def known_conditions(self):
|
|
|
|
|
self._check('known_conditions')
|
|
|
|
|
return [dict(k) for k in self.known if not k.get('ended')]
|
|
|
|
|
|
2026-11-25 20:32:07 -05:00
|
|
|
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
|