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

+1
View File
@@ -13,6 +13,7 @@ The **Core Monitoring** module provides the backend logic for collecting, extrac
- A background service/daemon.
- Parses OpenVPN server logs (`status.log`).
- Aggregates bandwidth usage into time-series tables (`usage_history`, `stats_hourly`, etc.).
- Several simultaneous sessions of one user (`duplicate-cn`) are one record: traffic, speed and history are summed per common name; a session is identified by `Client ID` (see `DOCS/Core_Monitoring/Data_Architecture.md`).
## Configuration
+9
View File
@@ -459,8 +459,17 @@ def _m001_baseline(conn):
_ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0')
def _m002_session_id(conn):
"""active_sessions.session_id: the Client ID of the session from the OpenVPN v2 status
(part of the gatherer's session key). NULL is allowed: rows of an old snapshot and a
status without the Client ID column."""
if not any(row[1] == "session_id" for row in conn.execute("PRAGMA table_info(active_sessions)")):
conn.execute("ALTER TABLE active_sessions ADD COLUMN session_id TEXT")
MIGRATIONS = [
Migration(1, "baseline", _m001_baseline),
Migration(2, "session_id", _m002_session_id),
]
# No separate "fresh" schema: the baseline migration creates everything on a new database
+37 -21
View File
@@ -169,15 +169,20 @@ class OpenVPNAPI:
c.total_bytes_received,
c.total_bytes_sent,
-- Пиковая скорость Download за последние 2 минуты
(SELECT MAX(uh.bytes_received_rate_mbps)
FROM usage_history uh
WHERE uh.client_id = c.id
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_recv_rate,
-- (скорость пользователя = сумма по его сессиям на одной отметке времени)
(SELECT MAX(s.rate) FROM (
SELECT SUM(uh.bytes_received_rate_mbps) as rate
FROM usage_history uh
WHERE uh.client_id = c.id
AND uh.timestamp >= datetime('now', '-30 seconds')
GROUP BY uh.timestamp) s) as current_recv_rate,
-- Пиковая скорость Upload за последние 2 минуты
(SELECT MAX(uh.bytes_sent_rate_mbps)
FROM usage_history uh
WHERE uh.client_id = c.id
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_sent_rate,
(SELECT MAX(s.rate) FROM (
SELECT SUM(uh.bytes_sent_rate_mbps) as rate
FROM usage_history uh
WHERE uh.client_id = c.id
AND uh.timestamp >= datetime('now', '-30 seconds')
GROUP BY uh.timestamp) s) as current_sent_rate,
strftime('%Y-%m-%d %H:%M:%S', c.updated_at) as last_updated
FROM clients c
ORDER BY c.status DESC, c.common_name
@@ -288,17 +293,27 @@ class OpenVPNAPI:
points_count = 96
if is_high_res:
# Внутренний запрос: сумма по сессиям на одной отметке времени
# (старые строки хранят по записи на сессию), внешний: MAX скорости в интервале
query = f'''
SELECT
datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp,
SUM(uh.bytes_received) as bytes_received,
SUM(uh.bytes_sent) as bytes_sent,
MAX(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
MAX(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
FROM usage_history uh
JOIN clients c ON uh.client_id = c.id
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
GROUP BY datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch')
datetime((strftime('%s', u.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp,
SUM(u.bytes_received) as bytes_received,
SUM(u.bytes_sent) as bytes_sent,
MAX(u.bytes_received_rate_mbps) as bytes_received_rate_mbps,
MAX(u.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
FROM (
SELECT uh.timestamp as timestamp,
SUM(uh.bytes_received) as bytes_received,
SUM(uh.bytes_sent) as bytes_sent,
SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
FROM usage_history uh
JOIN clients c ON uh.client_id = c.id
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
GROUP BY uh.timestamp
) u
GROUP BY datetime((strftime('%s', u.timestamp) / {interval}) * {interval}, 'unixepoch')
ORDER BY timestamp ASC
'''
elif is_aggregated:
@@ -318,13 +333,14 @@ class OpenVPNAPI:
query = f'''
SELECT
uh.timestamp,
uh.bytes_received,
uh.bytes_sent,
uh.bytes_received_rate_mbps,
uh.bytes_sent_rate_mbps
SUM(uh.bytes_received) as bytes_received,
SUM(uh.bytes_sent) as bytes_sent,
SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
FROM usage_history uh
JOIN clients c ON uh.client_id = c.id
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
GROUP BY uh.timestamp
ORDER BY uh.timestamp ASC
'''
+68 -25
View File
@@ -135,7 +135,7 @@ class OpenVPNDataGatherer:
self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection)
# In-Memory Cache для отслеживания сессий:
# (CN, RealAddress, connected_since_ts) -> {
# (CN, Client ID или RealAddress, connected_since_ts) -> {
# 'bytes_received', 'bytes_sent': счётчики на прошлом тике,
# 'last_seen': строка времени, 'connected_since': строка UTC (начало сессии),
# 'missing_ticks': сколько тиков подряд сессии нет в статусе (льготный период)}
@@ -183,7 +183,7 @@ class OpenVPNDataGatherer:
conn = self.db_manager.get_connection()
try:
rows = conn.execute(
'SELECT common_name, real_address, bytes_received, bytes_sent, connected_since '
'SELECT common_name, real_address, bytes_received, bytes_sent, connected_since, session_id '
'FROM active_sessions'
).fetchall()
finally:
@@ -192,10 +192,11 @@ class OpenVPNDataGatherer:
self.logger.warning(f"Could not load active_sessions snapshot: {e}")
return
for name, real_addr, rx, tx, since in rows:
for name, real_addr, rx, tx, since, session_id in rows:
try:
since_ts = calendar.timegm(time.strptime(str(since)[:19].replace('T', ' '), TS_FORMAT))
self.baseline[(name, real_addr, since_ts)] = (int(rx), int(tx), self.started_at)
# Тот же ключ, что у сборщика; строки снимка без session_id совпадают по адресу
self.baseline[(name, session_id or real_addr, since_ts)] = (int(rx), int(tx), self.started_at)
except (ValueError, TypeError):
# Старый формат (локальное время первого наблюдения) - совпасть с ключом не может
continue
@@ -382,7 +383,14 @@ class OpenVPNDataGatherer:
status_time = None
clients = []
# Индекс колонки Client ID в строках CLIENT_LIST (None = в статусе колонки нет)
client_id_idx = None
for line in lines:
if line.startswith('HEADER,CLIENT_LIST,'):
# В строке заголовка первым идёт слово HEADER, в строках данных его нет: сдвиг на 1
header = [h.strip() for h in line.split(',')]
client_id_idx = header.index('Client ID') - 1 if 'Client ID' in header else None
continue
if line.startswith('TIME,'):
try:
status_time = int(line.split(',')[2])
@@ -417,9 +425,19 @@ class OpenVPNDataGatherer:
if since_ts is not None and since_ts <= 0:
since_ts = None
# Client ID не меняется при float (смене адреса): идентификатор сессии;
# нет колонки или не число - session_id None (ключ сессии с real_address)
session_id = None
if client_id_idx is not None and client_id_idx < len(parts):
try:
session_id = str(int(parts[client_id_idx].strip()))
except ValueError:
session_id = None
client = {
'common_name': parts[1].strip(),
'real_address': parts[2].strip(),
'session_id': session_id,
'bytes_received': int(parts[5].strip()),
'bytes_sent': int(parts[6].strip()),
'connected_since_ts': since_ts,
@@ -454,11 +472,11 @@ class OpenVPNDataGatherer:
Прирост для сессии, которой нет в кэше (правила: DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md, 2.2).
Возвращает (inc_recv, inc_sent).
"""
name, real_addr, since_ts = key
name, sess_id, since_ts = key
if since_ts is None:
# Нестандартный статус: время начала сессии неизвестно, запасная эвристика по размеру счётчиков
self.logger.warning(f"No connected_since time_t for {name} ({real_addr}): using 10 MB heuristic")
self.logger.warning(f"No connected_since time_t for {name} ({sess_id}): using 10 MB heuristic")
threshold = 10 * 1024 * 1024
if curr_recv < threshold and curr_sent < threshold:
return curr_recv, curr_sent
@@ -476,7 +494,7 @@ class OpenVPNDataGatherer:
# Сессия старше демона, снимка нет: базовая линия, трафик до этого момента потерян
self.logger.warning(
f"Session of {name} ({real_addr}) started before the gatherer and has no snapshot: "
f"Session of {name} ({sess_id}) started before the gatherer and has no snapshot: "
f"baseline set, {curr_recv} B received / {curr_sent} B sent before this moment are not counted"
)
return 0, 0
@@ -501,7 +519,8 @@ class OpenVPNDataGatherer:
db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()}
# Структура для агрегации инкрементов по Common Name перед записью в БД
# cn -> { 'inc_rx': 0, 'inc_tx': 0, 'curr_rx': 0, 'curr_tx': 0, 'real_address': '...'}
# cn -> { 'inc_recv': 0, 'inc_tx': 0, 'max_rx': 0 (сумма текущих счётчиков сессий),
# 'max_tx': 0, 'real_address': '...' (сессия с самым поздним началом)}
cn_updates = {}
# Новое состояние кэша сессий (применяется после commit) и активные CN
@@ -516,9 +535,9 @@ class OpenVPNDataGatherer:
curr_sent = client['bytes_sent']
since_ts = client.get('connected_since_ts')
# Уникальный ключ сессии: один и тот же CN/адрес может переподключиться
# (новый connected_since) - это уже новая сессия
session_key = (name, real_addr, since_ts)
# Уникальный ключ сессии: Client ID не меняется при float (смене адреса);
# без Client ID - адрес. Переподключение (новый connected_since) - новая сессия
session_key = (name, client.get('session_id') or real_addr, since_ts)
active_cns.add(name)
# --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) ---
@@ -560,17 +579,20 @@ class OpenVPNDataGatherer:
if name not in cn_updates:
cn_updates[name] = {
'inc_recv': 0, 'inc_tx': 0,
'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД сохраним текущие счетчики самой большой сессии (примерно)
'real_address': real_addr # Берем последний адрес
'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД: сумма текущих счётчиков всех сессий CN
'real_address': real_addr,
'addr_since': since_ts or 0 # Начало сессии, чей адрес сохранён
}
cn_updates[name]['inc_recv'] += inc_recv
cn_updates[name]['inc_tx'] += inc_sent
# Сохраняем "текущее" значение как максимальное из сессий, чтобы в БД last_bytes было хоть что-то осмысленное
# (хотя при in-memory подходе поле last_bytes в БД теряет смысл для логики, но нужно для UI)
cn_updates[name]['max_rx'] = max(cn_updates[name]['max_rx'], curr_recv)
cn_updates[name]['max_tx'] = max(cn_updates[name]['max_tx'], curr_sent)
cn_updates[name]['real_address'] = real_addr
# last_bytes в БД = сумма текущих счётчиков всех сессий CN (нужно для UI)
cn_updates[name]['max_rx'] += curr_recv
cn_updates[name]['max_tx'] += curr_sent
# real_address = адрес сессии с самым поздним началом
if (since_ts or 0) >= cn_updates[name]['addr_since']:
cn_updates[name]['addr_since'] = since_ts or 0
cn_updates[name]['real_address'] = real_addr
# 3. Льготный период для сессий, которых нет в текущем статусе:
# запись остаётся в кэше, пока missing_ticks < session_grace_ticks
@@ -657,8 +679,8 @@ class OpenVPNDataGatherer:
if sess_data:
cursor.execute('''
INSERT INTO active_sessions
(client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen)
VALUES (?, ?, ?, ?, ?, ?, ?)
(client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen, session_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (
client['db_id'],
client['common_name'],
@@ -666,7 +688,8 @@ class OpenVPNDataGatherer:
client['bytes_received'],
client['bytes_sent'],
sess_data['connected_since'],
sess_data['last_seen']
sess_data['last_seen'],
client.get('session_id')
))
conn.commit()
@@ -690,6 +713,19 @@ class OpenVPNDataGatherer:
return active_clients
@staticmethod
def merge_sessions_by_cn(sessions):
"""Сворачивает список сессий в список по CN: одна запись на пользователя за тик (сумма приростов)."""
merged = {}
for s in sessions:
m = merged.setdefault(s['common_name'], {
'common_name': s['common_name'], 'db_id': s.get('db_id'),
'bytes_received_inc': 0, 'bytes_sent_inc': 0
})
m['bytes_received_inc'] += s.get('bytes_received_inc', 0)
m['bytes_sent_inc'] += s.get('bytes_sent_inc', 0)
return list(merged.values())
def calculate_rates(self, clients, time_diff):
"""Расчет скорости в Mbps"""
if time_diff <= 0:
@@ -745,9 +781,15 @@ class OpenVPNDataGatherer:
# Рваное чтение / нет файла: тик пропускаем целиком, БД и кэш не трогаем.
# last_check_time тоже не меняем: скорость следующего тика считается за весь интервал
self.invalid_ticks += 1
level = logging.ERROR if self.invalid_ticks >= self.invalid_max else logging.WARNING
self.logger.log(level, f"Skipping tick ({self.invalid_ticks} in a row): {reading.reason}")
# В журнал: 1-й тик, порог status_invalid_max (ERROR), далее раз в 60 тиков.
# Иначе на свежей установке без запущенного OpenVPN сообщение шло бы каждые 10 с
n = self.invalid_ticks
if n == 1 or n == self.invalid_max or n % 60 == 0:
level = logging.ERROR if n >= self.invalid_max else logging.WARNING
self.logger.log(level, f"Skipping tick ({n} in a row): {reading.reason}")
else:
if self.invalid_ticks:
self.logger.info(f"Status file is readable again after {self.invalid_ticks} skipped ticks")
self.invalid_ticks = 0
if reading.stale:
self.logger.warning(reading.reason)
@@ -761,8 +803,9 @@ class OpenVPNDataGatherer:
if self.last_check_time:
time_diff = (current_time - self.last_check_time).total_seconds()
# 4. Считаем скорости
clients_rated = self.calculate_rates(clients_with_updates, time_diff)
# 4. Сворачиваем сессии в записи по CN и считаем скорости (сумма по сессиям)
clients_rated = self.calculate_rates(
self.merge_sessions_by_cn(clients_with_updates), time_diff)
# 5. Сохраняем RAW историю (для графиков реального времени)
self.store_usage_history(clients_rated)
+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()
+5 -4
View File
@@ -151,8 +151,9 @@ def test_old_schema_is_migrated_without_data_loss(tmp_path, schema):
# Missing tables and columns are there, existing rows get the defaults
assert {"active_sessions", "users", "login_attempts"} <= table_names(db)
assert query(db, "SELECT totp_secret, is_2fa_enabled FROM users") == [(None, 0)]
assert query(db, "SELECT session_id FROM active_sessions") in ([], [(None,)]) # migration 2: column exists, NULL
# Stamped, and the backup is the untouched pre-migration copy
assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline")]
assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline"), (2, "session_id")]
backups = glob.glob(db + ".bak-*")
assert backups == [report.backup]
assert [query(backups[0], q) for q in DATA_QUERIES] == before
@@ -204,7 +205,7 @@ def test_fresh_database_gets_full_schema_without_backup(tmp_path):
assert glob.glob(db + ".bak-*") == []
assert {"clients", "usage_history", "active_sessions", "users", "login_attempts",
"stats_5min", "stats_daily", "schema_migrations"} <= table_names(db)
assert query(db, "SELECT version FROM schema_migrations") == [(1,)]
assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)]
def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch):
@@ -242,5 +243,5 @@ def test_simultaneous_start_makes_one_backup(tmp_path):
assert errors == []
assert len(glob.glob(db + ".bak-*")) == 1
assert sorted(len(r.applied) for r in reports) == [0, 1]
assert query(db, "SELECT version FROM schema_migrations") == [(1,)]
assert sorted(len(r.applied) for r in reports) == [0, len(migrations.MIGRATIONS)]
assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)]