Files
OpenVPN-Monitoring-Simple/APP_CORE/test_gatherer.py
T

216 lines
7.6 KiB
Python
Raw Normal View History

import copy
import logging
import signal
import sqlite3
import time
import pytest
from openvpn_gatherer_v3 import OpenVPNDataGatherer
MB = 1024 * 1024
T0 = 1_800_000_000 # fixed "now" of the fake clock (epoch)
HEADER = ("HEADER,CLIENT_LIST,Common Name,Real Address,Virtual Address,Virtual IPv6 Address,"
"Bytes Received,Bytes Sent,Connected Since,Connected Since (time_t),Username,Client ID,"
"Peer ID,Data Channel Cipher")
def write_status(path, now, clients, complete=True):
"""Synthetic OpenVPN status file v2. clients: (cn, real_address, rx, tx, connected_since_ts)."""
lines = ["TITLE,OpenVPN 2.6.8 x86_64-pc-linux-gnu", f"TIME,Mon Jan 1 00:00:00 2027,{int(now)}", HEADER]
for cn, real, rx, tx, since in clients:
lines.append(f"CLIENT_LIST,{cn},{real},10.8.0.2,,{rx},{tx},Mon Jan 1 00:00:00 2027,{since},"
f"UNDEF,1,0,AES-256-GCM")
lines += ["HEADER,ROUTING_TABLE,Virtual Address,Common Name,Real Address,Last Ref,Last Ref (time_t)",
"GLOBAL_STATS,Max bcast/mcast queue length,0"]
if complete:
lines.append("END")
with open(path, "w") as f:
f.write("\n".join(lines) + "\n")
class Clock:
def __init__(self):
self.t = T0
def __call__(self):
return self.t
class FakeEvent:
"""Replaces threading.Event: records the pauses instead of sleeping."""
def __init__(self):
self.flag = False
self.delays = []
def is_set(self):
return self.flag
def set(self):
self.flag = True
def wait(self, timeout):
self.delays.append(timeout)
return self.flag
class Env:
def __init__(self, tmp_path):
self.status = str(tmp_path / "status.log")
self.db = str(tmp_path / "gatherer.db")
self.clock = Clock()
def gatherer(self):
"""New daemon 'started' at the current fake time (config.ini and log go to the cwd = tmp_path)."""
g = OpenVPNDataGatherer()
g._now = self.clock
g.started_at = self.clock()
return g
def tick(self, g, clients, complete=True, advance=10):
self.clock.t += advance
write_status(self.status, self.clock.t, clients, complete)
g.run_monitoring_cycle()
def query(self, sql, args=()):
conn = sqlite3.connect(self.db)
try:
return conn.execute(sql, args).fetchall()
finally:
conn.close()
def totals(self, cn):
return self.query("SELECT total_bytes_received, total_bytes_sent FROM clients WHERE common_name=?",
(cn,))[0]
def history_sum(self):
return self.query("SELECT COALESCE(SUM(bytes_received),0), COUNT(*) FROM usage_history")[0]
@pytest.fixture
def env(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path) # the gatherer writes config.ini and its log into the cwd
e = Env(tmp_path)
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", e.db)
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_LOG_PATH", e.status)
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
return e
def test_new_fast_session_is_counted_from_zero(env):
g = env.gatherer()
since = T0 + 5 # started 5 s before the first frame
env.tick(g, [("alice", "1.1.1.1:1000", 50 * MB, MB, since)])
# BUG-03: 50 MB in the very first frame must not be dropped as "a continuing session"
assert env.totals("alice") == (50 * MB, MB)
assert env.query("SELECT bytes_received FROM usage_history") == [(50 * MB,)]
# active_sessions holds the real session start (UTC), not the first observation time
assert env.query("SELECT connected_since FROM active_sessions") == \
[(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(since)),)]
env.tick(g, [("alice", "1.1.1.1:1000", 51 * MB, MB, since)])
assert env.totals("alice") == (51 * MB, MB)
def test_daemon_restart_uses_snapshot_or_sets_baseline(env, caplog):
since = T0 + 5
g1 = env.gatherer()
env.tick(g1, [("alice", "1.1.1.1:1000", 1000, 500, since)])
env.tick(g1, [("alice", "1.1.1.1:1000", 3000, 700, since)])
assert env.totals("alice") == (3000, 700)
# Daemon restarts; the session is older than the daemon and the snapshot is in active_sessions:
# the traffic of the downtime is counted, nothing is counted twice
env.clock.t += 100
g2 = env.gatherer()
env.tick(g2, [("alice", "1.1.1.1:1000", 9000, 1700, since)])
assert env.totals("alice") == (9000, 1700)
# Snapshot lost: baseline, increment 0, one line in the log with the client name
conn = sqlite3.connect(env.db)
conn.execute("DELETE FROM active_sessions")
conn.commit()
conn.close()
env.clock.t += 100
g3 = env.gatherer()
with caplog.at_level(logging.WARNING):
env.tick(g3, [("alice", "1.1.1.1:1000", 20000, 2000, since)])
assert env.totals("alice") == (9000, 1700)
assert any(r.levelno == logging.WARNING and "alice" in r.getMessage() for r in caplog.records)
# the baseline works from now on
env.tick(g3, [("alice", "1.1.1.1:1000", 21000, 2100, since)])
assert env.totals("alice") == (10000, 1800)
def test_torn_read_skips_the_tick(env):
g = env.gatherer()
since = T0 + 5
env.tick(g, [("alice", "1.1.1.1:1000", 1000, 100, since)])
db_before = (env.totals("alice"), env.history_sum(),
env.query("SELECT status FROM clients"), env.query("SELECT * FROM active_sessions"))
cache_before = copy.deepcopy(g.session_cache)
# Frame without END (read while OpenVPN rewrites the file): no clients visible
env.tick(g, [], complete=False)
assert g.invalid_ticks == 1
assert (env.totals("alice"), env.history_sum(),
env.query("SELECT status FROM clients"), env.query("SELECT * FROM active_sessions")) == db_before
assert g.session_cache == cache_before
# Next intact frame: the difference for both intervals, no duplicates
env.tick(g, [("alice", "1.1.1.1:1000", 3000, 300, since)])
assert g.invalid_ticks == 0
assert env.totals("alice") == (3000, 300)
assert env.history_sum() == (3000, 2)
def test_session_missing_for_a_tick_and_beyond_grace(env):
g = env.gatherer()
since = T0 + 5
def alice(rx, s):
return [("alice", "1.1.1.1:1000", rx, 0, s)]
env.tick(g, alice(1000, since))
# Missing for one tick, returns with the same key: continues, no double counting
env.tick(g, [])
env.tick(g, alice(1500, since))
assert env.totals("alice") == (1500, 0)
assert env.history_sum()[0] == 1500
assert env.query("SELECT status FROM clients") == [("Active",)]
# Grace period (3 ticks): kept for two missing ticks, forgotten on the third
env.tick(g, [])
env.tick(g, [])
assert len(g.session_cache) == 1 and list(g.session_cache.values())[0]["missing_ticks"] == 2
env.tick(g, [])
assert g.session_cache == {}
# Reconnect with a new connected_since: counted from zero (50 MB in the first frame)
env.tick(g, alice(50 * MB, env.clock.t + 10 - 5))
assert env.totals("alice") == (1500 + 50 * MB, 0)
assert len(g.session_cache) == 1
def test_loop_survives_exceptions_and_stops_on_signal(env):
g = env.gatherer()
g.stop_event = FakeEvent()
calls = []
def cycle():
calls.append(1)
if len(calls) <= 2:
raise RuntimeError("boom")
if len(calls) == 4:
g._handle_signal(signal.SIGTERM, None) # what the SIGTERM handler does
g.run_monitoring_cycle = cycle
g.start_monitoring() # returns normally, no exception escapes
# 2 failures (exponential pause), 1 success (reset), the cycle that got the signal finishes, then exit
assert len(calls) == 4
assert g.stop_event.delays == [20, 40, 10, 10]