Phase 1, PR 3: reboots (#4), fencing and partitions, maintenance, known conditions, and the T2 to T4 replays #7

Merged
jared merged 1 commits from reboots into main 2026-11-25 23:21:41 -05:00
21 changed files with 954 additions and 31920 deletions

No files matched your search

+74 -29
View File
@@ -1,13 +1,13 @@
#!/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
Usage: .venv/bin/python scripts/record_fixture.py t1 [t2 t3 t4 dimm]
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.
Each fixture holds the raw series and log lines Thor's checks query, for the 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 to host/job/unit/transport, Ceph alert series that never switched on are
dropped, and journal lines used only to see *when* a host last logged keep no text.
"""
import json
import sys
@@ -16,7 +16,7 @@ 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.checks import cluster, counter_rises, memory, reboots, 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
@@ -24,49 +24,94 @@ 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')
STEP = 30
T2_SUPPRESSION = {'id': 2, 'target_type': 'all', 'target_name': '', 'reason': 'switch update',
'started_at': '2026-11-25T03:11:39Z', 'ended_at': '2026-11-25T03:41:39Z',
'started_by': 'jared', 'ended_by': 'expired'}
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'],
'start': 1795410000.0, 'end': 1795416000.0, # 05:00 to 06:40 UTC
# 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'}],
},
't2': {
'title': '2026-11-25 planned rack maintenance (switch and UPS firmware), thor#4',
'start': 1795575300.0, 'end': 1795579800.0, # 02:55 to 04:10 UTC
# Prometheus has no samples 03:16:30 to 03:38. Loki, Gandalf and Thor itself live on
# the same rack and are assumed dark for the same stretch.
'blind': {s: [[1795576590.0, 1795577880.0]] for s in ('prometheus', 'loki', 'gandalf', 'proxmox')},
'thor_down': [[1795576590.0, 1795577940.0]],
'suppressions': [T2_SUPPRESSION],
},
't3': {
'title': '2026-10-27 compute-storage-01 lost its only corosync link and was fenced',
'start': 1793115600.0, 'end': 1793132100.0, # 15:40 to 20:15 UTC
},
't4': {
'title': '2026-11-04 corosync partition: three nodes fenced',
'start': 1793824800.0, 'end': 1793832000.0, # 20:40 to 22:40 UTC
},
'dimm': {
'title': '2026-11-21 compute-storage-02 reboot from its failing DIMM (Tinker 693930698)',
'start': 1795230600.0, 'end': 1795234200.0, # 03:10 to 04:10 UTC
},
}
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())
hosts = HostRegistry()
start, end = spec['start'] - reboots.LOOKBACK_S - 600, spec['end'] + 600
prom, loki = PrometheusClient(PROM, timeout=120), LokiClient(LOKI, timeout=120)
exprs = [memory.COUNTER_QUERY, symptoms.CEPH_QUERY, reboots.boot_query(hosts)]
exprs += 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', []),
'blind': spec.get('blind', {}), 'thor_down': spec.get('thor_down', []),
'guests': spec.get('guests', []), 'suppressions': spec.get('suppressions', []),
'prometheus': {}, 'loki': {}}
for expr in exprs:
series = prom.query_range(expr, start, end, 30)
series = prom.query_range(expr, start, end, STEP)
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]
def grab(q, a, b, keep_text=True):
lines, t = [], a
while t < b: # hour by hour, so no window hits the line limit
for ts, line, labels in loki.lines(q, t, min(t + 3600, b), limit=5000, direction='forward'):
lines.append([ts, line if keep_text else '', {k: v for k, v in labels.items() if k in KEEP_LABELS}])
t += 3600
out['loki'][q] = lines
return lines
w0, w1 = spec['start'] - 600, end
for q in (symptoms.PVESTATD_QUERY, cluster.CRM_QUERY, cluster.WATCHDOG_QUERY, cluster.COROSYNC_QUERY):
out['loki'][q] = grab(q, w0, w1)
for s in out['prometheus'][memory.COUNTER_QUERY]:
host = hosts.by_instance(s['metric'].get('instance', ''))
if host and counter_rises(s['values'], spec['start']):
out['loki'][memory.kernel_query(hosts.loki_names(host))] = grab(
memory.kernel_query(hosts.loki_names(host)), w0, w1)
for s in out['prometheus'][reboots.boot_query(hosts)]:
host = hosts.by_instance(s['metric'].get('instance', ''))
for r in reboots.find_reboots(s['values'], spec['start']) if host else []:
names = hosts.loki_names(host)
q = reboots.logind_query(names)
out['loki'].setdefault(q, []).extend(grab(q, r['down_from'] - 900, r['boot'] + 60))
q = reboots.journal_query(names)
# The check only asks for the last line before the boot, so the last few are enough.
out['loki'].setdefault(q, []).extend(grab(q, r['down_from'] - 900, r['boot'], keep_text=False)[-50:])
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')
for name in sys.argv[1:]:
data = record(name)
path = ROOT / 'tests' / 'fixtures' / f'{name}.json'
path.write_text(json.dumps(data, sort_keys=True, separators=(',', ':')) + '\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, {path.stat().st_size // 1024} KB')
+12
View File
@@ -21,6 +21,10 @@ class FakeStore:
self.incidents: Dict[str, dict] = {}
self.actions: List[dict] = []
self.observations: Dict[str, dict] = {}
self.known: List[dict] = [
{'id': 1, 'kind': 'reboot', 'subject': 'compute-storage-02', 'ticket_id': '693930698',
'reason': 'compute-storage-02 reboots every 2 to 3 days from a failing DIMM.'},
]
def _check(self, name):
self.calls.append(name)
@@ -110,6 +114,14 @@ class FakeStore:
else:
self.observations[f['key']] = json.loads(json.dumps(f, default=str))
def delete_incident(self, key):
self._check('delete_incident')
self.incidents.pop(key, None)
def known_conditions(self):
self._check('known_conditions')
return [dict(k) for k in self.known if not k.get('ended')]
def blind_periods(self, since):
self._check('blind_periods')
return [b for b in self.blind if b['ended'] is None or b['ended'] >= since]
+1
View File
@@ -0,0 +1 @@
{"blind":{},"end":1795234200.0,"guests":[],"loki":{"{job=\"journal\", host=~\"compute\\\\-storage\\\\-02|large1\", unit=\"systemd-logind.service\"} |~ \"will (reboot|power off|halt|kexec) now\"":[],"{job=\"journal\", host=~\"compute\\\\-storage\\\\-02|large1\"}":[[1795231250.748729,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231250.748864,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231250.75181,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231250.75194,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231250.7520692,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231250.7521658,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231250.752228,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231250.75232,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231250.752386,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"init.scope"}],[1795231250.753731,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"init.scope"}],[1795231250.7792718,"",{"host":"compute-storage-02","job":"journal","transport":"kernel"}],[1795231250.7831838,"",{"host":"compute-storage-02","job":"journal","transport":"syslog","unit":"session.scope"}],[1795231250.783621,"",{"host":"compute-storage-02","job":"journal","transport":"syslog","unit":"session.scope"}],[1795231250.7841501,"",{"host":"compute-storage-02","job":"journal","transport":"syslog","unit":"ssh.service"}],[1795231250.786763,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"init.scope"}],[1795231250.788361,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"systemd-logind.service"}],[1795231250.789092,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"systemd-logind.service"}],[1795231260.934769,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"init.scope"}],[1795231260.935585,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.9358919,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.935981,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.936044,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.936102,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.936162,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.936321,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.936411,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.936505,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.9365828,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.9371772,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.937672,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.93778,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231260.938247,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231261.031942,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231261.0333838,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231261.0339048,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231261.0358589,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231261.035983,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231261.036078,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231261.036135,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"user@0.service"}],[1795231261.064689,"",{"host":"compute-storage-02","job":"journal","transport":"journal","unit":"systemd-logind.service"}],[1795231261.064944,"",{"host":"compute-storage-02","job":"journal","transport":"syslog","unit":"user@0.service"}],[1795231261.0662441,"",{"host":"computeLine truncated
+1 -31855
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
{"blind":{"gandalf":[[1795576590.0,1795577880.0]],"loki":[[1795576590.0,1795577880.0]],"prometheus":[[1795576590.0,1795577880.0]],"proxmox":[[1795576590.0,1795577880.0]]},"end":1795579800.0,"guests":[],"loki":{"{job=\"journal\", host=~\"compute\\\\-storage\\\\-01\", unit=\"systemd-logind.service\"} |~ \"will (reboot|power off|halt|kexec) now\"":[[1795576898.2785769,"The system will power off now!",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"systemd-logind.service"}]],"{job=\"journal\", host=~\"compute\\\\-storage\\\\-01\"}":[[1795576978.4488692,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-crm.service"}],[1795576980.187105,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795576985.1881752,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795576988.3714838,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.3719308,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.3719869,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372033,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372086,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372115,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372143,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.3721752,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372202,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.3722298,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372254,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372281,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372312,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372339,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372363,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372413,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372434,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.3724601,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.372483,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.386993,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.387059,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.3873181,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576988.3873658,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795576990.1893692,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795576995.1905038,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795577000.191815,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795577005.192954,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795577010.194064,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795577015.195106,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795577020.196154,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795577020.896232,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795577020.896553,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795577020.8965912,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795577020.896641,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795577020.896684,"",{"host":"compute-storage-01","job":"journal","transport":"journal","unit":"init.scope"}],[1795577025.19727,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1795577030.19822,"Line truncated
+1
View File
@@ -0,0 +1 @@
{"blind":{},"end":1793132100.0,"guests":[],"loki":{"{job=\"journal\", host=~\"compute\\\\-storage\\\\-01\", unit=\"systemd-logind.service\"} |~ \"will (reboot|power off|halt|kexec) now\"":[],"{job=\"journal\", host=~\"compute\\\\-storage\\\\-01\"}":[[1793116205.479008,"",{"host":"compute-storage-01","job":"journal","unit":"init.scope"}],[1793116205.4805,"",{"host":"compute-storage-01","job":"journal","unit":"systemd-logind.service"}],[1793116209.589037,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116216.5482292,"",{"host":"compute-storage-01","job":"journal","unit":"ceph-osd@7.service"}],[1793116219.252162,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116228.9796999,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116232.98267,"",{"host":"compute-storage-01","job":"journal","unit":"ceph-mgr@compute-storage-01.service"}],[1793116239.53916,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116245.087618,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.10053,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.10053,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.10053,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.100698,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.100698,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.100698,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.100698,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.100698,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.100698,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.100698,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116245.100698,"",{"host":"compute-storage-01","job":"journal","unit":"smartctl-exporter.service"}],[1793116248.821326,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116259.1866891,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116262.982234,"",{"host":"compute-storage-01","job":"journal","unit":"ceph-mgr@compute-storage-01.service"}],[1793116269.426559,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116279.5394938,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116288.367156,"",{"host":"compute-storage-01","job":"journal","unit":"ceph-osd@7.service"}],[1793116289.139137,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116292.982028,"",{"host":"compute-storage-01","job":"journal","unit":"ceph-mgr@compute-storage-01.service"}],[1793116298.67665,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116309.6191082,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116318.707457,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116322.9827,"",{"host":"compute-storage-01","job":"journal","unit":"ceph-mgr@compute-storage-01.service"}],[1793116329.5877042,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116339.122698,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116341.760001,"",{"host":"compute-storage-01","job":"journal","unit":"ssh.service"}],[1793116341.761685,"",{"host":"compute-storage-01","job":"journal","unit":"ssh.service"}],[1793116341.765128,"",{"host":"compute-storage-01","job":"journal","unit":"systemd-logind.service"}],[1793116341.778694,"",{"host":"compute-storage-01","job":"journal","unit":"init.scope"}],[1793116341.886134,"",{"host":"compute-storage-01","job":"journal","unit":"session-32288.scope"}],[1793116341.887172,"",{"host":"compute-storage-01","job":"journal","unit":"session-32288.scope"}],[1793116341.887272,"",{"host":"compute-storage-01","job":"journal","unit":"ssh.service"}],[1793116341.889955,"",{"host":"compute-storage-01","job":"journal","unit":"systemd-logind.service"}],[1793116341.8907,"",{"host":"compute-storage-01","job":"journal","unit":"init.scope"}],[1793116341.891649,"",{"host":"compute-storage-01","job":"journal","unit":"systemd-logind.service"}],[1793116349.554751,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116352.9830248,"",{"host":"compute-storage-01","job":"journal","unit":"ceph-mgr@compute-storage-01.service"}],[1793116358.962752,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.service"}],[1793116369.523223,"",{"host":"compute-storage-01","job":"journal","unit":"pvestatd.sLine truncated
+1
View File
@@ -0,0 +1 @@
{"blind":{},"end":1793832000.0,"guests":[],"loki":{"{job=\"journal\", host=~\"compute\\\\-storage\\\\-01\", unit=\"systemd-logind.service\"} |~ \"will (reboot|power off|halt|kexec) now\"":[],"{job=\"journal\", host=~\"compute\\\\-storage\\\\-01\"}":[[1793825464.821393,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825464.82141,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825464.8214242,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825464.821444,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825464.82146,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825464.821474,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825467.084974,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825481.92764,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825481.9276822,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825481.927799,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825481.927849,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825481.927886,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825481.92792,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"corosync.service"}],[1793825481.931382,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825481.934502,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825481.9345238,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825481.9390762,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825481.939105,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825482.220835,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825482.221645,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825482.2220109,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825482.230598,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1793825482.231528,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-lrm.service"}],[1793825482.242889,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-ha-crm.service"}],[1793825483.951335,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pvestatd.service"}],[1793825484.0730371,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pvestatd.service"}],[1793825484.183027,"",{"host":"compute-storage-01","job":"journal","transport":"stdout","unit":"promtail.service"}],[1793825488.2244549,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825488.2248042,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pve-cluster.service"}],[1793825493.282784,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pvestatd.service"}],[1793825493.3943071,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pvestatd.service"}],[1793825495.082861,"",{"host":"compute-storage-01","job":"journal","transport":"stdout","unit":"promtail.service"}],[1793825500.012836,"",{"host":"compute-storage-01","job":"journal","transport":"kernel"}],[1793825500.01323,"",{"host":"compute-storage-01","job":"journal","transport":"kernel"}],[1793825502.767096,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pvestatd.service"}],[1793825502.79983,"",{"host":"compute-storage-01","job":"journal","transport":"kernel"}],[1793825502.855337,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pvestatd.service"}],[1793825502.905832,"",{"host":"compute-storage-01","job":"journal","transport":"kernel"}],[1793825502.9059,"",{"host":"compute-storage-01","job":"journal","transport":"kernel"}],[1793825506.78284,"",{"host":"compute-storage-01","job":"journal","transport":"stdout","unit":"promtail.service"}],[1793825510.127275,"",{"host":"compute-storage-01","job":"journal","transport":"syslog","unit":"pvestatd.service"}],[1793825513.831062,"",{"host":"compute-storage-01","job":"journal","transport":"stdout"Line truncated
+26 -2
View File
@@ -78,6 +78,27 @@ class ReplayProxmox(_Blindable):
return []
class ReplayGandalf(_Blindable):
"""Suppressions as Gandalf would have shown them at the replay's current time."""
def __init__(self, fixture, clock):
super().__init__('gandalf', fixture, clock)
self.records = fixture.get('suppressions', [])
def suppressions(self, hours=24, include_ended=True):
from thor.checks.maintenance import parse_time
self._guard()
now, out = self.clock.t, []
for r in self.records:
start, end = parse_time(r['started_at']), parse_time(r.get('ended_at'))
if start > now or start < now - hours * 3600 - 86400:
continue
if end is not None and end > now:
r = dict(r, ended_at=None, state='active')
out.append(r)
return out
class Replay:
def __init__(self, name: str, settings: Settings = None):
self.fixture = load(name)
@@ -86,14 +107,17 @@ class Replay:
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)}
'proxmox': ReplayProxmox(self.fixture, self.clock),
'gandalf': ReplayGandalf(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']
down = self.fixture.get('thor_down', [])
while self.clock.t <= until:
self.results.append(self.monitor.cycle())
if not any(s <= self.clock.t <= e for s, e in down): # Thor was dark too: no cycle
self.results.append(self.monitor.cycle())
self.clock.advance(self.settings.cycle_seconds)
return self
+224
View File
@@ -0,0 +1,224 @@
import pytest
from thor.checks import NeedsSource
from thor.checks.cluster import ClusterCheck
from thor.checks.maintenance import MaintenanceCheck, parse_time
from thor.checks.reboots import RebootCheck, find_reboots
from thor.clients import SourceError
from thor.config import Settings
from thor.engine import Engine
from thor.hosts import HostRegistry
from thor.model import (CAUSE, CLEARED, LAYER_HOST_DOWN, LAYER_MAINTENANCE, NOTE, OPEN, SYMPTOM, Finding,
Incident)
from thor.monitor import CycleContext
from .test_checks import FakeProm
T0 = 1_793_116_000.0
class RoutedLoki:
"""Answers each LogQL query from its own list (matched by a substring)."""
def __init__(self, routes, error=None):
self.routes = routes
self.error = error
def lines(self, logql, start, end, limit=100, direction='backward'):
if self.error:
raise self.error
for needle, lines in self.routes.items():
if needle in logql:
out = sorted((x for x in lines if start <= x[0] <= end), key=lambda x: x[0],
reverse=direction != 'forward')
return out[:limit]
return []
class FakeGandalf:
def __init__(self, sups, error=None):
self.sups, self.error = sups, error
def suppressions(self, hours=24, include_ended=True):
if self.error:
raise self.error
return self.sups
def ctx(prom=None, loki=None, gandalf=None, up=None, start=T0, end=T0 + 300):
up = up or {'prometheus': True, 'loki': True, 'gandalf': True}
return CycleContext(start, end, False, {'prometheus': prom, 'loki': loki, 'gandalf': gandalf}, up, HostRegistry())
def boot_series(boot_old, boot_new, seen):
return {'node_boot_time_seconds': [{'metric': {'instance': '10.10.10.4:9100'},
'values': [(T0 - 60, boot_old), (T0 + 10, boot_old), (seen, boot_new)]}]}
# -- reboots ----------------------------------------------------------------------
def test_find_reboots():
assert find_reboots([(0, 100), (30, 100), (90, 5000)], after=10) == [{'boot': 5000, 'seen': 90, 'down_from': 30}]
assert find_reboots([(0, 100), (30, 130)], after=0) == [] # jitter, not a reboot
def test_reboot_planned_unexpected_and_unknown():
prom = FakeProm(boot_series(1000, T0 + 100, T0 + 200))
planned = RoutedLoki({'systemd-logind': [(T0 + 5, 'The system will reboot now!', {})]})
f = RebootCheck().run(ctx(prom, planned))
assert [(x.role, x.kind) for x in f] == [(NOTE, 'reboot_planned')]
unexpected = RoutedLoki({'host=~': [(T0 + 5, '', {})]})
f = RebootCheck().run(ctx(prom, unexpected))
assert (f[0].role, f[0].priority, f[0].summary) == (CAUSE, 3, 'Unexpected reboot of compute-storage-01')
quiet = RoutedLoki({'host=~': [(T0 - 1000, '', {})]})
f = RebootCheck().run(ctx(prom, quiet))
assert f[0].priority == 4 and 'journal went quiet' in f[0].summary and f[0].facts['journal_quiet']
def test_reboots_of_several_hosts_together_are_one_event():
series = {'node_boot_time_seconds': [
{'metric': {'instance': ip}, 'values': [(T0 - 60, 1000), (T0 + 200, T0 + 100)]}
for ip in ('10.10.10.4:9100', '10.10.10.11:9100')]}
found = RebootCheck().run(ctx(FakeProm(series), RoutedLoki({'host=~': [(T0 - 50, '', {})]})))
group = [f for f in found if f.kind == 'reboots']
assert len(group) == 1 and group[0].layer == LAYER_HOST_DOWN + 1
assert group[0].summary == '2 hosts rebooted at once: compute-storage-01, storage-01'
def test_reboot_check_needs_sources():
with pytest.raises(NeedsSource):
RebootCheck().run(ctx(up={'prometheus': False}))
with pytest.raises(NeedsSource):
RebootCheck().run(ctx(FakeProm(SourceError('prometheus', 'x'))))
prom = FakeProm(boot_series(1000, T0 + 100, T0 + 200))
with pytest.raises(NeedsSource, match='loki'):
RebootCheck().run(ctx(prom, up={'prometheus': True, 'loki': False}))
with pytest.raises(NeedsSource, match='loki'):
RebootCheck().run(ctx(prom, RoutedLoki({}, error=SourceError('loki', '500'))))
assert RebootCheck().run(ctx(FakeProm({}), None)) == []
# -- cluster ----------------------------------------------------------------------
def cluster_loki(crm=(), wd=(), coro=()):
return RoutedLoki({'pve-ha-crm': list(crm), 'watchdog-mux': list(wd), 'corosync': list(coro)})
def test_single_fence_is_a_host_incident():
loki = cluster_loki(crm=[(T0 + 10, "node 'compute-storage-01': state changed from 'unknown' => 'fence'", {})],
coro=[(T0 + 5, '[KNET ] link: host: 6 link: 0 is down', {'host': 'storage-01'})])
f = ClusterCheck().run(ctx(loki=loki))
assert len(f) == 1 and f[0].kind == 'fenced' and f[0].key == 'host:compute-storage-01:fenced'
assert f[0].priority == 2 and f[0].cluster_effect
assert f[0].facts['display']['Corosync links reported down'] == '1'
def test_two_nodes_out_is_a_partition_with_old_names_mapped():
loki = cluster_loki(
wd=[(T0 + 30, 'client watchdog expired - disable watchdog updates', {'host': 'compute-storage-01'})],
coro=[(T0 + 20, '[QUORUM] This node is within the non-primary component', {'host': 'micro1'}),
(T0 + 21, '[QUORUM] This node is within the non-primary component', {'host': 'nobody'})])
f = ClusterCheck().run(ctx(loki=loki))
assert len(f) == 1 and f[0].kind == 'partition' and f[0].priority == 1
assert f[0].summary == 'Cluster partition: compute-storage-01, monitor-01 fenced or out of quorum'
def test_cluster_check_quiet_and_blind():
assert ClusterCheck().run(ctx(loki=cluster_loki())) == []
with pytest.raises(NeedsSource):
ClusterCheck().run(ctx(up={'loki': False}))
with pytest.raises(NeedsSource):
ClusterCheck().run(ctx(loki=RoutedLoki({}, error=SourceError('loki', 'x'))))
def test_cluster_rules():
c = ClusterCheck()
inc = Incident(key='k', kind='partition', subject='cluster', layer=60, check='cluster',
events=[{'host': 'b'}, {'host': 'a'}, {'host': 'a'}])
assert c.summarize(inc) == 'Cluster partition: a, b fenced or out of quorum' and c.priority(inc) == 1
inc.kind, inc.summary = 'fenced', 'x'
assert c.summarize(inc) == 'x' and c.priority(inc) == 2
# -- maintenance ------------------------------------------------------------------
SUP = {'id': 2, 'target_type': 'all', 'target_name': '', 'reason': 'switch update', 'started_by': 'jared',
'started_at': '2026-10-27T15:50:00Z', 'ended_at': '2026-10-27T16:20:00Z'}
def test_maintenance_from_gandalf():
sups = [SUP, dict(SUP, id=3, target_type='host', target_name='large1', ended_at=None),
dict(SUP, id=4, target_type='interface'), dict(SUP, id=5, started_at='garbage'),
dict(SUP, id=6, target_type='host', target_name='unknown-host'),
dict(SUP, id=7, started_at='2026-10-20T00:00:00Z', ended_at='2026-10-20T01:00:00Z')]
found = {f.key: f for f in MaintenanceCheck().run(ctx(gandalf=FakeGandalf(sups)))}
assert set(found) == {'maintenance:gandalf:2', 'maintenance:gandalf:3'}
m = found['maintenance:gandalf:2']
assert m.ticket is False and m.layer == LAYER_MAINTENANCE and m.subject == 'cluster'
assert m.summary == 'Planned maintenance (switch update, by jared)'
assert found['maintenance:gandalf:3'].subject == 'compute-storage-02'
assert found['maintenance:gandalf:3'].end == T0 + 300 # still running: up to now
def test_maintenance_fails_open_without_gandalf():
assert MaintenanceCheck().run(ctx(gandalf=None)) == []
assert MaintenanceCheck().run(ctx(gandalf=FakeGandalf([]), up={'gandalf': False})) == []
assert MaintenanceCheck().run(ctx(gandalf=FakeGandalf([], error=SourceError('gandalf', 'x')))) == []
assert parse_time(None) is None and parse_time('nope') is None
# -- engine rules added for these checks --------------------------------------------
def engine():
writes = []
e = Engine(Settings(), HostRegistry(), {}, lambda m, *a, **k: writes.append((m, a)))
return e, writes
def F(kind, subject, layer, role=CAUSE, at=T0, key=None, **kw):
return Finding(kind=kind, subject=subject, role=role, layer=layer, start=at, end=at,
key=key or f'{subject}:{kind}', summary=f'{subject} {kind}', **kw)
def test_maintenance_explains_reboots_and_notes_without_tickets():
e, _ = engine()
m = F('maintenance', 'cluster', LAYER_MAINTENANCE, ticket=False)
reboot = F('reboot', 'storage-01', LAYER_HOST_DOWN, cluster_effect=True)
planned = F('reboot_planned', 'compute-storage-01', LAYER_HOST_DOWN, role=NOTE, cluster_effect=True)
assert e.process([m, reboot, planned], T0 + 10) == []
assert e.process([], T0 + 200) == [] # opens silently
inc = e.incidents['cluster:maintenance']
assert inc.state == OPEN and set(inc.symptoms) == {'storage-01:reboot', 'compute-storage-01:reboot_planned'}
assert 'storage-01:reboot' not in e.incidents
e.process([], T0 + 2000)
assert inc.state == CLEARED
def test_host_scoped_cause_does_not_explain_another_hosts_cause():
e, _ = engine()
e.process([F('maintenance', 'compute-storage-01', LAYER_MAINTENANCE, ticket=False)], T0)
e.process([F('reboot', 'storage-01', LAYER_HOST_DOWN, cluster_effect=True)], T0 + 10)
assert 'storage-01:reboot' in e.incidents
e.process([F('scrape', 'storage-01', 20, role=SYMPTOM, cluster_effect=True)], T0 + 20)
assert 'storage-01:scrape' in e.incidents['compute-storage-01:maintenance'].symptoms
def test_a_higher_cause_found_later_absorbs_pending_and_comments_on_opened():
e, writes = engine()
e.process([F('reboot', 'storage-01', LAYER_HOST_DOWN, cluster_effect=True)], T0) # pending
e.process([F('reboot', 'monitor-01', LAYER_HOST_DOWN, cluster_effect=True)], T0 - 200) # will open
e.process([], T0 + 200)
assert e.incidents['monitor-01:reboot'].state == OPEN
e.incidents['storage-01:reboot'].state = 'pending'
e.incidents['storage-01:reboot'].pending_since = T0 + 190
acts = e.process([F('partition', 'cluster', 60)], T0 + 250)
assert 'storage-01:reboot' not in e.incidents
assert any(w[0] == 'delete_incident' for w in writes)
assert [a.kind for a in acts] == ['root_cause']
assert e.incidents['monitor-01:reboot'].facts['root_cause'] == 'cluster:partition'
def test_known_condition_sends_a_note_to_its_ticket():
e, _ = engine()
e.known = [{'kind': 'reboot', 'subject': 'compute-storage-02', 'ticket_id': 693930698, 'reason': 'DIMM'}]
e.process([F('reboot', 'compute-storage-02', LAYER_HOST_DOWN, cluster_effect=True)], T0)
acts = e.process([], T0 + 200)
assert [(a.kind, a.payload['ticket_id']) for a in acts] == [('known_note', '693930698')]
assert 'known condition: DIMM' in acts[0].payload['comment']
assert e.process([], T0 + 400) == [] # no further traffic
+19 -1
View File
@@ -16,7 +16,7 @@ def db():
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', 'incidents', 'actions', 'observations',
'schema_version'):
'known_conditions', 'schema_version'):
d.execute(f'DROP TABLE IF EXISTS {t}') # nosec B608 - fixed table names
return d
@@ -99,3 +99,21 @@ def test_incidents_actions_observations(db):
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)
def test_known_conditions_seeded_and_managed(db):
db.migrate()
s = Store(db)
seeded = s.known_conditions()
assert [(k['kind'], k['subject'], k['ticket_id']) for k in seeded] == [
('reboot', 'compute-storage-02', '693930698'), ('ceph_flag', 'noout', '693930698'),
('ups_battery', 'ups', None)]
new = s.add_known_condition('reboot', 'pbs', '1', 'testing', 'jared', 1795410668.0)
assert len(s.known_conditions()) == 4
assert s.end_known_condition(new, 'jared', 1795410700.0) == 1
assert s.end_known_condition(new, 'jared', 1795410700.0) == 0
assert len(s.known_conditions()) == 3
s.save_incident({'key': 'k', 'state': 'pending', 'priority': 3, 'kind': 'x', 'subject': 's', 'mode': 'shadow',
'first_seen': 1.0, 'last_seen': 1.0}, 2.0)
s.delete_incident('k')
assert s.load_incidents(0) == []
+3 -2
View File
@@ -99,8 +99,9 @@ def test_migrate_applies_pending_migrations_once():
db, conns = make_db()
assert db.migrate() == len(MIGRATIONS)
executed = [sql for sql, _ in conns[0].executed]
creates = [s for s in executed if s.startswith('CREATE TABLE IF NOT EXISTS') and 'schema_version' not in s]
assert len(creates) == sum(len(list(_statements(m))) for m in MIGRATIONS)
applied = [s for s in executed if 'schema_version' not in s]
assert len(applied) == sum(len(list(_statements(m))) for m in MIGRATIONS)
assert any(s.startswith('INSERT INTO known_conditions') for s in applied)
assert any(s.startswith('INSERT INTO schema_version') for s in executed)
conns[0].executed.clear()
conns[0].version = len(MIGRATIONS)
+111
View File
@@ -0,0 +1,111 @@
"""Replays for the other incidents in the plan on thor#1 (Area 7).
* T2, 2026-11-25: planned rack maintenance. Zero tickets.
* T3, 2026-10-27: compute-storage-01 lost its only corosync link, was fenced, down 3.5 hours. One ticket.
* T4, 2026-11-04: corosync partition, three nodes fenced. One ticket.
* DIMM, 2026-11-21: compute-storage-02's known failing DIMM. No ticket, one note on 693930698.
"""
from datetime import datetime, timezone
import pytest
from .replay import Replay
def hm(ts: float) -> str:
return datetime.fromtimestamp(ts, tz=timezone.utc).strftime('%H:%M')
@pytest.fixture(scope='module')
def t2():
return Replay('t2').run()
@pytest.fixture(scope='module')
def t3():
return Replay('t3').run()
@pytest.fixture(scope='module')
def t4():
return Replay('t4').run()
@pytest.fixture(scope='module')
def dimm():
return Replay('dimm').run()
# -- T2: planned maintenance ------------------------------------------------
def test_t2_planned_maintenance_opens_no_ticket(t2):
assert t2.actions() == []
def test_t2_everything_lands_on_the_maintenance_timeline(t2):
inc = t2.store.incidents['maintenance:gandalf:2']
assert inc['ticket'] is False and inc['state'] == 'cleared'
assert inc['summary'] == 'Planned maintenance (switch update, by jared)'
rebooted = {s['subject'] for s in inc['symptoms'].values() if s['kind'] in ('reboot', 'reboot_planned')}
# Every rack host and compute-storage-02 came back with a new boot time.
assert rebooted >= {'compute-storage-01', 'compute-storage-02', 'compute-storage-gpu-01', 'storage-01',
'monitor-01', 'monitor-02'}
assert set(t2.store.incidents) == {'maintenance:gandalf:2'}
def test_t2_thor_was_dark_and_caught_up(t2):
caught_up = [r for r in t2.results if r.catching_up]
assert caught_up, 'the first cycle after the outage reviews the whole gap'
assert caught_up[0].window[1] - caught_up[0].window[0] > 20 * 60
# -- T3: one host fenced ------------------------------------------------------
def test_t3_one_ticket_for_the_fenced_host(t3):
opened = t3.opened()
assert len(opened) == 1
p = opened[0]['payload']
assert opened[0]['incident_key'] == 'host:compute-storage-01:fenced'
assert p['priority'] == 2
assert p['title'] == ('[compute-storage-01][auto][thor][software] compute-storage-01 lost its cluster link and '
'was fenced [single-node][production][issue]')
assert '15:55' <= hm(opened[0]['created']) <= '15:59'
def test_t3_ceph_fallout_and_the_late_reboot_attach_to_it(t3):
inc = t3.store.incidents['host:compute-storage-01:fenced']
kinds = {(s['kind'], s['subject']) for s in inc['symptoms'].values()}
assert ('ceph_alert', 'cluster') in kinds
assert ('scrape', 'compute-storage-01') in kinds
names = {k.split(':')[-1] for k in inc['symptoms'] if k.startswith('cluster:ceph_alert:')}
assert {'MON_DOWN', 'OSD_HOST_DOWN', 'OSD_DOWN'} <= names
# The host stayed down until 19:20; the incident stays open while it is down, then clears.
assert inc['state'] == 'cleared'
assert set(t3.store.incidents) == {'host:compute-storage-01:fenced'}
# -- T4: partition --------------------------------------------------------------
def test_t4_one_ticket_for_the_partition(t4):
opened = t4.opened()
assert len(opened) == 1
assert opened[0]['incident_key'] == 'cluster:corosync:partition'
assert opened[0]['payload']['priority'] == 1
assert opened[0]['payload']['title'].startswith('[proxmox-cluster][auto][thor][software] Cluster partition: ')
assert '20:52' <= hm(opened[0]['created']) <= '20:56'
assert {a['incident_key'] for a in t4.actions()} == {'cluster:corosync:partition'}
def test_t4_late_fence_and_reboots_fold_into_the_partition(t4):
inc = t4.store.incidents['cluster:corosync:partition']
assert 'storage-01' in inc['summary'] # fenced at 20:54, seen later on its own
assert 'host:storage-01:fenced' in inc['symptoms']
assert {'host:compute-storage-01:reboot', 'host:compute-storage-gpu-01:reboot'} <= set(inc['symptoms'])
assert inc['state'] == 'cleared'
# -- DIMM: known condition ------------------------------------------------------
def test_dimm_reboot_is_a_note_on_its_known_ticket_not_a_new_ticket(dimm):
assert dimm.opened() == []
notes = dimm.actions('known_note')
assert len(notes) == 1
assert notes[0]['payload']['ticket_id'] == '693930698'
assert 'compute-storage-02' in notes[0]['payload']['comment']
assert dimm.store.incidents['host:compute-storage-02:reboot']['state'] == 'cleared'
+107
View File
@@ -0,0 +1,107 @@
"""Corosync partitions and fencing (thor#1: Thor owns these unless Gandalf has network evidence).
Evidence, all from journals in Loki:
* the HA manager: ``node 'X': state changed from 'unknown' => 'fence'``;
* a node fencing itself: ``watchdog-mux: ... watchdog expired``;
* corosync: ``This node is within the non-primary component`` (lost quorum) and
``link: host: N link: M is down``.
One fenced host is "<host> lost its cluster link and was fenced" (P2, 2026-10-27). Two or more
fenced or out of quorum is a cluster partition (P1, 2026-11-04).
"""
import re
from typing import Dict, List, Set
from ..clients import SourceError
from ..model import CAUSE, LAYER_PARTITION, Finding
from . import NeedsSource
CRM_QUERY = '{job="journal", unit="pve-ha-crm.service"} |~ "node .+: state changed from"'
WATCHDOG_QUERY = '{job="journal", unit="watchdog-mux.service"} |= "watchdog expired"'
COROSYNC_QUERY = ('{job="journal", unit="corosync.service"} '
'|~ "non-primary component|link: host: [0-9]+ link: [0-9]+ is down"')
CRM_FENCE_RE = re.compile(r"node '([^']+)': state changed from '[^']+' => 'fence'")
LINK_DOWN_RE = re.compile(r'link: host: (\d+) link: (\d+) is down')
LOOKBACK_S = 300
CHECKS = [
'Which links dropped first: `journalctl -u corosync` on the fenced node(s) and their neighbours.',
'The switch ports for those nodes, and whether a UniFi update or reboot was running (Gandalf).',
'Both corosync links (10.10.10.x and 10.10.90.x) should be up: `corosync-cfgtool -s`.',
'HA guests that did not come back: `ha-manager status | grep -v started`.',
]
class ClusterCheck:
name = 'cluster'
def run(self, ctx) -> List[Finding]:
if not ctx.up.get('loki'):
raise NeedsSource('loki')
loki = ctx.sources['loki']
start, end = ctx.window_start - LOOKBACK_S, ctx.window_end
try:
crm = loki.lines(CRM_QUERY, start, end, limit=500, direction='forward')
wd = loki.lines(WATCHDOG_QUERY, start, end, limit=200, direction='forward')
coro = loki.lines(COROSYNC_QUERY, start, end, limit=1000, direction='forward')
except SourceError as e:
raise NeedsSource('loki', e.message) from e
fenced: Dict[str, float] = {}
quorum_lost: Dict[str, float] = {}
events: List[Dict] = []
for ts, line, _labels in crm:
m = CRM_FENCE_RE.search(line)
host = ctx.hosts.canonical(m.group(1)) if m else None
if host and host not in fenced:
fenced[host] = ts
events.append({'id': f'crm-fence:{host}:{int(ts)}', 'at': ts, 'host': host,
'text': f'HA manager fenced {host}'})
for ts, _line, labels in wd:
host = ctx.hosts.canonical(labels.get('host', ''))
if host and host not in fenced:
fenced[host] = ts
if host:
events.append({'id': f'watchdog:{host}:{int(ts)}', 'at': ts, 'host': host,
'text': f'{host} fenced itself (watchdog expired)'})
links: Set[str] = set()
for ts, line, labels in coro:
host = ctx.hosts.canonical(labels.get('host', ''))
if not host:
continue
if 'non-primary component' in line and host not in quorum_lost:
quorum_lost[host] = ts
events.append({'id': f'quorum:{host}:{int(ts)}', 'at': ts, 'host': host,
'text': f'{host} lost quorum (non-primary component)'})
m = LINK_DOWN_RE.search(line)
if m:
links.add(f'{host}>{m.group(1)}')
if not fenced and not quorum_lost:
return []
involved = sorted(set(fenced) | set(quorum_lost))
first = min(list(fenced.values()) + list(quorum_lost.values()))
last = max(e['at'] for e in events)
facts = {'display': {'Fenced': ', '.join(sorted(fenced)) or 'none',
'Lost quorum': ', '.join(sorted(quorum_lost)) or 'none',
'Corosync links reported down': str(len(links))},
'checks': CHECKS}
if len(involved) >= 2:
return [Finding(kind='partition', subject='cluster', role=CAUSE, layer=LAYER_PARTITION,
check=self.name, start=first, end=last, key='cluster:corosync:partition', priority=1,
summary=f'Cluster partition: {", ".join(involved)} fenced or out of quorum',
facts=dict(facts, escalation_reason='Two or more nodes were fenced or lost quorum.'),
events=events)]
host = involved[0]
# One layer below a partition, so a later fence seen on its own folds into an active one.
return [Finding(kind='fenced', subject=host, role=CAUSE, layer=LAYER_PARTITION - 1, check=self.name,
start=first, end=last, key=f'host:{host}:fenced', priority=2, cluster_effect=True,
summary=f'{host} lost its cluster link and was fenced', facts=facts, events=events)]
# Partition summaries are fixed by the check; keep the newest list of hosts.
def summarize(self, inc) -> str:
if inc.kind != 'partition':
return inc.summary
hosts = sorted({e['host'] for e in inc.events if e.get('host')})
return f'Cluster partition: {", ".join(hosts)} fenced or out of quorum'
def priority(self, inc) -> int:
return 1 if inc.kind == 'partition' else 2
+63
View File
@@ -0,0 +1,63 @@
"""Planned maintenance, from Gandalf's suppressions (thor#1: maintenance is declared once, in Gandalf).
A Gandalf maintenance becomes a cause that never opens a ticket: reboots, hosts going dark and
the symptoms that come with them attach to it and appear on Thor's timeline only (2026-11-25:
"switch update", 03:11:39 to 03:41:39). Suppressions are read with their start and end times,
because by the time Thor looks (after the rack is back) they may already have ended.
If Gandalf can't answer, maintenance is unknown and Thor fails open: things may get tickets.
"""
from datetime import datetime
from typing import List, Optional
from ..clients import SourceError
from ..model import CAUSE, LAYER_MAINTENANCE, Finding
MARGIN_S = 1800
def parse_time(value: Optional[str]) -> Optional[float]:
if not value:
return None
try:
return datetime.fromisoformat(value.replace('Z', '+00:00')).timestamp()
except ValueError:
return None
class MaintenanceCheck:
name = 'maintenance'
def run(self, ctx) -> List[Finding]:
gandalf = ctx.sources.get('gandalf')
if gandalf is None or not ctx.up.get('gandalf'):
return []
hours = int((ctx.window_end - ctx.window_start + MARGIN_S) // 3600) + 1
try:
sups = gandalf.suppressions(hours=hours, include_ended=True)
except SourceError:
return []
out = []
for s in sups:
kind = s.get('target_type')
if kind not in ('all', 'host'):
continue
start = parse_time(s.get('started_at'))
if start is None:
continue
end = parse_time(s.get('ended_at')) or ctx.window_end
if end < ctx.window_start - MARGIN_S or start > ctx.window_end:
continue
subject = 'cluster' if kind == 'all' else (ctx.hosts.canonical(s.get('target_name', '')) or '')
if not subject:
continue
who = s.get('started_by') or 'someone'
reason = s.get('reason') or 'maintenance'
out.append(Finding(
kind='maintenance', subject=subject, role=CAUSE, layer=LAYER_MAINTENANCE, check=self.name,
start=start, end=min(end, ctx.window_end), key=f'maintenance:gandalf:{s.get("id")}', ticket=False,
priority=5, summary=f'Planned maintenance ({reason}, by {who})',
facts={'gandalf_id': s.get('id'), 'scope': subject},
events=[{'id': f'gandalf:{s.get("id")}:start', 'at': start,
'text': f'Gandalf maintenance started by {who}: {reason}'}]))
return out
+129
View File
@@ -0,0 +1,129 @@
"""Reboots (thor#4): a host that went down and came back, and whether anyone asked for it.
* **That it rebooted:** ``node_boot_time_seconds`` changes. Only visible once the host is back.
* **Whether it was asked for:** a ``systemd-logind`` shutdown line shortly before it went down
(Gandalf's ``find_shutdown``). Planned reboots are timeline only; Gandalf tickets one that
doesn't come back.
* **Whether we can tell:** a journal that stopped reaching Loki well before the host went
down (switches rebooting, 2026-11-25) means "unknown", not "crash".
An unexpected reboot is a cause (P3, recovered). It is usually explained by something higher
(maintenance, a partition, fencing) and the engine then files it under that. Several hosts
rebooting within 15 minutes with nothing higher to explain them is one event, not one ticket
per host.
"""
from typing import Dict, List
from ..clients import SourceError
from ..clients.loki import LOGQL_SHUTDOWN_FILTER, SHUTDOWN_RE
from ..model import CAUSE, LAYER_HOST_DOWN, NOTE, Finding
from . import NeedsSource, query_regex
STEP_S = 30
LOOKBACK_S = 3 * 3600 # how far back to find the last sample before a boot
SHUTDOWN_LOOKBACK_S = 600
QUIET_BEFORE_S = 120 # journal silent this long before the host went down: "unknown"
GROUP_S = 15 * 60
GROUP_CHECKS = [
'Power: UPS state (`nut_ups_on_battery`), and the circuit or PDU these hosts share.',
'Was this planned? Start a Gandalf maintenance next time so Thor knows.',
'Corosync and HA logs around the time (`journalctl -u corosync -u pve-ha-crm`).',
]
def boot_query(hosts) -> str:
ips = query_regex(h.ip for h in hosts.all())
return f'node_boot_time_seconds{{instance=~"({ips}):9100"}}'
def logind_query(names: List[str]) -> str:
return (f'{{job="journal", host=~"{query_regex(names)}", unit="systemd-logind.service"}} '
f'|~ "{LOGQL_SHUTDOWN_FILTER}"')
def journal_query(names: List[str]) -> str:
return f'{{job="journal", host=~"{query_regex(names)}"}}'
def find_reboots(values, after: float) -> List[Dict]:
"""[{boot, seen, down_from}] for each new boot time seen after ``after``."""
out = []
for (pts, pv), (ts, v) in zip(values, values[1:]):
if ts > after and v > pv + 60:
out.append({'boot': v, 'seen': ts, 'down_from': pts})
return out
class RebootCheck:
name = 'reboots'
def run(self, ctx) -> List[Finding]:
if not ctx.up.get('prometheus'):
raise NeedsSource('prometheus')
try:
series = ctx.sources['prometheus'].query_range(boot_query(ctx.hosts), ctx.window_start - LOOKBACK_S,
ctx.window_end, STEP_S)
except SourceError as e:
raise NeedsSource('prometheus', e.message) from e
reboots = []
for s in series:
host = ctx.hosts.by_instance(s['metric'].get('instance', ''))
if host:
reboots += [dict(r, host=host) for r in find_reboots(s['values'], ctx.window_start)]
if not reboots:
return []
if not ctx.up.get('loki'):
raise NeedsSource('loki', 'hosts rebooted; need their journals to tell planned from not')
findings = [self._classify(ctx, r) for r in reboots]
causes = [f for f in findings if f.role == CAUSE]
group = self._group(causes)
return findings + ([group] if group else [])
def _classify(self, ctx, r: Dict) -> Finding:
host, names = r['host'], ctx.hosts.loki_names(r['host'])
loki = ctx.sources['loki']
try:
shutdown = None
for ts, line, _labels in loki.lines(logind_query(names), r['down_from'] - SHUTDOWN_LOOKBACK_S,
r['boot'], limit=20):
m = SHUTDOWN_RE.search(line)
if m:
shutdown = {'at': ts, 'kind': m.group(1)}
break
last = None
if not shutdown:
lines = loki.lines(journal_query(names), r['down_from'] - LOOKBACK_S, r['boot'] - 1, limit=1)
last = lines[0][0] if lines else None
except SourceError as e:
raise NeedsSource('loki', e.message) from e
base = dict(subject=host, layer=LAYER_HOST_DOWN, check=self.name, start=r['down_from'], end=r['seen'],
cluster_effect=True)
event = {'id': f'{host}:boot:{int(r["boot"])}', 'at': r['boot'], 'host': host}
if shutdown:
event['text'] = f'{host} rebooted on request ("{shutdown["kind"]}" at the logind line), back by boot'
return Finding(kind='reboot_planned', role=NOTE, key=f'host:{host}:reboot_planned', priority=5,
summary=f'Planned reboot of {host}', events=[event], **base)
if last is None or last < r['down_from'] - QUIET_BEFORE_S:
event['text'] = (f'{host} rebooted; its journal stopped reaching Loki before it went down, '
'so Thor cannot tell why')
return Finding(kind='reboot', role=CAUSE, key=f'host:{host}:reboot', priority=4,
summary=f'{host} rebooted (cause unknown: its journal went quiet first)',
facts={'journal_quiet': True}, events=[event], **base)
event['text'] = f'{host} rebooted with no shutdown request (crash, watchdog reset or power loss)'
return Finding(kind='reboot', role=CAUSE, key=f'host:{host}:reboot', priority=3,
summary=f'Unexpected reboot of {host}', events=[event], **base)
def _group(self, causes: List[Finding]):
"""Several unexplained reboots close together are one event (power, maintenance, a partition)."""
if len({f.subject for f in causes}) < 2:
return None
causes = sorted(causes, key=lambda f: f.start)
if causes[-1].start - causes[0].start > GROUP_S:
return None
hosts = sorted({f.subject for f in causes})
return Finding(kind='reboots', subject='cluster', role=CAUSE, layer=LAYER_HOST_DOWN + 1, check=self.name,
start=causes[0].start, end=max(f.end for f in causes),
key=f'cluster:reboots:{int(causes[0].start // GROUP_S)}', priority=2,
summary=f'{len(hosts)} hosts rebooted at once: {", ".join(hosts)}',
facts={'grouped_by_time': True, 'checks': GROUP_CHECKS},
events=[e for f in causes for e in f.events])
+46
View File
@@ -123,6 +123,31 @@ MIGRATIONS: List[str] = [
KEY idx_observations_last_seen (last_seen)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
""",
# 3: known conditions (thor#1), with the first entries the operator named
"""
CREATE TABLE IF NOT EXISTS known_conditions (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
kind VARCHAR(32) NOT NULL,
subject VARCHAR(64) NOT NULL,
ticket_id VARCHAR(16) NULL,
reason TEXT NOT NULL,
created_by VARCHAR(64) NOT NULL,
created_at DATETIME(3) NOT NULL,
ended_at DATETIME(3) NULL,
ended_by VARCHAR(64) NULL,
KEY idx_known_active (ended_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO known_conditions (kind, subject, ticket_id, reason, created_by, created_at) VALUES
('reboot', 'compute-storage-02', '693930698',
'compute-storage-02 reboots every 2 to 3 days from a failing DIMM (P0 Channel B DIMM 1, ECC errors).',
'thor#1', UTC_TIMESTAMP(3)),
('ceph_flag', 'noout', '693930698',
'noout is set on purpose while compute-storage-02 (no UPS, failing DIMM) can drop at any time.',
'thor#1', UTC_TIMESTAMP(3)),
('ups_battery', 'ups', NULL,
'The 2017 UPS battery reports replace-battery and a short runtime but works (Grafana silences until 2029).',
'thor#1', UTC_TIMESTAMP(3));
""",
]
@@ -352,3 +377,24 @@ class Store:
for r in rows:
r['first_seen'], r['last_seen'] = from_dt(r['first_seen']), from_dt(r['last_seen'])
return rows
def delete_incident(self, key: str) -> None:
self.db.execute('DELETE FROM incidents WHERE k=%s', (key,))
# -- known conditions -------------------------------------------------------
def known_conditions(self) -> List[Dict[str, Any]]:
rows = self.db.query("""SELECT id, kind, subject, ticket_id, reason, created_by, created_at
FROM known_conditions WHERE ended_at IS NULL ORDER BY id""")
for r in rows:
r['created_at'] = from_dt(r['created_at'])
return rows
def add_known_condition(self, kind: str, subject: str, ticket_id: Optional[str], reason: str,
created_by: str, now: float) -> int:
return self.db.execute(
"""INSERT INTO known_conditions (kind, subject, ticket_id, reason, created_by, created_at)
VALUES (%s, %s, %s, %s, %s, %s)""", (kind, subject, ticket_id, reason, created_by, to_dt(now)))
def end_known_condition(self, condition_id: int, ended_by: str, now: float) -> int:
return self.db.execute("""UPDATE known_conditions SET ended_at=%s, ended_by=%s
WHERE id=%s AND ended_at IS NULL""", (to_dt(now), ended_by, condition_id))
+97 -27
View File
@@ -37,6 +37,8 @@ class Engine:
self.checks = checks
self.write = write
self.incidents: Dict[str, Incident] = {}
# Known conditions (thor#1): {kind, subject, ticket_id, reason}. Loaded by the monitor.
self.known: List[dict] = []
def load(self, incidents: List[dict]) -> None:
for d in incidents:
@@ -53,15 +55,50 @@ class Engine:
host = self.hosts.get(inc.subject)
return bool(host and host.ceph_osds)
def _related(self, inc: Incident, f: Finding) -> bool:
def _related(self, inc: Incident, f: Finding, as_cause: bool = False) -> bool:
"""Can ``inc`` explain ``f``? ``as_cause``: f is a lower cause, not a plain symptom.
A host-scoped incident explains other hosts' symptoms (scrapes, pvestatd, Ceph alerts)
when it can stall the cluster, but never another host's own cause (its reboot).
"""
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:
if as_cause and f.subject != inc.subject and inc.subject != 'cluster':
return False
if f.start < inc.first_seen - ATTACH_BEFORE_S or f.start > self._last_activity(inc) + CLEAR_AFTER_S:
return False
if f.subject == inc.subject:
return True
return f.cluster_effect and self._can_stall_cluster(inc)
@staticmethod
def _last_activity(inc: Incident) -> float:
"""Latest evidence for the cause or anything attached to it (a host still down keeps it going)."""
return max([inc.last_seen] + [s.get('last', 0) for s in inc.symptoms.values()])
def _known_for(self, f: Finding) -> Optional[dict]:
for k in self.known:
if k.get('kind') in (f.kind, '*') and k.get('subject') in (f.subject, '*'):
return k
return None
def _attach(self, inc: Incident, f: Finding, new_symptoms: Dict[str, List[dict]]) -> None:
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
def _explaining(self, f: Finding, as_cause: bool = False) -> Optional[Incident]:
candidates = [i for i in self.incidents.values() if self._related(i, f, as_cause)]
return sorted(candidates, key=lambda i: (-i.layer, i.first_seen))[0] if candidates else None
def _refresh(self, inc: Incident) -> None:
check = self._check(inc)
if check is not None:
@@ -92,41 +129,62 @@ class Engine:
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)
# Highest causes first, so a lower cause they explain becomes their symptom.
for f in sorted((f for f in findings if f.role == CAUSE), key=lambda f: -f.layer):
own = self.incidents.get(f.key)
higher = None if own is not None and own.active else self._explaining(f, as_cause=True)
if higher is not None:
self._attach(higher, f, new_symptoms)
touched[higher.key] = higher
continue
touched[f.key] = self._merge_cause(f, now, catching_up)
self._absorb_lower(touched[f.key], now, actions, new_symptoms)
for f in findings:
self.write('save_observation', f.to_dict(), now)
if f.role != SYMPTOM:
if f.role == CAUSE:
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
inc = self._explaining(f)
# Notes (a planned reboot) only go on timeline-only incidents such as maintenance.
if inc is not None and (f.role == SYMPTOM or not inc.ticket):
self._attach(inc, f, new_symptoms)
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)
n_actions, state_before = len(actions), inc.state
self._lifecycle(inc, now, catching_up, before, new_symptoms.get(inc.key, []), actions)
if inc.key in touched or len(actions) > n_actions:
if inc.key in touched or len(actions) > n_actions or inc.state != state_before:
self.write('save_incident', inc.to_dict(), now)
return actions
def _absorb_lower(self, top: Incident, now: float, actions: List[Action],
new_symptoms: Dict[str, List[dict]]) -> None:
"""A higher cause turned up after a lower one it explains (Loki lines arrive late).
A lower incident still pending is folded in as a symptom. One already opened keeps its
ticket and gets a "Root cause" comment; the operator closes it (thor#1 contract).
"""
for low in list(self.incidents.values()):
if low is top or not low.active or low.layer >= top.layer or not low.ticket:
continue
probe = Finding(kind=low.kind, subject=low.subject, role=SYMPTOM, layer=low.layer, start=low.first_seen,
end=low.last_seen, key=low.key, summary=low.summary, cluster_effect=True)
if not self._related(top, probe, as_cause=True):
continue
self._attach(top, probe, new_symptoms)
if low.state == PENDING:
del self.incidents[low.key]
self.write('delete_incident', low.key)
elif top.ticket:
low.facts['root_cause'] = top.key
low.state, low.cleared_at = CLEARED, now
self._action(actions, low, 'root_cause', now,
comment=ticket_text.root_cause_comment(top), root_cause=top.key)
self.write('save_incident', low.to_dict(), now)
@staticmethod
def _new_round(inc: Incident, f: Finding) -> bool:
"""A cleared incident's cause is back: evidence newer than anything it had."""
@@ -139,7 +197,10 @@ class Engine:
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))
summary=f.summary, mode=self.settings.check_mode(f.check), ticket=f.ticket)
known = self._known_for(f)
if known:
inc.known_ticket, inc.known_reason = str(known['ticket_id']), known.get('reason', '')
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.
@@ -168,11 +229,20 @@ class Engine:
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))
if inc.known_ticket:
self._action(actions, inc, 'known_note', now, ticket_id=inc.known_ticket,
comment=ticket_text.known_note(inc))
elif inc.ticket:
self._action(actions, inc, 'open', now, **self._open_payload(inc))
self._sent(inc, now)
return
if inc.state != OPEN:
return
if not inc.ticket or inc.known_ticket:
# Timeline only (maintenance) or a known condition: no further ticket traffic.
if now - self._last_activity(inc) >= CLEAR_AFTER_S:
inc.state, inc.cleared_at = CLEARED, now
return
sent = inc.facts.get('sent_priority', before)
if inc.priority < sent:
reason = inc.facts.get('escalation_reason') or 'The incident got worse.'
@@ -186,7 +256,7 @@ class Engine:
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
clearing = now - self._last_activity(inc) >= 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.
+8 -2
View File
@@ -22,7 +22,7 @@ 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)
NOTE = 'note' # shown in Thor, never a ticket; only joins timeline-only incidents (maintenance)
# Incident states
PENDING = 'pending' # seen, held one cycle so same-moment symptoms land in the first text
@@ -44,7 +44,9 @@ class Finding:
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
cluster_effect: bool = False # can be the result of trouble on another host
# False for causes that explain things but never become tickets (planned maintenance).
ticket: bool = True
def to_dict(self) -> Dict[str, Any]:
return dict(self.__dict__)
@@ -71,6 +73,10 @@ class Incident:
ticket_id: Optional[str] = None
mode: str = 'shadow'
seen_after_the_fact: bool = False
ticket: bool = True
# A known condition covers this incident: notes go to that ticket instead of a new one.
known_ticket: Optional[str] = None
known_reason: str = ''
@property
def active(self) -> bool:
+10 -1
View File
@@ -133,6 +133,7 @@ class Monitor:
end = self.store.get_state('last_good_window_end')
statuses = self.store.source_statuses()
incidents = self.store.load_incidents(self.clock() - INCIDENT_RELOAD_S)
self.engine.known = self.store.known_conditions()
except DatabaseError as e:
logger.warning('Could not load previous state yet: %s', e)
return
@@ -222,6 +223,10 @@ class Monitor:
logger.exception('Check %s failed', check.name)
errors.append(f'{check.name}: {type(e).__name__}: {e}')
if self._loaded:
try:
self.engine.known = self.store.known_conditions()
except DatabaseError:
pass # keep the last list we had
self.engine.process(found, started, catching_up)
else:
# Without the stored incidents the engine would open duplicates; review again later.
@@ -276,9 +281,13 @@ def build_sources(s: config_mod.Settings) -> Dict[str, Source]:
def build_checks() -> List[Check]:
from .checks.cluster import ClusterCheck
from .checks.maintenance import MaintenanceCheck
from .checks.memory import MemoryCheck
from .checks.reboots import RebootCheck
from .checks.symptoms import CephAlertCheck, PvestatdCheck, ScrapeCheck
return [MemoryCheck(), ScrapeCheck(), PvestatdCheck(), CephAlertCheck()]
return [MaintenanceCheck(), ClusterCheck(), RebootCheck(), MemoryCheck(), ScrapeCheck(), PvestatdCheck(),
CephAlertCheck()]
def main() -> None: # pragma: no cover - process entry point
+4 -1
View File
@@ -13,7 +13,7 @@ from .db import DatabaseError
logger = logging.getLogger('thor.outbox')
MAX_ATTEMPTS = 30
CREATE_KINDS = ('open', 'escalate', 'refresh')
COMMENT_KINDS = ('also_seen', 'cleared')
COMMENT_KINDS = ('also_seen', 'cleared', 'root_cause')
class Outbox:
@@ -54,6 +54,9 @@ class Outbox:
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'] == 'known_note':
ok = self.tinker.comment(p['ticket_id'], p['comment'])
return ok, p['ticket_id'], '' if ok else 'comment failed'
if a['kind'] in COMMENT_KINDS:
ticket_id = self.store.incident_ticket(a['incident_key'])
if not ticket_id:
+16
View File
@@ -116,3 +116,19 @@ def cleared_comment(inc: Incident) -> str:
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)
def root_cause_comment(top: Incident) -> str:
return '\n'.join([f'**Root cause found:** {top.summary} (`{top.key}`).', '',
'Thor tracks the incident under its root cause from now on. This ticket gets no more '
'notes from Thor; close it when you are happy it is covered.'])
def known_note(inc: Incident) -> str:
lines = [f'**Seen again: {inc.summary}** ({utc(inc.first_seen)})', '']
if inc.known_reason:
lines.append(f'Thor treats this as a known condition: {inc.known_reason}')
lines += _events_lines(inc, limit=5)
lines += ['', '_Added by Thor instead of opening a new ticket. The known condition ends when this ticket '
'is closed._']
return '\n'.join(lines)