History and Analytics: average speed from bytes for periods over 24 hours
The aggregate tables (stats_*) keep only bytes, and the queries returned 0 as speed, so the Speed mode was empty for 7d and 30d. Speed is now the bucket average: bytes * 8 / 1e6 / bucket seconds; for the current incomplete bucket the duration is min(bucket length, time since its start), at least 1 s. Series are labelled "RX Mbps (avg)" / "TX Mbps (avg)" for ranges over 24h. One test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KC7BXv32Jwj8mY5sKX8u2F
This commit is contained in:
1 parent
e364a40e4b
commit
b3466f9c61
17 files changed
+97
-19
No files matched your search
@@ -29,6 +29,29 @@ app = Flask(__name__)
|
||||
# Cross-origin access is off by default (the UI is same-origin behind Nginx); allow extra origins via OVPMON_CORS_ORIGINS (comma-separated)
|
||||
CORS(app, resources={r"/api/*": {"origins": [o.strip() for o in os.getenv("OVPMON_CORS_ORIGINS", "").split(",") if o.strip()]}}, supports_credentials=True)
|
||||
|
||||
# Length of one bucket of the aggregate tables, seconds. The aggregates hold only bytes, so for periods
|
||||
# longer than a day the speed is the bucket average: bytes * 8 / 1e6 / bucket duration.
|
||||
BUCKET_SECONDS = {
|
||||
'stats_5min': 300,
|
||||
'stats_15min': 900,
|
||||
'stats_hourly': 3600,
|
||||
'stats_6h': 21600,
|
||||
'stats_daily': 86400,
|
||||
}
|
||||
|
||||
|
||||
def avg_rate_sql(table, bytes_expr, ts_expr):
|
||||
"""SQL expression of the average speed (Mbps) of a bucket of an aggregate table.
|
||||
|
||||
The current (incomplete) bucket lasts min(bucket length, time since its start), at least 1 second;
|
||||
timestamps of the aggregates are UTC. `table` is taken only from BUCKET_SECONDS (never user input),
|
||||
the other arguments are fixed column expressions of the caller.
|
||||
"""
|
||||
seconds = BUCKET_SECONDS[table]
|
||||
return (f"({bytes_expr}) * 8.0 / 1000000.0 / "
|
||||
f"MAX(1, MIN({seconds}, CAST(strftime('%s', 'now') AS INTEGER) - CAST(strftime('%s', {ts_expr}) AS INTEGER)))")
|
||||
|
||||
|
||||
class OpenVPNAPI:
|
||||
def get_config_value(self, section, key, fallback=None):
|
||||
try:
|
||||
@@ -322,8 +345,8 @@ class OpenVPNAPI:
|
||||
t.timestamp,
|
||||
t.bytes_received,
|
||||
t.bytes_sent,
|
||||
0 as bytes_received_rate_mbps,
|
||||
0 as bytes_sent_rate_mbps
|
||||
{avg_rate_sql(target_table, 't.bytes_received', 't.timestamp')} as bytes_received_rate_mbps,
|
||||
{avg_rate_sql(target_table, 't.bytes_sent', 't.timestamp')} as bytes_sent_rate_mbps
|
||||
FROM {target_table} t
|
||||
JOIN clients c ON t.client_id = c.id
|
||||
WHERE c.common_name = ? AND t.timestamp BETWEEN ? AND ?
|
||||
@@ -477,7 +500,8 @@ class OpenVPNAPI:
|
||||
if target_table == 'usage_history':
|
||||
rate_cols = "SUM(bytes_received_rate_mbps) as total_rx_rate, SUM(bytes_sent_rate_mbps) as total_tx_rate,"
|
||||
else:
|
||||
rate_cols = "0 as total_rx_rate, 0 as total_tx_rate,"
|
||||
rate_cols = (f"{avg_rate_sql(target_table, 'SUM(bytes_received)', 'timestamp')} as total_rx_rate, "
|
||||
f"{avg_rate_sql(target_table, 'SUM(bytes_sent)', 'timestamp')} as total_tx_rate,")
|
||||
|
||||
# Aggregation Query
|
||||
# Group by interval_seconds
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import importlib
|
||||
import sqlite3
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
MB = 1_000_000
|
||||
FMT = '%Y-%m-%d %H:%M:%S'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api(tmp_path, monkeypatch):
|
||||
"""OpenVPNAPI on a temporary migrated database (the module creates a global instance on import)."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", str(tmp_path / "api.db"))
|
||||
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||
module = importlib.import_module("openvpn_api_v3")
|
||||
return module.OpenVPNAPI()
|
||||
|
||||
|
||||
def test_aggregated_history_speed_is_bucket_average(api):
|
||||
now = datetime.utcnow()
|
||||
full = (now - timedelta(hours=5)).replace(minute=0, second=0, microsecond=0) # complete hourly bucket
|
||||
current = now - timedelta(seconds=1800) # bucket started 30 minutes ago: lasts 1800 s, not 3600 s
|
||||
conn = sqlite3.connect(api.db_manager.db_path)
|
||||
conn.execute("INSERT INTO clients (common_name) VALUES ('alice')")
|
||||
cid = conn.execute("SELECT id FROM clients WHERE common_name='alice'").fetchone()[0]
|
||||
for ts in (full, current):
|
||||
conn.execute("INSERT INTO stats_hourly (timestamp, client_id, bytes_received, bytes_sent) VALUES (?,?,?,?)",
|
||||
(ts.strftime(FMT), cid, 450 * MB, 90 * MB))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
res = api.get_client_history('alice', now - timedelta(days=7), now, resolution='hourly')
|
||||
full_row, current_row = res['data']
|
||||
# 450 MB over 3600 s = 1.0 Mbps (rx), 90 MB over 3600 s = 0.2 Mbps (tx)
|
||||
assert full_row['bytes_received_rate_mbps'] == pytest.approx(1.0)
|
||||
assert full_row['bytes_sent_rate_mbps'] == pytest.approx(0.2)
|
||||
# the same volume over 1800 s: twice as fast
|
||||
assert current_row['bytes_received_rate_mbps'] == pytest.approx(2.0, rel=0.01)
|
||||
assert current_row['bytes_sent_rate_mbps'] == pytest.approx(0.4, rel=0.01)
|
||||
|
||||
# Analytics 7d reads the same table: the sum of clients per timestamp, speed is non-zero
|
||||
history = api.get_analytics_data('7d')['global_history_24h']
|
||||
assert max(p['total_rx_rate'] for p in history) == pytest.approx(2.0, rel=0.01)
|
||||
Reference in new issue
Block a user