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

+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)