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>
This commit is contained in:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-07 09:38:09 +03:00
1 parent ad6995bb63
commit 7d6f44c965
11 files changed
+287 -57

No files matched your search

+63 -3
View File
@@ -3,6 +3,7 @@ import logging
import signal
import sqlite3
import time
from datetime import datetime, timedelta
import pytest
@@ -17,11 +18,11 @@ HEADER = ("HEADER,CLIENT_LIST,Common Name,Real Address,Virtual Address,Virtual I
def write_status(path, now, clients, complete=True):
"""Synthetic OpenVPN status file v2. clients: (cn, real_address, rx, tx, connected_since_ts)."""
"""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 in clients:
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,1,0,AES-256-GCM")
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:
@@ -167,6 +168,24 @@ def test_torn_read_skips_the_tick(env):
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
@@ -196,6 +215,47 @@ def test_session_missing_for_a_tick_and_beyond_grace(env):
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()