Files
thor/scripts/record_fixture.py
T

117 lines
5.8 KiB
Python
Raw Normal View History

#!/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 [t2 t3 t4 dimm]
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
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
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
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, '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]
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', {}), '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, 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]
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
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__':
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')