Files
ayurishchevandClaude Sonnet 5.5 7d6f44c965 Gatherer: aggregate several sessions of one user under the account
Session key uses the OpenVPN Client ID (survives float), one usage_history
row per user per tick, summed speeds in the API, last_bytes/real_address
per account, migration 2 (active_sessions.session_id). Also throttles the
"status file missing" log and reports recovery.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 09:38:09 +03:00

277 lines
11 KiB
Python

import copy
import logging
import signal
import sqlite3
import time
from datetime import datetime, timedelta
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[, client_id])."""
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, *cid 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,{cid[0] if cid else 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_missing_status_file_logs_sparingly_and_reports_recovery(env, caplog):
g = env.gatherer()
caplog.set_level(logging.INFO)
for _ in range(125): # no status file at all (OpenVPN not started yet)
g.run_monitoring_cycle()
skipped = [r for r in caplog.records if "Skipping tick" in r.getMessage()]
# tick 1, the threshold (6, ERROR), then every 60th
assert [r.getMessage().split("(")[1].split(" ")[0] for r in skipped] == ["1", "6", "60", "120"]
assert [r.levelno for r in skipped] == [logging.WARNING, logging.ERROR, logging.ERROR, logging.ERROR]
assert g.invalid_ticks == 125
caplog.clear()
env.tick(g, [("alice", "1.1.1.1:1000", 1000, 100, T0 + 5)])
again = [r for r in caplog.records if "readable again" in r.getMessage()]
assert len(again) == 1 and again[0].levelno == logging.INFO and "125" in again[0].getMessage()
assert g.invalid_ticks == 0
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_two_sessions_of_one_cn_are_one_record(env):
g = env.gatherer()
s1, s2 = T0 + 5, T0 + 8
def tick(rx1, rx2):
# скорость считается за 10 с (реальные часы теста не управляются)
g.last_check_time = datetime.now() - timedelta(seconds=10)
env.tick(g, [("alice", "1.1.1.1:1000", rx1, rx1 // 10, s1, 1),
("alice", "2.2.2.2:2000", rx2, rx2 // 10, s2, 2)])
tick(1000, 500)
tick(3000, 1500)
# Итоги = сумма обеих сессий; одна строка истории на тик, скорость = сумма сессий
assert env.totals("alice") == (4500, 450)
rows = env.query("SELECT bytes_received, bytes_received_rate_mbps FROM usage_history ORDER BY id")
assert [r[0] for r in rows] == [1500, 3000]
assert rows[1][1] == pytest.approx(3000 * 8 / 10 / 1_000_000, rel=0.01)
assert env.query("SELECT bytes_received FROM stats_5min") == [(4500,)]
# Одна сессия отключилась: статус Active, итог растёт только приростом оставшейся
env.tick(g, [("alice", "1.1.1.1:1000", 4000, 400, s1, 1)])
assert env.totals("alice") == (5500, 550)
assert env.query("SELECT status FROM clients") == [("Active",)]
def test_float_keeps_the_session_by_client_id(env):
since = T0 + 5
g = env.gatherer()
env.tick(g, [("alice", "1.1.1.1:1000", 1000, 100, since, 7)])
# float: другой адрес, тот же Client ID и начало - прирост = разница счётчиков
env.tick(g, [("alice", "2.2.2.2:2000", 3000, 300, since, 7)])
assert env.totals("alice") == (3000, 300)
assert env.query("SELECT real_address, session_id FROM active_sessions") == [("2.2.2.2:2000", "7")]
# Перезапуск демона: базовая линия из снимка по Client ID, адрес снова другой
env.clock.t += 100
g2 = env.gatherer()
env.tick(g2, [("alice", "3.3.3.3:3000", 9000, 900, since, 7)])
assert env.totals("alice") == (9000, 900)
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]