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