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:
1 parent
ad6995bb63
commit
7d6f44c965
11 files changed
+287
-57
No files matched your search
@@ -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).
|
||||
@@ -136,6 +136,11 @@ Returns a snapshot of all known clients.
|
||||
|
||||
### `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
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -8,11 +8,11 @@ The gatherer runs a continuous loop (default interval: **10 seconds**).
|
||||
|
||||
### A. Log Parsing
|
||||
- **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`.
|
||||
|
||||
### 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 |
|
||||
|-----------|-----------|
|
||||
@@ -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). |
|
||||
| `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.
|
||||
|
||||
### 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.
|
||||
- **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.
|
||||
@@ -34,7 +36,7 @@ Cache changes are collected in a temporary structure and applied only after the
|
||||
|
||||
### C. Rate Calculation
|
||||
- **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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user