Reboots, fencing and partitions, maintenance from Gandalf, known conditions; T2/T3/T4/DIMM replays
CI / Lint (flake8, house style) (pull_request) Successful in 54s
CI / Test (pytest) (pull_request) Successful in 55s
CI / Security (bandit, pip-audit) (pull_request) Successful in 56s
CI / Integration (MariaDB) (pull_request) Successful in 2m2s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Successful in 1m30s
CI / Deploy (pull_request) Skipped

- checks/reboots.py (thor#4): boot-time changes classified as planned (logind line),
  unexpected, or unknown (journal went quiet first); several together are one event.
- checks/cluster.py: HA fence lines, watchdog self-fences, corosync quorum loss: one host is
  'lost its cluster link and was fenced' (P2), two or more a cluster partition (P1).
- checks/maintenance.py: Gandalf suppressions (with ended ones) as a cause that never
  opens a ticket; everything under it goes on the timeline.
- Engine: higher causes first, lower causes they explain become symptoms; a higher cause
  found later absorbs pending ones and comments 'Root cause' on opened ones; host-scoped
  causes never explain another host's cause; incidents stay active while an attached host
  is still down; silent state changes are saved; notes join timeline-only incidents.
- Known conditions (migration 3, seeded): compute-storage-02 reboots and Ceph noout ->
  693930698, the old UPS battery. A match sends a note to that ticket instead of a new one.
- Replays: T2 0 tickets; T3 one P2 (fenced, cleared when the host is back); T4 one P1
  partition (storage-01's later fence and all reboots fold in); DIMM one note on 693930698.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-25 23:13:59 -05:00
1 parent 983ba27386
commit e70dee0ad8
21 files changed
+954 -31920

No files matched your search

+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)