Add an API endpoint with the traffic of a peer between two dates

This commit is contained in:
Eduardo Silva
2026-11-24 20:11:34 -03:00
parent 58b696df13
commit c97c182c35
5 changed files with 405 additions and 6 deletions
+137 -2
View File
@@ -1,15 +1,21 @@
import json import json
from datetime import timedelta import shutil
import subprocess
import tempfile
import time
import uuid
from datetime import datetime, timedelta, timezone as dt_timezone
from unittest.mock import patch from unittest.mock import patch
from django.test import TestCase, override_settings from django.test import TestCase, override_settings
from django.utils import timezone from django.utils import timezone
from api_v2.models import ApiKey from api_v2.models import ApiKey
from vpn_invite.models import InviteSettings, PeerInvite
from cluster.models import ClusterSettings, Worker from cluster.models import ClusterSettings, Worker
from cluster.tests import create_instance from cluster.tests import create_instance
from dns.models import DNSSettings, StaticHost from dns.models import DNSSettings, StaticHost
from vpn_invite.models import InviteSettings, PeerInvite
from wgrrd.functions import peer_rrd_path
from wireguard.models import Peer, WireGuardInstance from wireguard.models import Peer, WireGuardInstance
@@ -412,3 +418,132 @@ class ApiV2PeerInviteTests(TestCase):
def test_other_methods_are_not_allowed(self): def test_other_methods_are_not_allowed(self):
response = self.client.get(self.url, HTTP_TOKEN=str(self.api_key.token)) response = self.client.get(self.url, HTTP_TOKEN=str(self.api_key.token))
self.assertEqual(response.status_code, 405) self.assertEqual(response.status_code, 405)
def create_traffic_rrd(path, start, updates, download_rate=1000, upload_rate=500):
"""RRD with the same layout as the collector, receiving constant rates (bytes per second) every 5 minutes."""
subprocess.run([
"rrdtool", "create", path, "--start", str(start), "--step", "300",
"DS:tx:DERIVE:600:0:U", "DS:rx:DERIVE:600:0:U", "DS:status:GAUGE:600:0:1",
"RRA:AVERAGE:0.5:1:1440", "RRA:AVERAGE:0.5:6:700", "RRA:AVERAGE:0.5:24:775", "RRA:AVERAGE:0.5:288:797",
], check=True)
for index in range(1, updates + 1):
subprocess.run([
"rrdtool", "update", path,
f"{start + index * 300}:{index * 300 * download_rate}:{index * 300 * upload_rate}:1",
], check=True)
class ApiV2PeerTrafficTests(TestCase):
url = "/api/v2/peer_traffic/"
def setUp(self):
self.instance = create_instance(0)
self.other_instance = create_instance(1)
self.api_key = ApiKey.objects.create(name="traffic-test-key", enabled=True)
self.api_key.allowed_instances.add(self.instance)
self.peer = Peer.objects.create(wireguard_instance=self.instance, name="Test Peer", public_key="peer-public")
rrd_dir = tempfile.TemporaryDirectory()
self.addCleanup(rrd_dir.cleanup)
patcher = patch("wgrrd.functions.RRD_PEERS_PATH", rrd_dir.name)
patcher.start()
self.addCleanup(patcher.stop)
def request(self, payload, api_key=None):
return self.client.post(
self.url, data=json.dumps(payload), content_type="application/json",
HTTP_TOKEN=str((api_key or self.api_key).token),
)
def create_history(self, updates=24):
"""Two hours of history ending about an hour ago: 1000 B/s of download and 500 B/s of upload."""
if not shutil.which("rrdtool"):
self.skipTest("rrdtool is not installed")
self.history_start = (int(time.time()) // 300) * 300 - 3 * 3600
create_traffic_rrd(peer_rrd_path(self.peer), self.history_start, updates)
def iso(self, timestamp):
return datetime.fromtimestamp(timestamp, tz=dt_timezone.utc).isoformat()
@staticmethod
def period_seconds(body):
return datetime.fromisoformat(body["end"]).timestamp() - datetime.fromisoformat(body["start"]).timestamp()
def test_returns_download_and_upload_totals_of_the_period(self):
self.create_history()
response = self.request({
"instance": "wg0", "peer_uuid": str(self.peer.uuid),
"start": self.iso(self.history_start + 1200), "end": self.iso(self.history_start + 4800),
})
self.assertEqual(response.status_code, 200, response.content)
body = response.json()
# The returned period covers the requested one, rounded to the 5 minute samples
self.assertLessEqual(datetime.fromisoformat(body["start"]).timestamp(), self.history_start + 1200)
self.assertGreaterEqual(datetime.fromisoformat(body["end"]).timestamp(), self.history_start + 4800)
self.assertEqual(body["resolution_seconds"], 300)
# What the server sent to the peer is its download
self.assertEqual(body["download_bytes"], 1000 * self.period_seconds(body))
self.assertEqual(body["upload_bytes"], 500 * self.period_seconds(body))
self.assertNotIn("warning", body)
def test_period_without_end_goes_until_now(self):
self.create_history()
response = self.request({
"instance": "wg0", "peer_uuid": str(self.peer.uuid), "start": self.iso(self.history_start + 1200),
})
self.assertEqual(response.status_code, 200, response.content)
body = response.json()
# The history ends at its last update, so the returned end is the last sample
self.assertEqual(datetime.fromisoformat(body["end"]).timestamp(), self.history_start + 24 * 300)
self.assertEqual(body["download_bytes"], 1000 * self.period_seconds(body))
self.assertNotIn("warning", body)
def test_old_period_returns_the_resolution_and_a_warning(self):
self.create_history()
response = self.request({
"instance": "wg0", "peer_uuid": str(self.peer.uuid),
"start": self.iso(time.time() - 30 * 86400),
})
self.assertEqual(response.status_code, 200, response.content)
body = response.json()
self.assertEqual(body["resolution_seconds"], 7200)
self.assertIn("resolution of 2 hours", body["warning"])
# Most of the period is before the history of the peer
self.assertIn("Part of the period has no traffic data", body["warning"])
def test_selects_peer_by_public_key(self):
self.create_history()
response = self.request({
"instance": "wg0", "peer_public_key": "peer-public", "start": self.iso(self.history_start + 1200),
})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response.json()["peer_uuid"], str(self.peer.uuid))
def test_refuses_invalid_dates(self):
peer = {"instance": "wg0", "peer_uuid": str(self.peer.uuid)}
for payload, message in (
({}, "Invalid or missing start date."),
({"start": "yesterday"}, "Invalid or missing start date."),
({"start": "2026-11-01", "end": "2026-13-01"}, "Invalid end date."),
({"start": "2026-11-02T00:00:00", "end": "2026-11-01T00:00:00"}, "The start date must be before the end date."),
({"start": self.iso(time.time() + 3600)}, "The start date must be before the end date."),
):
response = self.request({**peer, **payload})
self.assertEqual(response.status_code, 400, payload)
self.assertEqual(response.json()["error_message"], message)
def test_unknown_peer_and_peer_without_history_return_404(self):
response = self.request({"instance": "wg0", "peer_uuid": str(uuid.uuid4()), "start": "2026-11-01"})
self.assertEqual(response.status_code, 404)
self.assertEqual(response.json()["error_message"], "Peer not found.")
response = self.request({"instance": "wg0", "peer_uuid": str(self.peer.uuid), "start": "2026-11-01"})
self.assertEqual(response.status_code, 404)
self.assertEqual(response.json()["error_message"], "There is no traffic history for this peer.")
def test_api_key_scope_is_respected(self):
other_peer = Peer.objects.create(wireguard_instance=self.other_instance, name="Other", public_key="other-public")
response = self.request({"instance": "wg1", "peer_uuid": str(other_peer.uuid), "start": "2026-11-01"})
self.assertEqual(response.status_code, 403)
# The peer of another instance is not found through an allowed instance
response = self.request({"instance": "wg0", "peer_uuid": str(other_peer.uuid), "start": "2026-11-01"})
self.assertEqual(response.status_code, 404)
+2
View File
@@ -8,6 +8,7 @@ from .views_api import (
api_v2_peer_detail, api_v2_peer_detail,
api_v2_peer_invite, api_v2_peer_invite,
api_v2_peer_list, api_v2_peer_list,
api_v2_peer_traffic,
api_v2_wireguard_status, api_v2_wireguard_status,
) )
@@ -17,6 +18,7 @@ urlpatterns = [
path('peer_list/', api_v2_peer_list, name='api_v2_peer_list'), path('peer_list/', api_v2_peer_list, name='api_v2_peer_list'),
path('peer_detail/', api_v2_peer_detail, name='api_v2_peer_detail'), path('peer_detail/', api_v2_peer_detail, name='api_v2_peer_detail'),
path('peer_invite/', api_v2_peer_invite, name='api_v2_peer_invite'), path('peer_invite/', api_v2_peer_invite, name='api_v2_peer_invite'),
path('peer_traffic/', api_v2_peer_traffic, name='api_v2_peer_traffic'),
path('wireguard_status/', api_v2_wireguard_status, name='api_v2_wireguard_status'), path('wireguard_status/', api_v2_wireguard_status, name='api_v2_wireguard_status'),
path('manage_cluster/status/', api_v2_manage_cluster_status, name='api_v2_manage_cluster_status'), path('manage_cluster/status/', api_v2_manage_cluster_status, name='api_v2_manage_cluster_status'),
path('manage_cluster/manage_status/', api_v2_manage_cluster_manage_status, name='api_v2_manage_cluster_manage_status'), path('manage_cluster/manage_status/', api_v2_manage_cluster_manage_status, name='api_v2_manage_cluster_manage_status'),
+174 -1
View File
@@ -1,7 +1,8 @@
import ipaddress import ipaddress
import json import json
import os
import re import re
from datetime import timedelta from datetime import datetime, time, timedelta
from functools import wraps from functools import wraps
from typing import List, Optional, Tuple from typing import List, Optional, Tuple
@@ -11,6 +12,7 @@ from django.core.exceptions import ValidationError
from django.db import transaction from django.db import transaction
from django.http import JsonResponse from django.http import JsonResponse
from django.utils import timezone from django.utils import timezone
from django.utils.dateparse import parse_date, parse_datetime
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from api.views import func_get_wireguard_status from api.views import func_get_wireguard_status
@@ -23,6 +25,7 @@ from dns.views import export_dns_configuration
from routing_templates.models import RoutingTemplate from routing_templates.models import RoutingTemplate
from speed_profiles.models import SpeedProfile from speed_profiles.models import SpeedProfile
from vpn_invite.models import InviteSettings, PeerInvite from vpn_invite.models import InviteSettings, PeerInvite
from wgrrd.functions import TrafficHistoryError, peer_rrd_path, peer_traffic_totals, traffic_warning
from wgwadmlibrary.tools import create_peer_invite, get_peer_invite_data, send_email from wgwadmlibrary.tools import create_peer_invite, get_peer_invite_data, send_email
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
from wireguard_peer.forms import normalize_endpoint from wireguard_peer.forms import normalize_endpoint
@@ -1041,6 +1044,176 @@ def api_v2_peer_invite(request):
return JsonResponse({"status": "success", "message": message, "invite_data": invite_data}, status=200) return JsonResponse({"status": "success", "message": message, "invite_data": invite_data}, status=200)
def _parse_api_datetime(value):
"""ISO 8601 date or date and time. Values without a timezone use the server timezone."""
if not isinstance(value, str) or not value.strip():
return None
value = value.strip()
try:
parsed = parse_datetime(value)
if parsed is None:
parsed_date = parse_date(value)
if parsed_date is None:
return None
parsed = datetime.combine(parsed_date, time.min)
except ValueError:
return None
if timezone.is_naive(parsed):
parsed = timezone.make_aware(parsed, timezone.get_current_timezone())
return parsed
def _api_datetime(timestamp):
return timezone.localtime(datetime.fromtimestamp(timestamp, tz=timezone.get_current_timezone())).isoformat()
@csrf_exempt
@api_doc(
summary="Download and upload totals of a peer between two dates, from the traffic history of the graphs",
auth="Header token: <ApiKey.token>",
methods=["POST", "GET"],
params=[
{"name": "instance", "in": "json", "type": "string", "required": True, "example": "wg0",
"description": "Required. Target instance name in the format wg{instance_id} (e.g. wg0, wg1)."},
{"name": "peer_uuid", "in": "json", "type": "string", "required": False,
"description": "Peer UUID selector. Inform peer_uuid or peer_public_key."},
{"name": "peer_public_key", "in": "json", "type": "string", "required": False,
"description": "Peer public key selector. Used when peer_uuid is not informed."},
{"name": "start", "in": "json", "type": "string", "required": True, "example": "2026-11-01T00:00:00-03:00",
"description": "Required. Start of the period, as an ISO 8601 date or date and time. Without a timezone, the "
"server timezone is used. The history keeps 5 minute samples for about 5 days, then averages "
"of 30 minutes (about 14 days), 2 hours (about 64 days) and 1 day (about 2 years). The "
"resolution depends on how old the start is; the response returns the start and end that "
"the history covers, and a warning when the resolution is larger than 5 minutes or part of "
"the period has no data."},
{"name": "end", "in": "json", "type": "string", "required": False, "example": "2026-11-15T23:59:59-03:00",
"description": "End of the period, in the same format as start. When omitted, the period ends now."},
],
returns=[
{"status": 200, "body": {
"status": "success", "peer_uuid": "...", "instance": "wg0",
"start": "2026-11-01T00:00:00-03:00", "end": "2026-11-15T23:55:00-03:00",
"download_bytes": 123456789, "upload_bytes": 9876543, "resolution_seconds": 300,
}},
{"status": 200, "body": {
"status": "success", "peer_uuid": "...", "instance": "wg0",
"start": "2026-08-01T00:00:00-03:00", "end": "2026-11-24T00:00:00-03:00",
"download_bytes": 123456789, "upload_bytes": 9876543, "resolution_seconds": 86400,
"warning": "The period starts before the detailed history; the totals were calculated with a "
"resolution of 1 day.",
}},
{"status": 400, "body": {"status": "error", "error_message": "Invalid or missing start date."}},
{"status": 400, "body": {"status": "error", "error_message": "Invalid end date."}},
{"status": 400, "body": {"status": "error", "error_message": "The start date must be before the end date."}},
{"status": 400, "body": {"status": "error", "error_message": "Missing peer selector (peer_uuid or peer_public_key)."}},
{"status": 403, "body": {"status": "error", "error_message": "This API key is not allowed to access the requested instance."}},
{"status": 404, "body": {"status": "error", "error_message": "Peer not found."}},
{"status": 404, "body": {"status": "error", "error_message": "There is no traffic history for this peer."}},
{"status": 405, "body": {"status": "error", "error_message": "Method not allowed."}},
{"status": 500, "body": {"status": "error", "error_message": "Could not read the traffic history: ..."}},
],
examples={
"traffic_by_uuid": {"method": "POST", "json": {
"instance": "wg0", "peer_uuid": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"start": "2026-11-01T00:00:00-03:00", "end": "2026-11-15T23:59:59-03:00",
}},
"traffic_until_now": {"method": "POST", "json": {
"instance": "wg0", "peer_public_key": "BASE64PUBLICKEY...", "start": "2026-11-01",
}},
}
)
def api_v2_peer_traffic(request):
if request.method not in ("POST", "GET"):
return JsonResponse({"status": "error", "error_message": "Method not allowed."}, status=405)
if request.method == "POST":
try:
payload = json.loads(request.body.decode("utf-8")) if request.body else {}
except Exception:
return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400)
if not isinstance(payload, dict):
return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400)
else:
payload = request.GET.dict()
try:
wireguard_instance = WireGuardInstance.objects.get(
instance_id=int(str(payload.get("instance")).replace("wg", ""))
)
except Exception:
wireguard_instance = None
if not wireguard_instance:
return JsonResponse({"status": "error", "error_message": "Invalid or missing WireGuard instance."}, status=400)
api_key, api_error = validate_api_key(request, wireguard_instance=wireguard_instance)
if not api_key:
return JsonResponse({"status": "error", "error_message": api_error}, status=403)
selector_peer_uuid = payload.get("peer_uuid")
selector_peer_public_key = payload.get("peer_public_key")
if not selector_peer_uuid and not selector_peer_public_key:
return JsonResponse(
{"status": "error", "error_message": "Missing peer selector (peer_uuid or peer_public_key)."},
status=400,
)
now = timezone.now()
start = _parse_api_datetime(payload.get("start"))
if not start:
return JsonResponse({"status": "error", "error_message": "Invalid or missing start date."}, status=400)
if payload.get("end") in (None, ""):
end = now
else:
end = _parse_api_datetime(payload.get("end"))
if not end:
return JsonResponse({"status": "error", "error_message": "Invalid end date."}, status=400)
end = min(end, now)
if start >= end:
return JsonResponse(
{"status": "error", "error_message": "The start date must be before the end date."}, status=400,
)
peers = Peer.objects.filter(wireguard_instance=wireguard_instance)
try:
if selector_peer_uuid:
peer = peers.filter(uuid=selector_peer_uuid).first()
else:
peer = peers.filter(public_key=selector_peer_public_key).first()
except ValidationError:
peer = None
if not peer:
return JsonResponse({"status": "error", "error_message": "Peer not found."}, status=404)
rrd_path = peer_rrd_path(peer)
if not os.path.exists(rrd_path):
return JsonResponse(
{"status": "error", "error_message": "There is no traffic history for this peer."}, status=404,
)
try:
totals = peer_traffic_totals(rrd_path, start.timestamp(), end.timestamp())
except TrafficHistoryError as error:
return JsonResponse(
{"status": "error", "error_message": f"Could not read the traffic history: {error}"}, status=500,
)
data = {
"status": "success",
"peer_uuid": str(peer.uuid),
"instance": f"wg{wireguard_instance.instance_id}",
"start": _api_datetime(totals["start"]),
"end": _api_datetime(totals["end"]),
"download_bytes": totals["download_bytes"],
"upload_bytes": totals["upload_bytes"],
"resolution_seconds": totals["resolution_seconds"],
}
warning = traffic_warning(totals)
if warning:
data["warning"] = warning
return JsonResponse(data, status=200)
@csrf_exempt @csrf_exempt
@api_doc( @api_doc(
summary="Get WireGuard status (dump) for all interfaces/peers", summary="Get WireGuard status (dump) for all interfaces/peers",
+90
View File
@@ -0,0 +1,90 @@
import base64
import math
import os
import subprocess
RRD_PEERS_PATH = '/rrd_data/peers'
# The RRD files keep 5 minute samples for a few days and coarser averages for older periods
DETAILED_RESOLUTION = 300
RESOLUTION_LABELS = {1800: '30 minutes', 7200: '2 hours', 86400: '1 day'}
class TrafficHistoryError(Exception):
pass
def peer_rrd_path(peer):
filename = base64.urlsafe_b64encode(peer.public_key.encode()).decode().replace('=', '')
return os.path.join(RRD_PEERS_PATH, f'{filename}.rrd')
def _run_rrdtool(arguments):
try:
result = subprocess.run(['rrdtool', *arguments], capture_output=True, text=True, timeout=30)
except (OSError, subprocess.TimeoutExpired) as error:
raise TrafficHistoryError(str(error))
if result.returncode != 0:
raise TrafficHistoryError(result.stderr.strip() or f'rrdtool exited with status {result.returncode}')
return result.stdout
def peer_traffic_totals(rrd_path, start, end):
"""Traffic of a peer between two timestamps (seconds), read from its RRD file.
The RRD stores the average rate (bytes per second) of each interval; the total is the rate multiplied by the
interval length. tx is what the server sent to the peer (the peer download) and rx what it received (upload).
Returns a dict with the totals, the period effectively covered, the resolution and the intervals without data.
"""
last_update = int(_run_rrdtool(['last', rrd_path]).strip())
output = _run_rrdtool([
'fetch', rrd_path, 'AVERAGE', '--start', str(int(start)), '--end', str(int(end)),
'--resolution', str(DETAILED_RESOLUTION),
])
lines = [line for line in output.splitlines() if line.strip()]
columns = lines[0].split()
tx_index, rx_index = columns.index('tx'), columns.index('rx')
rows = []
for line in lines[1:]:
timestamp, _, values = line.partition(':')
values = values.split()
rows.append((int(timestamp), float(values[tx_index]), float(values[rx_index])))
step = rows[1][0] - rows[0][0] if len(rows) > 1 else DETAILED_RESOLUTION
# Each row covers the interval that ends at its timestamp; intervals after the last update are still open
rows = [row for row in rows if row[0] <= last_update]
download = upload = 0.0
missing = 0
for _, tx, rx in rows:
if math.isnan(tx) or math.isnan(rx):
missing += 1
continue
download += tx * step
upload += rx * step
return {
'download_bytes': int(round(download)),
'upload_bytes': int(round(upload)),
'start': rows[0][0] - step if rows else int(start),
'end': rows[-1][0] if rows else int(start),
'resolution_seconds': step,
'intervals': len(rows),
'missing_intervals': missing,
}
def traffic_warning(totals):
"""Short warning about the precision of the totals, or '' when they use the detailed history with no gaps."""
warnings = []
step = totals['resolution_seconds']
if step > DETAILED_RESOLUTION:
label = RESOLUTION_LABELS.get(step, f'{step} seconds')
warnings.append(
f'The period starts before the detailed history; the totals were calculated with a resolution of {label}.'
)
if totals['intervals'] == 0 or totals['missing_intervals'] == totals['intervals']:
warnings.append('There is no traffic data in the requested period.')
elif totals['missing_intervals']:
warnings.append('Part of the period has no traffic data and is not included in the totals.')
return ' '.join(warnings)
+2 -3
View File
@@ -1,4 +1,3 @@
import base64
import os import os
import subprocess import subprocess
import tempfile import tempfile
@@ -9,6 +8,7 @@ from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404 from django.shortcuts import get_object_or_404
from user_manager.models import UserAcl from user_manager.models import UserAcl
from wgrrd.functions import peer_rrd_path
from wgwadmlibrary.tools import user_has_access_to_peer from wgwadmlibrary.tools import user_has_access_to_peer
from wireguard.models import Peer, WireGuardInstance from wireguard.models import Peer, WireGuardInstance
@@ -23,8 +23,7 @@ def view_rrd_graph(request):
if not user_has_access_to_peer(user_acl, peer): if not user_has_access_to_peer(user_acl, peer):
raise PermissionDenied raise PermissionDenied
graph_type = 'peer' graph_type = 'peer'
rrd_filename = base64.urlsafe_b64encode(peer.public_key.encode()).decode().replace('=', '') rrd_file_path = peer_rrd_path(peer)
rrd_file_path = f'/rrd_data/peers/{rrd_filename}.rrd'
graph_title = f'Peer {peer}' graph_title = f'Peer {peer}'
elif request.GET.get('instance'): elif request.GET.get('instance'):
wireguard_instance = get_object_or_404(WireGuardInstance, uuid=request.GET.get('instance')) wireguard_instance = get_object_or_404(WireGuardInstance, uuid=request.GET.get('instance'))