f7cbe7dc83
3 Datenpunkte korrigiert (Viola-Schema-Analyse auf .101/.45):
(3) user_visibility:
- last_status: liest jetzt gateway_state['platforms']['rocketchat']['state']
(real vorhanden: online/busy/away/offline) statt nicht-existentem 'last_status'
- last_message_ts: nicht im Schema -> aus journalctl rekonstruiert via
_extract_last_user_message() (Adapter-Log 'Message from <user> in <room>')
- Fallback 'unavailable' wenn platforms-Struktur fehlt
(5) counter_drift:
- liest gateway_state['active_agents'] (einziger serialisierter Counter)
statt nicht-existentem 'counters'
- Format 'active_agents: N (vor Crash)' vs '0 (nach Neustart)'
- dokumentiert: chat_profile/delegate_subagent/main_agent sind In-Memory
in PresenceEngine, nie serialisiert
(6) state_loss:
- feste ehrliche Ausweisung 'in-memory (lost on crash) — active_sessions,
pending_clarifies, pending_move_requests' statt 'unknown'/'none'
- diese Objekte werden nie serialisiert, sind nach Crash grundsätzlich verloren
Test-Mode auf reales Schema umgestellt (fake_gateway_state + fake_journal).
947 lines
41 KiB
Python
947 lines
41 KiB
Python
"""
|
|
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_state.json"
|
|
TAKEOVER_MARKER_PATH = HERMES_HOME / ".gateway-takeover.json"
|
|
|
|
# P-074a: Historische Pfad-Varianten als Fallback. Der Core schreibt:
|
|
# - gateway_state.json → HERMES_HOME/gateway_state.json
|
|
# (status.py:_get_pid_path().with_name("gateway_state.json"), _get_pid_path
|
|
# = HERMES_HOME/gateway.pid → with_name = HERMES_HOME/gateway_state.json)
|
|
# - restart_loop.json → HERMES_HOME/gateway/restart_loop.json
|
|
# (restart_loop_guard.py:_state_path = get_hermes_home()/"gateway"/...)
|
|
# Die Fallback-Lagen decken ältere/abweichende Core-Versionen ab, damit die
|
|
# 4-Quellen-Korrelation nicht an einem Pfad-Mismatch scheitert.
|
|
RESTART_LOOP_PATH_FALLBACK = HERMES_HOME / "restart_loop.json"
|
|
GATEWAY_STATE_PATH_FALLBACK = HERMES_HOME / "gateway" / "gateway_state.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 _get_process_start_time() -> float:
|
|
"""Ermittelt die Unix-Startzeit des aktuellen Prozesses via /proc/self/stat.
|
|
|
|
/proc/self/stat Feld 22 (1-indexed) = starttime in Clock-Ticks seit Boot.
|
|
/proc/stat enthält 'btime' = Boot-Zeit als Unix-Timestamp.
|
|
|
|
Returns:
|
|
Unix-Timestamp (float) der Prozess-Startzeit.
|
|
Fallback: time.time() wenn /proc nicht lesbar (Nicht-Linux).
|
|
"""
|
|
try:
|
|
# CLK_TCK (sysconf(_SC_CLK_TCK)) — typischerweise 100 auf Linux
|
|
clk_tck = os.sysconf(os.sysconf_names["SC_CLK_TCK"])
|
|
except (AttributeError, KeyError, ValueError):
|
|
clk_tck = 100 # Linux-Default
|
|
|
|
try:
|
|
# /proc/self/stat: Feld 22 = starttime (1-indexed, nach ')')
|
|
stat_content = Path("/proc/self/stat").read_text(encoding="utf-8")
|
|
# Format: pid (comm) state ppid ... starttime ...
|
|
# comm kann Leerzeichen enthalten → nach ')' splitten
|
|
after_comm = stat_content.rsplit(")", 1)[-1]
|
|
fields = after_comm.split()
|
|
# Nach ')' ist Feld 3 = state, Feld 4 = ppid, ... Feld 20 = starttime
|
|
# Also Index 19 (0-basiert) nach dem Split
|
|
if len(fields) >= 20:
|
|
starttime_ticks = int(fields[19])
|
|
else:
|
|
raise ValueError(f"Unexpected /proc/self/stat format: {len(fields)} fields")
|
|
except (OSError, ValueError, IndexError) as exc:
|
|
logger.debug("crash_forensics: cannot read /proc/self/stat: %s", exc)
|
|
return time.time()
|
|
|
|
try:
|
|
# /proc/stat: btime = Boot-Zeit als Unix-Timestamp
|
|
stat_content = Path("/proc/stat").read_text(encoding="utf-8")
|
|
for line in stat_content.splitlines():
|
|
if line.startswith("btime "):
|
|
boot_time = int(line.split()[1])
|
|
break
|
|
else:
|
|
raise ValueError("btime not found in /proc/stat")
|
|
except (OSError, ValueError) as exc:
|
|
logger.debug("crash_forensics: cannot read /proc/stat btime: %s", exc)
|
|
return time.time()
|
|
|
|
return boot_time + (starttime_ticks / clk_tck)
|
|
|
|
|
|
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 _resolve_path(primary: Path, fallback: Path) -> Optional[Path]:
|
|
"""P-074a: Primärpfad auflösen, bei Nicht-Existenz auf Fallback ausweichen.
|
|
|
|
Gibt den ersten existierenden Pfad zurück, sonst None. Verhindert, dass
|
|
die 4-Quellen-Korrelation an einem Pfad-Mismatch (Core schreibt an anderer
|
|
Stelle als das Plugin liest) scheitert. Quelle wird bei fehlender Datei
|
|
als 'nicht verfügbar' gewertet — kein Fehler, kein False-Positive.
|
|
"""
|
|
if primary.exists():
|
|
return primary
|
|
if fallback.exists():
|
|
logger.debug(
|
|
"crash_forensics: primary path %s missing — using fallback %s",
|
|
primary, fallback,
|
|
)
|
|
return fallback
|
|
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 []
|
|
|
|
|
|
def _extract_last_user_message(journal_entries: List[str]) -> Optional[str]:
|
|
"""Extrahiert die letzte User-Nachricht vor dem Crash aus Journal-Einträgen.
|
|
|
|
P-075: last_message_ts existiert NICHT im realen gateway_state.json-Schema.
|
|
Die letzte User-Aktivität vor dem Crash muss daher aus journalctl rekonstruiert
|
|
werden. Der Adapter loggt eingehende Nachrichten als:
|
|
|
|
"[rocketchat] Message from <user> in <room> [<type>]: <text>"
|
|
|
|
(adapter.py:2375). Diese Zeile ist der zuverlässigste Indikator für die
|
|
letzte User-Nachricht vor dem Crash.
|
|
|
|
Returns:
|
|
Formatierter String "user=<user>, room=<room>, text=<text>" oder None
|
|
wenn keine Nachrichten-Zeile gefunden wurde.
|
|
"""
|
|
message_lines = [ln for ln in journal_entries if "Message from" in ln]
|
|
if not message_lines:
|
|
return None
|
|
|
|
# Chronologisch letzte Nachricht (Journal ist aufsteigend sortiert)
|
|
last = message_lines[-1]
|
|
try:
|
|
after_marker = last.split("Message from", 1)[1].strip()
|
|
# after_marker = "<user> in <room> [<type>]: <text>"
|
|
user, _, rest = after_marker.partition(" in ")
|
|
room, _, rest = rest.partition(" [")
|
|
_, _, text = rest.partition("]: ")
|
|
return f"user={user.strip()}, room={room.strip()}, text={text.strip()[:60]}"
|
|
except Exception:
|
|
# Fallback: rohe Zeile (gekürzt) wenn das Format nicht passt
|
|
return last.strip()[:120]
|
|
|
|
|
|
# ── 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
|
|
"mixed" — Traceback enthält beide Pfade
|
|
"external (SIGKILL)" — systemd meldet status=9/KILL oder code=killed
|
|
OHNE Python-Traceback (kill -9, OOM-Killer)
|
|
"unknown" — keine Crash-Informationen gefunden
|
|
"""
|
|
plugin_hits = 0
|
|
core_hits = 0
|
|
sigkill_hits = 0
|
|
for line in journal_entries:
|
|
if "plugin/" in line or "/plugin/" in line:
|
|
plugin_hits += 1
|
|
# Core-Pfad: hermes-agent/ (Bindestrich, realer Install-Pfad) ODER
|
|
# hermes_agent/ (Unterstrich, historische/importierte Variante).
|
|
if (
|
|
"hermes_agent/" in line
|
|
or "/hermes_agent/" in line
|
|
or "hermes-agent/" in line
|
|
or "/hermes-agent/" in line
|
|
):
|
|
core_hits += 1
|
|
# P-074b: SIGKILL-Signatur — systemd beendet den Prozess hart, es gibt
|
|
# KEINEN Python-Traceback. Muster: 'status=9/KILL', 'code=killed',
|
|
# 'signal=KILL', 'SIGKILL'. Diese Zeilen sind ein eigenständiges
|
|
# Crash-Signal, kein Plugin-vs-Core-Crash.
|
|
low = line.lower()
|
|
if (
|
|
"status=9" in low
|
|
or "code=killed" in low
|
|
or "signal=kill" in low
|
|
or "sigkill" in low
|
|
):
|
|
sigkill_hits += 1
|
|
|
|
# P-074b: SIGKILL hat Vorrang, wenn kein Traceback vorliegt. Ein externer
|
|
# Kill (kill -9 / OOM) ist weder Plugin- noch Core-Crash — eigene Kategorie.
|
|
if sigkill_hits > 0 and plugin_hits == 0 and core_hits == 0:
|
|
return "external (SIGKILL)"
|
|
|
|
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.
|
|
|
|
P-075: Das reale gateway_state.json-Schema enthält KEIN 'counters'-Feld.
|
|
Die detaillierten Counter (chat_profile, delegate_subagent, main_agent)
|
|
sind In-Memory in der PresenceEngine und werden NIE serialisiert.
|
|
|
|
Der EINZIGE verfügbare Counter im realen Schema ist 'active_agents'
|
|
(int, z.B. 0). Wenn dieser vor dem Crash > 0 war, ist das der Drift —
|
|
nach dem Neustart ist er immer 0 (frischer Prozess).
|
|
|
|
baseline_json: Inhalt von gateway_state.json oder restart_loop.json
|
|
Returns: {'active_agents': {expected, actual, drift}} oder {} wenn
|
|
active_agents nicht vorhanden ist.
|
|
"""
|
|
drift: Dict[str, Dict[str, Any]] = {}
|
|
if not baseline_json:
|
|
return drift
|
|
|
|
# P-075: active_agents ist der einzige serialisierte Counter.
|
|
# Keine detaillierten Counter (chat_profile, delegate_subagent, main_agent)
|
|
# — die sind In-Memory in der PresenceEngine, nie serialisiert.
|
|
active_agents = baseline_json.get("active_agents")
|
|
if not isinstance(active_agents, (int, float)):
|
|
return drift
|
|
|
|
# Nach Crash ist active_agents immer 0 (frischer Prozess)
|
|
drift["active_agents"] = {
|
|
"expected": active_agents,
|
|
"actual": 0,
|
|
"drift": active_agents,
|
|
}
|
|
return drift
|
|
|
|
|
|
# ── State-Loss-Analyse ────────────────────────────────────────────────────
|
|
|
|
def _analyze_state_loss(gateway_state: Optional[Dict[str, Any]]) -> List[str]:
|
|
"""Weist In-Memory-Objekte aus, die bei einem Crash grundsätzlich verloren gehen.
|
|
|
|
P-075: active_sessions, pending_clarifies und pending_move_requests sind
|
|
In-Memory-Objekte der PresenceEngine/des Adapters. Sie werden NIE in
|
|
gateway_state.json serialisiert — sie existieren nur im laufenden Prozess
|
|
und sind nach einem Crash grundsätzlich verloren.
|
|
|
|
Statt 'unknown' (suggeriert Unwissen) wird ehrlich 'lost on crash'
|
|
ausgewiesen: Der User weiß damit klar, dass diese Daten bei einem Crash
|
|
verloren gehen.
|
|
"""
|
|
if not gateway_state:
|
|
return ["gateway_state.json not found"]
|
|
|
|
# P-075: Diese In-Memory-Objekte werden nie serialisiert — sie sind nach
|
|
# einem Crash grundsätzlich verloren. Feste, ehrliche Ausweisung statt
|
|
# 'unknown' oder 'none'.
|
|
return [
|
|
"in-memory (lost on crash) — active_sessions, pending_clarifies, pending_move_requests"
|
|
]
|
|
|
|
|
|
# ── 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:
|
|
# ── Timing-Verifikation (Rainer-Ergänzung P-072): ────────────────
|
|
# Prüft ob Plugin-Init VOR dem ersten connect() läuft.
|
|
# Wenn diese Zeile im Log erscheint BEVOR der Core-Heartbeat
|
|
# geschrieben wird, ist die Race-Condition bestätigt.
|
|
_proc_start = _get_process_start_time()
|
|
logger.info(
|
|
"crash_forensics: P-072 timing check — process_start=%.3f, "
|
|
"now=%.3f, delta=%.3fs (plugin init → forensics check)",
|
|
_proc_start, time.time(), time.time() - _proc_start,
|
|
)
|
|
|
|
# ── 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()
|
|
|
|
# P-072: PID-Vergleich + start_time-Check (Don's Race-Condition)
|
|
# Problem: Core-Heartbeat-Writer überschreibt heartbeat.pid mit
|
|
# current_pid BEVOR Plugin connect() aufruft → pid==current_pid
|
|
# → Forensik überspringt Crash-Erkennung.
|
|
# Fix: Wenn pid==current_pid, zusätzlich heartbeat.start_time mit
|
|
# Prozess-Start vergleichen.
|
|
if predecessor_pid == current_pid:
|
|
hb_start_time = heartbeat.get("start_time")
|
|
if hb_start_time is not None and isinstance(hb_start_time, (int, float)):
|
|
# Toleranz: 2s — Heartbeat-Schreibzeit vs. /proc/stat-Auflösung
|
|
if _proc_start - float(hb_start_time) > 2.0:
|
|
# Heartbeat start_time ist DEUTLICH älter als aktueller
|
|
# Prozess-Start → Vorgänger-Crash (Don's Race erkannt!)
|
|
logger.info(
|
|
"crash_forensics: P-072 RACE DETECTED — heartbeat.pid=%d "
|
|
"matches current_pid=%d BUT heartbeat.start_time=%.3f is "
|
|
"%.1fs OLDER than process start_time=%.3f → predecessor crash",
|
|
predecessor_pid, current_pid,
|
|
float(hb_start_time), _proc_start - float(hb_start_time),
|
|
_proc_start,
|
|
)
|
|
# NICHT returnen — weiter mit Forensik!
|
|
else:
|
|
# Heartbeat start_time ist NEU (>= Prozess-Start) →
|
|
# frischer Start, kein Crash (False-Positive-Schutz)
|
|
logger.debug(
|
|
"crash_forensics: P-072 fresh start confirmed — "
|
|
"heartbeat.pid=%d == current_pid=%d AND "
|
|
"heartbeat.start_time=%.3f >= process_start=%.3f "
|
|
"(delta=%.1fs) → no crash",
|
|
predecessor_pid, current_pid,
|
|
float(hb_start_time), _proc_start,
|
|
_proc_start - float(hb_start_time),
|
|
)
|
|
return None
|
|
else:
|
|
# Kein start_time im Heartbeat → Fallback auf alte Logik
|
|
# (konservativ: kein Crash melden)
|
|
logger.debug(
|
|
"crash_forensics: heartbeat pid matches current AND no "
|
|
"start_time in heartbeat — skipping (conservative fallback)"
|
|
)
|
|
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 ─────────────────────────────────
|
|
# P-074a: Pfad dynamisch auflösen (primär + Fallback). Fehlt die Datei
|
|
# auf beiden Lagen, ist die Quelle 'nicht verfügbar' — kein Fehler.
|
|
restart_loop_path = _resolve_path(RESTART_LOOP_PATH, RESTART_LOOP_PATH_FALLBACK)
|
|
restart_loop = _read_json(restart_loop_path) if restart_loop_path else None
|
|
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,
|
|
)
|
|
else:
|
|
logger.debug(
|
|
"crash_forensics: restart_loop.json not found at %s or %s — "
|
|
"source 3 unavailable", RESTART_LOOP_PATH, RESTART_LOOP_PATH_FALLBACK,
|
|
)
|
|
|
|
# ── Quelle 4: gateway_state.json ─────────────────────────────────
|
|
# P-074a: Pfad dynamisch auflösen (primär + Fallback).
|
|
gateway_state_path = _resolve_path(GATEWAY_STATE_PATH, GATEWAY_STATE_PATH_FALLBACK)
|
|
gateway_state = _read_json(gateway_state_path) if gateway_state_path else None
|
|
gateway_state_stale = False
|
|
if gateway_state and heartbeat:
|
|
updated_at = gateway_state.get("updated_at", 0)
|
|
# P-074c: updated_at ist im realen Core-Schema ein ISO-String
|
|
# (z.B. "2026-08-15T08:09:34.985914+00:00"), kein Unix-Float.
|
|
# Vor dem Pfad-Fix war gateway_state immer None (Pfad-Mismatch),
|
|
# daher lief dieser Code nie — der Typ-Bug war latent.
|
|
if isinstance(updated_at, str):
|
|
try:
|
|
updated_at = datetime.fromisoformat(
|
|
updated_at.replace("Z", "+00:00")
|
|
).timestamp()
|
|
except (ValueError, TypeError):
|
|
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
|
|
# P-075: last_status/last_message_ts existieren NICHT im realen Schema.
|
|
# - last_status → gateway_state['platforms']['rocketchat']['state']
|
|
# (real vorhanden: 'online', 'busy', 'away', 'offline')
|
|
# - last_message_ts → aus journalctl rekonstruiert (letzte User-Nachricht)
|
|
user_visibility = "unavailable"
|
|
if gateway_state:
|
|
platforms = gateway_state.get("platforms")
|
|
if isinstance(platforms, dict):
|
|
rc = platforms.get("rocketchat")
|
|
if isinstance(rc, dict):
|
|
last_status = rc.get("state", "unavailable")
|
|
last_msg = _extract_last_user_message(journal_entries)
|
|
if last_msg:
|
|
user_visibility = f"status={last_status}, last_msg={last_msg}"
|
|
else:
|
|
user_visibility = f"status={last_status}, last_msg=unavailable"
|
|
|
|
# (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",
|
|
"[rocketchat] Message from bernd in testraum [t]: Hallo, bitte pruefe den Status",
|
|
]
|
|
|
|
# P-075: Reales gateway_state.json-Schema (Viola-Analyse auf .101/.45).
|
|
# KEINE last_status/last_message_ts/counters/active_sessions-Felder.
|
|
fake_gateway_state = {
|
|
"pid": 12345,
|
|
"start_time": 8726113,
|
|
"updated_at": "2026-08-15T10:20:00+02:00",
|
|
"active_agents": 2,
|
|
"platforms": {
|
|
"rocketchat": {
|
|
"state": "online",
|
|
}
|
|
},
|
|
}
|
|
|
|
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)
|
|
|
|
# P-075: user_visibility aus realem Schema + journalctl-Rekonstruktion
|
|
last_status = fake_gateway_state["platforms"]["rocketchat"]["state"]
|
|
last_msg = _extract_last_user_message(fake_journal)
|
|
user_visibility = f"status={last_status}, last_msg={last_msg}"
|
|
|
|
# P-074b: SIGKILL-Szenario — reiner externer Kill ohne Traceback.
|
|
# Verifiziert, dass classify_crash_source() bei systemd 'status=9/KILL'
|
|
# eine Aussage liefert statt 'unknown'.
|
|
sigkill_journal = [
|
|
"systemd[1]: hermes-gateway.service: Main process exited, code=killed, status=9/KILL",
|
|
"systemd[1]: hermes-gateway.service: Failed with result 'signal'.",
|
|
]
|
|
sigkill_source = classify_crash_source(sigkill_journal)
|
|
logger.info(
|
|
"crash_forensics: P-074b SIGKILL classification check — "
|
|
"classify_crash_source(sigkill_journal)=%r", sigkill_source,
|
|
)
|
|
|
|
report = format_crash_forensic_report(
|
|
crash_source=crash_source,
|
|
blast_radius=blast_radius,
|
|
user_visibility=user_visibility,
|
|
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.
|
|
|
|
Drei Szenarien:
|
|
S1 (alt): heartbeat.pid != current_pid → Crash erkannt (bestehende Logik)
|
|
S2 (P-072 Don's Race): heartbeat.pid == current_pid, start_time ALT → Crash
|
|
S3 (P-072 False-Positive): heartbeat.pid == current_pid, start_time NEU → KEIN Crash
|
|
|
|
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 ALLE Szenarien bestanden, None wenn mindestens
|
|
ein Szenario fehlschlägt.
|
|
"""
|
|
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
|
|
|
|
current_pid = os.getpid()
|
|
proc_start = _get_process_start_time()
|
|
results: Dict[str, bool] = {}
|
|
|
|
try:
|
|
HEARTBEAT_PATH = test_heartbeat
|
|
RESTART_LOOP_PATH = test_restart_loop
|
|
TAKEOVER_MARKER_PATH = test_takeover
|
|
GATEWAY_STATE_PATH = test_gateway_state
|
|
|
|
# Gemeinsame restart_loop.json (frischer Boot → Crash-Signal)
|
|
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")
|
|
|
|
# ── S1: heartbeat.pid != current_pid (bestehende Logik) ──────────
|
|
logger.info("integration_test: === S1: pid != current_pid (existing logic) ===")
|
|
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")
|
|
report = await check_for_predecessor_crash()
|
|
results["S1"] = bool(report and "CRASH-FORENSIK:" in report)
|
|
logger.info(
|
|
"integration_test: S1 %s — pid=%d != current_pid=%d",
|
|
"PASS" if results["S1"] else "FAIL",
|
|
heartbeat_data["pid"], current_pid,
|
|
)
|
|
|
|
# ── S2: P-072 Don's Race — pid==current_pid, start_time ALT ──────
|
|
logger.info("integration_test: === S2: P-072 Don's Race (pid match, old start_time) ===")
|
|
old_start_time = proc_start - 120 # 2 Minuten VOR Prozess-Start
|
|
heartbeat_data = {
|
|
"pid": current_pid, # GLEICHE PID — Don's Race!
|
|
"updated_at": datetime.now(timezone.utc).isoformat(),
|
|
"start_time": old_start_time,
|
|
"monotonic": 12345.6,
|
|
}
|
|
test_heartbeat.write_text(json.dumps(heartbeat_data), encoding="utf-8")
|
|
report = await check_for_predecessor_crash()
|
|
results["S2"] = bool(report and "CRASH-FORENSIK:" in report)
|
|
logger.info(
|
|
"integration_test: S2 %s — pid=%d == current_pid=%d, "
|
|
"start_time=%.0f (%.0fs older than proc_start=%.0f)",
|
|
"PASS" if results["S2"] else "FAIL",
|
|
heartbeat_data["pid"], current_pid,
|
|
old_start_time, proc_start - old_start_time, proc_start,
|
|
)
|
|
|
|
# ── S3: P-072 False-Positive — pid==current_pid, start_time NEU ──
|
|
logger.info("integration_test: === S3: P-072 False-Positive (pid match, new start_time) ===")
|
|
new_start_time = proc_start + 5 # 5s NACH Prozess-Start (frischer Heartbeat)
|
|
heartbeat_data = {
|
|
"pid": current_pid, # GLEICHE PID
|
|
"updated_at": datetime.now(timezone.utc).isoformat(),
|
|
"start_time": new_start_time,
|
|
"monotonic": 12345.6,
|
|
}
|
|
test_heartbeat.write_text(json.dumps(heartbeat_data), encoding="utf-8")
|
|
report = await check_for_predecessor_crash()
|
|
# S3: KEIN Crash-Report erwartet (False-Positive-Schutz)
|
|
results["S3"] = not (report and "CRASH-FORENSIK:" in report)
|
|
logger.info(
|
|
"integration_test: S3 %s — pid=%d == current_pid=%d, "
|
|
"start_time=%.0f (%.0fs newer than proc_start=%.0f) → %s",
|
|
"PASS" if results["S3"] else "FAIL",
|
|
heartbeat_data["pid"], current_pid,
|
|
new_start_time, new_start_time - proc_start, proc_start,
|
|
"no report (correct)" if results["S3"] else "UNEXPECTED REPORT",
|
|
)
|
|
|
|
# ── Gesamtergebnis ───────────────────────────────────────────────
|
|
all_pass = all(results.values())
|
|
summary = ", ".join(f"{k}={v}" for k, v in sorted(results.items()))
|
|
if all_pass:
|
|
logger.info("integration_test: ALL PASS — %s", summary)
|
|
else:
|
|
failed = [k for k, v in results.items() if not v]
|
|
logger.warning("integration_test: FAILED scenarios: %s — %s", failed, summary)
|
|
|
|
return "ALL_PASS" if all_pass else None
|
|
|
|
finally:
|
|
# 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)
|