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
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 django.test import TestCase, override_settings
from django.utils import timezone
from api_v2.models import ApiKey
from vpn_invite.models import InviteSettings, PeerInvite
from cluster.models import ClusterSettings, Worker
from cluster.tests import create_instance
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
@@ -412,3 +418,132 @@ class ApiV2PeerInviteTests(TestCase):
def test_other_methods_are_not_allowed(self):
response = self.client.get(self.url, HTTP_TOKEN=str(self.api_key.token))
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_invite,
api_v2_peer_list,
api_v2_peer_traffic,
api_v2_wireguard_status,
)
@@ -17,6 +18,7 @@ urlpatterns = [
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_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('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'),
+174 -1
View File
@@ -1,7 +1,8 @@
import ipaddress
import json
import os
import re
from datetime import timedelta
from datetime import datetime, time, timedelta
from functools import wraps
from typing import List, Optional, Tuple
@@ -11,6 +12,7 @@ from django.core.exceptions import ValidationError
from django.db import transaction
from django.http import JsonResponse
from django.utils import timezone
from django.utils.dateparse import parse_date, parse_datetime
from django.views.decorators.csrf import csrf_exempt
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 speed_profiles.models import SpeedProfile
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 wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
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)
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
@api_doc(
summary="Get WireGuard status (dump) for all interfaces/peers",