Phase 1, PR 2: engine, memory check, symptoms, outbox, and the 11-23 replay #6

Merged
jared merged 1 commits from engine into main 2026-11-25 23:07:12 -05:00
22 changed files with 33803 additions and 17 deletions

No files matched your search

+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Record a replay fixture from the real Prometheus and Loki (read-only).
Usage: .venv/bin/python scripts/record_fixture.py t1
Each fixture holds the raw series and log lines Thor's checks query, for the whole incident
window plus margin. Replays (tests/replay.py) slice them by time, so a check can change its
windows without re-recording; a new query needs a re-record. Only what Thor parses is kept:
stream labels are cut down to host/job/unit/transport, and Ceph alert series that never
switched on are dropped.
"""
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from thor.checks import memory, symptoms # noqa: E402
from thor.clients.loki import LokiClient # noqa: E402
from thor.clients.prometheus import PrometheusClient # noqa: E402
from thor.hosts import HostRegistry # noqa: E402
PROM = 'http://10.10.10.48:9090'
LOKI = 'http://10.10.10.69:3100'
KEEP_LABELS = ('host', 'job', 'unit', 'transport')
SPECS = {
't1': {
'title': '2026-11-23 OOM loop on compute-storage-01 (CT 154), Tinker 615797777',
'start': 1795410000.0, # 2026-11-23 05:00:00 UTC
'end': 1795416000.0, # 2026-11-23 06:40:00 UTC
'oom_hosts': ['compute-storage-01'],
# Loki answered 500 around the 06:01 stall (Tinker 615797777).
'blind': {'loki': [[1795413600.0, 1795413690.0]]},
'guests': [{'vmid': 154, 'name': 'pelican-wings-02', 'type': 'lxc'}],
},
}
def record(name: str) -> dict:
spec = SPECS[name]
start, end = spec['start'] - 600, spec['end'] + 600
prom, loki, hosts = PrometheusClient(PROM, timeout=60), LokiClient(LOKI, timeout=60), HostRegistry()
exprs = [memory.COUNTER_QUERY, symptoms.CEPH_QUERY] + list(symptoms.ScrapeCheck().queries(hosts).values())
out = {'name': name, 'title': spec['title'], 'start': spec['start'], 'end': spec['end'],
'blind': spec.get('blind', {}), 'guests': spec.get('guests', []),
'prometheus': {}, 'loki': {}}
for expr in exprs:
series = prom.query_range(expr, start, end, 30)
if expr == symptoms.CEPH_QUERY:
series = [s for s in series if any(v >= 1 for _, v in s['values'])]
out['prometheus'][expr] = [{'metric': s['metric'], 'values': s['values']} for s in series]
logql = [symptoms.PVESTATD_QUERY] + [memory.kernel_query(hosts.loki_names(h)) for h in spec['oom_hosts']]
for q in logql:
lines, t = [], start
while t < end: # hour by hour, so no window hits the line limit
chunk = loki.lines(q, t, min(t + 3600, end), limit=5000, direction='forward')
lines += [[ts, line, {k: v for k, v in labels.items() if k in KEEP_LABELS}] for ts, line, labels in chunk]
t += 3600
out['loki'][q] = lines
return out
if __name__ == '__main__':
name = sys.argv[1]
data = record(name)
path = ROOT / 'tests' / 'fixtures' / f'{name}.json'
path.write_text(json.dumps(data, indent=1, sort_keys=True) + '\n')
n_series = sum(len(v) for v in data['prometheus'].values())
n_lines = sum(len(v) for v in data['loki'].values())
print(f'wrote {path}: {n_series} series, {n_lines} log lines')
+49
View File
@@ -18,6 +18,9 @@ class FakeStore:
self.sources: Dict[str, dict] = {} self.sources: Dict[str, dict] = {}
self.blind: List[dict] = [] self.blind: List[dict] = []
self.calls: List[str] = [] self.calls: List[str] = []
self.incidents: Dict[str, dict] = {}
self.actions: List[dict] = []
self.observations: Dict[str, dict] = {}
def _check(self, name): def _check(self, name):
self.calls.append(name) self.calls.append(name)
@@ -61,6 +64,52 @@ class FakeStore:
if b['source'] == source and b['ended'] is None: if b['source'] == source and b['ended'] is None:
b['ended'] = ended b['ended'] = ended
def save_incident(self, inc, now):
self._check('save_incident')
self.incidents[inc['key']] = json.loads(json.dumps(inc, default=str))
def load_incidents(self, since):
self._check('load_incidents')
return [dict(i) for i in self.incidents.values()
if i['state'] in ('pending', 'open') or i['last_seen'] >= since]
def add_action(self, action):
self._check('add_action')
a = json.loads(json.dumps(action, default=str))
a.update(id=len(self.actions) + 1, status='pending' if a['mode'] == 'live' else 'shadow',
attempts=0, next_attempt_at=a['created'] if a['mode'] == 'live' else None, ticket_id=None)
self.actions.append(a)
return a['id']
def due_actions(self, now, limit=20):
self._check('due_actions')
return [a for a in self.actions if a['status'] == 'pending' and a['next_attempt_at'] <= now][:limit]
def mark_action_sent(self, action_id, ticket_id, now):
self._check('mark_action_sent')
a = self.actions[action_id - 1]
a.update(status='sent', ticket_id=ticket_id, sent_at=now)
def mark_action_failed(self, action_id, error, attempts, retry_at):
self._check('mark_action_failed')
a = self.actions[action_id - 1]
a.update(status='pending' if retry_at is not None else 'failed', attempts=attempts,
next_attempt_at=retry_at, error=error)
def incident_ticket(self, key):
self._check('incident_ticket')
ids = [a['ticket_id'] for a in self.actions if a['incident_key'] == key and a.get('ticket_id')]
return ids[-1] if ids else None
def save_observation(self, f, now):
self._check('save_observation')
o = self.observations.get(f['key'])
if o:
o['start'], o['end'] = min(o['start'], f['start']), max(o['end'], f['end'])
o['summary'], o['role'] = f['summary'], f['role']
else:
self.observations[f['key']] = json.loads(json.dumps(f, default=str))
def blind_periods(self, since): def blind_periods(self, since):
self._check('blind_periods') self._check('blind_periods')
return [b for b in self.blind if b['ended'] is None or b['ended'] >= since] return [b for b in self.blind if b['ended'] is None or b['ended'] >= since]
+31855
View File
File diff suppressed because it is too large. Load diff
+105
View File
@@ -0,0 +1,105 @@
"""Replay a recorded incident through the real monitor, engine and checks (thor#1, Area 7).
Fixtures (tests/fixtures/<name>.json, made by scripts/record_fixture.py) hold raw series and
log lines for the incident window. The fakes below slice them by time; a query the fixture
doesn't have fails loudly so a changed check is noticed instead of silently seeing nothing.
"""
import json
from pathlib import Path
from typing import Dict, List
from thor.clients import SourceError
from thor.config import Settings
from thor.monitor import Monitor, build_checks
from .fakes import Clock, FakeStore
FIXTURES = Path(__file__).resolve().parent / 'fixtures'
def load(name: str) -> dict:
return json.loads((FIXTURES / f'{name}.json').read_text())
class _Blindable:
def __init__(self, name: str, fixture: dict, clock: Clock):
self.name = name
self.clock = clock
self.blind = fixture.get('blind', {}).get(name, [])
def _guard(self):
if any(s <= self.clock.t <= e for s, e in self.blind):
raise SourceError(self.name, 'HTTP 500 (recorded outage)')
def ping(self):
self._guard()
class ReplayPrometheus(_Blindable):
def __init__(self, fixture, clock):
super().__init__('prometheus', fixture, clock)
self.series: Dict[str, List[dict]] = fixture['prometheus']
self.asked: List[str] = []
def query_range(self, expr, start, end, step):
self._guard()
self.asked.append(expr)
if expr not in self.series:
raise AssertionError(f'fixture has no series for {expr!r}: re-record it')
return [{'metric': s['metric'], 'values': [(t, v) for t, v in s['values'] if start <= t <= end]}
for s in self.series[expr]]
class ReplayLoki(_Blindable):
def __init__(self, fixture, clock):
super().__init__('loki', fixture, clock)
self.streams: Dict[str, list] = fixture['loki']
def lines(self, logql, start, end, limit=100, direction='backward'):
self._guard()
if logql not in self.streams:
raise AssertionError(f'fixture has no lines for {logql!r}: re-record it')
out = [(ts, line, labels) for ts, line, labels in self.streams[logql] if start <= ts <= end]
out.sort(key=lambda x: x[0], reverse=(direction != 'forward'))
return out[:limit]
class ReplayProxmox(_Blindable):
def __init__(self, fixture, clock):
super().__init__('proxmox', fixture, clock)
self.guests = fixture.get('guests', [])
def resources(self, kind=None):
self._guard()
return list(self.guests)
def cluster_status(self):
self._guard()
return []
class Replay:
def __init__(self, name: str, settings: Settings = None):
self.fixture = load(name)
self.clock = Clock(self.fixture['start'])
self.store = FakeStore()
self.settings = settings or Settings()
self.prometheus = ReplayPrometheus(self.fixture, self.clock)
sources = {'prometheus': self.prometheus, 'loki': ReplayLoki(self.fixture, self.clock),
'proxmox': ReplayProxmox(self.fixture, self.clock)}
self.monitor = Monitor(self.settings, self.store, sources, checks=build_checks(), clock=self.clock)
self.results = []
def run(self, until: float = None):
until = until or self.fixture['end']
while self.clock.t <= until:
self.results.append(self.monitor.cycle())
self.clock.advance(self.settings.cycle_seconds)
return self
# -- what tests look at ---------------------------------------------------
def actions(self, kind: str = None) -> List[dict]:
return [a for a in self.store.actions if kind is None or a['kind'] == kind]
def opened(self) -> List[dict]:
return self.actions('open')
+163
View File
@@ -0,0 +1,163 @@
import pytest
from thor.checks import NeedsSource, counter_rises, query_regex
from thor.checks.memory import MemoryCheck, kernel_query, parse_kills
from thor.checks.symptoms import CephAlertCheck, PvestatdCheck, ScrapeCheck
from thor.clients import SourceError
from thor.hosts import HostRegistry
from thor.model import CAUSE, NOTE, Incident
from thor.monitor import CycleContext
GLOBAL = ('oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=ceph-osd@3.service,mems_allowed=0,'
'global_oom,task_memcg=/lxc/154/ns/system.slice/docker-a.scope,task=java,pid=711,uid=100999')
KILLED = ('Out of memory: Killed process 711 (java) total-vm:295326748kB, anon-rss:2351856kB, file-rss:8kB, '
'shmem-rss:16544832kB, UID:100999 pgtables:38172kB oom_score_adj:0')
MEMCG = ('oom-kill:constraint=CONSTRAINT_MEMCG,nodemask=(null),cpuset=/,mems_allowed=0,oom_memcg=/lxc/120,'
'task_memcg=/lxc/120/ns/x,task=node,pid=55,uid=0')
def test_counter_rises_and_resets():
vals = [(0, 2), (30, 2), (60, 3), (90, 3), (120, 5), (150, 1)]
assert counter_rises(vals, after=0) == [(60, 1), (120, 2), (150, 1)]
assert counter_rises(vals, after=100) == [(120, 2), (150, 1)]
def test_query_regex_escapes_for_promql_strings():
assert query_regex(['10.10.10.4', 'a-b']) == '10\\\\.10\\\\.10\\\\.4|a\\\\-b'
assert kernel_query(['compute-storage-01']).startswith('{job="journal", host=~"compute\\\\-storage\\\\-01"')
def test_parse_kills_pairs_lines_and_reads_everything():
kills = parse_kills([(10.0, GLOBAL, {}), (10.1, KILLED, {}), (20.0, MEMCG, {}),
(30.0, 'Out of memory: Killed process 99 (x) anon-rss:1kB', {})])
assert len(kills) == 3
g = kills[0]
assert g['global'] and g['guest'] == '154' and g['task'] == 'java' and g['pid'] == '711'
assert g['cpuset'] == 'ceph-osd@3.service'
assert g['shmem_rss_kb'] == 16544832 and g['anon_rss_kb'] == 2351856
assert not kills[1]['global'] and kills[1]['guest'] == '120'
assert kills[2]['pid'] == '99' and kills[2]['global'] # oom-kill line lost; Killed line kept
class FakeProm:
def __init__(self, series):
self.series = series
def query_range(self, expr, start, end, step):
if isinstance(self.series, Exception):
raise self.series
return [{'metric': s['metric'], 'values': [(t, v) for t, v in s['values'] if start <= t <= end]}
for s in self.series.get(expr.split('{')[0], [])]
class FakeLoki:
def __init__(self, lines):
self._lines = lines
def lines(self, logql, start, end, limit=100, direction='backward'):
if isinstance(self._lines, Exception):
raise self._lines
return [x for x in self._lines if start <= x[0] <= end]
class FakePx:
def resources(self, kind=None):
return [{'vmid': 154, 'name': 'pelican-wings-02'}]
def ctx(prom=None, loki=None, up=None, start=0.0, end=300.0):
up = up or {'prometheus': True, 'loki': True, 'proxmox': True}
return CycleContext(start, end, False, {'prometheus': prom, 'loki': loki, 'proxmox': FakePx()}, up,
HostRegistry())
OOM_SERIES = {'node_vmstat_oom_kill': [
{'metric': {'instance': '10.10.10.4:9100'}, 'values': [(0, 2), (30, 2), (60, 3), (90, 4)]},
{'metric': {'instance': '10.10.10.29:9100'}, 'values': [(0, 0), (60, 9)]}, # a guest: ignored
]}
def test_memory_check_global_and_cgroup():
lines = [(55.0, GLOBAL, {}), (55.1, KILLED, {}), (85.0, MEMCG, {})]
found = MemoryCheck().run(ctx(FakeProm(OOM_SERIES), FakeLoki(lines)))
roles = {f.role: f for f in found}
assert set(roles) == {CAUSE, NOTE}
c = roles[CAUSE]
assert c.key == 'host:compute-storage-01:oom' and len(c.events) == 1
assert c.events[0]['ceph'] and 'CT 154 pelican-wings-02' in c.events[0]['text']
assert roles[NOTE].key == 'host:compute-storage-01:oom_cgroup'
def test_memory_check_counts_kills_whose_lines_never_reached_loki():
found = MemoryCheck().run(ctx(FakeProm(OOM_SERIES), FakeLoki([])))
assert len(found) == 1 and len(found[0].events) == 2
assert 'never reached Loki' in found[0].events[0]['text']
def test_memory_check_needs_sources():
with pytest.raises(NeedsSource):
MemoryCheck().run(ctx(up={'prometheus': False}))
with pytest.raises(NeedsSource):
MemoryCheck().run(ctx(FakeProm(SourceError('prometheus', 'x')), None))
with pytest.raises(NeedsSource, match='loki'):
MemoryCheck().run(ctx(FakeProm(OOM_SERIES), None, up={'prometheus': True, 'loki': False}))
with pytest.raises(NeedsSource, match='loki'):
MemoryCheck().run(ctx(FakeProm(OOM_SERIES), FakeLoki(SourceError('loki', '500'))))
assert MemoryCheck().run(ctx(FakeProm({}), None)) == []
def test_memory_rules_summary_and_priority():
m = MemoryCheck()
inc = Incident(key='k', kind='oom', subject='compute-storage-01', layer=40, check='memory',
facts={'guest_names': {'154': 'pelican-wings-02'}},
events=[{'at': 0, 'guest': '154', 'task': 'java'}])
assert m.summarize(inc) == 'Out of memory: CT 154 pelican-wings-02 java OOM-killed 1 time'
assert m.priority(inc) == 3
inc.events += [{'at': 600, 'guest': '154'}, {'at': 1200, 'guest': '154'}]
assert m.priority(inc) == 2
inc.symptoms = {'s': {'subject': 'storage-01', 'cluster_effect': True}}
assert m.priority(inc) == 1
inc.symptoms = {}
inc.events.append({'at': 1300, 'guest': '155', 'ceph': True})
assert m.priority(inc) == 1
assert m.summarize(inc) == 'Out of memory: 4 OOM kills on compute-storage-01'
def test_scrape_check():
series = {'up': [{'metric': {'instance': '10.10.10.2:9100'}, 'values': [(30, 1), (60, 0)]}],
'scrape_duration_seconds': [{'metric': {'instance': '10.10.10.11:9100'}, 'values': [(30, 7.5)]},
{'metric': {'instance': '10.10.10.8:9100'}, 'values': [(30, 0.1)]}]}
found = {f.subject: f for f in ScrapeCheck().run(ctx(FakeProm(series)))}
assert set(found) == {'compute-storage-02', 'storage-01'}
assert 'timed out' in found['compute-storage-02'].summary
assert 'up to 7.5 s' in found['storage-01'].summary
assert found['storage-01'].cluster_effect
def test_pvestatd_check_maps_old_host_names():
lines = [(10.0, 'got timeout', {'host': 'micro1'}), (11.0, 'got timeout', {'host': 'micro1'}),
(12.0, 'got timeout', {'host': 'someone-else'})]
found = PvestatdCheck().run(ctx(loki=FakeLoki(lines)))
assert len(found) == 1 and found[0].subject == 'monitor-01' and '(2x)' in found[0].summary
def test_ceph_alert_check_only_alerts_that_switch_on():
series = {'ceph_health_detail': [
{'metric': {'name': 'BLUESTORE_SLOW_OP_ALERT'}, 'values': [(0, 1), (60, 1)]}, # standing
{'metric': {'name': 'OSD_SLOW_PING_TIME_BACK'}, 'values': [(0, 0), (60, 1), (90, 0)]},
]}
found = CephAlertCheck().run(ctx(FakeProm(series), start=30))
assert [f.key for f in found] == ['cluster:ceph_alert:OSD_SLOW_PING_TIME_BACK']
assert found[0].start == 60 and found[0].subject == 'cluster'
def test_symptom_checks_need_their_source():
for check, up in ((ScrapeCheck(), {'prometheus': False}), (PvestatdCheck(), {'loki': False}),
(CephAlertCheck(), {'prometheus': False})):
with pytest.raises(NeedsSource):
check.run(ctx(up=up))
for check in (ScrapeCheck(), CephAlertCheck()):
with pytest.raises(NeedsSource):
check.run(ctx(FakeProm(SourceError('prometheus', 'x'))))
with pytest.raises(NeedsSource):
PvestatdCheck().run(ctx(loki=FakeLoki(SourceError('loki', 'x'))))
+39 -1
View File
@@ -15,7 +15,8 @@ def db():
host=os.environ['THOR_TEST_DB_HOST'], port=int(os.environ.get('THOR_TEST_DB_PORT', '3306')), 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'), 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', ''))) password=os.environ.get('THOR_TEST_DB_PASSWORD', '')))
for t in ('state', 'cycles', 'source_status', 'blind_periods', 'schema_version'): for t in ('state', 'cycles', 'source_status', 'blind_periods', 'incidents', 'actions', 'observations',
'schema_version'):
d.execute(f'DROP TABLE IF EXISTS {t}') # nosec B608 - fixed table names d.execute(f'DROP TABLE IF EXISTS {t}') # nosec B608 - fixed table names
return d return d
@@ -61,3 +62,40 @@ def test_unreachable_database_raises_database_error():
d = Database(DatabaseSettings(host='127.0.0.1', port=1, user='x', password='y')) d = Database(DatabaseSettings(host='127.0.0.1', port=1, user='x', password='y'))
with pytest.raises(DatabaseError): with pytest.raises(DatabaseError):
d.query('SELECT 1') d.query('SELECT 1')
def test_incidents_actions_observations(db):
db.migrate()
s = Store(db)
t = 1795410668.0
inc = {'key': 'host:compute-storage-01:oom', 'state': 'open', 'priority': 1, 'kind': 'oom',
'subject': 'compute-storage-01', 'mode': 'shadow', 'first_seen': t, 'last_seen': t + 60,
'opened_at': t + 120, 'cleared_at': None, 'events': [{'at': t}]}
s.save_incident(inc, t + 120)
inc['state'] = 'cleared'
inc['cleared_at'] = t + 1000
s.save_incident(inc, t + 1000)
assert s.load_incidents(t) == [inc]
assert s.load_incidents(t + 5000) == [] # cleared and old: not reloaded
shadow = s.add_action({'incident_key': inc['key'], 'kind': 'open', 'created': t, 'mode': 'shadow',
'payload': {'title': 'x'}})
live = s.add_action({'incident_key': inc['key'], 'kind': 'open', 'created': t, 'mode': 'live',
'payload': {'title': 'y'}})
due = s.due_actions(t + 1)
assert [a['id'] for a in due] == [live] and due[0]['payload'] == {'title': 'y'}
s.mark_action_failed(live, 'down', 1, t + 100)
assert s.due_actions(t + 50) == []
s.mark_action_sent(live, '615797777', t + 200)
assert s.incident_ticket(inc['key']) == '615797777'
assert s.incident_ticket('other') is None
s.mark_action_failed(shadow, 'x', 30, None)
recent = s.recent_actions(t - 1)
assert {a['id'] for a in recent} == {shadow, live}
f = {'key': 'host:storage-01:scrape', 'kind': 'scrape', 'subject': 'storage-01', 'role': 'symptom',
'start': t + 10, 'end': t + 20, 'summary': 'slow'}
s.save_observation(f, t + 20)
s.save_observation(dict(f, start=t + 5, end=t + 15, summary='timed out'), t + 30)
obs = s.recent_observations(t)
assert len(obs) == 1 and obs[0]['summary'] == 'timed out'
assert obs[0]['first_seen'] == pytest.approx(t + 5, abs=0.001)
assert obs[0]['last_seen'] == pytest.approx(t + 20, abs=0.001)
+161
View File
@@ -0,0 +1,161 @@
from thor.config import Settings
from thor.engine import CLEAR_AFTER_S, Engine
from thor.hosts import HostRegistry
from thor.model import CAUSE, CLEARED, LAYER_RESOURCE, LAYER_SCRAPE, NOTE, OPEN, PENDING, SYMPTOM, Finding
T0 = 1_795_410_668.0
class Rules:
name = 'memory'
def summarize(self, inc):
return f'{len(inc.events)} kills on {inc.subject}'
def priority(self, inc):
return 2 if len(inc.events) >= 3 else 3
def engine(mode=None):
writes = []
s = Settings()
if mode:
s.checks = {'memory': mode}
e = Engine(s, HostRegistry(), {'memory': Rules()}, lambda m, *a, **k: writes.append((m, a, k)))
return e, writes
def cause(at, host='compute-storage-01', n=1):
return Finding(kind='oom', subject=host, role=CAUSE, layer=LAYER_RESOURCE, start=at, end=at,
key=f'host:{host}:oom', summary='x', check='memory',
events=[{'id': f'{host}:{at + i}', 'at': at + i, 'text': 'kill'} for i in range(n)])
def symptom(at, host, kind='scrape', cluster=True):
return Finding(kind=kind, subject=host, role=SYMPTOM, layer=LAYER_SCRAPE, start=at, end=at,
key=f'host:{host}:{kind}', summary=f'{host} {kind}', cluster_effect=cluster)
def kinds(actions):
return [a.kind for a in actions]
def test_new_cause_is_held_one_cycle_then_opened_in_shadow():
e, writes = engine()
assert e.process([cause(T0)], T0 + 30) == []
inc = e.incidents['host:compute-storage-01:oom']
assert inc.state == PENDING and inc.mode == 'shadow'
acts = e.process([], T0 + 150)
assert kinds(acts) == ['open']
a = acts[0]
assert a.mode == 'shadow' and a.payload['dedup_key'] == inc.key
assert a.payload['title'] == '[compute-storage-01][auto][thor][software] 1 kills on compute-storage-01 ' \
'[single-node][production][issue]'
assert [w[1][0]['kind'] for w in writes if w[0] == 'add_action'] == ['open']
assert inc.state == OPEN
def test_symptoms_attach_to_the_cause_even_on_other_hosts_when_it_can_stall_the_cluster():
e, _ = engine()
e.process([cause(T0), symptom(T0 - 5, 'monitor-01', 'pvestatd')], T0 + 30)
inc = e.incidents['host:compute-storage-01:oom']
assert 'host:monitor-01:pvestatd' in inc.symptoms # 5 s before the cause is fine
acts = e.process([symptom(T0 + 100, 'storage-01')], T0 + 150)
assert kinds(acts) == ['open'] # attached while pending: it's in the first text
assert 'storage-01 scrape' in acts[0].payload['description']
acts = e.process([symptom(T0 + 200, 'compute-storage-02')], T0 + 270)
assert kinds(acts) == ['also_seen'] # after opening: a comment
def test_local_symptom_does_not_attach_to_a_host_without_osds():
e, _ = engine()
e.process([cause(T0, host='monitor-02'), symptom(T0, 'storage-01')], T0 + 30)
assert not e.incidents['host:monitor-02:oom'].symptoms
e.process([symptom(T0 + 10, 'monitor-02')], T0 + 40)
assert 'host:monitor-02:scrape' in e.incidents['host:monitor-02:oom'].symptoms
def test_unexplained_symptom_opens_nothing():
e, writes = engine()
assert e.process([symptom(T0, 'storage-01')], T0) == []
assert not e.incidents
assert any(w[0] == 'save_observation' for w in writes)
def test_notes_never_open_anything():
e, _ = engine()
note = Finding(kind='oom_cgroup', subject='compute-storage-01', role=NOTE, layer=LAYER_RESOURCE, start=T0,
end=T0, key='host:compute-storage-01:oom_cgroup', summary='cgroup')
e.process([note], T0)
e.process([], T0 + 300)
assert not e.incidents
def test_also_seen_after_open_and_escalation_only_upwards():
e, _ = engine()
e.process([cause(T0)], T0)
e.process([], T0 + 120)
acts = e.process([symptom(T0 + 130, 'storage-01'), cause(T0 + 140, n=3)], T0 + 240)
assert 'escalate' in kinds(acts) and 'also_seen' in kinds(acts)
esc = [a for a in acts if a.kind == 'escalate'][0]
assert (esc.payload['old'], esc.payload['new']) == (3, 2)
assert e.process([], T0 + 360) == [] # nothing new: no repeat actions
def test_events_are_deduplicated_when_a_window_is_reviewed_again():
e, _ = engine()
e.process([cause(T0)], T0)
e.process([cause(T0)], T0 + 120)
assert len(e.incidents['host:compute-storage-01:oom'].events) == 1
def test_clears_after_fifteen_quiet_minutes_and_comes_back_as_a_new_round():
e, _ = engine()
e.process([cause(T0)], T0)
e.process([], T0 + 120)
acts = e.process([], T0 + CLEAR_AFTER_S + 1)
assert 'cleared' in kinds(acts)
inc = e.incidents['host:compute-storage-01:oom']
assert inc.state == CLEARED
e.process([cause(T0 + 5000)], T0 + 5000)
assert inc.state == PENDING and inc.first_seen == T0 + 5000 and inc.symptoms == {}
acts = e.process([], T0 + 5120)
assert kinds(acts) == ['open']
def test_live_mode_actions_and_catch_up_open_at_once():
e, _ = engine(mode='live')
acts = e.process([cause(T0)], T0 + 3600, catching_up=True)
assert kinds(acts) == ['open'] and acts[0].mode == 'live'
inc = e.incidents['host:compute-storage-01:oom']
assert inc.seen_after_the_fact
assert 'Seen after the fact' in acts[0].payload['description']
def test_refresh_when_summary_changes_rate_limited_and_once_more_when_clearing():
class Flat(Rules):
def priority(self, inc):
return 3
e, _ = engine()
e.checks['memory'] = Flat()
e.process([cause(T0)], T0)
e.process([], T0 + 120) # opened, sent at T0+120
e.process([cause(T0 + 200)], T0 + 240) # summary changed, but < 30 min since sent
assert 'refresh' not in kinds(e.process([], T0 + 360))
for t in range(600, 1900, 300): # keep it active
e.process([cause(T0 + t)], T0 + t + 10)
assert 'refresh' in kinds(e.process([cause(T0 + 1950)], T0 + 1960))
e.process([cause(T0 + 2000)], T0 + 2010) # changed again, too soon to refresh
acts = kinds(e.process([], T0 + 2000 + CLEAR_AFTER_S + 1))
assert acts == ['refresh', 'cleared'] # final text goes out before the note
def test_load_and_covering():
e, _ = engine()
e.process([cause(T0)], T0)
saved = e.incidents['host:compute-storage-01:oom'].to_dict()
e2, _ = engine()
e2.load([saved])
assert [i.key for i in e2.covering(host='compute-storage-01')] == ['host:compute-storage-01:oom']
assert [i.key for i in e2.covering(scope='cluster')] == ['host:compute-storage-01:oom']
assert e2.covering(host='monitor-01') == []
+17 -4
View File
@@ -1,4 +1,5 @@
from thor.config import Settings from thor.config import Settings
from thor.model import NOTE, Finding
from thor.monitor import MAX_PENDING_WRITES, Monitor from thor.monitor import MAX_PENDING_WRITES, Monitor
from .fakes import Clock, FakeSource, FakeStore from .fakes import Clock, FakeSource, FakeStore
@@ -87,11 +88,13 @@ def test_known_down_source_from_previous_process_is_not_reopened():
def test_database_away_buffers_writes_and_flushes_later(): 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.""" """T1 shape: CT 149 freezes with Ceph; Thor keeps cycling and writes when it's back."""
store = FakeStore() store = FakeStore()
store.down = True
m, clock = make(store) m, clock = make(store)
m.cycle() # loaded while the database answered
store.down = True
clock.advance(120)
r1 = m.cycle() r1 = m.cycle()
assert r1.ok assert r1.ok
assert m.pending # nothing written yet assert m.pending # nothing written yet
clock.advance(120) clock.advance(120)
r2 = m.cycle() r2 = m.cycle()
assert r2.window[0] == r1.window[1] # the window still advances in memory assert r2.window[0] == r1.window[1] # the window still advances in memory
@@ -99,10 +102,19 @@ def test_database_away_buffers_writes_and_flushes_later():
clock.advance(120) clock.advance(120)
m.cycle() m.cycle()
assert not m.pending assert not m.pending
assert len(store.cycles) == 3 assert len(store.cycles) == 4
assert store.state['last_good_window_end'] == clock.t assert store.state['last_good_window_end'] == clock.t
def test_database_away_at_start_holds_the_window_until_incidents_load():
store = FakeStore()
store.down = True
m, clock = make(store)
r = m.cycle()
assert not r.ok and 'waiting for the database' in r.error
assert m.last_good_end is None
def test_pending_writes_are_bounded(): def test_pending_writes_are_bounded():
store = FakeStore() store = FakeStore()
store.down = True store.down = True
@@ -127,7 +139,8 @@ def test_failing_check_keeps_the_window_for_next_cycle_and_others_still_run():
def run(self, ctx): def run(self, ctx):
ran.append((ctx.window_start, ctx.window_end, dict(ctx.up))) ran.append((ctx.window_start, ctx.window_end, dict(ctx.up)))
return [{'x': 1}] return [Finding(kind='x', subject='storage-01', role=NOTE, layer=10, start=ctx.window_start,
end=ctx.window_end, key='host:storage-01:x', summary='x')]
store = FakeStore() store = FakeStore()
m, clock = make(store, checks=[Boom(), Fine()]) m, clock = make(store, checks=[Boom(), Fine()])
+125
View File
@@ -0,0 +1,125 @@
from thor import ticket_text
from thor.clients.tinker import TicketResult
from thor.db import DatabaseError
from thor.hosts import HostRegistry
from thor.model import Incident
from thor.outbox import MAX_ATTEMPTS, Outbox
from .fakes import FakeStore
class FakeTinker:
configured = True
def __init__(self, ok=True):
self.ok = ok
self.created, self.comments = [], []
def create(self, **kw):
self.created.append(kw)
return TicketResult('555', 'created', ok=True) if self.ok else TicketResult(None, error='down')
def comment(self, ticket_id, text):
self.comments.append((ticket_id, text))
return self.ok
def live(store, kind, key='host:h:oom', **payload):
base = {'title': 't', 'description': 'd', 'priority': 2, 'category': 'Software', 'type': 'Issue',
'dedup_key': key}
base.update(payload)
return store.add_action({'incident_key': key, 'kind': kind, 'created': 100.0, 'mode': 'live', 'payload': base})
def test_outbox_sends_creates_then_comments_and_skips_shadow():
store, tinker = FakeStore(), FakeTinker()
store.add_action({'incident_key': 'k', 'kind': 'open', 'created': 1.0, 'mode': 'shadow', 'payload': {}})
live(store, 'open')
live(store, 'escalate', comment='raised')
live(store, 'also_seen', comment='also')
assert Outbox(store, tinker).flush(200.0) == 3
assert len(tinker.created) == 2 and tinker.created[0]['dedup_key'] == 'host:h:oom'
assert tinker.comments == [('555', 'raised'), ('555', 'also')]
assert store.actions[0]['status'] == 'shadow'
def test_outbox_retries_with_backoff_and_gives_up():
store, tinker = FakeStore(), FakeTinker(ok=False)
aid = live(store, 'open')
Outbox(store, tinker).flush(200.0)
a = store.actions[aid - 1]
assert a['status'] == 'pending' and a['attempts'] == 1 and a['next_attempt_at'] == 320.0
a['attempts'] = MAX_ATTEMPTS - 1
a['next_attempt_at'] = 0
Outbox(store, tinker).flush(500.0)
assert a['status'] == 'failed'
def test_outbox_comment_waits_for_its_ticket_and_unknown_kinds_fail():
store, tinker = FakeStore(), FakeTinker()
aid = live(store, 'cleared', comment='done')
bad = live(store, 'weird', key='other')
Outbox(store, tinker).flush(200.0)
assert 'no ticket yet' in store.actions[aid - 1]['error']
assert 'unknown action' in store.actions[bad - 1]['error']
def test_outbox_does_nothing_unconfigured_or_without_db():
store = FakeStore()
t = FakeTinker()
t.configured = False
assert Outbox(store, t).flush(1.0) == 0
store.down = True
assert Outbox(store, FakeTinker()).flush(1.0) == 0
def test_outbox_stops_when_db_goes_away_mid_flush():
store, tinker = FakeStore(), FakeTinker()
live(store, 'open')
def boom(*a):
raise DatabaseError('gone')
store.mark_action_sent = boom
assert Outbox(store, tinker).flush(200.0) == 0
def test_hosts_by_instance_aliases_and_proxmox_updates():
h = HostRegistry()
assert h.by_instance('10.10.10.4:9100') == 'compute-storage-01'
assert h.by_instance('10.10.10.99:9100') is None
assert h.canonical('large1') == 'compute-storage-02'
assert h.canonical('nope') is None
assert h.loki_names('compute-storage-02') == ['compute-storage-02', 'large1']
assert h.loki_names('unknown') == ['unknown']
h.update_from_proxmox([
{'type': 'cluster', 'name': 'lotuscluster'},
{'type': 'node', 'name': 'monitor-02', 'ip': '10.10.10.19'}, # IP change
{'type': 'node', 'name': 'storage-02', 'ip': '10.10.10.11'}, # rename of storage-01
{'type': 'node', 'name': 'brand-new', 'ip': '10.10.10.12'},
])
assert h.get('monitor-02').ip == '10.10.10.19'
assert h.canonical('storage-01') == 'storage-02' and h.get('storage-02').ceph_osds
assert h.get('brand-new').cluster_node and h.get('pbs').ip == '10.10.10.3'
assert len(h.all()) == 8
def test_ticket_text_pieces():
assert ticket_text.duration(5) == '5 s'
assert ticket_text.duration(125) == '2 min'
assert ticket_text.duration(3600 * 3 + 60) == '3 h 1 min'
assert ticket_text.duration(3600 * 5) == '5 h'
assert ticket_text.duration(86400 * 3) == '3 d'
assert ticket_text.duration(86400 * 3 + 7200) == '3 d 2 h'
assert ticket_text.utc(None) == 'unknown'
inc = Incident(key='cluster:x', kind='partition', subject='cluster', layer=60, check='c', summary='Split',
first_seen=1795410668.0, last_seen=1795410968.0, priority=1,
facts={'display': {'Hosts': 'a, b'}, 'escalation_reason': 'two hosts fenced'},
events=[{'at': 1795410668.0 + i, 'text': f'e{i}'} for i in range(20)],
symptoms={'s': {'summary': 'slow', 'first': 1795410668.0, 'last': 1795410900.0}})
assert ticket_text.title(inc) == '[proxmox-cluster][auto][thor][software] Split [cluster-wide][production][issue]'
d = ticket_text.description(inc, 'https://thor', related=['673679581'])
assert '- **Hosts:** a, b' in d and 'Why this priority' in d and '(5 earlier, see Thor)' in d
assert '#673679581' in d and 'to 05:15:00' in d and '[Thor](https://thor/incident/cluster:x)' in d
assert 'Thor raised the priority: P3 Medium to P1 Critical' in ticket_text.escalation_comment(3, 1, 'r')
assert 'Also seen: slow' in ticket_text.also_seen_comment('slow', 1795410668.0)
assert 'Lasted:** 5 min' in ticket_text.cleared_comment(inc)
+82
View File
@@ -0,0 +1,82 @@
"""T1, the reference incident (thor#1): 2026-11-23 OOM loop on compute-storage-01 (CT 154).
Right outcome: exactly one ticket, for the out-of-memory host, naming CT 154; the Ceph alerts,
pvestatd timeouts and scrape timeouts on other hosts are "Also seen" on it, not tickets of
their own (Gandalf's false P1 network ticket, Tinker 615797777, is what this replaces).
"""
from datetime import datetime, timezone
import pytest
from .replay import Replay
KEY = 'host:compute-storage-01:oom'
def hm(ts: float) -> str:
return datetime.fromtimestamp(ts, tz=timezone.utc).strftime('%H:%M')
@pytest.fixture(scope='module')
def t1():
return Replay('t1').run()
def test_exactly_one_ticket_for_the_oom_host(t1):
opened = t1.opened()
assert len(opened) == 1, [a['payload']['title'] for a in opened]
a = opened[0]
assert a['incident_key'] == KEY
assert a['mode'] == 'shadow' and a['status'] == 'shadow' # nothing is sent in phase 1
p = a['payload']
assert p['dedup_key'] == KEY
assert p['title'].startswith('[compute-storage-01][auto][thor][software] Out of memory: CT 154 pelican-wings-02')
assert p['title'].endswith('[single-node][production][issue]')
# Opened soon after the first kill (05:11:30 by the counter), after one cycle's hold.
assert '05:12' <= hm(a['created']) <= '05:17'
def test_no_other_incident_becomes_a_ticket(t1):
assert set(t1.store.incidents) == {KEY}
assert {a['incident_key'] for a in t1.actions()} == {KEY}
def test_counts_all_eleven_kills_of_ct_154(t1):
inc = t1.store.incidents[KEY]
assert len(inc['events']) == 11
assert all(e['guest'] == '154' for e in inc['events'])
assert inc['summary'] == 'Out of memory: CT 154 pelican-wings-02 java OOM-killed 11 times'
def test_opens_at_p1_because_the_cluster_stalled_with_the_first_kill(t1):
"""pvestatd timed out on three other hosts at 05:11:03 (never on normal days) as the first
kill landed at 05:11:08: other hosts stalling means P1 from the start (operator decision,
2026-11-25; the thor#1 table had guessed P3 rising to P1 at 06:01)."""
opened = t1.opened()[0]
assert opened['payload']['priority'] == 1
assert 'pvestatd' in opened['payload']['description']
assert not t1.actions('escalate') # nothing higher to go to
def test_symptoms_on_other_hosts_are_also_seen_not_tickets(t1):
symptoms = t1.store.incidents[KEY]['symptoms']
kinds = {(s['kind'], s['subject']) for s in symptoms.values()}
assert ('scrape', 'compute-storage-02') in kinds
assert ('scrape', 'storage-01') in kinds
assert ('pvestatd', 'monitor-01') in kinds
assert any(k == 'ceph_alert' for k, _ in kinds)
assert t1.actions('also_seen'), 'symptoms after the ticket opened are added as comments'
def test_clears_fifteen_minutes_after_the_last_kill(t1):
cleared = t1.actions('cleared')
assert len(cleared) == 1
# Last kill 06:01:27 (counter 06:02:00): cleared 15 minutes later, within a cycle or two.
assert '06:16' <= hm(cleared[0]['created']) <= '06:21'
assert t1.store.incidents[KEY]['state'] == 'cleared'
def test_loki_outage_at_06_00_delays_but_loses_nothing(t1):
held = [r for r in t1.results if not r.ok]
assert held, 'the recorded Loki 500s should hold at least one window'
assert all('loki' in r.error for r in held)
+40
View File
@@ -0,0 +1,40 @@
"""Checks: turn source data for one review window into findings.
A check that needs a source that is blind right now raises :class:`NeedsSource`. The monitor
then keeps the window, so the same stretch is reviewed again once the source answers:
missing data is never read as "nothing happened".
"""
import re
from typing import Iterable, List, Tuple
class NeedsSource(Exception):
def __init__(self, source: str, why: str = ''):
super().__init__(f'needs {source}{": " + why if why else ""}')
self.source = source
def query_regex(values: Iterable[str]) -> str:
"""An alternation for a PromQL/LogQL ``=~`` matcher, inside a double-quoted string.
Regex metacharacters are escaped, and the backslashes themselves doubled, because
both languages treat ``\\.`` in a string literal as an (invalid) escape sequence.
"""
return '|'.join(re.escape(v).replace('\\', '\\\\') for v in values)
def counter_rises(values: List[Tuple[float, float]], after: float) -> List[Tuple[float, float]]:
"""(time, increase) for each rise of a counter after ``after``.
A drop means the counter reset (the host rebooted); the new value counts as the increase.
"""
out = []
prev = None
for ts, val in values:
if prev is not None and ts > after:
if val > prev:
out.append((ts, val - prev))
elif val < prev and val > 0:
out.append((ts, val))
prev = val
return out
+210
View File
@@ -0,0 +1,210 @@
"""Host out of memory (thor#1: memory is Thor's first check; hwmonDaemon#39 superseded).
Evidence:
* ``node_vmstat_oom_kill`` from Prometheus says *that* the kernel killed something, and when.
It counts every kill, including a container hitting its own memory limit.
* The kernel's ``oom-kill:`` line in Loki says *which kind* and *who*: ``global_oom`` (the
whole host ran out) vs ``CONSTRAINT_MEMCG`` (a cgroup's own limit), the ``cpuset`` that
triggered it (the 2026-11-23 06:01:27 kill came from the ceph-osd slice), the victim and
its container (``task_memcg=/lxc/154/...``).
Rules (thor#1, Area 4): a global OOM opens a ticket at the first kill (P3), P2 at 3 or more
kills in 30 minutes, P1 when it hits Ceph (a kill from an OSD slice, or the cluster stalling
while it happens). A container's own limit is a guest problem: shown in Thor, never ticketed.
"""
import re
from typing import Dict, List, Optional
from ..clients import SourceError
from ..model import CAUSE, LAYER_RESOURCE, NOTE, Finding, Incident
from . import NeedsSource, counter_rises, query_regex
COUNTER_QUERY = 'node_vmstat_oom_kill'
MEM_QUERY = 'node_memory_MemAvailable_bytes'
STEP_S = 30
LOOP_WINDOW_S = 30 * 60
LOOP_KILLS = 3
KILL_LINE_RE = re.compile(r'oom-kill:(\S+)')
KILLED_RE = re.compile(r'(?:Memory cgroup out of memory|Out of memory): Killed process (\d+) \(([^)]*)\)(.*)')
RSS_RE = re.compile(r'(anon|file|shmem)-rss:(\d+)kB')
GUEST_RE = re.compile(r'/(?:lxc|qemu\.slice)/(\d+)')
# From the 2026-11-23 follow-up (Tinker 615797777).
OOM_CHECKS = [
'Which guest grew: the victims above, and `pct config <id>` / the app\'s own memory settings '
'(e.g. a JVM -Xmx, or a Pelican limit that is not well above it).',
'Is the host overcommitted? Running guests\' memory limits plus Ceph OSD memory targets '
'(about 4 GB per OSD) against the host\'s RAM (Thor shows this).',
'Cap the guest below what the host can spare, or move it to a host with room.',
'If a kill came from a ceph-osd slice, check `ceph -s` and slow ops once memory is back.',
]
def kernel_query(names: List[str]) -> str:
hosts = query_regex(names)
return (f'{{job="journal", host=~"{hosts}", transport="kernel"}} '
f'|~ "oom-kill:|Killed process"')
def parse_kills(lines) -> List[Dict]:
"""Kill events from kernel lines, oldest first. Pairs each oom-kill line with its 'Killed process'."""
kills: List[Dict] = []
by_pid: Dict[str, Dict] = {}
for ts, line, _labels in sorted(lines, key=lambda x: x[0]):
m = KILL_LINE_RE.search(line)
if m:
fields: Dict[str, str] = {}
flags = set()
for part in m.group(1).split(','):
if '=' in part:
k, v = part.split('=', 1)
fields[k] = v
else:
flags.add(part)
memcg = fields.get('task_memcg', '')
g = GUEST_RE.search(memcg)
kill = {
'at': ts, 'pid': fields.get('pid', ''), 'task': fields.get('task', ''),
'global': 'global_oom' in flags or fields.get('constraint') == 'CONSTRAINT_NONE',
'constraint': fields.get('constraint', ''), 'cpuset': fields.get('cpuset', ''),
'memcg': memcg, 'guest': g.group(1) if g else None,
}
kills.append(kill)
by_pid[kill['pid']] = kill
continue
m = KILLED_RE.search(line)
if m:
pid, task, rest = m.groups()
kill = by_pid.get(pid)
if kill is None: # the oom-kill line was lost; keep what we know
kill = {'at': ts, 'pid': pid, 'task': task, 'global': line.startswith('Out of memory'),
'constraint': '', 'cpuset': '', 'memcg': '', 'guest': None}
kills.append(kill)
by_pid[pid] = kill
for kind, kb in RSS_RE.findall(rest):
kill[f'{kind}_rss_kb'] = int(kb)
return kills
def _gb(kb: Optional[int]) -> str:
return f'{kb / 1024 / 1024:.1f} GB' if kb else '?'
def _hits_ceph(kill: Dict) -> bool:
return 'ceph-osd' in kill.get('cpuset', '') or kill.get('task') == 'ceph-osd'
class MemoryCheck:
name = 'memory'
def run(self, ctx) -> List[Finding]:
if not ctx.up.get('prometheus'):
raise NeedsSource('prometheus')
prom = ctx.sources['prometheus']
try:
series = prom.query_range(COUNTER_QUERY, ctx.window_start - 2 * STEP_S, ctx.window_end, STEP_S)
except SourceError as e:
raise NeedsSource('prometheus', e.message) from e
findings: List[Finding] = []
for s in series:
host = ctx.hosts.by_instance(s['metric'].get('instance', ''))
if not host:
continue # guests' own exporters: their kills are the guest's business
rises = counter_rises(s['values'], ctx.window_start)
if not rises:
continue
findings += self._host_findings(ctx, host, rises)
return findings
def _guest_names(self, ctx) -> Dict[str, str]:
if not ctx.up.get('proxmox'):
return {}
try:
return {str(r.get('vmid')): r.get('name', '') for r in ctx.sources['proxmox'].resources('vm')}
except SourceError:
return {}
def _host_findings(self, ctx, host: str, rises) -> List[Finding]:
if not ctx.up.get('loki'):
raise NeedsSource('loki', f'{host} had OOM kills; need the kernel lines to tell what kind')
loki = ctx.sources['loki']
start = min(ts for ts, _ in rises) - 3 * STEP_S
try:
lines = loki.lines(kernel_query(ctx.hosts.loki_names(host)), start, ctx.window_end + 5,
limit=1000, direction='forward')
except SourceError as e:
raise NeedsSource('loki', e.message) from e
kills = [k for k in parse_kills(lines) if k['at'] > start]
counted = int(sum(d for _, d in rises))
names = self._guest_names(ctx) if kills else {}
global_kills = [k for k in kills if k['global']]
memcg_kills = [k for k in kills if not k['global']]
if counted > len(kills):
# Some kills never reached Loki (lines lost while shipping). Count them as host
# kills: the counter says they happened and we can't rule out a global OOM.
for ts, _ in rises[len(kills):]:
global_kills.append({'at': ts, 'pid': '', 'task': '', 'global': True, 'constraint': 'unknown',
'cpuset': '', 'memcg': '', 'guest': None, 'unknown': True})
findings = []
if global_kills:
events = [self._event(host, k, names) for k in global_kills]
findings.append(Finding(
kind='oom', subject=host, role=CAUSE, layer=LAYER_RESOURCE, check=self.name,
start=min(k['at'] for k in global_kills), end=max(k['at'] for k in global_kills),
key=f'host:{host}:oom', summary=f'Out of memory on {host}', priority=3,
facts={'guest_names': names, 'checks': OOM_CHECKS}, events=events))
if memcg_kills:
findings.append(Finding(
kind='oom_cgroup', subject=host, role=NOTE, layer=LAYER_RESOURCE, check=self.name,
start=min(k['at'] for k in memcg_kills), end=max(k['at'] for k in memcg_kills),
key=f'host:{host}:oom_cgroup', priority=4,
summary=f'{len(memcg_kills)} container memory-limit kill(s) on {host}',
events=[self._event(host, k, names) for k in memcg_kills]))
return findings
@staticmethod
def _event(host: str, k: Dict, names: Dict[str, str]) -> Dict:
if k.get('unknown'):
text = 'OOM kill counted by the kernel, but its log line never reached Loki'
else:
who = f'{k["task"] or "process"} (pid {k["pid"]})'
if k.get('guest'):
g = k['guest']
who += f' in CT {g}' + (f' {names[g]}' if names.get(g) else '')
text = f'{"global" if k["global"] else "cgroup"} OOM killed {who}'
if k.get('shmem_rss_kb') or k.get('anon_rss_kb'):
text += f', anon {_gb(k.get("anon_rss_kb"))}, shmem {_gb(k.get("shmem_rss_kb"))}'
if k.get('cpuset'):
text += f', triggered from {k["cpuset"]}'
return {'id': f'{host}:{k.get("pid") or "?"}:{int(k["at"])}', 'at': k['at'], 'text': text,
'guest': k.get('guest'), 'task': k.get('task'), 'ceph': _hits_ceph(k)}
# -- what the engine asks about this check's incidents ----------------
def summarize(self, inc: Incident) -> str:
n = len(inc.events)
guests = sorted({e['guest'] for e in inc.events if e.get('guest')})
names = inc.facts.get('guest_names') or {}
if len(guests) == 1:
g = guests[0]
label = f'CT {g}' + (f' {names[g]}' if names.get(g) else '')
task = next((e.get('task') for e in reversed(inc.events) if e.get('guest') == g and e.get('task')), '')
what = f'{label} {task}'.strip()
return f'Out of memory: {what} OOM-killed {n} time{"s" if n != 1 else ""}'
return f'Out of memory: {n} OOM kill{"s" if n != 1 else ""} on {inc.subject}'
def priority(self, inc: Incident) -> int:
if any(e.get('ceph') for e in inc.events):
inc.facts['escalation_reason'] = 'An OOM kill was triggered from a Ceph OSD: storage is affected.'
return 1
stalled = {s['subject'] for s in inc.symptoms.values()
if s.get('cluster_effect') and s['subject'] not in (inc.subject,)}
if stalled:
inc.facts['escalation_reason'] = ('While this host is out of memory, the cluster is stalling: '
+ ', '.join(sorted(stalled)) + '.')
return 1
times = sorted(e['at'] for e in inc.events)
for i in range(len(times)):
if sum(1 for t in times[i:] if t - times[i] <= LOOP_WINDOW_S) >= LOOP_KILLS:
inc.facts['escalation_reason'] = (f'{LOOP_KILLS} or more OOM kills within 30 minutes: '
'the host is in an OOM loop.')
return 2
return 3
+118
View File
@@ -0,0 +1,118 @@
"""Symptom checks: things that are usually the *result* of a cause elsewhere.
They never open tickets on their own in phase 1. The engine attaches them as "Also seen" to
the cause that explains them (thor#1, Area 4). From 2026-11-23:
* node_exporter scrapes that are slow or fail on several hosts at once (Gandalf misread these
as a network failure, gandalf#57);
* ``pvestatd: got timeout`` on every node;
* Ceph health alerts that switch on while it happens (OSD slow ping, stalled DB reads).
Alerts already on at the start of the window are standing conditions, not symptoms.
"""
from typing import Dict, List
from ..clients import SourceError
from ..model import LAYER_CEPH, LAYER_SCRAPE, SYMPTOM, Finding
from . import NeedsSource, query_regex
STEP_S = 30
SLOW_SCRAPE_S = 5.0
PVESTATD_QUERY = '{job="journal", unit="pvestatd.service"} |= "got timeout"'
CEPH_QUERY = 'ceph_health_detail'
def node_instances_regex(hosts) -> str:
return query_regex(h.ip for h in hosts.all())
class ScrapeCheck:
name = 'scrapes'
def queries(self, hosts) -> Dict[str, str]:
ips = node_instances_regex(hosts)
return {'up': f'up{{instance=~"({ips}):9100"}}',
'duration': f'scrape_duration_seconds{{instance=~"({ips}):9100"}}'}
def run(self, ctx) -> List[Finding]:
if not ctx.up.get('prometheus'):
raise NeedsSource('prometheus')
q = self.queries(ctx.hosts)
try:
up = ctx.sources['prometheus'].query_range(q['up'], ctx.window_start, ctx.window_end, STEP_S)
dur = ctx.sources['prometheus'].query_range(q['duration'], ctx.window_start, ctx.window_end, STEP_S)
except SourceError as e:
raise NeedsSource('prometheus', e.message) from e
bad: Dict[str, Dict] = {}
for s in up:
host = ctx.hosts.by_instance(s['metric'].get('instance', ''))
for ts, v in s['values']:
if host and v == 0 and ts > ctx.window_start:
b = bad.setdefault(host, {'failed': [], 'slow': []})
b['failed'].append(ts)
for s in dur:
host = ctx.hosts.by_instance(s['metric'].get('instance', ''))
for ts, v in s['values']:
if host and v >= SLOW_SCRAPE_S and ts > ctx.window_start:
b = bad.setdefault(host, {'failed': [], 'slow': []})
b['slow'].append((ts, v))
out = []
for host, b in sorted(bad.items()):
times = b['failed'] + [t for t, _ in b['slow']]
worst = max((v for _, v in b['slow']), default=0)
if b['failed']:
summary = f'{host}: node_exporter scrape timed out'
else:
summary = f'{host}: node_exporter scrapes slow (up to {worst:.1f} s)'
out.append(Finding(kind='scrape', subject=host, role=SYMPTOM, layer=LAYER_SCRAPE, check=self.name,
start=min(times), end=max(times), key=f'host:{host}:scrape', summary=summary,
cluster_effect=True, facts={'failed': len(b['failed']), 'worst_s': worst}))
return out
class PvestatdCheck:
name = 'pvestatd'
def run(self, ctx) -> List[Finding]:
if not ctx.up.get('loki'):
raise NeedsSource('loki')
try:
lines = ctx.sources['loki'].lines(PVESTATD_QUERY, ctx.window_start, ctx.window_end, limit=500)
except SourceError as e:
raise NeedsSource('loki', e.message) from e
by_host: Dict[str, List[float]] = {}
for ts, _line, labels in lines:
host = ctx.hosts.canonical(labels.get('host', ''))
if host:
by_host.setdefault(host, []).append(ts)
return [Finding(kind='pvestatd', subject=h, role=SYMPTOM, layer=LAYER_SCRAPE, check=self.name,
start=min(t), end=max(t), key=f'host:{h}:pvestatd', cluster_effect=True,
summary=f'{h}: pvestatd timed out talking to the cluster ({len(t)}x)')
for h, t in sorted(by_host.items())]
class CephAlertCheck:
name = 'ceph_alerts'
def run(self, ctx) -> List[Finding]:
if not ctx.up.get('prometheus'):
raise NeedsSource('prometheus')
try:
series = ctx.sources['prometheus'].query_range(CEPH_QUERY, ctx.window_start - STEP_S,
ctx.window_end, STEP_S)
except SourceError as e:
raise NeedsSource('prometheus', e.message) from e
out = []
for s in series:
name = s['metric'].get('name')
values = s['values']
if not name or not values:
continue
rises = [ts for (pt, pv), (ts, v) in zip(values, values[1:]) if pv == 0 and v >= 1]
if not rises:
continue
on = [ts for ts, v in values if v >= 1]
out.append(Finding(kind='ceph_alert', subject='cluster', role=SYMPTOM, layer=LAYER_CEPH,
check=self.name, start=min(rises), end=max(on), key=f'cluster:ceph_alert:{name}',
cluster_effect=True, summary=f'Ceph raised {name}',
facts={'severity': s['metric'].get('severity', '')}))
return out
+2 -1
View File
@@ -38,9 +38,10 @@ class ProxmoxClient:
order = self.nodes[self._preferred:] + self.nodes[:self._preferred] order = self.nodes[self._preferred:] + self.nodes[:self._preferred]
for node in order: for node in order:
try: try:
# The cluster CA is self-signed, so TLS verification is off unless configured.
resp = self.session.get(f'https://{node}:8006/api2/json{path}', params=params, resp = self.session.get(f'https://{node}:8006/api2/json{path}', params=params,
headers=headers, timeout=self.timeout, headers=headers, timeout=self.timeout,
verify=self.verify_tls) # nosec B501 - cluster CA is self-signed verify=self.verify_tls) # nosec B501
if resp.status_code in (401, 403): if resp.status_code in (401, 403):
# The token is cluster-wide, so another node won't accept it either. # The token is cluster-wide, so another node won't accept it either.
raise SourceError(self.name, f'token refused (HTTP {resp.status_code})') raise SourceError(self.name, f'token refused (HTTP {resp.status_code})')
+133
View File
@@ -76,6 +76,53 @@ MIGRATIONS: List[str] = [
KEY idx_blind_source (source, started_at) KEY idx_blind_source (source, started_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
""", """,
# 2: incidents, ticket actions (outbox) and observations
"""
CREATE TABLE IF NOT EXISTS incidents (
k VARCHAR(191) NOT NULL PRIMARY KEY,
state VARCHAR(16) NOT NULL,
priority TINYINT NOT NULL,
kind VARCHAR(32) NOT NULL,
subject VARCHAR(64) NOT NULL,
mode VARCHAR(8) NOT NULL,
first_seen DATETIME(3) NOT NULL,
last_seen DATETIME(3) NOT NULL,
opened_at DATETIME(3) NULL,
cleared_at DATETIME(3) NULL,
data MEDIUMTEXT NOT NULL,
updated_at DATETIME(3) NOT NULL,
KEY idx_incidents_state (state),
KEY idx_incidents_last_seen (last_seen)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS actions (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
incident_key VARCHAR(191) NOT NULL,
kind VARCHAR(16) NOT NULL,
mode VARCHAR(8) NOT NULL,
status VARCHAR(16) NOT NULL,
created_at DATETIME(3) NOT NULL,
sent_at DATETIME(3) NULL,
attempts INT NOT NULL DEFAULT 0,
next_attempt_at DATETIME(3) NULL,
ticket_id VARCHAR(16) NULL,
error TEXT NULL,
payload MEDIUMTEXT NOT NULL,
KEY idx_actions_due (status, next_attempt_at),
KEY idx_actions_incident (incident_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS observations (
k VARCHAR(191) NOT NULL PRIMARY KEY,
kind VARCHAR(32) NOT NULL,
subject VARCHAR(64) NOT NULL,
role VARCHAR(8) NOT NULL,
first_seen DATETIME(3) NOT NULL,
last_seen DATETIME(3) NOT NULL,
summary VARCHAR(512) NOT NULL,
data MEDIUMTEXT NOT NULL,
updated_at DATETIME(3) NOT NULL,
KEY idx_observations_last_seen (last_seen)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
""",
] ]
@@ -219,3 +266,89 @@ class Store:
WHERE ended_at IS NULL OR ended_at >= %s ORDER BY started_at""", (to_dt(since),)) 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']), return [{'source': r['source'], 'started': from_dt(r['started_at']),
'ended': from_dt(r['ended_at']), 'reason': r['reason'] or ''} for r in rows] 'ended': from_dt(r['ended_at']), 'reason': r['reason'] or ''} for r in rows]
# -- incidents ----------------------------------------------------------
def save_incident(self, inc: Dict[str, Any], now: float) -> None:
self.db.execute(
"""INSERT INTO incidents (k, state, priority, kind, subject, mode, first_seen, last_seen,
opened_at, cleared_at, data, updated_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE state=VALUES(state), priority=VALUES(priority), mode=VALUES(mode),
first_seen=VALUES(first_seen), last_seen=VALUES(last_seen), opened_at=VALUES(opened_at),
cleared_at=VALUES(cleared_at), data=VALUES(data), updated_at=VALUES(updated_at)""",
(inc['key'], inc['state'], int(inc['priority']), inc['kind'], inc['subject'], inc['mode'],
to_dt(inc['first_seen']), to_dt(inc['last_seen']), to_dt(inc.get('opened_at')),
to_dt(inc.get('cleared_at')), json.dumps(inc, default=str), to_dt(now)))
def load_incidents(self, since: float) -> List[Dict[str, Any]]:
"""Active incidents, plus any seen since ``since`` (so a recurrence finds its old record)."""
rows = self.db.query(
"""SELECT data FROM incidents WHERE state IN ('pending', 'open') OR last_seen >= %s""",
(to_dt(since),))
out = []
for r in rows:
try:
out.append(json.loads(r['data']))
except ValueError:
logger.error('Skipping an incident with unreadable data')
return out
# -- actions (the outbox) -------------------------------------------------
def add_action(self, action: Dict[str, Any]) -> int:
live = action.get('mode') == 'live'
return self.db.execute(
"""INSERT INTO actions (incident_key, kind, mode, status, created_at, next_attempt_at, payload)
VALUES (%s, %s, %s, %s, %s, %s, %s)""",
(action['incident_key'], action['kind'], action['mode'], 'pending' if live else 'shadow',
to_dt(action['created']), to_dt(action['created']) if live else None,
json.dumps(action.get('payload') or {}, default=str)))
def due_actions(self, now: float, limit: int = 20) -> List[Dict[str, Any]]:
rows = self.db.query(
"""SELECT id, incident_key, kind, attempts, payload FROM actions
WHERE status='pending' AND next_attempt_at <= %s ORDER BY id LIMIT %s""",
(to_dt(now), int(limit)))
for r in rows:
r['payload'] = json.loads(r['payload'] or '{}')
return rows
def mark_action_sent(self, action_id: int, ticket_id: Optional[str], now: float) -> None:
self.db.execute("UPDATE actions SET status='sent', sent_at=%s, ticket_id=%s, error=NULL WHERE id=%s",
(to_dt(now), ticket_id, action_id))
def mark_action_failed(self, action_id: int, error: str, attempts: int, retry_at: Optional[float]) -> None:
status = 'pending' if retry_at is not None else 'failed'
self.db.execute('UPDATE actions SET status=%s, attempts=%s, next_attempt_at=%s, error=%s WHERE id=%s',
(status, attempts, to_dt(retry_at), error[:2000], action_id))
def incident_ticket(self, incident_key: str) -> Optional[str]:
rows = self.db.query("""SELECT ticket_id FROM actions WHERE incident_key=%s AND ticket_id IS NOT NULL
ORDER BY id DESC LIMIT 1""", (incident_key,))
return rows[0]['ticket_id'] if rows else None
def recent_actions(self, since: float, limit: int = 200) -> List[Dict[str, Any]]:
rows = self.db.query("""SELECT id, incident_key, kind, mode, status, created_at, ticket_id, error, payload
FROM actions WHERE created_at >= %s ORDER BY id DESC LIMIT %s""",
(to_dt(since), int(limit)))
for r in rows:
r['created_at'] = from_dt(r['created_at'])
r['payload'] = json.loads(r['payload'] or '{}')
return rows
# -- observations -----------------------------------------------------------
def save_observation(self, f: Dict[str, Any], now: float) -> None:
self.db.execute(
"""INSERT INTO observations (k, kind, subject, role, first_seen, last_seen, summary, data, updated_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE first_seen=LEAST(first_seen, VALUES(first_seen)),
last_seen=GREATEST(last_seen, VALUES(last_seen)), summary=VALUES(summary),
role=VALUES(role), data=VALUES(data), updated_at=VALUES(updated_at)""",
(f['key'], f['kind'], f['subject'], f['role'], to_dt(f['start']), to_dt(f['end']),
f['summary'][:512], json.dumps(f, default=str), to_dt(now)))
def recent_observations(self, since: float) -> List[Dict[str, Any]]:
rows = self.db.query("""SELECT k, kind, subject, role, first_seen, last_seen, summary FROM observations
WHERE last_seen >= %s ORDER BY last_seen DESC""", (to_dt(since),))
for r in rows:
r['first_seen'], r['last_seen'] = from_dt(r['first_seen']), from_dt(r['last_seen'])
return rows
+210
View File
@@ -0,0 +1,210 @@
"""Root-cause grouping: findings in, incidents and ticket actions out (thor#1, Area 4).
* A **cause** finding opens or updates the incident with its key. New incidents are held one
cycle (``PENDING``) so symptoms from the same moment land in the first ticket text.
* A **symptom** attaches to the highest-precedence active incident it relates to: the same
host, or any host for a symptom with a cluster-wide effect (scrape timeouts, pvestatd
timeouts, new Ceph alerts) when the cause can stall the cluster (a Ceph host). Symptoms
nothing explains stay in Thor only; they never open tickets in phase 1.
* An incident clears after ``CLEAR_AFTER_S`` without new evidence: a "Cleared" note, never a
status change. Priority only ever goes up while an incident is active.
* Every Tinker-facing step is an :class:`Action`. In shadow mode it is recorded, never sent.
Checks own the meaning of their incidents: ``summarize(inc)`` and ``priority(inc)`` are
asked of the check that raised the cause, so the engine stays generic.
"""
import logging
from typing import Callable, Dict, List, Optional
from . import ticket_text
from .config import Settings
from .hosts import HostRegistry
from .model import CAUSE, CLEARED, OPEN, PENDING, SYMPTOM, Action, Finding, Incident
logger = logging.getLogger('thor.engine')
CLEAR_AFTER_S = 15 * 60 # thor#1: cleared after 15 minutes clean
REFRESH_EVERY_S = 30 * 60 # re-send a changed description at most this often
ATTACH_BEFORE_S = 5 * 60 # a symptom may show up a little before its cause is seen
MAX_EVENTS = 500 # per incident, oldest dropped first
class Engine:
def __init__(self, settings: Settings, hosts: HostRegistry, checks: Dict[str, object],
write: Callable[..., None]):
self.settings = settings
self.hosts = hosts
self.checks = checks
self.write = write
self.incidents: Dict[str, Incident] = {}
def load(self, incidents: List[dict]) -> None:
for d in incidents:
inc = Incident.from_dict(d)
self.incidents[inc.key] = inc
# -- helpers ------------------------------------------------------------
def _check(self, inc: Incident):
return self.checks.get(inc.check)
def _can_stall_cluster(self, inc: Incident) -> bool:
if inc.subject == 'cluster':
return True
host = self.hosts.get(inc.subject)
return bool(host and host.ceph_osds)
def _related(self, inc: Incident, f: Finding) -> bool:
if not inc.active or inc.layer <= f.layer:
return False
if f.start < inc.first_seen - ATTACH_BEFORE_S or f.start > inc.last_seen + CLEAR_AFTER_S:
return False
if f.subject == inc.subject:
return True
return f.cluster_effect and self._can_stall_cluster(inc)
def _refresh(self, inc: Incident) -> None:
check = self._check(inc)
if check is not None:
if hasattr(check, 'summarize'):
inc.summary = check.summarize(inc)
if hasattr(check, 'priority'):
inc.priority = min(inc.priority, check.priority(inc))
def _action(self, actions: List[Action], inc: Incident, kind: str, now: float, **payload) -> None:
a = Action(inc.key, kind, now, inc.mode, payload)
actions.append(a)
self.write('add_action', a.__dict__)
verb = 'would send' if inc.mode != 'live' else 'queued'
logger.info('[%s] %s %s for %s (P%s): %s', inc.mode, verb, kind, inc.key, inc.priority, inc.summary)
@staticmethod
def _sent(inc: Incident, now: float) -> None:
inc.facts.update(sent_summary=inc.summary, sent_symptoms=len(inc.symptoms), sent_at=now)
def _open_payload(self, inc: Incident) -> dict:
return {'title': ticket_text.title(inc), 'priority': inc.priority, 'category': ticket_text.category(inc),
'type': 'Issue', 'dedup_key': inc.key,
'description': ticket_text.description(inc, self.settings.public_url)}
# -- the cycle ------------------------------------------------------------
def process(self, findings: List[Finding], now: float, catching_up: bool = False) -> List[Action]:
actions: List[Action] = []
touched: Dict[str, Incident] = {}
new_symptoms: Dict[str, List[dict]] = {}
for f in findings:
if f.role == CAUSE:
touched[f.key] = self._merge_cause(f, now, catching_up)
for f in findings:
self.write('save_observation', f.to_dict(), now)
if f.role != SYMPTOM:
continue
candidates = [i for i in self.incidents.values() if self._related(i, f)]
if not candidates:
continue
inc = sorted(candidates, key=lambda i: (-i.layer, i.first_seen))[0]
rec = inc.symptoms.get(f.key)
if rec is None:
rec = {'kind': f.kind, 'subject': f.subject, 'summary': f.summary, 'first': f.start,
'last': f.end, 'cluster_effect': f.cluster_effect}
inc.symptoms[f.key] = rec
if inc.state == OPEN:
new_symptoms.setdefault(inc.key, []).append(rec)
else:
rec['first'] = min(rec['first'], f.start)
rec['last'] = max(rec['last'], f.end)
rec['summary'] = f.summary
touched[inc.key] = inc
for inc in list(self.incidents.values()):
before = inc.priority
if inc.key in touched:
self._refresh(inc)
n_actions = len(actions)
self._lifecycle(inc, now, catching_up, before, new_symptoms.get(inc.key, []), actions)
if inc.key in touched or len(actions) > n_actions:
self.write('save_incident', inc.to_dict(), now)
return actions
@staticmethod
def _new_round(inc: Incident, f: Finding) -> bool:
"""A cleared incident's cause is back: evidence newer than anything it had."""
if f.events:
return any(e.get('at', 0) > inc.last_seen for e in f.events)
return f.end > inc.last_seen
def _merge_cause(self, f: Finding, now: float, catching_up: bool) -> Incident:
inc = self.incidents.get(f.key)
if inc is None:
inc = Incident(key=f.key, kind=f.kind, subject=f.subject, layer=f.layer, check=f.check,
priority=f.priority, first_seen=f.start, last_seen=f.end, pending_since=now,
summary=f.summary, mode=self.settings.check_mode(f.check))
self.incidents[f.key] = inc
elif inc.state == CLEARED and self._new_round(inc, f):
# It came back: a new round for the same key. Tinker decides reopen vs new ticket.
inc.state, inc.pending_since, inc.cleared_at = PENDING, now, None
inc.first_seen, inc.symptoms, inc.priority = f.start, {}, f.priority
inc.facts.pop('sent_priority', None)
inc.mode = self.settings.check_mode(f.check)
inc.first_seen = min(inc.first_seen, f.start)
inc.last_seen = max(inc.last_seen, f.end)
inc.facts.update(f.facts)
known = {e.get('id') for e in inc.events}
for e in f.events:
if e.get('id') not in known:
inc.events.append(e)
known.add(e.get('id'))
inc.events.sort(key=lambda e: e.get('at', 0))
del inc.events[:-MAX_EVENTS]
inc.priority = min(inc.priority, f.priority)
if catching_up and inc.state == PENDING and f.end < now - 2 * self.settings.cycle_seconds:
inc.seen_after_the_fact = True
return inc
def _lifecycle(self, inc: Incident, now: float, catching_up: bool, before: int,
new_symptoms: List[dict], actions: List[Action]) -> None:
if inc.state == PENDING:
if now - inc.pending_since >= self.settings.cycle_seconds or catching_up:
inc.state, inc.opened_at = OPEN, now
inc.facts['sent_priority'] = inc.priority
self._action(actions, inc, 'open', now, **self._open_payload(inc))
self._sent(inc, now)
return
if inc.state != OPEN:
return
sent = inc.facts.get('sent_priority', before)
if inc.priority < sent:
reason = inc.facts.get('escalation_reason') or 'The incident got worse.'
self._action(actions, inc, 'escalate', now, old=sent, new=inc.priority,
comment=ticket_text.escalation_comment(sent, inc.priority, reason),
**self._open_payload(inc))
inc.facts['sent_priority'] = inc.priority
self._sent(inc, now)
if new_symptoms:
text = '\n\n'.join(ticket_text.also_seen_comment(s['summary'], s['first'])
for s in sorted(new_symptoms, key=lambda s: s['first']))
self._action(actions, inc, 'also_seen', now, comment=text,
symptoms=[s['summary'] for s in new_symptoms])
clearing = now - inc.last_seen >= CLEAR_AFTER_S
changed = inc.summary != inc.facts.get('sent_summary') or len(inc.symptoms) != inc.facts.get('sent_symptoms')
if changed and (clearing or now - inc.facts.get('sent_at', 0) >= REFRESH_EVERY_S):
# Same dedup_key: Tinker updates the open ticket's title and description in place.
self._action(actions, inc, 'refresh', now, **self._open_payload(inc))
self._sent(inc, now)
if clearing:
inc.state, inc.cleared_at = CLEARED, now
self._action(actions, inc, 'cleared', now, comment=ticket_text.cleared_comment(inc))
# -- for the web UI and /covering --------------------------------------
def active(self) -> List[Incident]:
return [i for i in self.incidents.values() if i.active]
def covering(self, host: Optional[str] = None, scope: Optional[str] = None) -> List[Incident]:
out = []
for inc in self.active():
if host and (inc.subject == host or (inc.subject == 'cluster')):
out.append(inc)
elif scope == 'cluster' and self._can_stall_cluster(inc):
out.append(inc)
return out
+87
View File
@@ -0,0 +1,87 @@
"""Which hosts Thor watches, and how each source names them.
Sources disagree: Prometheus labels hosts by ``instance`` (IP:port) and a job name that can
be stale (compute-storage-02's is still ``largeoneexporter``), and Loki's ``host`` label
used the old names (``micro1``, ``large1``) before 2026-11-18. Thor maps everything to one
canonical name: by IP for Prometheus, through an alias table for Loki.
The node list comes from the Proxmox API when it answers (``/cluster/status``); the
defaults below cover the time it doesn't. PBS isn't a cluster node but is watched too.
"""
from dataclasses import dataclass, field
from typing import Dict, Iterable, List, Optional
@dataclass
class Host:
name: str
ip: str
cluster_node: bool = True
# Hosts running Ceph OSDs: trouble on them can stall storage for the whole cluster.
ceph_osds: bool = False
aliases: List[str] = field(default_factory=list)
DEFAULT_HOSTS = [
Host('compute-storage-01', '10.10.10.4', ceph_osds=True),
Host('compute-storage-02', '10.10.10.2', ceph_osds=True, aliases=['large1']),
Host('compute-storage-gpu-01', '10.10.10.10', ceph_osds=True),
Host('storage-01', '10.10.10.11', ceph_osds=True),
Host('monitor-01', '10.10.10.8', aliases=['micro1']),
Host('monitor-02', '10.10.10.9'),
Host('pbs', '10.10.10.3', cluster_node=False),
]
class HostRegistry:
def __init__(self, hosts: Iterable[Host] = DEFAULT_HOSTS):
self._hosts: Dict[str, Host] = {}
for h in hosts:
self._hosts[h.name] = Host(h.name, h.ip, h.cluster_node, h.ceph_osds, list(h.aliases))
def all(self) -> List[Host]:
return sorted(self._hosts.values(), key=lambda h: h.name)
def get(self, name: str) -> Optional[Host]:
return self._hosts.get(self.canonical(name) or '')
def canonical(self, name: str) -> Optional[str]:
"""The current name for a host name or old alias, or None if not watched."""
if name in self._hosts:
return name
for h in self._hosts.values():
if name in h.aliases:
return h.name
return None
def by_instance(self, instance: str) -> Optional[str]:
"""Host for a Prometheus ``instance`` like ``10.10.10.4:9100``."""
ip = instance.rsplit(':', 1)[0].strip('[]')
for h in self._hosts.values():
if h.ip == ip:
return h.name
return None
def loki_names(self, name: str) -> List[str]:
"""Every name a host's journal lines may carry in Loki (current first)."""
h = self.get(name)
return [h.name] + h.aliases if h else [name]
def update_from_proxmox(self, cluster_status: List[dict]) -> None:
"""Pick up node renames, IP changes and new nodes from ``/cluster/status``."""
for entry in cluster_status:
if entry.get('type') != 'node' or not entry.get('name') or not entry.get('ip'):
continue
name, ip = entry['name'], entry['ip']
existing = self._hosts.get(name)
if existing:
existing.ip = ip
continue
# Same IP under a new name: a rename. Keep the old name as an alias.
for old in list(self._hosts.values()):
if old.ip == ip and old.cluster_node:
del self._hosts[old.name]
self._hosts[name] = Host(name, ip, True, old.ceph_osds, old.aliases + [old.name])
break
else:
self._hosts[name] = Host(name, ip, True)
+95
View File
@@ -0,0 +1,95 @@
"""Findings, incidents and ticket actions.
A check turns source data into **findings**. A finding is either a **cause** (something that
can own a ticket: a host out of memory) or a **symptom** (something that is usually the
result of a cause: scrapes timing out, a new Ceph alert). The engine groups findings into
**incidents**, one per root cause, keyed by the incident key that becomes the Tinker
``dedup_key`` (``scope:subject:kind``, thor#1 contract).
"""
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
# Cause precedence (thor#1, Area 4): when several causes are active, symptoms attach to the
# highest. Maintenance, power, network and partitions arrive with later checks.
LAYER_MAINTENANCE = 90
LAYER_POWER = 80
LAYER_NETWORK = 70
LAYER_PARTITION = 60
LAYER_HOST_DOWN = 50
LAYER_RESOURCE = 40
LAYER_CEPH = 30
LAYER_SCRAPE = 20
CAUSE = 'cause'
SYMPTOM = 'symptom'
NOTE = 'note' # shown in Thor, never a ticket and never attached (e.g. a container's own OOM)
# Incident states
PENDING = 'pending' # seen, held one cycle so same-moment symptoms land in the first text
OPEN = 'open'
CLEARED = 'cleared'
@dataclass
class Finding:
kind: str
subject: str # canonical host name, or 'cluster'
role: str # CAUSE, SYMPTOM or NOTE
layer: int
start: float
end: float
key: str # incident key for a cause; a stable symptom key otherwise
summary: str
priority: int = 3
check: str = ''
facts: Dict[str, Any] = field(default_factory=dict)
events: List[Dict[str, Any]] = field(default_factory=list) # dated items, deduplicated by 'id'
cluster_effect: bool = False # a symptom that can come from trouble on another host
def to_dict(self) -> Dict[str, Any]:
return dict(self.__dict__)
@dataclass
class Incident:
key: str
kind: str
subject: str
layer: int
check: str
state: str = PENDING
priority: int = 3
first_seen: float = 0.0
last_seen: float = 0.0
pending_since: float = 0.0
opened_at: Optional[float] = None
cleared_at: Optional[float] = None
summary: str = ''
facts: Dict[str, Any] = field(default_factory=dict)
events: List[Dict[str, Any]] = field(default_factory=list)
symptoms: Dict[str, Dict[str, Any]] = field(default_factory=dict)
ticket_id: Optional[str] = None
mode: str = 'shadow'
seen_after_the_fact: bool = False
@property
def active(self) -> bool:
return self.state in (PENDING, OPEN)
def to_dict(self) -> Dict[str, Any]:
return dict(self.__dict__)
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> 'Incident':
known = {k: v for k, v in d.items() if k in cls.__dataclass_fields__}
return cls(**known)
@dataclass
class Action:
"""Something to tell Tinker. In shadow mode it is recorded and never sent."""
incident_key: str
kind: str # 'open', 'escalate', 'refresh', 'also_seen', 'cleared'
created: float
mode: str # 'shadow' or 'live'
payload: Dict[str, Any] = field(default_factory=dict)
+56 -9
View File
@@ -17,17 +17,26 @@ from dataclasses import dataclass, field
from typing import Callable, Dict, List, Optional, Protocol, Tuple from typing import Callable, Dict, List, Optional, Protocol, Tuple
from . import config as config_mod from . import config as config_mod
from .checks import NeedsSource
from .clients import SourceError from .clients import SourceError
from .clients.gandalf import GandalfClient from .clients.gandalf import GandalfClient
from .clients.loki import LokiClient from .clients.loki import LokiClient
from .clients.prometheus import PrometheusClient from .clients.prometheus import PrometheusClient
from .clients.proxmox import ProxmoxClient from .clients.proxmox import ProxmoxClient
from .clients.tinker import TinkerClient
from .db import Database, DatabaseError, Store from .db import Database, DatabaseError, Store
from .engine import Engine
from .hosts import HostRegistry
from .model import Finding
from .outbox import Outbox
logger = logging.getLogger('thor.monitor') logger = logging.getLogger('thor.monitor')
# Writes kept while the database is away. A cycle produces a handful, so this is days. # Writes kept while the database is away. A quiet cycle produces a handful; an incident adds
MAX_PENDING_WRITES = 5000 # a few dozen, so this is roughly a day.
MAX_PENDING_WRITES = 20000
# How far back incidents are reloaded on start, so a recurrence finds its old record.
INCIDENT_RELOAD_S = 7 * 86400
class Source(Protocol): class Source(Protocol):
@@ -53,12 +62,13 @@ class CycleContext:
catching_up: bool catching_up: bool
sources: Dict[str, Source] sources: Dict[str, Source]
up: Dict[str, bool] up: Dict[str, bool]
hosts: HostRegistry = field(default_factory=HostRegistry)
class Check(Protocol): class Check(Protocol):
name: str name: str
def run(self, ctx: CycleContext) -> List[dict]: ... def run(self, ctx: CycleContext) -> List[Finding]: ...
@dataclass @dataclass
@@ -76,13 +86,17 @@ class CycleResult:
class Monitor: class Monitor:
def __init__(self, settings: config_mod.Settings, store: Store, sources: Dict[str, Source], def __init__(self, settings: config_mod.Settings, store: Store, sources: Dict[str, Source],
checks: Optional[List[Check]] = None, clock: Callable[[], float] = time.time, checks: Optional[List[Check]] = None, clock: Callable[[], float] = time.time,
prepare: Optional[Callable[[], object]] = None): prepare: Optional[Callable[[], object]] = None, hosts: Optional[HostRegistry] = None,
outbox: Optional[Outbox] = None):
self.settings = settings self.settings = settings
self.prepare = prepare self.prepare = prepare
self.store = store self.store = store
self.sources = sources self.sources = sources
self.checks = checks or [] self.checks = checks or []
self.clock = clock self.clock = clock
self.hosts = hosts or HostRegistry()
self.outbox = outbox
self.engine = Engine(settings, self.hosts, {c.name: c for c in self.checks}, self._write)
self.source_state: Dict[str, SourceState] = {name: SourceState() for name in sources} self.source_state: Dict[str, SourceState] = {name: SourceState() for name in sources}
self.pending: List[Tuple[str, tuple, dict]] = [] self.pending: List[Tuple[str, tuple, dict]] = []
self.last_good_end: Optional[float] = None self.last_good_end: Optional[float] = None
@@ -118,6 +132,7 @@ class Monitor:
self.prepare() # schema migrations self.prepare() # schema migrations
end = self.store.get_state('last_good_window_end') end = self.store.get_state('last_good_window_end')
statuses = self.store.source_statuses() statuses = self.store.source_statuses()
incidents = self.store.load_incidents(self.clock() - INCIDENT_RELOAD_S)
except DatabaseError as e: except DatabaseError as e:
logger.warning('Could not load previous state yet: %s', e) logger.warning('Could not load previous state yet: %s', e)
return return
@@ -130,6 +145,7 @@ class Monitor:
self.source_state[name] = SourceState(up=st['up'], since=st['since'] or 0.0, self.source_state[name] = SourceState(up=st['up'], since=st['since'] or 0.0,
last_ok=st['last_ok'], last_error=st['last_error'], last_ok=st['last_ok'], last_error=st['last_error'],
known=True) known=True)
self.engine.load(incidents)
self._loaded = True self._loaded = True
# -- sources ------------------------------------------------------------ # -- sources ------------------------------------------------------------
@@ -162,6 +178,15 @@ class Monitor:
up[name] = ok up[name] = ok
return up return up
def _refresh_hosts(self, up: Dict[str, bool]) -> None:
px = self.sources.get('proxmox')
if px is None or not up.get('proxmox') or not hasattr(px, 'cluster_status'):
return
try:
self.hosts.update_from_proxmox(px.cluster_status())
except SourceError as e:
logger.warning('Could not refresh the node list: %s', e.message)
# -- the cycle ------------------------------------------------------------ # -- the cycle ------------------------------------------------------------
def window(self, now: float) -> Tuple[float, float, bool]: def window(self, now: float) -> Tuple[float, float, bool]:
"""(start, end, catching_up) for this cycle.""" """(start, end, catching_up) for this cycle."""
@@ -182,14 +207,26 @@ class Monitor:
start, end, catching_up = self.window(started) start, end, catching_up = self.window(started)
up = self.check_sources(started) up = self.check_sources(started)
blind = [n for n, ok in up.items() if not ok] blind = [n for n, ok in up.items() if not ok]
ctx = CycleContext(start, end, catching_up, self.sources, up) self._refresh_hosts(up)
findings, errors = 0, [] ctx = CycleContext(start, end, catching_up, self.sources, up, self.hosts)
found: List[Finding] = []
errors = []
for check in self.checks: for check in self.checks:
try: try:
findings += len(check.run(ctx) or []) found += list(check.run(ctx) or [])
except NeedsSource as e:
# Not a bug: the source is blind. Keep the window so it's reviewed once it answers.
logger.warning('Check %s waits: %s', check.name, e)
errors.append(f'{check.name}: {e}')
except Exception as e: except Exception as e:
logger.exception('Check %s failed', check.name) logger.exception('Check %s failed', check.name)
errors.append(f'{check.name}: {type(e).__name__}: {e}') errors.append(f'{check.name}: {type(e).__name__}: {e}')
if self._loaded:
self.engine.process(found, started, catching_up)
else:
# Without the stored incidents the engine would open duplicates; review again later.
errors.append('engine: waiting for the database to load stored incidents')
findings = len(found)
finished = self.clock() finished = self.clock()
# A cycle is good when it ran; blind sources don't make it bad (they're recorded). # 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. # A failing check does, so its window is reviewed again next cycle.
@@ -205,7 +242,8 @@ class Monitor:
self.last_good_end = end self.last_good_end = end
self._write('set_state', 'last_good_window_end', end, finished) self._write('set_state', 'last_good_window_end', end, finished)
self._write('set_state', 'last_good_cycle', finished, finished) self._write('set_state', 'last_good_cycle', finished, finished)
self.flush() if self.flush() and self.outbox is not None:
self.outbox.flush(finished)
return result return result
def run_forever(self) -> None: def run_forever(self) -> None:
@@ -237,11 +275,20 @@ def build_sources(s: config_mod.Settings) -> Dict[str, Source]:
} }
def build_checks() -> List[Check]:
from .checks.memory import MemoryCheck
from .checks.symptoms import CephAlertCheck, PvestatdCheck, ScrapeCheck
return [MemoryCheck(), ScrapeCheck(), PvestatdCheck(), CephAlertCheck()]
def main() -> None: # pragma: no cover - process entry point def main() -> None: # pragma: no cover - process entry point
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s: %(message)s') logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(name)s: %(message)s')
settings = config_mod.load() settings = config_mod.load()
db = Database(settings.database) db = Database(settings.database)
monitor = Monitor(settings, Store(db), build_sources(settings), prepare=db.migrate) store = Store(db)
outbox = Outbox(store, TinkerClient(settings.tinker_url, settings.tinker_api_key))
monitor = Monitor(settings, store, build_sources(settings), checks=build_checks(), prepare=db.migrate,
outbox=outbox)
signal.signal(signal.SIGTERM, monitor.stop) signal.signal(signal.SIGTERM, monitor.stop)
signal.signal(signal.SIGINT, monitor.stop) signal.signal(signal.SIGINT, monitor.stop)
monitor.run_forever() monitor.run_forever()
+63
View File
@@ -0,0 +1,63 @@
"""Sends live ticket actions to Tinker, with retries. Shadow actions never get here.
No check is live before tinker_tickets#123 ships (thor#1), so in phase 1 this mostly waits.
An action that can't be sent stays pending and is retried with backoff; Tinker being down
(it lives on CT 132 and the same MariaDB) never loses an action.
"""
import logging
from typing import Optional
from .clients.tinker import TinkerClient, backoff_s
from .db import DatabaseError
logger = logging.getLogger('thor.outbox')
MAX_ATTEMPTS = 30
CREATE_KINDS = ('open', 'escalate', 'refresh')
COMMENT_KINDS = ('also_seen', 'cleared')
class Outbox:
def __init__(self, store, tinker: TinkerClient):
self.store = store
self.tinker = tinker
def flush(self, now: float) -> int:
"""Send what's due. Returns how many actions were sent."""
if not self.tinker.configured:
return 0
try:
due = self.store.due_actions(now)
except DatabaseError:
return 0
sent = 0
for a in due:
ok, ticket_id, error = self._send(a)
try:
if ok:
self.store.mark_action_sent(a['id'], ticket_id, now)
sent += 1
else:
attempts = int(a['attempts']) + 1
retry_at: Optional[float] = now + backoff_s(attempts) if attempts < MAX_ATTEMPTS else None
self.store.mark_action_failed(a['id'], error, attempts, retry_at)
logger.warning('Action %s (%s %s) not sent: %s', a['id'], a['kind'], a['incident_key'], error)
except DatabaseError:
break
return sent
def _send(self, a):
p = a['payload']
if a['kind'] in CREATE_KINDS:
r = self.tinker.create(title=p['title'], description=p['description'], priority=p['priority'],
category=p['category'], ticket_type=p.get('type', 'Issue'),
dedup_key=p['dedup_key'])
if r.ok and a['kind'] == 'escalate' and p.get('comment'):
self.tinker.comment(r.ticket_id, p['comment'])
return r.ok, r.ticket_id, r.error
if a['kind'] in COMMENT_KINDS:
ticket_id = self.store.incident_ticket(a['incident_key'])
if not ticket_id:
return False, None, 'no ticket yet for this incident (its open action is not sent)'
ok = self.tinker.comment(ticket_id, p['comment'])
return ok, ticket_id, '' if ok else 'comment failed'
return False, None, f'unknown action kind {a["kind"]}'
+118
View File
@@ -0,0 +1,118 @@
"""Markdown for the tickets and notes Thor sends to Tinker.
Pure formatting: the engine passes the facts in. ``duration`` and ``utc`` are lifted from
Gandalf's ``ticket_text.py`` (LotusGuild/gandalf@1c250d6). Titles follow the standard on
the wiki (thor#1): ``[source][auto][thor][area] Summary [scope][production][type]``.
"""
from datetime import datetime, timezone
from typing import Dict, Iterable, List, Optional
from .model import Incident
AREA_BY_KIND = {'oom': 'software', 'oom_cgroup': 'software'}
CATEGORY_BY_AREA = {'software': 'Software', 'hardware': 'Hardware', 'network': 'Network', 'ceph': 'Software'}
PRIORITY_LABEL = {1: 'P1 Critical', 2: 'P2 High', 3: 'P3 Medium', 4: 'P4 Low', 5: 'P5 Minimal'}
def duration(seconds) -> str:
seconds = max(0, int(seconds))
if seconds < 60:
return f'{seconds} s'
minutes = seconds // 60
if minutes < 60:
return f'{minutes} min'
hours, minutes = divmod(minutes, 60)
if hours < 48:
return f'{hours} h {minutes} min' if minutes else f'{hours} h'
days, hours = divmod(hours, 24)
return f'{days} d {hours} h' if hours else f'{days} d'
def utc(ts: Optional[float], with_date: bool = True) -> str:
if ts is None:
return 'unknown'
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
return dt.strftime('%Y-%m-%d %H:%M:%S UTC' if with_date else '%H:%M:%S')
def area(inc: Incident) -> str:
return AREA_BY_KIND.get(inc.kind, 'software')
def category(inc: Incident) -> str:
return CATEGORY_BY_AREA.get(area(inc), 'Software')
def title(inc: Incident) -> str:
source = inc.subject if inc.subject != 'cluster' else 'proxmox-cluster'
scope = 'cluster-wide' if inc.subject == 'cluster' else 'single-node'
return f'[{source}][auto][thor][{area(inc)}] {inc.summary} [{scope}][production][issue]'
def _events_lines(inc: Incident, limit: int = 15) -> List[str]:
events = sorted(inc.events, key=lambda e: e.get('at', 0))
lines = [f'- {utc(e.get("at"), with_date=False)}: {e.get("text", "")}' for e in events[-limit:]]
if len(events) > limit:
lines.insert(0, f'- ({len(events) - limit} earlier, see Thor)')
return lines
def symptom_lines(symptoms: Dict[str, Dict]) -> List[str]:
out = []
for s in sorted(symptoms.values(), key=lambda s: s.get('first', 0)):
span = utc(s.get('first'), with_date=False)
if s.get('last') and s['last'] - s.get('first', s['last']) >= 60:
span += f' to {utc(s["last"], with_date=False)}'
out.append(f'- {span}: {s.get("summary", "")}')
return out
def description(inc: Incident, public_url: str = '', related: Iterable[str] = ()) -> str:
lines = [f'## {inc.summary}', '']
lines.append(f'- **First seen:** {utc(inc.first_seen)}')
lines.append(f'- **Last seen:** {utc(inc.last_seen)}')
lines.append(f'- **Priority:** {PRIORITY_LABEL.get(inc.priority, inc.priority)}')
if inc.facts.get('escalation_reason') and inc.priority < 3:
lines.append(f'- **Why this priority:** {inc.facts["escalation_reason"]}')
for key, value in (inc.facts.get('display') or {}).items():
lines.append(f'- **{key}:** {value}')
if inc.seen_after_the_fact:
lines += ['', '_Seen after the fact: Thor was away or blind while this happened and found it '
'when it caught up._']
if inc.events:
lines += ['', '### What happened'] + _events_lines(inc)
if inc.symptoms:
lines += ['', '### Also seen in this incident'] + symptom_lines(inc.symptoms)
related = list(related)
if related:
lines += ['', '### Related open tickets'] + [f'- #{t}' for t in related]
checks = inc.facts.get('checks') or []
if checks:
lines += ['', '### What to check'] + [f'{n}. {c}' for n, c in enumerate(checks, 1)]
if public_url:
lines += ['', f'- [Thor]({public_url}/incident/{inc.key})']
lines += ['', '_Opened automatically by Thor (thor#1). It adds a note here when the problem clears, '
'but leaves closing the ticket to you._']
return '\n'.join(lines)
def also_seen_comment(summary: str, first: float) -> str:
return '\n'.join([f'**Also seen: {summary}** ({utc(first)})', '',
'_Thor added this here instead of opening another ticket, since it is part of the '
'same incident._'])
def escalation_comment(old: int, new: int, reason: str) -> str:
change = f'{PRIORITY_LABEL.get(old, old)} to {PRIORITY_LABEL.get(new, new)}'
return '\n'.join([f'**Thor raised the priority: {change}.**', '', reason])
def cleared_comment(inc: Incident) -> str:
lasted = (inc.last_seen - inc.first_seen) if inc.last_seen and inc.first_seen else 0
lines = [f'**Cleared**: {inc.summary}.', '',
f'- **Last seen:** {utc(inc.last_seen)}',
f'- **Lasted:** {duration(lasted)} (first seen {utc(inc.first_seen)})']
if inc.symptoms:
lines.append(f'- **Also seen:** {len(inc.symptoms)} related symptom(s), listed above')
lines += ['', '_Thor leaves this ticket open. Close it once you know why it happened._']
return '\n'.join(lines)
+3 -2
View File
@@ -5,7 +5,8 @@ database answers and the monitor loop finished a good cycle recently (like Ganda
``health()``), and it reports the commit it runs so a deploy can confirm itself. ``health()``), and it reports the commit it runs so a deploy can confirm itself.
""" """
import os import os
import subprocess # nosec B404 - fixed git command, no user input # subprocess runs one fixed git command with no user input.
import subprocess # nosec B404
import time import time
from typing import Callable, Optional from typing import Callable, Optional
@@ -22,7 +23,7 @@ def detect_version(root: Optional[str] = None) -> str:
return sha return sha
root = root or os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) root = root or os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
try: try:
out = subprocess.run(['git', '-C', root, 'rev-parse', 'HEAD'], capture_output=True, # nosec B603 B607 out = subprocess.run(['git', '-C', root, 'rev-parse', 'HEAD'], capture_output=True, # nosec B603,B607
text=True, timeout=5, check=True) text=True, timeout=5, check=True)
return out.stdout.strip() or 'unknown' return out.stdout.strip() or 'unknown'
except (OSError, subprocess.SubprocessError): except (OSError, subprocess.SubprocessError):