diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..d62f352 --- /dev/null +++ b/.flake8 @@ -0,0 +1,3 @@ +[flake8] +max-line-length = 120 +exclude = .git,__pycache__,.venv diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8e4f74d --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.venv/ +__pycache__/ +*.pyc +.coverage +.pytest_cache/ diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..f14816f --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,5 @@ +pytest>=8 +pytest-cov>=5 +flake8>=7 +bandit>=1.7 +pip-audit>=2.7 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..7249e17 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +flask>=3.0 +gunicorn>=22 +pymysql>=1.1 +requests>=2.32 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/fakes.py b/tests/fakes.py new file mode 100644 index 0000000..0bef5be --- /dev/null +++ b/tests/fakes.py @@ -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 diff --git a/tests/test_clients.py b/tests/test_clients.py new file mode 100644 index 0000000..9054698 --- /dev/null +++ b/tests/test_clients.py @@ -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=''), + 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 diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..8ae1f9e --- /dev/null +++ b/tests/test_config.py @@ -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 diff --git a/tests/test_db_mariadb.py b/tests/test_db_mariadb.py new file mode 100644 index 0000000..d038991 --- /dev/null +++ b/tests/test_db_mariadb.py @@ -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') diff --git a/tests/test_monitor.py b/tests/test_monitor.py new file mode 100644 index 0000000..22e32f0 --- /dev/null +++ b/tests/test_monitor.py @@ -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 diff --git a/tests/test_web.py b/tests/test_web.py new file mode 100644 index 0000000..648e846 --- /dev/null +++ b/tests/test_web.py @@ -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 diff --git a/thor/__init__.py b/thor/__init__.py new file mode 100644 index 0000000..204a48c --- /dev/null +++ b/thor/__init__.py @@ -0,0 +1,3 @@ +"""Thor: out-of-band host and cluster health for the LotusGuild cluster (thor#1).""" + +APP_NAME = 'thor' diff --git a/thor/clients/__init__.py b/thor/clients/__init__.py new file mode 100644 index 0000000..56a0f20 --- /dev/null +++ b/thor/clients/__init__.py @@ -0,0 +1,15 @@ +"""Read-only clients for the sources Thor watches through, plus the Tinker ticket client. + +Every client raises :class:`SourceError` when its source can't answer. Callers must treat +that as "unknown" (Thor is blind to that source), never as "nothing found" (thor#1, +Area 1 rule 3; same principle as Gandalf's ``reboots.LokiError``). +""" + + +class SourceError(Exception): + """A source could not answer: unreachable, timed out, HTTP error or a malformed reply.""" + + def __init__(self, source: str, message: str): + super().__init__(f'{source}: {message}') + self.source = source + self.message = message diff --git a/thor/clients/gandalf.py b/thor/clients/gandalf.py new file mode 100644 index 0000000..1327943 --- /dev/null +++ b/thor/clients/gandalf.py @@ -0,0 +1,63 @@ +"""Read-only client for Gandalf's API (machine key, gandalf#66 / gandalf#68). + +Thor uses Gandalf's reachability data instead of probing hosts itself, and Gandalf's +suppressions (with their start and end times) as the record of planned maintenance. +""" +from typing import Dict, List, Optional + +import requests + +from . import SourceError + +# Gandalf serves at most 31 days of suppression history. +MAX_SUPPRESSION_HOURS = 31 * 24 + + +class GandalfClient: + name = 'gandalf' + + def __init__(self, url: str, api_key: str, timeout: float = 10.0, + session: Optional[requests.Session] = None): + self.url = url.rstrip('/') + self.api_key = api_key + self.timeout = timeout + self.session = session or requests.Session() + + @property + def configured(self) -> bool: + return bool(self.url and self.api_key) + + def _get(self, path: str, params: Optional[dict] = None): + if not self.configured: + raise SourceError(self.name, 'no API key configured') + try: + resp = self.session.get(f'{self.url}{path}', params=params, timeout=self.timeout, + headers={'Authorization': f'Bearer {self.api_key}'}) + if resp.status_code in (401, 403): + raise SourceError(self.name, f'key refused (HTTP {resp.status_code})') + resp.raise_for_status() + return resp.json() + except SourceError: + raise + except (requests.RequestException, ValueError) as e: + raise SourceError(self.name, str(e)) from e + + def suppressions(self, hours: int = 24, include_ended: bool = True) -> List[Dict]: + """Every suppression in force in the last ``hours``, with started_at, ended_at, state.""" + hours = max(1, min(int(hours), MAX_SUPPRESSION_HOURS)) + params = {'include_ended': '1', 'hours': str(hours)} if include_ended else None + data = self._get('/api/suppressions', params) + if isinstance(data, dict): + data = data.get('suppressions') + if not isinstance(data, list) or not all(isinstance(s, dict) for s in data): + raise SourceError(self.name, 'unexpected suppressions reply') + return data + + def status(self) -> Dict: + data = self._get('/api/status') + if not isinstance(data, dict): + raise SourceError(self.name, 'unexpected status reply') + return data + + def ping(self) -> None: + self.status() diff --git a/thor/clients/loki.py b/thor/clients/loki.py new file mode 100644 index 0000000..9aad770 --- /dev/null +++ b/thor/clients/loki.py @@ -0,0 +1,89 @@ +"""Loki client and the planned-shutdown lookup. + +Lifted from Gandalf's ``reboots.py`` (gandalf#65, at LotusGuild/gandalf@1c250d6), which was +written to move here unchanged. Changes: lines keep their stream labels (Thor needs the +``host``), errors are :class:`SourceError`, and windows longer than Loki's 30 day limit are +refused up front. +""" +import re +import time +from typing import Dict, List, Optional, Tuple + +import requests + +from . import SourceError + +# What systemd-logind logs when a shutdown is requested (reboot, poweroff, halt, kexec). +SHUTDOWN_RE = re.compile(r'The system will (reboot|power off|halt|suspend|kexec) now') +LOGQL_SHUTDOWN_FILTER = 'will (reboot|power off|halt|kexec) now' +# How far before a host went missing to look for its shutdown line. +SHUTDOWN_LOOKBACK_S = 600 +# Loki rejects queries spanning more than 30 days. +MAX_WINDOW_S = 30 * 24 * 3600 + +Line = Tuple[float, str, Dict[str, str]] + + +def quote(value: str) -> str: + """Quote a value for use inside a LogQL label matcher.""" + return value.replace('\\', '\\\\').replace('"', '\\"') + + +class LokiClient: + name = 'loki' + + def __init__(self, url: str, timeout: float = 10.0, session: Optional[requests.Session] = None): + self.url = url.rstrip('/') + self.timeout = timeout + self.session = session or requests.Session() + + def lines(self, logql: str, start: float, end: float, limit: int = 100, + direction: str = 'backward') -> List[Line]: + """[(unix seconds, line, labels)], newest first unless direction='forward'.""" + if end - start > MAX_WINDOW_S: + raise SourceError(self.name, 'window longer than 30 days') + try: + resp = self.session.get( + f'{self.url}/loki/api/v1/query_range', + params={'query': logql, 'start': f'{int(start * 1e9)}', 'end': f'{int(end * 1e9)}', + 'limit': limit, 'direction': direction}, + timeout=self.timeout, + ) + resp.raise_for_status() + data = resp.json() + except (requests.RequestException, ValueError) as e: + raise SourceError(self.name, str(e)) from e + if not isinstance(data, dict) or data.get('status') != 'success': + raise SourceError(self.name, f'unsuccessful reply: {str(data)[:200]}') + out: List[Line] = [] + for stream in (data.get('data') or {}).get('result') or []: + labels = stream.get('stream') or {} + for ts, line in stream.get('values') or []: + out.append((int(ts) / 1e9, line, labels)) + out.sort(key=lambda x: x[0], reverse=(direction != 'forward')) + return out + + def ping(self) -> None: + """Loki's /ready can return 503 while queries still work, so test with a query.""" + now = time.time() + self.lines('{job="journal"} |= "thor-ping-never-matches"', now - 60, now, limit=1) + + +def shutdown_query(host: str) -> str: + return (f'{{host="{quote(host)}", job="journal", unit="systemd-logind.service"}} ' + f'|~ "{LOGQL_SHUTDOWN_FILTER}"') + + +def find_shutdown(loki: LokiClient, host: str, before: float, + lookback_s: float = SHUTDOWN_LOOKBACK_S) -> Optional[dict]: + """The shutdown request a host logged in the lookback window before ``before``, or None. + + Raises SourceError when Loki can't answer, so "no line" is never confused with "no data". + A missing line is still not proof of a crash: the journal may have stopped reaching Loki + before the host went down (thor#4, 2026-11-25). + """ + for ts, line, _labels in loki.lines(shutdown_query(host), before - lookback_s, before, limit=20): + m = SHUTDOWN_RE.search(line) + if m: + return {'at': ts, 'kind': m.group(1), 'line': line.strip()} + return None diff --git a/thor/clients/prometheus.py b/thor/clients/prometheus.py new file mode 100644 index 0000000..c6889f2 --- /dev/null +++ b/thor/clients/prometheus.py @@ -0,0 +1,62 @@ +"""Prometheus HTTP API client (instant and range queries).""" +from typing import Dict, List, Optional, Tuple + +import requests + +from . import SourceError + +Sample = Tuple[float, float] + + +class PrometheusClient: + name = 'prometheus' + + def __init__(self, url: str, timeout: float = 10.0, session: Optional[requests.Session] = None): + self.url = url.rstrip('/') + self.timeout = timeout + self.session = session or requests.Session() + + def _get(self, path: str, params: dict) -> dict: + try: + resp = self.session.get(f'{self.url}{path}', params=params, timeout=self.timeout) + resp.raise_for_status() + data = resp.json() + except (requests.RequestException, ValueError) as e: + raise SourceError(self.name, str(e)) from e + if not isinstance(data, dict) or data.get('status') != 'success': + raise SourceError(self.name, f'unsuccessful reply: {str(data)[:200]}') + return data.get('data') or {} + + def query(self, expr: str, at: Optional[float] = None) -> List[Dict]: + """Instant query. Returns [{'metric': {...}, 'ts': float, 'value': float}].""" + params = {'query': expr} + if at is not None: + params['time'] = f'{at:.3f}' + data = self._get('/api/v1/query', params) + out = [] + for r in data.get('result') or []: + ts, val = r.get('value', (None, None)) + try: + out.append({'metric': r.get('metric') or {}, 'ts': float(ts), 'value': float(val)}) + except (TypeError, ValueError): + continue + return out + + def query_range(self, expr: str, start: float, end: float, step: float) -> List[Dict]: + """Range query. Returns [{'metric': {...}, 'values': [(ts, value), ...]}].""" + data = self._get('/api/v1/query_range', { + 'query': expr, 'start': f'{start:.3f}', 'end': f'{end:.3f}', 'step': f'{step:g}'}) + out = [] + for r in data.get('result') or []: + values: List[Sample] = [] + for ts, val in r.get('values') or []: + try: + values.append((float(ts), float(val))) + except (TypeError, ValueError): + continue + out.append({'metric': r.get('metric') or {}, 'values': values}) + return out + + def ping(self) -> None: + """Raises SourceError unless Prometheus answers a trivial query.""" + self.query('vector(1)') diff --git a/thor/clients/proxmox.py b/thor/clients/proxmox.py new file mode 100644 index 0000000..71fdd19 --- /dev/null +++ b/thor/clients/proxmox.py @@ -0,0 +1,73 @@ +"""Read-only Proxmox VE API client, authenticated with an API token (thor@pve, PVEAuditor). + +Any node answers for the whole cluster, so each call tries the configured nodes in order +and remembers the last one that answered. +""" +from typing import Dict, List, Optional + +import requests +import urllib3 + +from . import SourceError + + +class ProxmoxClient: + name = 'proxmox' + + def __init__(self, nodes: List[str], token_id: str, token_secret: str, verify_tls: bool = False, + timeout: float = 10.0, session: Optional[requests.Session] = None): + self.nodes = list(nodes) + self.token_id = token_id + self.token_secret = token_secret + self.verify_tls = verify_tls + self.timeout = timeout + self.session = session or requests.Session() + self._preferred = 0 + if not verify_tls: + urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + + @property + def configured(self) -> bool: + return bool(self.nodes and self.token_id and self.token_secret) + + def get(self, path: str, params: Optional[dict] = None): + if not self.configured: + raise SourceError(self.name, 'no API token configured') + headers = {'Authorization': f'PVEAPIToken={self.token_id}={self.token_secret}'} + errors = [] + order = self.nodes[self._preferred:] + self.nodes[:self._preferred] + for node in order: + try: + resp = self.session.get(f'https://{node}:8006/api2/json{path}', params=params, + headers=headers, timeout=self.timeout, + verify=self.verify_tls) # nosec B501 - cluster CA is self-signed + if resp.status_code in (401, 403): + # The token is cluster-wide, so another node won't accept it either. + raise SourceError(self.name, f'token refused (HTTP {resp.status_code})') + resp.raise_for_status() + data = resp.json() + except SourceError: + raise + except (requests.RequestException, ValueError) as e: + errors.append(f'{node}: {e}') + continue + self._preferred = self.nodes.index(node) + return data.get('data') if isinstance(data, dict) else None + raise SourceError(self.name, '; '.join(errors) or 'no nodes configured') + + def cluster_status(self) -> List[Dict]: + """Cluster and node entries: name, ip, online, nodeid, quorate.""" + return self.get('/cluster/status') or [] + + def ceph_flags(self) -> Dict[str, bool]: + """{flag: set?} including pause, which the Prometheus exporter doesn't export.""" + return {f['name']: bool(f.get('value')) for f in (self.get('/cluster/ceph/flags') or [])} + + def ha_status(self) -> List[Dict]: + return self.get('/cluster/ha/status/current') or [] + + def resources(self, kind: Optional[str] = None) -> List[Dict]: + return self.get('/cluster/resources', params={'type': kind} if kind else None) or [] + + def ping(self) -> None: + self.get('/version') diff --git a/thor/clients/tinker.py b/thor/clients/tinker.py new file mode 100644 index 0000000..1f653c6 --- /dev/null +++ b/thor/clients/tinker.py @@ -0,0 +1,145 @@ +"""Tinker Tickets Bearer API client. + +Adapted from Gandalf's ``TicketClient`` (LotusGuild/gandalf@1c250d6, monitor.py). Changes: +every create carries a ``dedup_key`` (tinker_tickets#123; older Tinker ignores the field), +errors don't raise, and nothing here decides whether a ticket should be sent. Shadow mode is +enforced by the caller, which never reaches this client for a check that isn't live. +""" +import logging +from typing import Dict, Optional +from urllib.parse import urljoin + +import requests + +logger = logging.getLogger('thor.tinker') + + +class TicketResult: + """What Tinker did with a create: its ticket id and action (created, deduplicated, ...).""" + + def __init__(self, ticket_id: Optional[str], action: str = '', ok: bool = False, error: str = ''): + self.ticket_id = ticket_id + self.action = action + self.ok = ok + self.error = error + + def __repr__(self): + return f'TicketResult({self.ticket_id!r}, {self.action!r}, ok={self.ok})' + + +class TinkerClient: + name = 'tinker' + OPEN_STATUSES = 'Open,Pending,In Progress' + _OPEN_TICKETS_MAX_PAGES = 20 + + def __init__(self, url: str, api_key: str, timeout: float = 15.0, + session: Optional[requests.Session] = None): + self.url = url + self.api_key = api_key + self.timeout = timeout + self.session = session or requests.Session() + # Tinker serves its other API scripts under api/ beside create_ticket_api.php + self.comment_url = urljoin(url, 'api/ticket_comment_api.php') if url else '' + self.read_url = urljoin(url, 'api/tickets_api.php') if url else '' + self.writes_denied = False + + @property + def configured(self) -> bool: + return bool(self.url and self.api_key) + + def _headers(self) -> Dict[str, str]: + return {'Authorization': f'Bearer {self.api_key}'} + + def create(self, *, title: str, description: str, priority: int, category: str, + ticket_type: str, dedup_key: str) -> TicketResult: + if not self.configured: + return TicketResult(None, error='not configured') + if self.writes_denied: + return TicketResult(None, error='key lacks write scope') + payload = { + 'title': title, 'description': description, 'status': 'Open', + 'priority': str(int(priority)), 'category': category, 'type': ticket_type, + 'dedup_key': dedup_key, + } + try: + resp = self.session.post(self.url, json=payload, headers=self._headers(), timeout=self.timeout) + if resp.status_code in (401, 403): + self.writes_denied = True + logger.error('Tinker refused a create (HTTP %s); ticket writes are off until restart', + resp.status_code) + return TicketResult(None, error=f'HTTP {resp.status_code}') + resp.raise_for_status() + data = resp.json() + except (requests.RequestException, ValueError) as e: + return TicketResult(None, error=str(e)) + if data.get('success') and data.get('ticket_id'): + return TicketResult(str(data['ticket_id']), data.get('action') or 'created', ok=True) + if data.get('existing_ticket_id'): + return TicketResult(str(data['existing_ticket_id']), 'deduplicated', ok=True) + return TicketResult(None, error=f'unexpected reply: {str(data)[:200]}') + + def comment(self, ticket_id: str, text: str) -> bool: + """Add a Markdown comment. False means try again later; a deleted ticket counts as done.""" + if not self.configured or self.writes_denied: + return False + try: + resp = self.session.post( + self.comment_url, headers=self._headers(), timeout=self.timeout, + json={'ticket_id': str(ticket_id), 'comment_text': text, 'markdown_enabled': True}) + if resp.status_code in (401, 403): + self.writes_denied = True + logger.error('Tinker refused a comment on #%s (HTTP %s)', ticket_id, resp.status_code) + return False + if resp.status_code == 404: + logger.warning('Ticket #%s no longer exists; dropping the comment', ticket_id) + return True + resp.raise_for_status() + return bool(resp.json().get('success')) + except (requests.RequestException, ValueError) as e: + logger.error('Comment on #%s failed: %s', ticket_id, e) + return False + + def open_tickets(self) -> Optional[Dict[str, Dict]]: + """{ticket_id: {title, status, priority}} for every ticket not closed, or None if unknown.""" + if not self.configured: + return None + found: Dict[str, Dict] = {} + try: + for page in range(1, self._OPEN_TICKETS_MAX_PAGES + 1): + resp = self.session.get(self.read_url, headers=self._headers(), timeout=self.timeout, + params={'status': self.OPEN_STATUSES, 'limit': 100, 'page': page}) + resp.raise_for_status() + data = resp.json() + if not data.get('success'): + return None + for t in data.get('tickets') or []: + found[str(t.get('ticket_id'))] = { + 'title': t.get('title') or '', 'status': t.get('status') or '', + 'priority': t.get('priority')} + if page >= int(data.get('pages') or 1): + return found + logger.warning('Open ticket list is longer than expected; using the first pages only') + return found + except (requests.RequestException, ValueError) as e: + logger.error('Reading open tickets failed: %s', e) + return None + + def ticket(self, ticket_id: str) -> Optional[Dict]: + """One ticket with its comments, or None if Tinker can't say.""" + if not self.configured: + return None + try: + resp = self.session.get(self.read_url, headers=self._headers(), timeout=self.timeout, + params={'ticket_id': str(ticket_id)}) + if resp.status_code == 404: + return None + resp.raise_for_status() + data = resp.json() + except (requests.RequestException, ValueError): + return None + return data.get('ticket') if data.get('success') else None + + +def backoff_s(attempts: int, base: float = 120.0, cap: float = 3600.0) -> float: + """Delay before retrying an outbox item that has failed ``attempts`` times.""" + return min(cap, base * (2 ** max(0, attempts - 1))) diff --git a/thor/config.py b/thor/config.py new file mode 100644 index 0000000..2af777a --- /dev/null +++ b/thor/config.py @@ -0,0 +1,152 @@ +"""Settings for Thor. + +Two sources, read in this order (later wins): + +1. ``/etc/thor/thor.json``: non-secret settings (URLs, cadence, check modes). Optional; + every key has a default. ``deploy/thor.example.json`` documents them. +2. ``/etc/thor/*.env``: one ``KEY=VALUE`` per line, holding secrets (Proxmox token, + database password, Gandalf and Tinker keys). Readable by root and the ``thor`` group + only, never in the repo. +3. The process environment, for tests and one-off runs. + +Nothing here talks to the network; a missing secret just leaves that source unconfigured, +and the monitor reports it as unavailable instead of failing to start. +""" +import json +import os +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List, Mapping, Optional + +DEFAULT_CONFIG_PATH = '/etc/thor/thor.json' +DEFAULT_ENV_DIR = '/etc/thor' + +# Every check starts in shadow: it is evaluated and shown in Thor, and what it would have +# opened is logged, but nothing is sent to Tinker (thor#1, Area 5). +CHECK_MODES = ('off', 'shadow', 'live') + + +@dataclass +class DatabaseSettings: + host: str = '' + port: int = 3306 + name: str = 'thor' + user: str = 'thor' + password: str = '' + + @property + def configured(self) -> bool: + return bool(self.host and self.user and self.password) + + +@dataclass +class Settings: + prometheus_url: str = 'http://10.10.10.48:9090' + loki_url: str = 'http://10.10.10.69:3100' + # Any node answers for the whole cluster; Thor tries them in this order. + proxmox_nodes: List[str] = field(default_factory=lambda: [ + '10.10.10.11', '10.10.10.10', '10.10.10.4', '10.10.10.2', '10.10.10.8', '10.10.10.9']) + proxmox_token_id: str = '' + proxmox_token_secret: str = '' + # Proxmox nodes use their self-signed cluster CA. + proxmox_verify_tls: bool = False + gandalf_url: str = 'http://10.10.10.61' + gandalf_api_key: str = '' + tinker_url: str = 'https://t.lotusguild.org/create_ticket_api.php' + tinker_api_key: str = '' + public_url: str = 'https://thor.lotusguild.org' + cycle_seconds: int = 120 + catchup_hours: int = 24 + # How many missed cycles before /health reports the monitor as stale. + stale_after_cycles: int = 3 + http_timeout_s: float = 10.0 + checks: Dict[str, str] = field(default_factory=dict) + database: DatabaseSettings = field(default_factory=DatabaseSettings) + + def check_mode(self, name: str) -> str: + mode = self.checks.get(name, 'shadow') + return mode if mode in CHECK_MODES else 'shadow' + + @property + def stale_after_s(self) -> int: + return self.cycle_seconds * self.stale_after_cycles + + +def parse_env_file(text: str) -> Dict[str, str]: + """KEY=VALUE lines; blank lines and # comments ignored; optional surrounding quotes.""" + out = {} + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith('#') or '=' not in line: + continue + key, value = line.split('=', 1) + key, value = key.strip(), value.strip() + if len(value) >= 2 and value[0] == value[-1] and value[0] in '"\'': + value = value[1:-1] + if key: + out[key] = value + return out + + +def read_env_dir(env_dir: str) -> Dict[str, str]: + values: Dict[str, str] = {} + path = Path(env_dir) + if not path.is_dir(): + return values + for f in sorted(path.glob('*.env')): + try: + values.update(parse_env_file(f.read_text())) + except OSError: + continue + return values + + +def _as_bool(value) -> bool: + if isinstance(value, bool): + return value + return str(value).strip().lower() in ('1', 'true', 'yes', 'on') + + +def load(config_path: Optional[str] = None, env_dir: Optional[str] = None, + environ: Optional[Mapping[str, str]] = None) -> Settings: + config_path = config_path or os.environ.get('THOR_CONFIG', DEFAULT_CONFIG_PATH) + env_dir = env_dir or os.environ.get('THOR_ENV_DIR', DEFAULT_ENV_DIR) + environ = os.environ if environ is None else environ + + s = Settings() + try: + with open(config_path) as f: + data = json.load(f) + except FileNotFoundError: + data = {} + for key in ('prometheus_url', 'loki_url', 'gandalf_url', 'tinker_url', 'public_url'): + if data.get(key): + setattr(s, key, str(data[key]).rstrip('/') if key != 'tinker_url' else str(data[key])) + for key in ('cycle_seconds', 'catchup_hours', 'stale_after_cycles'): + if key in data: + setattr(s, key, int(data[key])) + if 'http_timeout_s' in data: + s.http_timeout_s = float(data['http_timeout_s']) + if data.get('proxmox_nodes'): + 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('checks'), dict): + s.checks = {str(k): str(v) for k, v in data['checks'].items()} + + env = read_env_dir(env_dir) + env.update({k: v for k, v in environ.items() if k.isupper()}) + + s.proxmox_token_id = env.get('PVE_TOKEN_ID', s.proxmox_token_id) + s.proxmox_token_secret = env.get('PVE_TOKEN_SECRET', s.proxmox_token_secret) + s.gandalf_url = env.get('GANDALF_URL', s.gandalf_url).rstrip('/') + s.gandalf_api_key = env.get('GANDALF_API_KEY', s.gandalf_api_key) + s.tinker_url = env.get('TINKER_URL', s.tinker_url) + s.tinker_api_key = env.get('TINKER_API_KEY', s.tinker_api_key) + db = s.database + db.host = env.get('DB_HOST', db.host) + db.port = int(env.get('DB_PORT', db.port)) + db.name = env.get('DB_NAME', db.name) + db.user = env.get('DB_USER', db.user) + db.password = env.get('DB_PASSWORD', db.password) + return s diff --git a/thor/db.py b/thor/db.py new file mode 100644 index 0000000..932948d --- /dev/null +++ b/thor/db.py @@ -0,0 +1,221 @@ +"""MariaDB access: connection handling, versioned migrations, and the queries Thor uses. + +Thor shares MariaDB CT 149 with Gandalf and Tinker (thor#1). That database freezes when +Ceph stalls, so every caller must survive :class:`DatabaseError`: the monitor keeps what it +saw in memory and writes it on the next cycle that has a database. + +All times are stored as naive UTC ``DATETIME(3)``; this module converts to and from unix +seconds so the rest of Thor only deals in floats. +""" +import json +import logging +import threading +from contextlib import contextmanager +from datetime import datetime, timezone +from typing import Any, Dict, Iterator, List, Optional + +import pymysql +import pymysql.cursors + +from .config import DatabaseSettings + +logger = logging.getLogger('thor.db') + + +class DatabaseError(Exception): + """The database could not be reached or refused a statement.""" + + +def to_dt(ts: Optional[float]) -> Optional[datetime]: + if ts is None: + return None + return datetime.fromtimestamp(ts, tz=timezone.utc).replace(tzinfo=None) + + +def from_dt(dt: Optional[datetime]) -> Optional[float]: + if dt is None: + return None + return dt.replace(tzinfo=timezone.utc).timestamp() + + +# Each migration runs once, in order, and is recorded in schema_version. Never edit one +# that has shipped; add a new one. +MIGRATIONS: List[str] = [ + # 1: monitor bookkeeping + """ + CREATE TABLE IF NOT EXISTS state ( + k VARCHAR(64) NOT NULL PRIMARY KEY, + v MEDIUMTEXT NOT NULL, + updated_at DATETIME(3) NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + CREATE TABLE IF NOT EXISTS cycles ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + started_at DATETIME(3) NOT NULL, + finished_at DATETIME(3) NULL, + window_start DATETIME(3) NOT NULL, + window_end DATETIME(3) NOT NULL, + ok TINYINT(1) NOT NULL DEFAULT 0, + blind_sources VARCHAR(255) NOT NULL DEFAULT '', + error TEXT NULL, + KEY idx_cycles_started (started_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + CREATE TABLE IF NOT EXISTS source_status ( + name VARCHAR(32) NOT NULL PRIMARY KEY, + up TINYINT(1) NOT NULL, + since DATETIME(3) NOT NULL, + last_ok DATETIME(3) NULL, + last_error TEXT NULL, + updated_at DATETIME(3) NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + CREATE TABLE IF NOT EXISTS blind_periods ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + source VARCHAR(32) NOT NULL, + started_at DATETIME(3) NOT NULL, + ended_at DATETIME(3) NULL, + reason TEXT NULL, + KEY idx_blind_source (source, started_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + """, +] + + +def _statements(sql: str) -> Iterator[str]: + for part in sql.split(';'): + if part.strip(): + yield part.strip() + + +class Database: + def __init__(self, settings: DatabaseSettings, connect=None): + self.settings = settings + self._connect = connect or self._default_connect + self._local = threading.local() + + def _default_connect(self): + s = self.settings + return pymysql.connect( + host=s.host, port=s.port, user=s.user, password=s.password, database=s.name, + autocommit=True, cursorclass=pymysql.cursors.DictCursor, connect_timeout=10, + read_timeout=30, write_timeout=30, charset='utf8mb4', + init_command="SET time_zone='+00:00'", + ) + + @contextmanager + def cursor(self): + """A cursor on a per-thread connection, reconnecting as needed. Raises DatabaseError.""" + try: + conn = getattr(self._local, 'conn', None) + if conn is None: + conn = self._connect() + self._local.conn = conn + else: + try: + conn.ping(reconnect=False) + except pymysql.MySQLError: + try: + conn.close() + except pymysql.MySQLError: + pass + self._local.conn = None + conn = self._connect() + self._local.conn = conn + with conn.cursor() as cur: + yield cur + except pymysql.MySQLError as e: + self._local.conn = None + raise DatabaseError(str(e)) from e + + def execute(self, sql: str, params: tuple = ()) -> int: + with self.cursor() as cur: + cur.execute(sql, params) + return cur.lastrowid or cur.rowcount + + def query(self, sql: str, params: tuple = ()) -> List[Dict[str, Any]]: + with self.cursor() as cur: + cur.execute(sql, params) + return list(cur.fetchall()) + + def migrate(self) -> int: + """Apply pending migrations. Returns the schema version now in place.""" + self.execute("""CREATE TABLE IF NOT EXISTS schema_version ( + version INT NOT NULL PRIMARY KEY, applied_at DATETIME(3) NOT NULL + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4""") + rows = self.query('SELECT COALESCE(MAX(version), 0) AS v FROM schema_version') + current = int(rows[0]['v']) if rows else 0 + for version, sql in enumerate(MIGRATIONS, start=1): + if version <= current: + continue + for stmt in _statements(sql): + self.execute(stmt) + self.execute('INSERT INTO schema_version (version, applied_at) VALUES (%s, UTC_TIMESTAMP(3))', + (version,)) + logger.info('Applied schema migration %d', version) + current = version + return current + + +class Store: + """The queries the monitor and web app use. Every method may raise DatabaseError.""" + + def __init__(self, db: Database): + self.db = db + + # -- key/value state -------------------------------------------------- + def set_state(self, key: str, value: Any, now: float) -> None: + self.db.execute( + """INSERT INTO state (k, v, updated_at) VALUES (%s, %s, %s) + ON DUPLICATE KEY UPDATE v=VALUES(v), updated_at=VALUES(updated_at)""", + (key, json.dumps(value, default=str), to_dt(now))) + + def get_state(self, key: str, default: Any = None) -> Any: + rows = self.db.query('SELECT v FROM state WHERE k=%s', (key,)) + if not rows: + return default + try: + return json.loads(rows[0]['v']) + except ValueError: + return default + + # -- cycles ----------------------------------------------------------- + def record_cycle(self, *, started: float, finished: float, window_start: float, window_end: float, + ok: bool, blind: List[str], error: str = '') -> int: + return self.db.execute( + """INSERT INTO cycles (started_at, finished_at, window_start, window_end, ok, blind_sources, error) + VALUES (%s, %s, %s, %s, %s, %s, %s)""", + (to_dt(started), to_dt(finished), to_dt(window_start), to_dt(window_end), int(ok), + ','.join(sorted(blind))[:255], error or None)) + + def prune_cycles(self, older_than: float) -> int: + return self.db.execute('DELETE FROM cycles WHERE started_at < %s', (to_dt(older_than),)) + + # -- sources ---------------------------------------------------------- + def source_statuses(self) -> Dict[str, Dict[str, Any]]: + out = {} + for r in self.db.query('SELECT name, up, since, last_ok, last_error FROM source_status'): + out[r['name']] = {'up': bool(r['up']), 'since': from_dt(r['since']), + 'last_ok': from_dt(r['last_ok']), 'last_error': r['last_error'] or ''} + return out + + def save_source_status(self, name: str, up: bool, since: float, last_ok: Optional[float], + last_error: str, now: float) -> None: + self.db.execute( + """INSERT INTO source_status (name, up, since, last_ok, last_error, updated_at) + VALUES (%s, %s, %s, %s, %s, %s) + ON DUPLICATE KEY UPDATE up=VALUES(up), since=VALUES(since), last_ok=VALUES(last_ok), + last_error=VALUES(last_error), updated_at=VALUES(updated_at)""", + (name, int(up), to_dt(since), to_dt(last_ok), last_error or None, to_dt(now))) + + def open_blind_period(self, source: str, started: float, reason: str) -> None: + self.db.execute('INSERT INTO blind_periods (source, started_at, reason) VALUES (%s, %s, %s)', + (source, to_dt(started), reason[:2000])) + + def close_blind_period(self, source: str, ended: float) -> None: + self.db.execute('UPDATE blind_periods SET ended_at=%s WHERE source=%s AND ended_at IS NULL', + (to_dt(ended), source)) + + def blind_periods(self, since: float) -> List[Dict[str, Any]]: + rows = self.db.query( + """SELECT source, started_at, ended_at, reason FROM blind_periods + WHERE ended_at IS NULL OR ended_at >= %s ORDER BY started_at""", (to_dt(since),)) + return [{'source': r['source'], 'started': from_dt(r['started_at']), + 'ended': from_dt(r['ended_at']), 'reason': r['reason'] or ''} for r in rows] diff --git a/thor/monitor.py b/thor/monitor.py new file mode 100644 index 0000000..db02d3a --- /dev/null +++ b/thor/monitor.py @@ -0,0 +1,249 @@ +"""Thor's monitor loop (``thor-monitor.service``). + +Design rules from thor#1, Area 1, because Thor runs on the cluster it watches: + +* **Decide from history, not live edges.** Each cycle reviews the window since the last good + one. If Thor was frozen or down, the next cycle covers the gap, up to ``catchup_hours``. +* **Blind is its own state.** A source that can't answer opens a blind period; nothing it + would have said is ever read as "all clear" or as "host down". +* **Survive the database.** CT 149 freezes when Ceph stalls. Writes are buffered in memory and + flushed on the next cycle that has a database; the loop itself never stops for it. +""" +import logging +import signal +import threading +import time +from dataclasses import dataclass, field +from typing import Callable, Dict, List, Optional, Protocol, Tuple + +from . import config as config_mod +from .clients import SourceError +from .clients.gandalf import GandalfClient +from .clients.loki import LokiClient +from .clients.prometheus import PrometheusClient +from .clients.proxmox import ProxmoxClient +from .db import Database, DatabaseError, Store + +logger = logging.getLogger('thor.monitor') + +# Writes kept while the database is away. A cycle produces a handful, so this is days. +MAX_PENDING_WRITES = 5000 + + +class Source(Protocol): + name: str + + def ping(self) -> None: ... + + +@dataclass +class SourceState: + up: bool = True + since: float = 0.0 + last_ok: Optional[float] = None + last_error: str = '' + known: bool = False # False until the first check of this process or a value loaded from the DB + + +@dataclass +class CycleContext: + """What a check gets each cycle.""" + window_start: float + window_end: float + catching_up: bool + sources: Dict[str, Source] + up: Dict[str, bool] + + +class Check(Protocol): + name: str + + def run(self, ctx: CycleContext) -> List[dict]: ... + + +@dataclass +class CycleResult: + started: float + finished: float + window: Tuple[float, float] + ok: bool + blind: List[str] = field(default_factory=list) + catching_up: bool = False + findings: int = 0 + error: str = '' + + +class Monitor: + def __init__(self, settings: config_mod.Settings, store: Store, sources: Dict[str, Source], + checks: Optional[List[Check]] = None, clock: Callable[[], float] = time.time, + prepare: Optional[Callable[[], object]] = None): + self.settings = settings + self.prepare = prepare + self.store = store + self.sources = sources + self.checks = checks or [] + self.clock = clock + self.source_state: Dict[str, SourceState] = {name: SourceState() for name in sources} + self.pending: List[Tuple[str, tuple, dict]] = [] + self.last_good_end: Optional[float] = None + self._loaded = False + self._stop = threading.Event() + + # -- persistence that tolerates a missing database ---------------------- + def _write(self, method: str, *args, **kwargs) -> None: + self.pending.append((method, args, kwargs)) + if len(self.pending) > MAX_PENDING_WRITES: + dropped = len(self.pending) - MAX_PENDING_WRITES + del self.pending[:dropped] + logger.error('Database away too long: dropped %d oldest buffered writes', dropped) + + def flush(self) -> bool: + """Write everything buffered, oldest first. False if the database is still away.""" + while self.pending: + method, args, kwargs = self.pending[0] + try: + getattr(self.store, method)(*args, **kwargs) + except DatabaseError as e: + logger.warning('Database unavailable, %d writes buffered: %s', len(self.pending), e) + return False + self.pending.pop(0) + return True + + def _load(self) -> None: + """Restore where the last process left off. Retried each cycle until the DB answers.""" + if self._loaded: + return + try: + if self.prepare: + self.prepare() # schema migrations + end = self.store.get_state('last_good_window_end') + statuses = self.store.source_statuses() + except DatabaseError as e: + logger.warning('Could not load previous state yet: %s', e) + return + if isinstance(end, (int, float)): + self.last_good_end = float(end) + for name, st in statuses.items(): + if name in self.source_state: + self.source_state[name] = SourceState(up=st['up'], since=st['since'] or 0.0, + last_ok=st['last_ok'], last_error=st['last_error'], + known=True) + self._loaded = True + + # -- sources ------------------------------------------------------------ + def check_sources(self, now: float) -> Dict[str, bool]: + up = {} + for name, src in self.sources.items(): + st = self.source_state[name] + try: + src.ping() + ok, err = True, '' + except SourceError as e: + ok, err = False, e.message + except Exception as e: # a client bug must not stop the loop + logger.exception('Source %s raised unexpectedly', name) + ok, err = False, f'{type(e).__name__}: {e}' + changed = (not st.known) or st.up != ok + if changed: + if st.known or not ok: + logger.log(logging.INFO if ok else logging.WARNING, 'Source %s is %s%s', name, + 'back' if ok else 'unavailable', '' if ok else f': {err}') + if not ok: + self._write('open_blind_period', name, now, err) + elif st.known: + self._write('close_blind_period', name, now) + st.up, st.since, st.known = ok, now, True + if ok: + st.last_ok = now + st.last_error = err + self._write('save_source_status', name, ok, st.since, st.last_ok, err, now) + up[name] = ok + return up + + # -- the cycle ------------------------------------------------------------ + def window(self, now: float) -> Tuple[float, float, bool]: + """(start, end, catching_up) for this cycle.""" + cycle = self.settings.cycle_seconds + if self.last_good_end is None: + return now - cycle, now, False + start = self.last_good_end + earliest = now - self.settings.catchup_hours * 3600 + if start < earliest: + logger.warning('Thor was away %.1f h; catching up on the last %d h only', + (now - start) / 3600, self.settings.catchup_hours) + start = earliest + return start, now, (now - start) > 2 * cycle + + def cycle(self) -> CycleResult: + started = self.clock() + self._load() + start, end, catching_up = self.window(started) + up = self.check_sources(started) + blind = [n for n, ok in up.items() if not ok] + ctx = CycleContext(start, end, catching_up, self.sources, up) + findings, errors = 0, [] + for check in self.checks: + try: + findings += len(check.run(ctx) or []) + except Exception as e: + logger.exception('Check %s failed', check.name) + errors.append(f'{check.name}: {type(e).__name__}: {e}') + finished = self.clock() + # A cycle is good when it ran; blind sources don't make it bad (they're recorded). + # A failing check does, so its window is reviewed again next cycle. + ok = not errors + result = CycleResult(started, finished, (start, end), ok, blind, catching_up, findings, + '; '.join(errors)) + self._write('record_cycle', started=started, finished=finished, window_start=start, + window_end=end, ok=ok, blind=blind, error=result.error) + heartbeat = {'started': started, 'finished': finished, 'ok': ok, 'blind': blind, + 'window_start': start, 'window_end': end, 'catching_up': catching_up} + self._write('set_state', 'last_cycle', heartbeat, finished) + if ok: + self.last_good_end = end + self._write('set_state', 'last_good_window_end', end, finished) + self._write('set_state', 'last_good_cycle', finished, finished) + self.flush() + return result + + def run_forever(self) -> None: + logger.info('Thor monitor starting: %d s cycle, %d sources, %d checks', + self.settings.cycle_seconds, len(self.sources), len(self.checks)) + while not self._stop.is_set(): + began = self.clock() + try: + r = self.cycle() + logger.info('Cycle %s in %.1f s: window %.0f s%s%s', 'ok' if r.ok else 'FAILED', + r.finished - r.started, r.window[1] - r.window[0], + f', blind: {",".join(r.blind)}' if r.blind else '', + ' (catching up)' if r.catching_up else '') + except Exception: + logger.exception('Cycle crashed') + self._stop.wait(max(1.0, self.settings.cycle_seconds - (self.clock() - began))) + + def stop(self, *_args) -> None: + self._stop.set() + + +def build_sources(s: config_mod.Settings) -> Dict[str, Source]: + return { + 'prometheus': PrometheusClient(s.prometheus_url, timeout=s.http_timeout_s), + 'loki': LokiClient(s.loki_url, timeout=s.http_timeout_s), + 'proxmox': ProxmoxClient(s.proxmox_nodes, s.proxmox_token_id, s.proxmox_token_secret, + verify_tls=s.proxmox_verify_tls, timeout=s.http_timeout_s), + 'gandalf': GandalfClient(s.gandalf_url, s.gandalf_api_key, timeout=s.http_timeout_s), + } + + +def main() -> None: # pragma: no cover - process entry point + logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s: %(message)s') + settings = config_mod.load() + db = Database(settings.database) + monitor = Monitor(settings, Store(db), build_sources(settings), prepare=db.migrate) + signal.signal(signal.SIGTERM, monitor.stop) + signal.signal(signal.SIGINT, monitor.stop) + monitor.run_forever() + + +if __name__ == '__main__': # pragma: no cover + main() diff --git a/thor/web/__init__.py b/thor/web/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/thor/web/app.py b/thor/web/app.py new file mode 100644 index 0000000..941237b --- /dev/null +++ b/thor/web/app.py @@ -0,0 +1,111 @@ +"""Thor's web process (``thor.service``): health, metrics, and later the UI, API and MCP. + +``/health`` is what Kuma probes and what the deploy script waits on: 200 only when the +database answers and the monitor loop finished a good cycle recently (like Gandalf's +``health()``), and it reports the commit it runs so a deploy can confirm itself. +""" +import os +import subprocess # nosec B404 - fixed git command, no user input +import time +from typing import Callable, Optional + +from flask import Flask, Response, jsonify + +from .. import config as config_mod +from ..db import Database, DatabaseError, Store + + +def detect_version(root: Optional[str] = None) -> str: + """The deployed commit: THOR_SHA if set, else ``git rev-parse HEAD``, else 'unknown'.""" + sha = os.environ.get('THOR_SHA', '').strip() + if sha: + return sha + root = root or os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + try: + out = subprocess.run(['git', '-C', root, 'rev-parse', 'HEAD'], capture_output=True, # nosec B603 B607 + text=True, timeout=5, check=True) + return out.stdout.strip() or 'unknown' + except (OSError, subprocess.SubprocessError): + return 'unknown' + + +def _metric_escape(value: str) -> str: + return value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n') + + +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.after_request + def security_headers(resp): + resp.headers.setdefault('X-Content-Type-Options', 'nosniff') + resp.headers.setdefault('X-Frame-Options', 'DENY') + resp.headers.setdefault('Referrer-Policy', 'same-origin') + return resp + + @app.route('/health') + def health(): + body = {'status': 'ok', 'sha': version, 'db': False, 'monitor': 'unknown'} + code = 200 + try: + last_good = store.get_state('last_good_cycle') + last = store.get_state('last_cycle') or {} + body['db'] = True + except DatabaseError: + body.update(status='degraded', monitor='unknown (no database)') + return jsonify(body), 503 + now = clock() + if not isinstance(last_good, (int, float)): + body.update(monitor='no good cycle yet', status='degraded') + code = 503 + else: + age = now - float(last_good) + body['monitor_age_s'] = int(age) + if age > settings.stale_after_s: + body.update(monitor='stale', status='degraded') + code = 503 + else: + body['monitor'] = 'ok' + if isinstance(last, dict) and last.get('blind'): + body['blind'] = sorted(last['blind']) + return jsonify(body), code + + @app.route('/metrics') + def metrics(): + lines = [ + '# HELP thor_build_info The commit Thor runs.', + '# TYPE thor_build_info gauge', + f'thor_build_info{{sha="{_metric_escape(version)}"}} 1', + ] + try: + last_good = store.get_state('last_good_cycle') + last = store.get_state('last_cycle') or {} + sources = store.source_statuses() + db_up = 1 + except DatabaseError: + last_good, last, sources, db_up = None, {}, {}, 0 + lines += ['# HELP thor_database_up Whether the web process can read Thor\'s database.', + '# TYPE thor_database_up gauge', f'thor_database_up {db_up}'] + if isinstance(last_good, (int, float)): + lines += ['# HELP thor_last_good_cycle_timestamp_seconds When the monitor last finished a good cycle.', + '# TYPE thor_last_good_cycle_timestamp_seconds gauge', + f'thor_last_good_cycle_timestamp_seconds {float(last_good):.3f}'] + if isinstance(last, dict) and 'started' in last and 'finished' in last: + lines += ['# HELP thor_cycle_duration_seconds How long the last monitor cycle took.', + '# TYPE thor_cycle_duration_seconds gauge', + f'thor_cycle_duration_seconds {float(last["finished"]) - float(last["started"]):.3f}'] + if sources: + lines += ['# HELP thor_source_up Whether a source Thor reads answered on the last check.', + '# TYPE thor_source_up gauge'] + lines += [f'thor_source_up{{source="{_metric_escape(n)}"}} {int(st["up"])}' + for n, st in sorted(sources.items())] + return Response('\n'.join(lines) + '\n', mimetype='text/plain; version=0.0.4') + + return app + + +def build_app() -> Flask: # pragma: no cover - gunicorn entry point + settings = config_mod.load() + return create_app(settings, Store(Database(settings.database)), detect_version()) diff --git a/thor/web/wsgi.py b/thor/web/wsgi.py new file mode 100644 index 0000000..60bf691 --- /dev/null +++ b/thor/web/wsgi.py @@ -0,0 +1,4 @@ +"""gunicorn entry point: ``gunicorn thor.web.wsgi:app``.""" +from .app import build_app + +app = build_app()