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

+3
View File
@@ -8,3 +8,6 @@ deploy/native/ui-dist.tar.gz
# Python caches (tests and compile steps create them inside the tree) # Python caches (tests and compile steps create them inside the tree)
__pycache__/ __pycache__/
*.pyc *.pyc
# local development environment
venv/
+1
View File
@@ -13,6 +13,7 @@ The **Core Monitoring** module provides the backend logic for collecting, extrac
- A background service/daemon. - A background service/daemon.
- Parses OpenVPN server logs (`status.log`). - Parses OpenVPN server logs (`status.log`).
- Aggregates bandwidth usage into time-series tables (`usage_history`, `stats_hourly`, etc.). - 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 ## Configuration
+9
View File
@@ -459,8 +459,17 @@ def _m001_baseline(conn):
_ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0') _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 = [ MIGRATIONS = [
Migration(1, "baseline", _m001_baseline), 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 # 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_received,
c.total_bytes_sent, c.total_bytes_sent,
-- Пиковая скорость Download за последние 2 минуты -- Пиковая скорость Download за последние 2 минуты
(SELECT MAX(uh.bytes_received_rate_mbps) -- (скорость пользователя = сумма по его сессиям на одной отметке времени)
FROM usage_history uh (SELECT MAX(s.rate) FROM (
WHERE uh.client_id = c.id SELECT SUM(uh.bytes_received_rate_mbps) as rate
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_recv_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 минуты -- Пиковая скорость Upload за последние 2 минуты
(SELECT MAX(uh.bytes_sent_rate_mbps) (SELECT MAX(s.rate) FROM (
FROM usage_history uh SELECT SUM(uh.bytes_sent_rate_mbps) as rate
WHERE uh.client_id = c.id FROM usage_history uh
AND uh.timestamp >= datetime('now', '-30 seconds')) as current_sent_rate, 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 strftime('%Y-%m-%d %H:%M:%S', c.updated_at) as last_updated
FROM clients c FROM clients c
ORDER BY c.status DESC, c.common_name ORDER BY c.status DESC, c.common_name
@@ -288,17 +293,27 @@ class OpenVPNAPI:
points_count = 96 points_count = 96
if is_high_res: if is_high_res:
# Внутренний запрос: сумма по сессиям на одной отметке времени
# (старые строки хранят по записи на сессию), внешний: MAX скорости в интервале
query = f''' query = f'''
SELECT SELECT
datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp, datetime((strftime('%s', u.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp,
SUM(uh.bytes_received) as bytes_received, SUM(u.bytes_received) as bytes_received,
SUM(uh.bytes_sent) as bytes_sent, SUM(u.bytes_sent) as bytes_sent,
MAX(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps, MAX(u.bytes_received_rate_mbps) as bytes_received_rate_mbps,
MAX(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps MAX(u.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
FROM usage_history uh FROM (
JOIN clients c ON uh.client_id = c.id SELECT uh.timestamp as timestamp,
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ? SUM(uh.bytes_received) as bytes_received,
GROUP BY datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch') 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 ORDER BY timestamp ASC
''' '''
elif is_aggregated: elif is_aggregated:
@@ -318,13 +333,14 @@ class OpenVPNAPI:
query = f''' query = f'''
SELECT SELECT
uh.timestamp, uh.timestamp,
uh.bytes_received, SUM(uh.bytes_received) as bytes_received,
uh.bytes_sent, SUM(uh.bytes_sent) as bytes_sent,
uh.bytes_received_rate_mbps, SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps,
uh.bytes_sent_rate_mbps SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps
FROM usage_history uh FROM usage_history uh
JOIN clients c ON uh.client_id = c.id JOIN clients c ON uh.client_id = c.id
WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ? WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ?
GROUP BY uh.timestamp
ORDER BY uh.timestamp ASC ORDER BY uh.timestamp ASC
''' '''
+68 -25
View File
@@ -135,7 +135,7 @@ class OpenVPNDataGatherer:
self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection) self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection)
# In-Memory Cache для отслеживания сессий: # In-Memory Cache для отслеживания сессий:
# (CN, RealAddress, connected_since_ts) -> { # (CN, Client ID или RealAddress, connected_since_ts) -> {
# 'bytes_received', 'bytes_sent': счётчики на прошлом тике, # 'bytes_received', 'bytes_sent': счётчики на прошлом тике,
# 'last_seen': строка времени, 'connected_since': строка UTC (начало сессии), # 'last_seen': строка времени, 'connected_since': строка UTC (начало сессии),
# 'missing_ticks': сколько тиков подряд сессии нет в статусе (льготный период)} # 'missing_ticks': сколько тиков подряд сессии нет в статусе (льготный период)}
@@ -183,7 +183,7 @@ class OpenVPNDataGatherer:
conn = self.db_manager.get_connection() conn = self.db_manager.get_connection()
try: try:
rows = conn.execute( 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' 'FROM active_sessions'
).fetchall() ).fetchall()
finally: finally:
@@ -192,10 +192,11 @@ class OpenVPNDataGatherer:
self.logger.warning(f"Could not load active_sessions snapshot: {e}") self.logger.warning(f"Could not load active_sessions snapshot: {e}")
return return
for name, real_addr, rx, tx, since in rows: for name, real_addr, rx, tx, since, session_id in rows:
try: try:
since_ts = calendar.timegm(time.strptime(str(since)[:19].replace('T', ' '), TS_FORMAT)) 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): except (ValueError, TypeError):
# Старый формат (локальное время первого наблюдения) - совпасть с ключом не может # Старый формат (локальное время первого наблюдения) - совпасть с ключом не может
continue continue
@@ -382,7 +383,14 @@ class OpenVPNDataGatherer:
status_time = None status_time = None
clients = [] clients = []
# Индекс колонки Client ID в строках CLIENT_LIST (None = в статусе колонки нет)
client_id_idx = None
for line in lines: 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,'): if line.startswith('TIME,'):
try: try:
status_time = int(line.split(',')[2]) status_time = int(line.split(',')[2])
@@ -417,9 +425,19 @@ class OpenVPNDataGatherer:
if since_ts is not None and since_ts <= 0: if since_ts is not None and since_ts <= 0:
since_ts = None 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 = { client = {
'common_name': parts[1].strip(), 'common_name': parts[1].strip(),
'real_address': parts[2].strip(), 'real_address': parts[2].strip(),
'session_id': session_id,
'bytes_received': int(parts[5].strip()), 'bytes_received': int(parts[5].strip()),
'bytes_sent': int(parts[6].strip()), 'bytes_sent': int(parts[6].strip()),
'connected_since_ts': since_ts, 'connected_since_ts': since_ts,
@@ -454,11 +472,11 @@ class OpenVPNDataGatherer:
Прирост для сессии, которой нет в кэше (правила: DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md, 2.2). Прирост для сессии, которой нет в кэше (правила: DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md, 2.2).
Возвращает (inc_recv, inc_sent). Возвращает (inc_recv, inc_sent).
""" """
name, real_addr, since_ts = key name, sess_id, since_ts = key
if since_ts is None: 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 threshold = 10 * 1024 * 1024
if curr_recv < threshold and curr_sent < threshold: if curr_recv < threshold and curr_sent < threshold:
return curr_recv, curr_sent return curr_recv, curr_sent
@@ -476,7 +494,7 @@ class OpenVPNDataGatherer:
# Сессия старше демона, снимка нет: базовая линия, трафик до этого момента потерян # Сессия старше демона, снимка нет: базовая линия, трафик до этого момента потерян
self.logger.warning( 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" f"baseline set, {curr_recv} B received / {curr_sent} B sent before this moment are not counted"
) )
return 0, 0 return 0, 0
@@ -501,7 +519,8 @@ class OpenVPNDataGatherer:
db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()} db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()}
# Структура для агрегации инкрементов по Common Name перед записью в БД # Структура для агрегации инкрементов по 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 = {} cn_updates = {}
# Новое состояние кэша сессий (применяется после commit) и активные CN # Новое состояние кэша сессий (применяется после commit) и активные CN
@@ -516,9 +535,9 @@ class OpenVPNDataGatherer:
curr_sent = client['bytes_sent'] curr_sent = client['bytes_sent']
since_ts = client.get('connected_since_ts') since_ts = client.get('connected_since_ts')
# Уникальный ключ сессии: один и тот же CN/адрес может переподключиться # Уникальный ключ сессии: Client ID не меняется при float (смене адреса);
# (новый connected_since) - это уже новая сессия # без Client ID - адрес. Переподключение (новый connected_since) - новая сессия
session_key = (name, real_addr, since_ts) session_key = (name, client.get('session_id') or real_addr, since_ts)
active_cns.add(name) active_cns.add(name)
# --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) --- # --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) ---
@@ -560,17 +579,20 @@ class OpenVPNDataGatherer:
if name not in cn_updates: if name not in cn_updates:
cn_updates[name] = { cn_updates[name] = {
'inc_recv': 0, 'inc_tx': 0, 'inc_recv': 0, 'inc_tx': 0,
'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД сохраним текущие счетчики самой большой сессии (примерно) 'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД: сумма текущих счётчиков всех сессий CN
'real_address': real_addr # Берем последний адрес 'real_address': real_addr,
'addr_since': since_ts or 0 # Начало сессии, чей адрес сохранён
} }
cn_updates[name]['inc_recv'] += inc_recv cn_updates[name]['inc_recv'] += inc_recv
cn_updates[name]['inc_tx'] += inc_sent cn_updates[name]['inc_tx'] += inc_sent
# Сохраняем "текущее" значение как максимальное из сессий, чтобы в БД last_bytes было хоть что-то осмысленное # last_bytes в БД = сумма текущих счётчиков всех сессий CN (нужно для UI)
# (хотя при in-memory подходе поле last_bytes в БД теряет смысл для логики, но нужно для UI) cn_updates[name]['max_rx'] += curr_recv
cn_updates[name]['max_rx'] = max(cn_updates[name]['max_rx'], curr_recv) cn_updates[name]['max_tx'] += curr_sent
cn_updates[name]['max_tx'] = max(cn_updates[name]['max_tx'], curr_sent) # real_address = адрес сессии с самым поздним началом
cn_updates[name]['real_address'] = real_addr 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. Льготный период для сессий, которых нет в текущем статусе: # 3. Льготный период для сессий, которых нет в текущем статусе:
# запись остаётся в кэше, пока missing_ticks < session_grace_ticks # запись остаётся в кэше, пока missing_ticks < session_grace_ticks
@@ -657,8 +679,8 @@ class OpenVPNDataGatherer:
if sess_data: if sess_data:
cursor.execute(''' cursor.execute('''
INSERT INTO active_sessions INSERT INTO active_sessions
(client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen) (client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen, session_id)
VALUES (?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', ( ''', (
client['db_id'], client['db_id'],
client['common_name'], client['common_name'],
@@ -666,7 +688,8 @@ class OpenVPNDataGatherer:
client['bytes_received'], client['bytes_received'],
client['bytes_sent'], client['bytes_sent'],
sess_data['connected_since'], sess_data['connected_since'],
sess_data['last_seen'] sess_data['last_seen'],
client.get('session_id')
)) ))
conn.commit() conn.commit()
@@ -690,6 +713,19 @@ class OpenVPNDataGatherer:
return active_clients 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): def calculate_rates(self, clients, time_diff):
"""Расчет скорости в Mbps""" """Расчет скорости в Mbps"""
if time_diff <= 0: if time_diff <= 0:
@@ -745,9 +781,15 @@ class OpenVPNDataGatherer:
# Рваное чтение / нет файла: тик пропускаем целиком, БД и кэш не трогаем. # Рваное чтение / нет файла: тик пропускаем целиком, БД и кэш не трогаем.
# last_check_time тоже не меняем: скорость следующего тика считается за весь интервал # last_check_time тоже не меняем: скорость следующего тика считается за весь интервал
self.invalid_ticks += 1 self.invalid_ticks += 1
level = logging.ERROR if self.invalid_ticks >= self.invalid_max else logging.WARNING # В журнал: 1-й тик, порог status_invalid_max (ERROR), далее раз в 60 тиков.
self.logger.log(level, f"Skipping tick ({self.invalid_ticks} in a row): {reading.reason}") # Иначе на свежей установке без запущенного 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: else:
if self.invalid_ticks:
self.logger.info(f"Status file is readable again after {self.invalid_ticks} skipped ticks")
self.invalid_ticks = 0 self.invalid_ticks = 0
if reading.stale: if reading.stale:
self.logger.warning(reading.reason) self.logger.warning(reading.reason)
@@ -761,8 +803,9 @@ class OpenVPNDataGatherer:
if self.last_check_time: if self.last_check_time:
time_diff = (current_time - self.last_check_time).total_seconds() time_diff = (current_time - self.last_check_time).total_seconds()
# 4. Считаем скорости # 4. Сворачиваем сессии в записи по CN и считаем скорости (сумма по сессиям)
clients_rated = self.calculate_rates(clients_with_updates, time_diff) clients_rated = self.calculate_rates(
self.merge_sessions_by_cn(clients_with_updates), time_diff)
# 5. Сохраняем RAW историю (для графиков реального времени) # 5. Сохраняем RAW историю (для графиков реального времени)
self.store_usage_history(clients_rated) self.store_usage_history(clients_rated)
+63 -3
View File
@@ -3,6 +3,7 @@ import logging
import signal import signal
import sqlite3 import sqlite3
import time import time
from datetime import datetime, timedelta
import pytest 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): 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] 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}," 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)", lines += ["HEADER,ROUTING_TABLE,Virtual Address,Common Name,Real Address,Last Ref,Last Ref (time_t)",
"GLOBAL_STATS,Max bcast/mcast queue length,0"] "GLOBAL_STATS,Max bcast/mcast queue length,0"]
if complete: if complete:
@@ -167,6 +168,24 @@ def test_torn_read_skips_the_tick(env):
assert env.history_sum() == (3000, 2) 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): def test_session_missing_for_a_tick_and_beyond_grace(env):
g = env.gatherer() g = env.gatherer()
since = T0 + 5 since = T0 + 5
@@ -196,6 +215,47 @@ def test_session_missing_for_a_tick_and_beyond_grace(env):
assert len(g.session_cache) == 1 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): def test_loop_survives_exceptions_and_stops_on_signal(env):
g = env.gatherer() g = env.gatherer()
g.stop_event = FakeEvent() 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 # Missing tables and columns are there, existing rows get the defaults
assert {"active_sessions", "users", "login_attempts"} <= table_names(db) 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 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 # 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-*") backups = glob.glob(db + ".bak-*")
assert backups == [report.backup] assert backups == [report.backup]
assert [query(backups[0], q) for q in DATA_QUERIES] == before 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 glob.glob(db + ".bak-*") == []
assert {"clients", "usage_history", "active_sessions", "users", "login_attempts", assert {"clients", "usage_history", "active_sessions", "users", "login_attempts",
"stats_5min", "stats_daily", "schema_migrations"} <= table_names(db) "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): 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 errors == []
assert len(glob.glob(db + ".bak-*")) == 1 assert len(glob.glob(db + ".bak-*")) == 1
assert sorted(len(r.applied) for r in reports) == [0, 1] assert sorted(len(r.applied) for r in reports) == [0, len(migrations.MIGRATIONS)]
assert query(db, "SELECT version FROM schema_migrations") == [(1,)] assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)]
@@ -0,0 +1,37 @@
# Учёт нескольких сессий одного пользователя (итог, 2026-10-06)
План: [2026-10-06_Multi_Session_Stats_PLAN.md](2026-10-06_Multi_Session_Stats_PLAN.md). Пользователь (CN) с несколькими устройствами (`duplicate-cn`) учитывается одной записью.
## Что сделано
| ID | Изменение |
|---|---|
| MS-1, MS-5 | `parse_status` берёт индекс колонки `Client ID` из строки `HEADER,CLIENT_LIST,...`; нет колонки или не число = `session_id None`. Ключ сессии `(CN, session_id or real_address, since_ts)` в кэше, базовой линии и снимке. Миграция 002: `active_sessions.session_id TEXT` (NULL допустим); старые строки снимка совпадают по запасному ключу |
| MS-4 | `clients.real_address` = адрес сессии с самым поздним началом; `last_bytes_*` = сумма текущих счётчиков всех сессий CN |
| MS-3 | `run_monitoring_cycle`: сессии сворачиваются в записи по CN (`merge_sessions_by_cn`) перед расчётом скоростей, `usage_history` и агрегацией: одна строка на CN за тик |
| MS-2, MS-3 (старые строки) | API: `current_recv_rate` / `current_sent_rate` = `MAX` по отметке времени от `SUM` скоростей; `get_client_history` (быстрый и обычный режимы) суммирует строки по `timestamp` до `MAX` |
| Документация | `Data_Architecture.md`, `API_Reference.md`, `APP_CORE/README.md`, эта сводка и строка в `Changes/README.md` |
Файлы: `APP_CORE/openvpn_gatherer_v3.py`, `APP_CORE/migrations.py`, `APP_CORE/openvpn_api_v3.py`, `APP_CORE/test_gatherer.py`, `APP_CORE/test_migrations.py`.
## Тесты
- `test_gatherer.py`: 2 новых теста (две сессии одного CN; `float` с тем же `Client ID` и перезапуск демона по снимку). До правки кода оба красные. `write_status` получил необязательный `client_id` (по умолчанию 1).
- `test_migrations.py`: ожидания обновлены под версию 2 (список применённых миграций, число миграций за запуск), добавлена проверка наличия колонки `session_id`. Новых тестов не добавлялось.
- Итог `pytest` в `APP_CORE`: 16 из 16 (14 прежних + 2 новых).
## Ручная проверка API (шаг 6)
Временная БД (миграции 1 и 2 применены), клиент `alice`, на двух отметках времени по две строки `usage_history` (две сессии): скорость Download 1,0 + 2,0 и 4,0 + 0,5.
| Проверка | Результат |
|---|---|
| `get_current_stats`: `current_recv_rate` / `current_sent_rate` | 4,5 / 0,45 (MAX от сумм: 3,0 и 4,5; прежнее поведение дало бы 4,0) |
| `get_client_history`, обычный режим | 2 точки: объём 300 и 450 байт, скорость 3,0 и 4,5 (суммы по сессиям) |
| `get_client_history`, быстрый режим (интервал 30 с) | объём 750, скорость 4,5 (MAX от сумм) |
## Отклонения от плана и замечания
- Отклонений от плана нет. Миграция 002 идемпотентна (колонка добавляется, только если её нет).
- Каталог `venv/` в корне проекта создан для запуска тестов; в `.gitignore` его нет, в `git status` он виден как неотслеживаемый.
- Не проверялось: работа на живом OpenVPN с `float` и `duplicate-cn`, обновление `update.sh` с миграцией 002 на тестовом хосте. Системная история (`/analytics`) уже суммировала по отметке времени, не менялась.
@@ -0,0 +1,53 @@
# Учёт нескольких сессий одного пользователя (план, 2026-10-06)
Источник: анализ логики сбора статистики (запрос от 2026-10-06). Затронутый код: `APP_CORE/openvpn_gatherer_v3.py`, `APP_CORE/openvpn_api_v3.py`, `APP_CORE/migrations.py`, `APP_CORE/test_gatherer.py`.
Цель: пользователь (CN) с несколькими устройствами одновременно (`duplicate-cn`) учитывается **одной записью**: байты, скорость, история и «последние» значения агрегируются под учётной записью независимо от числа сессий.
## 1. Что уже верно (не меняем)
Итоги `clients.total_bytes_*` и корзины `stats_*` суммируют приросты всех сессий CN. Статус «Disconnected» ставится по CN, а не по сессии.
## 2. Проблемы и решения
| ID | Проблема | Решение |
|---|---|---|
| MS-1 (высокая) | Смена `real_address` без переподключения (`float`, Wi-Fi → LTE) меняет ключ сессии `(CN, адрес, начало)`; сессия считается новой, и её счётчики засчитываются повторно | Ключ сессии: `(CN, session_id, начало)`, где `session_id` это `Client ID` из статуса v2. Он не меняется при `float`. Если `Client ID` в статусе нет (старый OpenVPN), запасной ключ с `real_address` |
| MS-2 (средняя) | `current_recv_rate` / `current_sent_rate` = `MAX` по строкам сессий: при двух устройствах видна скорость одного | Скорость пользователя = **сумма** по сессиям за тик |
| MS-3 (средняя) | `usage_history` получает строку на сессию за тик: дубли времени в сыром графике, скорость в группировке берётся как `MAX` по сессиям | Писать **одну строку на CN за тик** (сумма байтов и скоростей). Для уже записанных строк (хранятся 7 дней) запросы API суммируют по `timestamp` до `MAX` |
| MS-4 (низкая) | `clients.real_address` и `last_bytes_*` отражают одну сессию (последнюю в списке / максимальную) | `real_address` = адрес сессии с самым поздним началом; `last_bytes_*` = **сумма** текущих счётчиков всех активных сессий |
| MS-5 (низкая) | Коллизия ключа: одинаковые CN, адрес и секунда подключения | Закрывается MS-1 (`Client ID` уникален в рамках процесса OpenVPN) |
## 3. Шаги
| # | Шаг | Результат |
|---|---|---|
| 0 | Тесты (минимум, см. п. 4) пишутся первыми и воспроизводят MS-1 и MS-3 на текущем коде (красные) | дефекты подтверждены |
| 1 | `parse_status`: индекс колонки `Client ID` берётся из строки `HEADER,CLIENT_LIST,...`; нет колонки или значение не число = `session_id = None`. В `client` добавляется `session_id` | сборщик знает идентификатор сессии |
| 2 | Миграция 002 (`migrations.py`): колонка `active_sessions.session_id TEXT` (NULL допустим). Резервная копия, проверки и защита от понижения версии уже в механизме миграций | снимок хранит идентификатор |
| 3 | Ключ сессии `(CN, session_id or real_address, since_ts)`; `_load_baseline` и запись снимка (шаг 6 цикла) используют тот же ключ. Старые строки снимка без `session_id` совпадают по запасному ключу, потерь при обновлении нет | MS-1, MS-5 закрыты |
| 4 | `update_client_status_and_bytes`: `real_address` берётся от сессии с максимальным `since_ts`; `last_bytes_*` = сумма `curr_recv/curr_sent` сессий CN | MS-4 закрыт |
| 5 | `run_monitoring_cycle`: перед `store_usage_history` и `aggregate` свернуть список сессий в список **по CN** (сумма `*_inc`, сумма скоростей, один `db_id`). `calculate_rates` считать по свёрнутому списку | MS-3 закрыт для новых данных, меньше записей |
| 6 | API: `current_*_rate` = `MAX` по `timestamp` от `SUM` скоростей; в `get_client_history` группировка по `timestamp` с `SUM` скорости перед `MAX` (быстрый и обычный режимы) | MS-2 закрыт, старые строки считаются верно |
| 7 | Документация: `DOCS/Core_Monitoring/Data_Architecture.md` (ключ сессии, агрегация по CN), `API_Reference.md` (смысл `real_address`, `last_bytes`, скорости), `APP_CORE/README.md`, строка в таблице `DOCS/Changes/README.md`, README.md проекта при необходимости, сводка `2026-10-06_Multi_Session_Stats.md` | документация актуальна |
## 4. Автотесты (минимум, 2 шт., в `test_gatherer.py`)
1. **Две сессии одного CN**: разные адреса и начала, разный трафик. Проверка: `clients.total_bytes_*` = сумма; в `usage_history` одна строка на тик, скорость = сумма; в `stats_5min` одна строка; отключение одной сессии оставляет статус Active и не искажает итог.
2. **`float`**: сессия меняет `real_address` при том же `Client ID` и начале. Проверка: прирост = разница счётчиков, без повторного учёта; то же после перезапуска демона (базовая линия из снимка с `session_id`).
Изменение API (шаг 6) проверяется вручную на копии БД с двумя сессиями (SQL-запросы), отдельный автотест не добавляется.
## 5. Совместимость и риски
- Схема: одна необязательная колонка, миграция автоматическая, перед ней резервная копия. Возврат на старый код после миграции требует восстановления БД из копии (защита от понижения версии, см. [Database migrations](../General/Database_Migrations.md)).
- Обновление при работающих сессиях: кэш пуст, базовая линия из старого снимка (без `session_id`) совпадает по запасному ключу, трафик не теряется и не дублируется.
- Значения `real_address` и `last_bytes_*` в таблице клиентов меняют смысл для пользователей с несколькими сессиями (суммарно, а не одна сессия). Подробности по каждой сессии остаются в `active_sessions`.
- Откат кода без миграции: не нужен, изменения сборщика и API обратимо совместимы со схемой (колонка необязательна).
## 6. Порядок выполнения
1. Утверждение плана.
2. Реализация субагентом (Sonnet 5.5, Medium Effort): шаги 0-6.
3. Проверка: `pytest` в `APP_CORE`, ручная проверка API (шаг 6).
4. Документация и сводка (шаг 7).
+5
View File
@@ -136,6 +136,11 @@ Returns a snapshot of all known clients.
### `GET /stats` ### `GET /stats`
Field notes (a user with several simultaneous sessions is one record):
- `current_recv_rate_mbps` / `current_sent_rate_mbps`: peak over the last 30 seconds of the **sum of the rates of all sessions** of the user at one tick (not the rate of a single session).
- `real_address`: the address of the session with the latest start. `last_bytes_received/sent` (table `clients`): the sum of the current counters of all active sessions. Per-session values are in `GET /sessions`.
- In `GET /stats/<common_name>` the history of every interval has the volume and the rate summed over the user's sessions (rate: `MAX` over the interval of the per-tick sum).
#### Example Response #### Example Response
```json ```json
{ {
+6 -4
View File
@@ -8,11 +8,11 @@ The gatherer runs a continuous loop (default interval: **10 seconds**).
### A. Log Parsing ### A. Log Parsing
- **Source**: `/var/log/openvpn/openvpn-status.log` (Status File v2, CSV format). - **Source**: `/var/log/openvpn/openvpn-status.log` (Status File v2, CSV format).
- **Target Fields**: `Common Name`, `Real Address`, `Bytes Sent`, `Bytes Received`, `Connected Since (time_t)`. - **Target Fields**: `Common Name`, `Real Address`, `Bytes Sent`, `Bytes Received`, `Connected Since (time_t)`, `Client ID` (the column index is taken from the `HEADER,CLIENT_LIST,...` line; a missing column or a non-numeric value means no session id).
- **Filtering**: Only lines starting with `CLIENT_LIST`. - **Filtering**: Only lines starting with `CLIENT_LIST`.
### B. Delta Calculation (`update_client_status_and_bytes`) ### B. Delta Calculation (`update_client_status_and_bytes`)
The log provides *lifetime* counters for a session. The gatherer calculates the traffic *delta* (increment) since the last check. A session is identified by the key `(common_name, real_address, connected_since_ts)`, where `connected_since_ts` is the `Connected Since (time_t)` column (index 8) of `CLIENT_LIST`. A reconnect always gets a new `connected_since_ts` and therefore a new session. The log provides *lifetime* counters for a session. The gatherer calculates the traffic *delta* (increment) since the last check. A session is identified by the key `(common_name, session_id or real_address, connected_since_ts)`, where `session_id` is the `Client ID` of the status file (it does not change when the client address changes without a reconnect, `float`) and `connected_since_ts` is the `Connected Since (time_t)` column (index 8) of `CLIENT_LIST`. If the status has no `Client ID` (old OpenVPN), `real_address` is used instead. A reconnect always gets a new `connected_since_ts` and therefore a new session. `active_sessions.session_id` (TEXT, nullable, migration 2) stores the id; old snapshot rows without it match by the fallback key.
| Situation | Increment | | Situation | Increment |
|-----------|-----------| |-----------|-----------|
@@ -22,10 +22,12 @@ The log provides *lifetime* counters for a session. The gatherer calculates the
| Not in cache, session older than the daemon and no snapshot (first start after an update, lost DB) | Baseline: increment `0`, a WARNING with the client name is logged (the only case of lost traffic, once per session). | | Not in cache, session older than the daemon and no snapshot (first start after an update, lost DB) | Baseline: increment `0`, a WARNING with the client name is logged (the only case of lost traffic, once per session). |
| `connected_since_ts` is missing or not a number (non-standard status file) | Fallback heuristic: counters below 10 MB are counted as a new session, otherwise increment `0`; a WARNING is logged. | | `connected_since_ts` is missing or not a number (non-standard status file) | Fallback heuristic: counters below 10 MB are counted as a new session, otherwise increment `0`; a WARNING is logged. |
**Several sessions of one user** (`duplicate-cn`): the increments of all sessions of a common name are added up and belong to one `clients` row. In `clients`, `real_address` is the address of the session with the latest start and `last_bytes_received/sent` is the **sum** of the current counters of all active sessions; per-session details stay in `active_sessions`. Before writing `usage_history` and the aggregates the sessions are collapsed into **one record per common name per tick** (sum of increments and of rates).
Cache changes are collected in a temporary structure and applied only after the database transaction is committed. If the transaction fails, the cache is unchanged and the next tick counts the difference for the whole interval. Cache changes are collected in a temporary structure and applied only after the database transaction is committed. If the transaction fails, the cache is unchanged and the next tick counts the difference for the whole interval.
### B1. Read Validity, Grace Period, Restart and Shutdown ### B1. Read Validity, Grace Period, Restart and Shutdown
- **Validity** (`parse_status`): the status file must contain a `TITLE` line, a `TIME,<text>,<epoch>` line and end with `END`. A missing file, a read error or an incomplete file (read while OpenVPN rewrites it) makes the gatherer **skip the tick entirely**: the database and the cache are not touched, and the next valid tick counts the difference for the whole interval. After `status_invalid_max` (default 6) skipped ticks in a row the message is logged at ERROR level. - **Validity** (`parse_status`): the status file must contain a `TITLE` line, a `TIME,<text>,<epoch>` line and end with `END`. A missing file, a read error or an incomplete file (read while OpenVPN rewrites it) makes the gatherer **skip the tick entirely**: the database and the cache are not touched, and the next valid tick counts the difference for the whole interval. The skip is logged on the first tick, at `status_invalid_max` (default 6, level ERROR) and then every 60th tick (about every 10 minutes at the default interval), not on every tick; when the file is readable again one INFO line says after how many skipped ticks.
- **Freshness**: if `TIME` is older than `status_stale_seconds` (default 60 s), OpenVPN is considered stopped: there are no clients, all clients become `Disconnected`, sessions leave the cache via the grace period. A valid, fresh file without `CLIENT_LIST` lines simply means no clients. - **Freshness**: if `TIME` is older than `status_stale_seconds` (default 60 s), OpenVPN is considered stopped: there are no clients, all clients become `Disconnected`, sessions leave the cache via the grace period. A valid, fresh file without `CLIENT_LIST` lines simply means no clients.
- **Grace period**: a session missing from the status is not dropped at once. Its `missing_ticks` counter grows each tick and the session is removed from the cache when it reaches `session_grace_ticks` (default 3, about 30 s). A session that comes back with the same key continues without double counting. A removed session is remembered (last counters, 1 hour) so that a late return with the same key is still counted as a continuation. - **Grace period**: a session missing from the status is not dropped at once. Its `missing_ticks` counter grows each tick and the session is removed from the cache when it reaches `session_grace_ticks` (default 3, about 30 s). A session that comes back with the same key continues without double counting. A removed session is remembered (last counters, 1 hour) so that a late return with the same key is still counted as a continuation.
- **Restart**: at start the gatherer loads `active_sessions` as the baseline (see the table above). `active_sessions.connected_since` stores the real session start in UTC (`YYYY-MM-DD HH:MM:SS`), which is also what `/sessions` returns. - **Restart**: at start the gatherer loads `active_sessions` as the baseline (see the table above). `active_sessions.connected_since` stores the real session start in UTC (`YYYY-MM-DD HH:MM:SS`), which is also what `/sessions` returns.
@@ -34,7 +36,7 @@ Cache changes are collected in a temporary structure and applied only after the
### C. Rate Calculation ### C. Rate Calculation
- **Speed**: Calculated as `Increment * 8 / (Interval * 1_000_000)` to get **Mbps**. - **Speed**: Calculated as `Increment * 8 / (Interval * 1_000_000)` to get **Mbps**.
- **Storage**: Raw samples (10s resolution) including speed and volume are stored in the `usage_history` table. - **Storage**: Raw samples (10s resolution) including speed and volume are stored in the `usage_history` table: one row per user per tick (the rate is the sum over the user's sessions). Rows written by earlier versions have one row per session; the API sums rows with the same `timestamp` before taking `MAX` over an interval.
## 2. Data Aggregation (TSDB) ## 2. Data Aggregation (TSDB)