""" 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 datetime import datetime, timezone 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 _TAKEOVER_MARKER_TTL_S = 60 # aus gateway/status.py: Marker älter 60s = stale # ── 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. Echtes Schema (shutdown_watchdog.py:232-271): - pid: int - updated_at: ISO-String - start_time: optional, Unix-Float - monotonic: float - mem: optional (rss, mem_avail, swap) """ data = _read_json(HEARTBEAT_PATH) if not data: return None # 'pid' ist das einzige Pflichtfeld if "pid" not in data: return None return data def _parse_heartbeat_timestamp(heartbeat: Dict[str, Any]) -> Optional[float]: """Parse den Heartbeat-Zeitstempel aus 3 Quellen in Prioritäts-Reihenfolge. 1. 'start_time' (Unix-Float) — Prozess-Start, zuverlässigster Wert 2. 'updated_at' (ISO-String) — letzter Heartbeat-Schreibzeitpunkt 3. mtime der Heartbeat-Datei — letzter Fallback Returns: Unix-Timestamp (float) oder None wenn keine Quelle verfügbar. """ # Quelle 1: start_time (Unix-Float) — Prozess-Start start_time = heartbeat.get("start_time") if isinstance(start_time, (int, float)) and start_time > 0: return float(start_time) # Quelle 2: updated_at (ISO-String) updated_at = heartbeat.get("updated_at") if isinstance(updated_at, str): try: dt = datetime.fromisoformat(updated_at.replace("Z", "+00:00")) return dt.timestamp() except (ValueError, TypeError): pass # Quelle 3: mtime der Heartbeat-Datei try: return os.path.getmtime(HEARTBEAT_PATH) except OSError: pass return None def _parse_restart_loop_recent(restart_loop: Dict[str, Any]) -> bool: """Prüft ob restart_loop.json einen kürzlichen Crash anzeigt. Echtes Schema (restart_loop_guard.py:82-88): {'boots': [ts1, ts2, ...]} — Liste von Boot-Timestamps (Floats) Returns: True wenn der letzte Boot-Eintrag innerhalb RESTART_LOOP_WINDOW_S liegt. """ boots = restart_loop.get("boots", []) if not boots: return False try: last_boot = float(boots[-1]) except (TypeError, ValueError, IndexError): return False return (time.time() - last_boot) < RESTART_LOOP_WINDOW_S def _is_planned_takeover(heartbeat: Dict[str, Any]) -> bool: """Prüft ob ein --replace / geplanter Takeover stattfand. Zwei Prüfungen (nach Rainer-Review): 1. TTL: Marker älter als _TAKEOVER_MARKER_TTL_S (60s) → stale, ignorieren 2. start_time: Wenn Heartbeat 'start_time' neuer als Marker → geplanter Takeover Der Core (gateway/status.py:1601-1660) löscht den Marker nach erfolgreichem --replace Shutdown. Ein stale Marker (älter 60s) ist eine Leiche und darf keinen False-Positive-Crash-Report auslösen. """ marker = _read_json(TAKEOVER_MARKER_PATH) if not marker: return False # Prüfung 1: TTL — Marker muss frisch sein # Core-Verhalten (gateway/status.py:_marker_is_stale): ValueError/TypeError # beim Parsen → Marker ist stale → ignorieren. written_at = marker.get("written_at", "") if written_at: try: written_dt = datetime.fromisoformat(written_at.replace("Z", "+00:00")) marker_age = (datetime.now(timezone.utc) - written_dt).total_seconds() if marker_age > _TAKEOVER_MARKER_TTL_S: logger.debug( "crash_forensics: takeover marker stale (%.0fs > %ds TTL) — ignoring", marker_age, _TAKEOVER_MARKER_TTL_S, ) return False except (ValueError, TypeError): logger.debug( "crash_forensics: takeover marker has unparseable written_at=%r — " "treating as stale (matching Core _marker_is_stale behavior)", written_at, ) return False # Prüfung 2: Heartbeat start_time neuer als Marker → geplanter Takeover hb_start = heartbeat.get("start_time") if hb_start is not None and written_at: try: written_dt = datetime.fromisoformat(written_at.replace("Z", "+00:00")) marker_ts = written_dt.timestamp() if float(hb_start) > marker_ts: logger.debug( "crash_forensics: heartbeat start_time (%.0f) newer than " "takeover marker (%.0f) — planned takeover, not a crash", float(hb_start), marker_ts, ) return True except (ValueError, TypeError): pass # Frischer Marker existiert → konservativ als Takeover werten logger.debug("crash_forensics: fresh takeover marker found — skipping crash detection") return True # ── 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-Zeitstempel parsen (start_time → updated_at → mtime) heartbeat_ts = _parse_heartbeat_timestamp(heartbeat) if heartbeat_ts is None: logger.debug("crash_forensics: cannot determine heartbeat age — skipping") return None 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(heartbeat): 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: restart_loop_crash = _parse_restart_loop_recent(restart_loop) if restart_loop_crash: boots = restart_loop.get("boots", []) last_boot = float(boots[-1]) if boots else 0 logger.info( "crash_forensics: restart_loop.json confirms crash — " "last_boot=%.0fs ago", time.time() - last_boot, ) # ── 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 # ── Integrationstest: Echte Dateien ────────────────────────────────────── async def run_integration_test() -> Optional[str]: """Integrationstest: check_for_predecessor_crash() mit echten Dateien. Erstellt temporär: - gateway.heartbeat mit korrektem Schema (pid, updated_at, start_time) - restart_loop.json mit {'boots': [time.time()]} Ruft check_for_predecessor_crash() auf und prüft ob der CRASH-FORENSIK Report erscheint. Räumt die Test-Dateien danach wieder auf. Returns: Report-String wenn Test erfolgreich (Crash erkannt), None wenn nicht. """ import tempfile test_dir = Path(tempfile.mkdtemp(prefix="crash_forensics_test_")) test_heartbeat = test_dir / "gateway.heartbeat" test_restart_loop = test_dir / "restart_loop.json" test_takeover = test_dir / ".gateway-takeover.json" test_gateway_state = test_dir / "gateway_state.json" # Überschreibe globale Pfade für den Test global HEARTBEAT_PATH, RESTART_LOOP_PATH, TAKEOVER_MARKER_PATH, GATEWAY_STATE_PATH _orig_heartbeat = HEARTBEAT_PATH _orig_restart_loop = RESTART_LOOP_PATH _orig_takeover = TAKEOVER_MARKER_PATH _orig_gateway_state = GATEWAY_STATE_PATH try: HEARTBEAT_PATH = test_heartbeat RESTART_LOOP_PATH = test_restart_loop TAKEOVER_MARKER_PATH = test_takeover GATEWAY_STATE_PATH = test_gateway_state # 1. Echte gateway.heartbeat mit korrektem Schema erstellen fake_start_time = time.time() - 30 # vor 30s gestartet heartbeat_data = { "pid": 99999, # fake PID, != current_pid "updated_at": datetime.now(timezone.utc).isoformat(), "start_time": fake_start_time, "monotonic": 12345.6, } test_heartbeat.write_text(json.dumps(heartbeat_data), encoding="utf-8") logger.info("integration_test: wrote heartbeat — pid=%d, start_time=%.0f", heartbeat_data["pid"], fake_start_time) # 2. Echte restart_loop.json mit {'boots': [time.time()]} erstellen restart_data = {"boots": [time.time()]} test_restart_loop.parent.mkdir(parents=True, exist_ok=True) test_restart_loop.write_text(json.dumps(restart_data), encoding="utf-8") logger.info("integration_test: wrote restart_loop.json — boots=[%.0f]", restart_data["boots"][0]) # 3. check_for_predecessor_crash() aufrufen report = await check_for_predecessor_crash() # 4. Prüfen: CRASH-FORENSIK Eintrag muss erscheinen if report and "CRASH-FORENSIK:" in report: logger.info("integration_test: PASS — crash detected:\n%s", report) else: logger.warning("integration_test: FAIL — no crash report generated (report=%s)", report) return report finally: # 5. Test-Dateien löschen HEARTBEAT_PATH = _orig_heartbeat RESTART_LOOP_PATH = _orig_restart_loop TAKEOVER_MARKER_PATH = _orig_takeover GATEWAY_STATE_PATH = _orig_gateway_state import shutil shutil.rmtree(test_dir, ignore_errors=True) logger.info("integration_test: cleaned up %s", test_dir)