Keep GSMTAP capture alive + server-side liveness logging

The GSMTAP capture thread died silently whenever a single non-SIM or
truncated GSMTAP datagram arrived (read_packet() raises ValueError,
uncaught in the loop, killing the daemon thread while UDP kept
flowing) — matching the "stops listening after a sniffer restart"
symptom.

Fixes:
- GsmtapListener.iter_messages() now catches ValueError/struct.error
  from read_packet(), drops the offending datagram (counted via a new
  `dropped` counter) and keeps listening.
- CaptureManager._capture_loop() guards the DB insert so a transient
  error can't kill the thread; a top-level guard logs
  "ERROR: capture thread stopped on error …" + traceback and clears
  the session so /api/status no longer reports a stuck "active".
- Server now logs capture liveness to stderr: "Capture started", a
  periodic "Capture alive: session=N messages=M bytes=B dropped=D"
  heartbeat (default every 60 s, configurable via log_interval), and
  "Capture stopped" (or "empty session discarded").

Tests: +5 (listener survives non-SIM/short packet, capture loop
survives insert error, logs stop-on-error, heartbeat+stop log).
Stays on 1.22.0 (backend-only).
This commit is contained in:
catarrh committed 2026-08-26 22:21:14 +03:00
1 parent 79acb3773f
commit 51e1b4ae08
3 files changed
+220 -8

No files matched your search

+133
View File
@@ -1,7 +1,10 @@
"""Tests for CaptureManager session lifecycle (empty-session discard)."""
import contextlib
import io
import os
import tempfile
import time
import unittest
from simtrace2_pysniff.server.capture import CaptureManager, gsmtap_msg_type
@@ -99,5 +102,135 @@ class TestCaptureManager(unittest.TestCase):
self.assertIsNone(mgr.device_connected)
class _FlakyReceiver:
"""Mimics GsmtapReceiver.read_packet, emitting scripted behaviors."""
def __init__(self, listener, behaviors):
self._listener = listener
self._behaviors = list(behaviors)
self._i = 0
def read_packet(self):
b = self._behaviors[self._i]
self._i += 1
if b == 'raise_non_sim':
raise ValueError('Not a GSMTAP SIM packet (type=99)')
if b == 'raise_short':
raise ValueError('GSMTAP packet too short: 3 bytes')
if b == 'none':
return None, None, 0
# 'good': return a valid APDU and terminate the loop.
self._listener._running = False
return 0x00, b'\x80\xf2\x00\x00\x00', 0
def close(self):
pass
class _NullDb:
def create_session(self, mode):
return 1
def count_messages(self, sid):
return 0
def delete_session(self, sid):
pass
def close_session(self, sid):
pass
def insert_message(self, *a, **k):
raise RuntimeError('db down')
class _OneShotBackend:
def start(self):
pass
def stop(self):
pass
def iter_messages(self):
yield ('tpdu', b'\x80\xf2\x00\x00\x00', 0)
class _RaisingBackend:
def start(self):
pass
def stop(self):
pass
def iter_messages(self):
raise RuntimeError('boom')
yield # unreachable
class TestGsmtapListenerRobustness(unittest.TestCase):
def test_listener_survives_bad_packet(self):
from simtrace2_pysniff.server.capture import GsmtapListener
listener = GsmtapListener(bind_port=0)
listener._receiver.close() # drop the real socket before swapping
listener._receiver = _FlakyReceiver(listener, ['raise_non_sim', 'good'])
listener.start()
out = list(listener.iter_messages())
listener.stop()
self.assertEqual(out, [('tpdu', b'\x80\xf2\x00\x00\x00', 0)])
self.assertEqual(listener.dropped, 1)
def test_listener_survives_short_packet(self):
from simtrace2_pysniff.server.capture import GsmtapListener
listener = GsmtapListener(bind_port=0)
listener._receiver.close() # drop the real socket before swapping
listener._receiver = _FlakyReceiver(listener, ['raise_short', 'good'])
listener.start()
out = list(listener.iter_messages())
listener.stop()
self.assertEqual(out, [('tpdu', b'\x80\xf2\x00\x00\x00', 0)])
self.assertEqual(listener.dropped, 1)
class TestCaptureLoopRobustness(unittest.TestCase):
def test_capture_loop_survives_insert_error(self):
mgr = CaptureManager(_OneShotBackend(), _NullDb())
mgr._session_id = 1
mgr._start_time = 0.0
# Must not raise; counters stay untouched on a dropped insert.
mgr._capture_loop()
self.assertEqual(mgr._session_id, 1)
self.assertEqual(mgr._msg_count, 0)
def test_capture_loop_logs_stop_on_error(self):
mgr = CaptureManager(_RaisingBackend(), _NullDb())
mgr._session_id = 7
mgr._start_time = 0.0
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
mgr._capture_loop()
self.assertIn('stopped on error', buf.getvalue())
self.assertIsNone(mgr._session_id)
def test_capture_heartbeat_and_stop_log(self):
tmp = tempfile.NamedTemporaryFile(suffix='.db', delete=False)
tmp.close()
db = Database(tmp.name)
mgr = CaptureManager(_FakeBackend([('tpdu', b'\x80\xf2\x00\x00\x00', 0)]), db)
mgr._log_interval = 0.05
buf = io.StringIO()
with contextlib.redirect_stderr(buf):
mgr.start_session()
time.sleep(0.25)
mgr.stop_session()
log = buf.getvalue()
self.assertIn('Capture started', log)
self.assertIn('Capture alive', log)
self.assertIn('messages=1', log)
self.assertIn('bytes=5', log)
self.assertIn('Capture stopped', log)
db._conn.close()
os.remove(tmp.name)
if __name__ == '__main__':
unittest.main()