""" Post-Crash-Forensik: Erkennung und Analyse von Gateway-Abstürzen beim Neustart. Wird von adapter.py connect() ALS ALLERERSTES aufgerufen (vor REST-Login, vor DDP). Läuft im try/except — Forensik-Fehler blockieren NIEMALS den Gateway-Start. 4-Quellen-Korrelation für Crasherkennung: (1) Heartbeat-Leiche: ~/.hermes/state/gateway.heartbeat — pid != current_pid (2) journalctl: journalctl --user -u hermes-gateway -n 50 — code=killed/dumped (3) restart_loop.json: ~/.hermes/gateway/restart_loop.json — Boot-Timestamp < 60s (4) gateway_state.json: updated_at älter als 5s UND heartbeat existiert Filter: - Heartbeat älter als 1h → skip (veraltete Leiche) - planned_takeover (gateway --replace) → KEIN Crash Output: 6 Datenpunkte mit 'CRASH-FORENSIK:' Präfix im Gateway-Log. """ from __future__ import annotations import asyncio import json import logging import os import time from pathlib import Path from typing import Any, Dict, List, Optional, Tuple logger = logging.getLogger("hermes-rocketchat.crash_forensics") # ── Pfade ──────────────────────────────────────────────────────────────── HERMES_HOME = Path(os.environ.get("HERMES_HOME", os.path.expanduser("~/.hermes"))) HEARTBEAT_PATH = HERMES_HOME / "state" / "gateway.heartbeat" RESTART_LOOP_PATH = HERMES_HOME / "gateway" / "restart_loop.json" GATEWAY_STATE_PATH = HERMES_HOME / "gateway" / "gateway_state.json" TAKEOVER_MARKER_PATH = HERMES_HOME / ".gateway-takeover.json" # ── Konstanten ─────────────────────────────────────────────────────────── HEARTBEAT_MAX_AGE_S = 3600 # 1h — ältere Heartbeats sind veraltete Leichen RESTART_LOOP_WINDOW_S = 60 # 60s — Boot-Timestamp innerhalb dieses Fensters = Crash GATEWAY_STATE_STALE_S = 5 # 5s — updated_at älter = Gateway hing fest # ── Hilfsfunktionen ────────────────────────────────────────────────────── def _read_json(path: Path) -> Optional[Dict[str, Any]]: """JSON-Datei lesen, None bei Fehler.""" try: if path.exists(): return json.loads(path.read_text(encoding="utf-8")) except (json.JSONDecodeError, OSError) as exc: logger.debug("crash_forensics: cannot read %s: %s", path, exc) return None def _read_heartbeat() -> Optional[Dict[str, Any]]: """Heartbeat-Datei lesen und validieren.""" data = _read_json(HEARTBEAT_PATH) if not data: return None # Validiere Struktur if "pid" not in data or "ts" not in data: return None return data def _is_planned_takeover() -> bool: """Prüft ob ein --replace / geplanter Takeover stattfand.""" marker = _read_json(TAKEOVER_MARKER_PATH) if marker: logger.debug("crash_forensics: takeover marker found — skipping crash detection") return True return False # ── Journal-Abfrage ────────────────────────────────────────────────────── async def gather_journal_for_pid(pid: int, since_unix: float) -> List[str]: """journalctl --user -u hermes-gateway Einträge seit since_unix abrufen. Nutzt asyncio.create_subprocess_exec für async-Kompatibilität. Timeout: 2.0s. """ try: since_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(since_unix)) proc = await asyncio.create_subprocess_exec( "journalctl", "--user", "-u", "hermes-gateway", "--since", since_str, "-n", "50", "--no-pager", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, ) try: stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=2.0) except asyncio.TimeoutError: proc.kill() await proc.wait() return [] return stdout.decode("utf-8", errors="replace").splitlines() except Exception as exc: logger.debug("crash_forensics: journalctl failed: %s", exc) return [] # ── Crash-Quellen-Klassifikation ───────────────────────────────────────── def classify_crash_source(journal_entries: List[str]) -> str: """Klassifiziere Crash-Quelle aus Journal-Einträgen. Returns: "plugin" — Traceback enthält plugin/ Pfade "core" — Traceback enthält hermes_agent/ Pfade "unknown" — keine Traceback-Informationen gefunden """ plugin_hits = 0 core_hits = 0 for line in journal_entries: if "plugin/" in line or "/plugin/" in line: plugin_hits += 1 if "hermes_agent/" in line or "/hermes_agent/" in line: core_hits += 1 if plugin_hits > core_hits: return "plugin" elif core_hits > plugin_hits: return "core" elif plugin_hits > 0 and core_hits > 0: return "mixed" return "unknown" # ── Blast-Radius-Analyse ───────────────────────────────────────────────── def _analyze_blast_radius(journal_entries: List[str]) -> List[str]: """Identifiziere betroffene Komponenten aus Traceback.""" components = set() # Klasse/Modul-Name → Komponenten-Name component_patterns = { "PresenceEngine": "PresenceEngine", "presence_engine": "PresenceEngine", "OnboardingSm": "OnboardingSm", "onboarding": "OnboardingSm", "Archivar": "Archivar", "archivar": "Archivar", "Router": "Router", "router": "Router", "Booster": "Booster", "booster": "Booster", "RoomMap": "RoomMap", "room_map": "RoomMap", "ButtonBuilder": "ButtonBuilder", "button_builder": "ButtonBuilder", "DDPClient": "DDPClient", "ddp": "DDPClient", "RocketChatREST": "RocketChatREST", "adapter": "Adapter", } for line in journal_entries: for pattern, component in component_patterns.items(): if pattern in line: components.add(component) return sorted(components) if components else ["unknown"] # ── Counter-Drift-Rekonstruktion ───────────────────────────────────────── def reconstruct_counter_drift(baseline_json: Optional[Dict[str, Any]]) -> Dict[str, Any]: """Vergleicht erwartete Counter (aus baseline) mit Ist-Zustand. baseline_json: Inhalt von gateway_state.json oder restart_loop.json Returns: {counter: {expected, actual, drift}} """ drift: Dict[str, Dict[str, Any]] = {} if not baseline_json: return drift counters_expected = baseline_json.get("counters", {}) if not counters_expected: return drift # Aktuelle Counter sind nach Crash immer 0 (frischer Prozess) for counter_name, expected_value in counters_expected.items(): if isinstance(expected_value, (int, float)): drift[counter_name] = { "expected": expected_value, "actual": 0, "drift": expected_value, } return drift # ── State-Loss-Analyse ──────────────────────────────────────────────────── def _analyze_state_loss(gateway_state: Optional[Dict[str, Any]]) -> List[str]: """Identifiziere In-Memory-Objekte die nach Crash leer sind.""" lost = [] if not gateway_state: return ["gateway_state.json not found"] # Prüfe typische In-Memory-Strukturen die im State gespeichert werden state_objects = [ "active_sessions", "pending_clarifies", "pending_move_requests", "session_room_preferences", "recent_auto_routes", "explicit_switch_sticky", "clarify_state", "onboarding_state", ] for obj_name in state_objects: val = gateway_state.get(obj_name) if val is not None and (val == [] or val == {} or val == 0 or val is None): lost.append(obj_name) return lost if lost else ["none"] # ── Forensik-Report-Formatierung ───────────────────────────────────────── def format_crash_forensic_report( crash_source: str, blast_radius: List[str], user_visibility: str, recovery_time_s: float, counter_drift: Dict[str, Any], state_loss: List[str], predecessor_pid: int, journal_summary: str, ) -> str: """Formatiere strukturierten Forensik-Report mit 6 Datenpunkten. Alle Zeilen mit 'CRASH-FORENSIK:' Präfix für einfaches Greppen. """ lines = [ "CRASH-FORENSIK: ================================================================", f"CRASH-FORENSIK: Vorgänger-Crash erkannt — predecessor_pid={predecessor_pid}", f"CRASH-FORENSIK: (1) crash_source={crash_source}", f"CRASH-FORENSIK: (2) blast_radius={','.join(blast_radius)}", f"CRASH-FORENSIK: (3) user_visibility={user_visibility}", f"CRASH-FORENSIK: (4) recovery_time={recovery_time_s:.1f}s", ] if counter_drift: drift_str = " ".join( f"{k}:{v['expected']}→{v['actual']}(Δ{v['drift']})" for k, v in sorted(counter_drift.items()) ) lines.append(f"CRASH-FORENSIK: (5) counter_drift={drift_str}") else: lines.append("CRASH-FORENSIK: (5) counter_drift=none") lines.append(f"CRASH-FORENSIK: (6) state_loss={','.join(state_loss)}") lines.append(f"CRASH-FORENSIK: journal_summary={journal_summary}") lines.append("CRASH-FORENSIK: ================================================================") return "\n".join(lines) # ── Master-Funktion ────────────────────────────────────────────────────── async def check_for_predecessor_crash() -> Optional[str]: """Master-Funktion: Prüft auf Vorgänger-Crash via 4-Quellen-Korrelation. Returns: Formatierter Forensik-Report-String wenn Crash erkannt, sonst None. NIEMALS Exception werfen — alle Fehler werden geloggt und führen zu None. """ try: # ── Filter 1: Heartbeat prüfen ────────────────────────────────── heartbeat = _read_heartbeat() if not heartbeat: logger.debug("crash_forensics: no heartbeat file — skipping") return None predecessor_pid = heartbeat.get("pid", 0) current_pid = os.getpid() # Gleicher PID = kein Crash (eigener Heartbeat) if predecessor_pid == current_pid: logger.debug("crash_forensics: heartbeat pid matches current — skipping") return None # Heartbeat zu alt → veraltete Leiche heartbeat_ts = heartbeat.get("ts", 0) heartbeat_age = time.time() - heartbeat_ts if heartbeat_age > HEARTBEAT_MAX_AGE_S: logger.debug( "crash_forensics: heartbeat age %.0fs > %ds — skipping stale corpse", heartbeat_age, HEARTBEAT_MAX_AGE_S, ) return None # ── Filter 2: planned_takeover prüfen ─────────────────────────── if _is_planned_takeover(): logger.info( "crash_forensics: planned takeover detected — predecessor pid=%d was " "replaced via --replace, NOT a crash", predecessor_pid, ) return None # ── Quelle 1: Heartbeat-Leiche bestätigt ──────────────────────── logger.info( "crash_forensics: heartbeat corpse found — predecessor pid=%d, " "age=%.0fs, current pid=%d", predecessor_pid, heartbeat_age, current_pid, ) # ── Quelle 2: journalctl ──────────────────────────────────────── journal_since = heartbeat_ts - 10 # 10s vor Heartbeat für Kontext journal_entries = await gather_journal_for_pid(predecessor_pid, journal_since) crash_source = classify_crash_source(journal_entries) blast_radius = _analyze_blast_radius(journal_entries) # Journal-Summary: letzte 3 relevante Zeilen journal_summary = "..." crash_lines = [ ln for ln in journal_entries if any(kw in ln.lower() for kw in ("killed", "dumped", "traceback", "error", "signal", "exit")) ] if crash_lines: journal_summary = " | ".join(crash_lines[-3:])[:200] # ── Quelle 3: restart_loop.json ───────────────────────────────── restart_loop = _read_json(RESTART_LOOP_PATH) restart_loop_crash = False if restart_loop: boot_ts = restart_loop.get("boot_ts", 0) if boot_ts and (time.time() - boot_ts) < RESTART_LOOP_WINDOW_S: restart_loop_crash = True logger.info( "crash_forensics: restart_loop.json confirms crash — " "boot_ts=%.0fs ago", time.time() - boot_ts, ) # ── Quelle 4: gateway_state.json ───────────────────────────────── gateway_state = _read_json(GATEWAY_STATE_PATH) gateway_state_stale = False if gateway_state and heartbeat: updated_at = gateway_state.get("updated_at", 0) if updated_at and (heartbeat_ts - updated_at) > GATEWAY_STATE_STALE_S: gateway_state_stale = True logger.info( "crash_forensics: gateway_state.json stale — " "updated_at=%.0fs before heartbeat", heartbeat_ts - updated_at, ) # ── Korrelation: Mindestens 2 Quellen müssen zustimmen ───────── crash_signals = sum([ True, # Heartbeat-Leiche (immer True an dieser Stelle) bool(journal_entries and crash_source != "unknown"), restart_loop_crash, gateway_state_stale, ]) if crash_signals < 2: logger.debug( "crash_forensics: only %d/4 crash signals — insufficient correlation, " "skipping report", crash_signals, ) return None # ── Datenpunkte sammeln ───────────────────────────────────────── # (3) user_visibility user_visibility = "unknown" if gateway_state: last_status = gateway_state.get("last_status", "unknown") last_msg_age = "N/A" last_msg_ts = gateway_state.get("last_message_ts", 0) if last_msg_ts: last_msg_age = f"{time.time() - last_msg_ts:.0f}s ago" user_visibility = f"status={last_status}, last_msg={last_msg_age}" # (4) recovery_time recovery_time_s = heartbeat_age # (5) counter_drift counter_drift = reconstruct_counter_drift(gateway_state) # (6) state_loss state_loss = _analyze_state_loss(gateway_state) # ── Report formatieren ─────────────────────────────────────────── report = format_crash_forensic_report( crash_source=crash_source, blast_radius=blast_radius, user_visibility=user_visibility, recovery_time_s=recovery_time_s, counter_drift=counter_drift, state_loss=state_loss, predecessor_pid=predecessor_pid, journal_summary=journal_summary, ) return report except Exception as exc: logger.warning("crash_forensics: check_for_predecessor_crash failed: %s", exc, exc_info=True) return None # ── Test-Mode: Simulierter Forensik-Testlauf ───────────────────────────── async def run_post_crash_forensic_test() -> str: """Test-Mode: Simuliert einen Forensik-Durchlauf mit synthetischen Daten. Kann von Bernd manuell aufgerufen werden um die Forensik-Pipeline zu testen ohne einen echten Gateway-Crash zu provozieren. Returns: Formatierter Test-Report-String. """ # Simulierte Journal-Einträge mit Plugin-Crash-Signatur fake_journal = [ "hermes-gateway[12345]: Traceback (most recent call last):", "hermes-gateway[12345]: File \"/home/bernd/.hermes/plugins/platforms/rocketchat/plugin/adapter.py\", line 2000, in _handle_message", "hermes-gateway[12345]: File \"/home/bernd/.hermes/plugins/platforms/rocketchat/plugin/archivar/presence_engine.py\", line 500, in resolve_phase", "hermes-gateway[12345]: File \"/home/bernd/.hermes/hermes-agent/agent/run_agent.py\", line 800, in run_conversation", "hermes-gateway[12345]: SystemExit: 75", "systemd[1]: hermes-gateway.service: Main process exited, code=killed, status=9/KILL", ] fake_gateway_state = { "updated_at": time.time() - 120, "last_status": "online", "last_message_ts": time.time() - 180, "counters": { "main_agent": 1, "delegate_subagent": 2, "chat_profile": 1, }, "active_sessions": [], "pending_clarifies": {}, "pending_move_requests": {}, } crash_source = classify_crash_source(fake_journal) blast_radius = _analyze_blast_radius(fake_journal) counter_drift = reconstruct_counter_drift(fake_gateway_state) state_loss = _analyze_state_loss(fake_gateway_state) report = format_crash_forensic_report( crash_source=crash_source, blast_radius=blast_radius, user_visibility="status=online, last_msg=180s ago", recovery_time_s=45.0, counter_drift=counter_drift, state_loss=state_loss, predecessor_pid=12345, journal_summary="SystemExit: 75 | code=killed, status=9/KILL", ) return report