"""Root-cause grouping: findings in, incidents and ticket actions out (thor#1, Area 4). * A **cause** finding opens or updates the incident with its key. New incidents are held one cycle (``PENDING``) so symptoms from the same moment land in the first ticket text. * A **symptom** attaches to the highest-precedence active incident it relates to: the same host, or any host for a symptom with a cluster-wide effect (scrape timeouts, pvestatd timeouts, new Ceph alerts) when the cause can stall the cluster (a Ceph host). Symptoms nothing explains stay in Thor only; they never open tickets in phase 1. * An incident clears after ``CLEAR_AFTER_S`` without new evidence: a "Cleared" note, never a status change. Priority only ever goes up while an incident is active. * Every Tinker-facing step is an :class:`Action`. In shadow mode it is recorded, never sent. Checks own the meaning of their incidents: ``summarize(inc)`` and ``priority(inc)`` are asked of the check that raised the cause, so the engine stays generic. """ import logging from typing import Callable, Dict, List, Optional from . import ticket_text from .config import Settings from .hosts import HostRegistry from .model import CAUSE, CLEARED, OPEN, PENDING, SYMPTOM, Action, Finding, Incident logger = logging.getLogger('thor.engine') CLEAR_AFTER_S = 15 * 60 # thor#1: cleared after 15 minutes clean REFRESH_EVERY_S = 30 * 60 # re-send a changed description at most this often ATTACH_BEFORE_S = 5 * 60 # a symptom may show up a little before its cause is seen MAX_EVENTS = 500 # per incident, oldest dropped first class Engine: def __init__(self, settings: Settings, hosts: HostRegistry, checks: Dict[str, object], write: Callable[..., None]): self.settings = settings self.hosts = hosts self.checks = checks self.write = write self.incidents: Dict[str, Incident] = {} def load(self, incidents: List[dict]) -> None: for d in incidents: inc = Incident.from_dict(d) self.incidents[inc.key] = inc # -- helpers ------------------------------------------------------------ def _check(self, inc: Incident): return self.checks.get(inc.check) def _can_stall_cluster(self, inc: Incident) -> bool: if inc.subject == 'cluster': return True host = self.hosts.get(inc.subject) return bool(host and host.ceph_osds) def _related(self, inc: Incident, f: Finding) -> bool: if not inc.active or inc.layer <= f.layer: return False if f.start < inc.first_seen - ATTACH_BEFORE_S or f.start > inc.last_seen + CLEAR_AFTER_S: return False if f.subject == inc.subject: return True return f.cluster_effect and self._can_stall_cluster(inc) def _refresh(self, inc: Incident) -> None: check = self._check(inc) if check is not None: if hasattr(check, 'summarize'): inc.summary = check.summarize(inc) if hasattr(check, 'priority'): inc.priority = min(inc.priority, check.priority(inc)) def _action(self, actions: List[Action], inc: Incident, kind: str, now: float, **payload) -> None: a = Action(inc.key, kind, now, inc.mode, payload) actions.append(a) self.write('add_action', a.__dict__) verb = 'would send' if inc.mode != 'live' else 'queued' logger.info('[%s] %s %s for %s (P%s): %s', inc.mode, verb, kind, inc.key, inc.priority, inc.summary) @staticmethod def _sent(inc: Incident, now: float) -> None: inc.facts.update(sent_summary=inc.summary, sent_symptoms=len(inc.symptoms), sent_at=now) def _open_payload(self, inc: Incident) -> dict: return {'title': ticket_text.title(inc), 'priority': inc.priority, 'category': ticket_text.category(inc), 'type': 'Issue', 'dedup_key': inc.key, 'description': ticket_text.description(inc, self.settings.public_url)} # -- the cycle ------------------------------------------------------------ def process(self, findings: List[Finding], now: float, catching_up: bool = False) -> List[Action]: actions: List[Action] = [] touched: Dict[str, Incident] = {} new_symptoms: Dict[str, List[dict]] = {} for f in findings: if f.role == CAUSE: touched[f.key] = self._merge_cause(f, now, catching_up) for f in findings: self.write('save_observation', f.to_dict(), now) if f.role != SYMPTOM: continue candidates = [i for i in self.incidents.values() if self._related(i, f)] if not candidates: continue inc = sorted(candidates, key=lambda i: (-i.layer, i.first_seen))[0] rec = inc.symptoms.get(f.key) if rec is None: rec = {'kind': f.kind, 'subject': f.subject, 'summary': f.summary, 'first': f.start, 'last': f.end, 'cluster_effect': f.cluster_effect} inc.symptoms[f.key] = rec if inc.state == OPEN: new_symptoms.setdefault(inc.key, []).append(rec) else: rec['first'] = min(rec['first'], f.start) rec['last'] = max(rec['last'], f.end) rec['summary'] = f.summary touched[inc.key] = inc for inc in list(self.incidents.values()): before = inc.priority if inc.key in touched: self._refresh(inc) n_actions = len(actions) self._lifecycle(inc, now, catching_up, before, new_symptoms.get(inc.key, []), actions) if inc.key in touched or len(actions) > n_actions: self.write('save_incident', inc.to_dict(), now) return actions @staticmethod def _new_round(inc: Incident, f: Finding) -> bool: """A cleared incident's cause is back: evidence newer than anything it had.""" if f.events: return any(e.get('at', 0) > inc.last_seen for e in f.events) return f.end > inc.last_seen def _merge_cause(self, f: Finding, now: float, catching_up: bool) -> Incident: inc = self.incidents.get(f.key) if inc is None: inc = Incident(key=f.key, kind=f.kind, subject=f.subject, layer=f.layer, check=f.check, priority=f.priority, first_seen=f.start, last_seen=f.end, pending_since=now, summary=f.summary, mode=self.settings.check_mode(f.check)) self.incidents[f.key] = inc elif inc.state == CLEARED and self._new_round(inc, f): # It came back: a new round for the same key. Tinker decides reopen vs new ticket. inc.state, inc.pending_since, inc.cleared_at = PENDING, now, None inc.first_seen, inc.symptoms, inc.priority = f.start, {}, f.priority inc.facts.pop('sent_priority', None) inc.mode = self.settings.check_mode(f.check) inc.first_seen = min(inc.first_seen, f.start) inc.last_seen = max(inc.last_seen, f.end) inc.facts.update(f.facts) known = {e.get('id') for e in inc.events} for e in f.events: if e.get('id') not in known: inc.events.append(e) known.add(e.get('id')) inc.events.sort(key=lambda e: e.get('at', 0)) del inc.events[:-MAX_EVENTS] inc.priority = min(inc.priority, f.priority) if catching_up and inc.state == PENDING and f.end < now - 2 * self.settings.cycle_seconds: inc.seen_after_the_fact = True return inc def _lifecycle(self, inc: Incident, now: float, catching_up: bool, before: int, new_symptoms: List[dict], actions: List[Action]) -> None: if inc.state == PENDING: if now - inc.pending_since >= self.settings.cycle_seconds or catching_up: inc.state, inc.opened_at = OPEN, now inc.facts['sent_priority'] = inc.priority self._action(actions, inc, 'open', now, **self._open_payload(inc)) self._sent(inc, now) return if inc.state != OPEN: return sent = inc.facts.get('sent_priority', before) if inc.priority < sent: reason = inc.facts.get('escalation_reason') or 'The incident got worse.' self._action(actions, inc, 'escalate', now, old=sent, new=inc.priority, comment=ticket_text.escalation_comment(sent, inc.priority, reason), **self._open_payload(inc)) inc.facts['sent_priority'] = inc.priority self._sent(inc, now) if new_symptoms: text = '\n\n'.join(ticket_text.also_seen_comment(s['summary'], s['first']) for s in sorted(new_symptoms, key=lambda s: s['first'])) self._action(actions, inc, 'also_seen', now, comment=text, symptoms=[s['summary'] for s in new_symptoms]) clearing = now - inc.last_seen >= CLEAR_AFTER_S changed = inc.summary != inc.facts.get('sent_summary') or len(inc.symptoms) != inc.facts.get('sent_symptoms') if changed and (clearing or now - inc.facts.get('sent_at', 0) >= REFRESH_EVERY_S): # Same dedup_key: Tinker updates the open ticket's title and description in place. self._action(actions, inc, 'refresh', now, **self._open_payload(inc)) self._sent(inc, now) if clearing: inc.state, inc.cleared_at = CLEARED, now self._action(actions, inc, 'cleared', now, comment=ticket_text.cleared_comment(inc)) # -- for the web UI and /covering -------------------------------------- def active(self) -> List[Incident]: return [i for i in self.incidents.values() if i.active] def covering(self, host: Optional[str] = None, scope: Optional[str] = None) -> List[Incident]: out = [] for inc in self.active(): if host and (inc.subject == host or (inc.subject == 'cluster')): out.append(inc) elif scope == 'cluster' and self._can_stall_cluster(inc): out.append(inc) return out