Skeleton: config, source clients, DB migrations, monitor loop with blind tracking, health and metrics

Work in progress for thor#1 phase 1 (PR 1 of 6). Not yet pushed: CI workflow and deploy files still to add.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-25 20:32:07 -05:00
1 parent 4cdb54147e
commit eecb24297a
24 files changed
+1897

No files matched your search

View File
Whitespace-only changes.
+134
View File
@@ -0,0 +1,134 @@
"""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] = []
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 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
+218
View File
@@ -0,0 +1,218 @@
import pytest
import requests
from thor.clients import SourceError
from thor.clients.gandalf import GandalfClient
from thor.clients.loki import LokiClient, find_shutdown, quote, shutdown_query
from thor.clients.prometheus import PrometheusClient
from thor.clients.proxmox import ProxmoxClient
from thor.clients.tinker import TinkerClient, backoff_s
from .fakes import FakeResponse, FakeSession
PROM = 'http://prom:9090'
LOKI = 'http://loki:3100'
# -- Prometheus ----------------------------------------------------------
def test_prometheus_instant_query_parses_and_skips_bad_values():
sess = FakeSession().add('GET', f'{PROM}/api/v1/query', FakeResponse(200, {
'status': 'success', 'data': {'result': [
{'metric': {'instance': '10.10.10.4:9100'}, 'value': [1795410700.1, '11']},
{'metric': {}, 'value': [1795410700.1, 'NaN-not']},
]}}))
out = PrometheusClient(PROM, session=sess).query('node_vmstat_oom_kill', at=1795410700)
assert out == [{'metric': {'instance': '10.10.10.4:9100'}, 'ts': 1795410700.1, 'value': 11.0}]
assert sess.requests[0]['params']['time'] == '1795410700.000'
def test_prometheus_range_query():
sess = FakeSession().add('GET', f'{PROM}/api/v1/query_range', FakeResponse(200, {
'status': 'success', 'data': {'result': [{'metric': {'a': 'b'}, 'values': [[1, '2'], [3, 'x']]}]}}))
out = PrometheusClient(PROM, session=sess).query_range('up', 0, 10, 5)
assert out == [{'metric': {'a': 'b'}, 'values': [(1.0, 2.0)]}]
assert sess.requests[0]['params']['step'] == '5'
@pytest.mark.parametrize('reply', [
FakeResponse(500, {'status': 'error'}),
FakeResponse(200, {'status': 'error', 'error': 'bad query'}),
FakeResponse(200, None, text='<html>'),
requests.ConnectionError('refused'),
requests.Timeout('slow'),
])
def test_prometheus_failures_are_source_errors(reply):
sess = FakeSession().add('GET', PROM, reply)
with pytest.raises(SourceError) as e:
PrometheusClient(PROM, session=sess).ping()
assert e.value.source == 'prometheus'
# -- Loki ----------------------------------------------------------------
def _loki_reply(*streams):
return FakeResponse(200, {'status': 'success', 'data': {'result': [
{'stream': labels, 'values': values} for labels, values in streams]}})
def test_loki_lines_keep_labels_and_sort():
sess = FakeSession().add('GET', f'{LOKI}/loki/api/v1/query_range', _loki_reply(
({'host': 'a'}, [['2000000000', 'old']]),
({'host': 'b'}, [['3000000000', 'new']]),
))
out = LokiClient(LOKI, session=sess).lines('{job="journal"}', 0, 10)
assert out == [(3.0, 'new', {'host': 'b'}), (2.0, 'old', {'host': 'a'})]
fwd = LokiClient(LOKI, session=sess).lines('{job="journal"}', 0, 10, direction='forward')
assert [x[1] for x in fwd] == ['old', 'new']
def test_loki_refuses_windows_over_30_days_and_errors():
with pytest.raises(SourceError):
LokiClient(LOKI, session=FakeSession()).lines('{a="b"}', 0, 31 * 86400)
sess = FakeSession().add('GET', LOKI, FakeResponse(500, {'status': 'error'}))
with pytest.raises(SourceError):
LokiClient(LOKI, session=sess).ping()
def test_find_shutdown_matches_logind_line_and_quotes_host():
line = 'The system will power off now!'
sess = FakeSession().add('GET', LOKI, _loki_reply(
({'host': 'compute-storage-01'}, [['1795576895000000000', line]])))
found = find_shutdown(LokiClient(LOKI, session=sess), 'compute-storage-01', before=1795577000)
assert found == {'at': 1795576895.0, 'kind': 'power off', 'line': line}
q = sess.requests[0]['params']['query']
assert q.startswith('{host="compute-storage-01", job="journal", unit="systemd-logind.service"}')
assert shutdown_query('a"b').startswith('{host="a\\"b"')
assert quote('x\\y') == 'x\\\\y'
def test_find_shutdown_none_vs_unknown():
sess = FakeSession().add('GET', LOKI, _loki_reply())
assert find_shutdown(LokiClient(LOKI, session=sess), 'storage-01', before=100.0) is None
down = FakeSession().add('GET', LOKI, requests.ConnectionError('x'))
with pytest.raises(SourceError):
find_shutdown(LokiClient(LOKI, session=down), 'storage-01', before=100.0)
# -- Proxmox -------------------------------------------------------------
def test_proxmox_fails_over_between_nodes_and_remembers():
sess = (FakeSession()
.add('GET', 'https://10.0.0.1:8006', requests.ConnectionError('down'))
.add('GET', 'https://10.0.0.2:8006', FakeResponse(200, {'data': [
{'name': 'noout', 'value': 1}, {'name': 'pause', 'value': 0}]})))
px = ProxmoxClient(['10.0.0.1', '10.0.0.2'], 'thor@pve!monitor', 'secret', session=sess)
assert px.ceph_flags() == {'noout': True, 'pause': False}
assert sess.requests[1]['headers']['Authorization'] == 'PVEAPIToken=thor@pve!monitor=secret'
assert sess.requests[1]['verify'] is False
px.ceph_flags()
assert sess.requests[2]['url'].startswith('https://10.0.0.2:8006') # preferred node first now
def test_proxmox_token_refusal_does_not_try_other_nodes():
sess = (FakeSession().add('GET', 'https://10.0.0.1:8006', FakeResponse(401, {}))
.add('GET', 'https://10.0.0.2:8006', FakeResponse(200, {'data': {}})))
with pytest.raises(SourceError, match='token refused'):
ProxmoxClient(['10.0.0.1', '10.0.0.2'], 'id', 's', session=sess).ping()
assert len(sess.requests) == 1
def test_proxmox_unconfigured_and_all_nodes_down():
with pytest.raises(SourceError, match='no API token'):
ProxmoxClient(['10.0.0.1'], '', '', session=FakeSession()).ping()
sess = FakeSession().add('GET', 'https://', requests.ConnectionError('x'))
with pytest.raises(SourceError, match='10.0.0.1'):
ProxmoxClient(['10.0.0.1'], 'id', 's', session=sess).cluster_status()
def test_proxmox_helpers_pass_params():
sess = FakeSession().add('GET', 'https://n:8006', FakeResponse(200, {'data': [{'vmid': 154}]}))
px = ProxmoxClient(['n'], 'id', 's', session=sess)
assert px.resources('vm') == [{'vmid': 154}]
assert sess.requests[0]['params'] == {'type': 'vm'}
assert px.ha_status() == [{'vmid': 154}]
# -- Gandalf -------------------------------------------------------------
T2_SUPPRESSION = {'id': 2, 'reason': 'switch update', 'started_at': '2026-11-25T03:11:39Z',
'ended_at': '2026-11-25T03:41:39Z', 'state': 'expired', 'target_type': 'all'}
def test_gandalf_suppressions_with_history():
sess = FakeSession().add('GET', 'http://g/api/suppressions',
FakeResponse(200, {'since': 'x', 'suppressions': [T2_SUPPRESSION]}))
g = GandalfClient('http://g/', 'key', session=sess)
assert g.suppressions(hours=48) == [T2_SUPPRESSION]
req = sess.requests[0]
assert req['params'] == {'include_ended': '1', 'hours': '48'}
assert req['headers']['Authorization'] == 'Bearer key'
g.suppressions(hours=10_000)
assert sess.requests[1]['params']['hours'] == str(31 * 24)
def test_gandalf_errors():
with pytest.raises(SourceError, match='no API key'):
GandalfClient('http://g', '', session=FakeSession()).ping()
sess = FakeSession().add('GET', 'http://g', FakeResponse(401, {}))
with pytest.raises(SourceError, match='key refused'):
GandalfClient('http://g', 'k', session=sess).status()
bad = FakeSession().add('GET', 'http://g', FakeResponse(200, ['not', 'a', 'dict']))
with pytest.raises(SourceError):
GandalfClient('http://g', 'k', session=bad).status()
with pytest.raises(SourceError):
GandalfClient('http://g', 'k', session=bad).suppressions()
# -- Tinker --------------------------------------------------------------
TINKER = 'https://t/create_ticket_api.php'
def test_tinker_create_sends_dedup_key_and_reads_action():
sess = FakeSession().add('POST', TINKER, FakeResponse(200, {'success': True, 'ticket_id': '123', 'action': 'new'}))
t = TinkerClient(TINKER, 'k', session=sess)
r = t.create(title='[h][auto][thor][software] x', description='d', priority=3, category='Software',
ticket_type='Issue', dedup_key='host:h:oom')
assert (r.ticket_id, r.action, r.ok) == ('123', 'new', True)
body = sess.requests[0]['json']
assert body['dedup_key'] == 'host:h:oom' and body['priority'] == '3' and body['status'] == 'Open'
def test_tinker_create_failures():
assert not TinkerClient('', '').create(title='t', description='', priority=3, category='c',
ticket_type='Issue', dedup_key='k').ok
sess = FakeSession().add('POST', TINKER, FakeResponse(403, {}))
t = TinkerClient(TINKER, 'k', session=sess)
r = t.create(title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k')
assert r.error == 'HTTP 403'
assert t.writes_denied
assert t.comment('1', 'x') is False
dup = FakeSession().add('POST', TINKER, FakeResponse(200, {'existing_ticket_id': 77}))
r = TinkerClient(TINKER, 'k', session=dup).create(
title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k')
assert (r.ticket_id, r.action) == ('77', 'deduplicated')
odd = FakeSession().add('POST', TINKER, FakeResponse(200, {'success': False}))
assert 'unexpected' in TinkerClient(TINKER, 'k', session=odd).create(
title='t', description='', priority=3, category='c', ticket_type='Issue', dedup_key='k').error
def test_tinker_comment_and_reads():
sess = (FakeSession()
.add('POST', 'https://t/api/ticket_comment_api.php', FakeResponse(200, {'success': True}),
FakeResponse(404, {}), requests.ConnectionError('x'))
.add('GET', 'https://t/api/tickets_api.php',
FakeResponse(200, {'success': True, 'pages': 2,
'tickets': [{'ticket_id': 1, 'title': 'a', 'status': 'Open'}]}),
FakeResponse(200, {'success': True, 'pages': 2,
'tickets': [{'ticket_id': 2, 'title': 'b', 'status': 'Pending'}]}),
FakeResponse(200, {'success': True, 'ticket': {'ticket_id': '693930698'}})))
t = TinkerClient(TINKER, 'k', session=sess)
assert t.comment('1', 'hi') is True
assert t.comment('1', 'hi') is True # deleted ticket: done
assert t.comment('1', 'hi') is False # network error: retry later
assert set(t.open_tickets()) == {'1', '2'}
assert t.ticket('693930698') == {'ticket_id': '693930698'}
assert TinkerClient('', '').open_tickets() is None
def test_backoff():
assert backoff_s(1) == 120
assert backoff_s(3) == 480
assert backoff_s(50) == 3600
+41
View File
@@ -0,0 +1,41 @@
import json
from thor import config
def test_parse_env_file_handles_comments_quotes_and_junk():
text = '# comment\n\nA=1\nB = "two words"\nC=\'x=y\'\nnot a line\n=nokey\n'
assert config.parse_env_file(text) == {'A': '1', 'B': 'two words', 'C': 'x=y'}
def test_defaults_without_any_files(tmp_path):
s = config.load(str(tmp_path / 'missing.json'), str(tmp_path / 'nodir'), environ={})
assert s.prometheus_url == 'http://10.10.10.48:9090'
assert s.cycle_seconds == 120
assert s.catchup_hours == 24
assert s.stale_after_s == 360
assert not s.database.configured
assert s.proxmox_nodes[0] == '10.10.10.11'
def test_json_and_env_files_and_environment_layer_in_order(tmp_path):
(tmp_path / 'thor.json').write_text(json.dumps({
'prometheus_url': 'http://prom:9090/', 'cycle_seconds': 60, 'checks': {'memory': 'live', 'x': 'bogus'},
'proxmox_nodes': ['10.0.0.1'], 'proxmox_verify_tls': 'yes'}))
env = tmp_path / 'env'
env.mkdir()
(env / 'db.env').write_text('DB_HOST=10.10.10.50\nDB_PASSWORD=from-file\n')
(env / 'pve.env').write_text('PVE_TOKEN_ID=thor@pve!monitor\nPVE_TOKEN_SECRET=s3cret\n')
(env / 'ignored.txt').write_text('DB_HOST=wrong\n')
s = config.load(str(tmp_path / 'thor.json'), str(env), environ={'DB_PASSWORD': 'from-env', 'lower': 'x'})
assert s.prometheus_url == 'http://prom:9090'
assert s.cycle_seconds == 60
assert s.proxmox_nodes == ['10.0.0.1']
assert s.proxmox_verify_tls is True
assert s.database.host == '10.10.10.50'
assert s.database.password == 'from-env'
assert s.database.configured
assert s.proxmox_token_id == 'thor@pve!monitor'
assert s.check_mode('memory') == 'live'
assert s.check_mode('x') == 'shadow' # unknown mode falls back to shadow
assert s.check_mode('never-set') == 'shadow' # every check starts in shadow
+63
View File
@@ -0,0 +1,63 @@
"""Runs against a real MariaDB when THOR_TEST_DB_HOST is set (the CI integration job)."""
import os
import pytest
from thor.config import DatabaseSettings
from thor.db import MIGRATIONS, Database, DatabaseError, Store, from_dt, to_dt
pytestmark = pytest.mark.skipif(not os.environ.get('THOR_TEST_DB_HOST'), reason='needs THOR_TEST_DB_HOST')
@pytest.fixture
def db():
d = Database(DatabaseSettings(
host=os.environ['THOR_TEST_DB_HOST'], port=int(os.environ.get('THOR_TEST_DB_PORT', '3306')),
name=os.environ.get('THOR_TEST_DB_NAME', 'thor'), user=os.environ.get('THOR_TEST_DB_USER', 'thor'),
password=os.environ.get('THOR_TEST_DB_PASSWORD', '')))
for t in ('state', 'cycles', 'source_status', 'blind_periods', 'schema_version'):
d.execute(f'DROP TABLE IF EXISTS {t}') # nosec B608 - fixed table names
return d
def test_migrate_is_idempotent(db):
assert db.migrate() == len(MIGRATIONS)
assert db.migrate() == len(MIGRATIONS)
assert len(db.query('SELECT * FROM schema_version')) == len(MIGRATIONS)
def test_store_round_trips(db):
db.migrate()
s = Store(db)
t = 1795575600.123
s.set_state('last_cycle', {'blind': ['loki'], 'ok': True}, t)
s.set_state('last_cycle', {'blind': [], 'ok': True}, t + 1)
assert s.get_state('last_cycle') == {'blind': [], 'ok': True}
assert s.get_state('missing', 'dflt') == 'dflt'
s.record_cycle(started=t, finished=t + 2, window_start=t - 120, window_end=t, ok=True, blind=['loki'])
s.record_cycle(started=t - 100000, finished=t, window_start=t, window_end=t, ok=False, blind=[], error='x')
assert s.prune_cycles(t - 1) == 1
s.save_source_status('loki', False, t, None, 'HTTP 500', t)
s.save_source_status('loki', True, t + 5, t + 5, '', t + 5)
loki = s.source_statuses()['loki']
assert loki == {'up': True, 'since': pytest.approx(t + 5, abs=0.001),
'last_ok': pytest.approx(t + 5, abs=0.001), 'last_error': ''}
s.open_blind_period('loki', t, 'HTTP 500')
assert s.blind_periods(t - 10)[0]['ended'] is None
s.close_blind_period('loki', t + 60)
periods = s.blind_periods(t - 10)
assert periods[0]['ended'] == pytest.approx(t + 60, abs=0.001)
assert s.blind_periods(t + 61) == []
def test_time_conversion_is_utc():
t = 1795575600.5
assert from_dt(to_dt(t)) == t
assert to_dt(t).isoformat() == '2026-11-25T03:00:00.500000'
assert to_dt(None) is None and from_dt(None) is None
def test_unreachable_database_raises_database_error():
d = Database(DatabaseSettings(host='127.0.0.1', port=1, user='x', password='y'))
with pytest.raises(DatabaseError):
d.query('SELECT 1')
+178
View File
@@ -0,0 +1,178 @@
from thor.config import Settings
from thor.monitor import MAX_PENDING_WRITES, Monitor
from .fakes import Clock, FakeSource, FakeStore
def make(store=None, sources=None, checks=None, clock=None, prepare=None):
settings = Settings()
clock = clock or Clock()
sources = sources if sources is not None else {n: FakeSource(n) for n in ('prometheus', 'loki')}
return Monitor(settings, store or FakeStore(), sources, checks=checks, clock=clock, prepare=prepare), clock
def test_first_cycle_covers_one_cycle_and_records_heartbeat():
store = FakeStore()
m, clock = make(store)
r = m.cycle()
assert r.ok and not r.blind and not r.catching_up
assert r.window == (clock.t - 120, clock.t)
assert store.state['last_good_window_end'] == clock.t
assert store.state['last_good_cycle'] == clock.t
assert store.cycles[0]['ok'] is True
assert store.sources['prometheus']['up'] is True
assert store.blind == []
def test_next_cycle_starts_where_the_last_good_one_ended():
m, clock = make()
first = m.cycle()
clock.advance(120)
second = m.cycle()
assert second.window[0] == first.window[1]
assert not second.catching_up
def test_restart_resumes_from_stored_window_and_catches_up():
"""T2 shape: Thor goes dark with the rack, comes back 22 minutes later, reviews the gap."""
store = FakeStore()
m, clock = make(store)
m.cycle()
gone_at = clock.t
clock.advance(22 * 60)
m2, _ = make(store, clock=clock) # new process
r = m2.cycle()
assert r.window == (gone_at, clock.t)
assert r.catching_up
def test_catch_up_is_capped_at_24_hours():
store = FakeStore()
m, clock = make(store)
m.cycle()
clock.advance(3 * 86400)
r = make(store, clock=clock)[0].cycle()
assert r.window == (clock.t - 24 * 3600, clock.t)
assert r.catching_up
def test_blind_source_opens_and_closes_a_blind_period():
store = FakeStore()
loki = FakeSource('loki', up=False, error='HTTP 500')
m, clock = make(store, {'prometheus': FakeSource('prometheus'), 'loki': loki})
r = m.cycle()
assert r.ok and r.blind == ['loki'] # blind is recorded, it doesn't fail the cycle
assert store.blind == [{'source': 'loki', 'started': clock.t, 'ended': None, 'reason': 'HTTP 500'}]
assert store.state['last_cycle']['blind'] == ['loki']
clock.advance(120)
m.cycle() # still down: no second period
assert len(store.blind) == 1
loki.up = True
clock.advance(120)
m.cycle()
assert store.blind[0]['ended'] == clock.t
assert store.sources['loki']['up'] is True
def test_known_down_source_from_previous_process_is_not_reopened():
store = FakeStore()
store.sources['loki'] = {'up': False, 'since': 10.0, 'last_ok': None, 'last_error': 'x'}
store.blind.append({'source': 'loki', 'started': 10.0, 'ended': None, 'reason': 'x'})
m, _ = make(store, {'loki': FakeSource('loki', up=False)})
m.cycle()
assert len(store.blind) == 1
assert store.sources['loki']['since'] == 10.0
def test_database_away_buffers_writes_and_flushes_later():
"""T1 shape: CT 149 freezes with Ceph; Thor keeps cycling and writes when it's back."""
store = FakeStore()
store.down = True
m, clock = make(store)
r1 = m.cycle()
assert r1.ok
assert m.pending # nothing written yet
clock.advance(120)
r2 = m.cycle()
assert r2.window[0] == r1.window[1] # the window still advances in memory
store.down = False
clock.advance(120)
m.cycle()
assert not m.pending
assert len(store.cycles) == 3
assert store.state['last_good_window_end'] == clock.t
def test_pending_writes_are_bounded():
store = FakeStore()
store.down = True
m, _ = make(store)
for i in range(MAX_PENDING_WRITES + 10):
m._write('set_state', 'k', i, 0)
assert len(m.pending) == MAX_PENDING_WRITES
assert m.pending[-1][1][1] == MAX_PENDING_WRITES + 9
def test_failing_check_keeps_the_window_for_next_cycle_and_others_still_run():
ran = []
class Boom:
name = 'boom'
def run(self, ctx):
raise RuntimeError('bug')
class Fine:
name = 'fine'
def run(self, ctx):
ran.append((ctx.window_start, ctx.window_end, dict(ctx.up)))
return [{'x': 1}]
store = FakeStore()
m, clock = make(store, checks=[Boom(), Fine()])
r = m.cycle()
assert not r.ok and 'boom: RuntimeError: bug' in r.error
assert r.findings == 1 and ran
assert 'last_good_window_end' not in store.state
assert 'last_good_cycle' not in store.state
def test_source_that_raises_unexpectedly_counts_as_blind():
class Broken:
name = 'proxmox'
def ping(self):
raise KeyError('bug')
m, _ = make(sources={'proxmox': Broken()})
r = m.cycle()
assert r.blind == ['proxmox']
def test_prepare_runs_once_and_is_retried_until_db_answers():
store = FakeStore()
store.down = True
calls = []
def prepare():
calls.append(1)
if store.down:
from thor.db import DatabaseError
raise DatabaseError('down')
m, clock = make(store, prepare=prepare)
m.cycle()
store.down = False
clock.advance(120)
m.cycle()
clock.advance(120)
m.cycle()
assert len(calls) == 2
def test_stop_ends_run_forever():
m, clock = make()
m.settings.cycle_seconds = 1
m.stop()
m.run_forever() # returns at once
+59
View File
@@ -0,0 +1,59 @@
from thor.config import Settings
from thor.web.app import create_app, detect_version
from .fakes import Clock, FakeStore
def client(store, clock=None):
app = create_app(Settings(), store, 'abc123', clock=clock or Clock())
return app.test_client()
def test_health_ok_when_monitor_fresh():
clock = Clock()
store = FakeStore()
store.state['last_good_cycle'] = clock.t - 30
store.state['last_cycle'] = {'blind': ['loki']}
r = client(store, clock).get('/health')
assert r.status_code == 200
body = r.get_json()
assert body == {'status': 'ok', 'sha': 'abc123', 'db': True, 'monitor': 'ok', 'monitor_age_s': 30,
'blind': ['loki']}
assert r.headers['X-Frame-Options'] == 'DENY'
def test_health_503_when_stale_never_ran_or_no_db():
clock = Clock()
store = FakeStore()
r = client(store, clock).get('/health')
assert r.status_code == 503 and r.get_json()['monitor'] == 'no good cycle yet'
store.state['last_good_cycle'] = clock.t - 361
r = client(store, clock).get('/health')
assert r.status_code == 503 and r.get_json()['monitor'] == 'stale'
store.down = True
r = client(store, clock).get('/health')
assert r.status_code == 503 and r.get_json()['db'] is False
def test_metrics():
clock = Clock()
store = FakeStore()
store.state['last_good_cycle'] = 1795575600.0
store.state['last_cycle'] = {'started': 10.0, 'finished': 12.5}
store.sources = {'loki': {'up': False}, 'prometheus': {'up': True}}
text = client(store, clock).get('/metrics').get_data(as_text=True)
assert 'thor_build_info{sha="abc123"} 1' in text
assert 'thor_database_up 1' in text
assert 'thor_last_good_cycle_timestamp_seconds 1795575600.000' in text
assert 'thor_cycle_duration_seconds 2.500' in text
assert 'thor_source_up{source="loki"} 0' in text
store.down = True
text = client(store, clock).get('/metrics').get_data(as_text=True)
assert 'thor_database_up 0' in text and 'thor_source_up' not in text
def test_detect_version(monkeypatch, tmp_path):
monkeypatch.setenv('THOR_SHA', 'deadbeef')
assert detect_version() == 'deadbeef'
monkeypatch.delenv('THOR_SHA')
assert detect_version(str(tmp_path)) == 'unknown' # not a git checkout