Add speed profiles to limit the bandwidth of each peer

This commit is contained in:
Eduardo Silva
2026-11-24 17:05:13 -03:00
parent 026c82445b
commit 3f2da7e545
35 changed files with 1538 additions and 25 deletions
+17
View File
@@ -1,5 +1,6 @@
import glob
import ipaddress
import logging
import os
import re
import subprocess
@@ -9,8 +10,10 @@ from django.utils.translation import gettext_lazy as _
from cluster.models import ClusterSettings, Worker
from wireguard.models import WireGuardInstance
from wireguard_tools.speed_limits import apply_speed_limits, format_speed_limit_comment, remove_speed_limits
WIREGUARD_CONFIG_DIR = '/etc/wireguard'
SPEED_LIMIT_WARNING = 'speed limits not fully applied'
# Configurations of instances that run on workers (distributed cluster mode). Kept out of WIREGUARD_CONFIG_DIR
# so the primary server does not bring them up.
CLUSTER_WIREGUARD_CONFIG_DIR = '/etc/wireguard/cluster'
@@ -35,6 +38,9 @@ def peer_config_lines(peer) -> list:
allowed_ips_line = "AllowedIPs = " + ", ".join(f"{ip.allowed_ip}/{ip.netmask}" for ip in allowed_ips)
lines = [peer_title, f"{prepend_line}[Peer]", f"{prepend_line}PublicKey = {peer.public_key}"]
speed_profile = peer.speed_profile
if allowed_ips and speed_profile and speed_profile.config_comment():
lines.append(format_speed_limit_comment(speed_profile.config_comment()))
if peer.pre_shared_key:
lines.append(f"{prepend_line}PresharedKey = {peer.pre_shared_key}")
if peer.endpoint:
@@ -100,6 +106,8 @@ def stop_primary_interfaces() -> list:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
errors.append((interface_name, result.stderr.strip()))
# The ifb used by the upload limits is not removed with the interface
remove_speed_limits(interface_name)
return errors
@@ -114,6 +122,10 @@ def start_primary_interfaces() -> list:
result = subprocess.run(['wg-quick', 'up', interface_name], capture_output=True, text=True)
if result.returncode != 0:
errors.append((interface_name, result.stderr.strip()))
continue
# A failure in the speed limits never keeps the interface down
for speed_limit_error in apply_speed_limits(interface_name, config_path):
logging.warning("%s: %s: %s", interface_name, SPEED_LIMIT_WARNING, speed_limit_error)
return errors
@@ -247,6 +259,11 @@ def reload_wireguard_interface(target: Union[str, WireGuardInstance], config_dir
if route_errors:
return False, f"{interface_name} reloaded with route errors: {'; '.join(route_errors)}"
# A failure in the speed limits does not undo the reload: it is only reported
speed_limit_errors = apply_speed_limits(interface_name, conf_path)
if speed_limit_errors:
return True, f"{interface_name} reloaded, but {SPEED_LIMIT_WARNING}: {'; '.join(speed_limit_errors)}"
return True, f"{interface_name} reloaded successfully"
except subprocess.CalledProcessError as e:
+178
View File
@@ -0,0 +1,178 @@
"""
Per peer bandwidth limits of a WireGuard interface, applied with tc.
The limits are read from the WireGuard configuration file: each limited peer has a "# Speed limit:" comment in its
[Peer] block. Both directions are shaped with htb, one class per peer matching all of its allowed IPs:
- download (traffic that reaches the peer) on the egress of the WireGuard interface;
- upload (traffic that the peer sends) on an ifb interface that receives the ingress of the WireGuard interface.
Shaping queues the excess instead of dropping it, which keeps TCP close to the configured rate. Upload limits need
the ifb kernel module; without it only the download limits are applied and the failure is reported.
Standard library only: the cluster node agent ships an identical copy of this file.
Usage as a script: python3 speed_limits.py <interface> <config_path>
"""
import ipaddress
import subprocess
import sys
SPEED_LIMIT_COMMENT = '# Speed limit:'
LIMIT_KEYS = ('download_kbit', 'download_burst', 'upload_kbit', 'upload_burst')
def format_speed_limit_comment(settings):
return f'{SPEED_LIMIT_COMMENT} {settings}'
def ifb_name(interface):
"""ifb interface that shapes the upload of a WireGuard interface (interface names are limited to 15 chars)."""
return f'ifb{interface}'[:15]
def parse_speed_limits(config_content):
"""Return a list of {'networks': [...], 'download_kbit': int, ...} for each limited peer of the configuration."""
peers = []
current = None
for raw_line in config_content.splitlines():
line = raw_line.strip()
if line.startswith('[') and line.endswith(']'):
if current is not None:
peers.append(current)
current = {'networks': [], 'limits': {}} if line == '[Peer]' else None
continue
if current is None:
continue
if line.startswith(SPEED_LIMIT_COMMENT):
for item in line[len(SPEED_LIMIT_COMMENT):].split():
key, _, value = item.partition('=')
if key in LIMIT_KEYS and value.isdigit() and int(value) > 0:
current['limits'][key] = int(value)
elif line.split('=', 1)[0].strip() == 'AllowedIPs' and '=' in line:
for value in line.split('=', 1)[1].split(','):
try:
network = ipaddress.ip_network(value.strip(), strict=False)
except ValueError:
continue
if network.version == 4:
current['networks'].append(network)
if current is not None:
peers.append(current)
limited_peers = []
for peer in peers:
limits = peer['limits']
if not peer['networks'] or not (limits.get('download_kbit') or limits.get('upload_kbit')):
continue
limited_peers.append({'networks': peer['networks'], **limits})
return limited_peers
def _filter_priority(network):
# The most specific network is matched first, as in routing
return 100 + 32 - network.prefixlen
def _htb_commands(device, peers, direction, match):
"""htb root with one class per peer; unclassified traffic (default 0) is sent without limits."""
commands = [f'qdisc add dev {device} root handle 1: htb default 0']
for index, peer in enumerate(peers, start=1):
class_id = f'1:{index:x}'
rate = f"{peer[f'{direction}_kbit']}kbit"
class_command = f'class add dev {device} parent 1: classid {class_id} htb rate {rate} ceil {rate}'
if peer.get(f'{direction}_burst'):
burst = f"{peer[f'{direction}_burst']}b"
class_command += f' burst {burst} cburst {burst}'
commands.append(class_command)
for network in peer['networks']:
commands.append(
f'filter add dev {device} parent 1: protocol ip prio {_filter_priority(network)} '
f'u32 match ip {match} {network} flowid {class_id}'
)
return commands
def build_tc_commands(interface, limited_peers, upload=True):
"""tc batch commands that install the limits on a clean interface (and on a clean ifb for the upload)."""
commands = []
download_peers = [peer for peer in limited_peers if peer.get('download_kbit')]
upload_peers = [peer for peer in limited_peers if peer.get('upload_kbit')] if upload else []
if download_peers:
commands += _htb_commands(interface, download_peers, 'download', 'dst')
if upload_peers:
ifb = ifb_name(interface)
commands.append(f'qdisc add dev {interface} handle ffff: ingress')
# Only the traffic of limited peers goes through the ifb; the rest is not touched
for peer in upload_peers:
for network in peer['networks']:
commands.append(
f'filter add dev {interface} parent ffff: protocol ip prio {_filter_priority(network)} '
f'u32 match ip src {network} action mirred egress redirect dev {ifb}'
)
commands += _htb_commands(ifb, upload_peers, 'upload', 'src')
return commands
def remove_speed_limits(interface, run=None):
"""Remove the limits of an interface and its ifb. Missing qdiscs and devices are not an error."""
run = run or subprocess.run
for parent in ('root', 'ingress'):
run(['tc', 'qdisc', 'del', 'dev', interface, parent], capture_output=True, text=True)
run(['ip', 'link', 'delete', ifb_name(interface)], capture_output=True, text=True)
def _prepare_ifb(interface, run):
"""Create (or reuse) the ifb of an interface with a clean root. Returns an error message or ''."""
ifb = ifb_name(interface)
result = run(['ip', 'link', 'add', ifb, 'type', 'ifb'], capture_output=True, text=True)
if result.returncode != 0 and 'exists' not in (result.stderr or '').lower():
return f'upload limits need the ifb kernel module ({(result.stderr or "").strip() or "ifb not available"})'
run(['tc', 'qdisc', 'del', 'dev', ifb, 'root'], capture_output=True, text=True)
# The default queue of an ifb (32 packets) is too short for shaped traffic
result = run(['ip', 'link', 'set', ifb, 'up', 'txqueuelen', '1000'], capture_output=True, text=True)
if result.returncode != 0:
return f'{ifb}: {(result.stderr or "").strip()}'
return ''
def apply_speed_limits(interface, config_path, run=None):
"""Replace the limits of a running interface with the ones of its configuration. Returns the errors found."""
run = run or subprocess.run
try:
with open(config_path) as config_file:
limited_peers = parse_speed_limits(config_file.read())
except OSError as error:
return [f'{config_path}: {error}']
errors = []
for parent in ('root', 'ingress'):
run(['tc', 'qdisc', 'del', 'dev', interface, parent], capture_output=True, text=True)
upload = any(peer.get('upload_kbit') for peer in limited_peers)
if upload:
ifb_error = _prepare_ifb(interface, run)
if ifb_error:
# Download limits do not depend on the ifb and are still applied
errors.append(ifb_error)
upload = False
else:
run(['ip', 'link', 'delete', ifb_name(interface)], capture_output=True, text=True)
commands = build_tc_commands(interface, limited_peers, upload=upload)
if not commands:
return errors
result = run(['tc', '-batch', '-'], input='\n'.join(commands) + '\n', capture_output=True, text=True)
if result.returncode != 0:
# Do not leave a partial set of limits behind
remove_speed_limits(interface, run)
errors.append((result.stderr or result.stdout).strip() or f'tc exited with status {result.returncode}')
return errors
if __name__ == '__main__':
if len(sys.argv) != 3:
print(f'Usage: {sys.argv[0]} <interface> <config_path>', file=sys.stderr)
sys.exit(2)
errors = apply_speed_limits(sys.argv[1], sys.argv[2])
for error in errors:
print(f'{sys.argv[1]}: speed limits not fully applied: {error}', file=sys.stderr)
sys.exit(1 if errors else 0)
+18 -4
View File
@@ -2,6 +2,7 @@ import importlib.util
import ipaddress
import os
import subprocess
import sys
import tempfile
from unittest.mock import patch
@@ -16,10 +17,15 @@ from wireguard_tools import functions
def load_cluster_worker():
module_path = os.path.join(settings.BASE_DIR, 'containers', 'cluster_node', 'cluster_worker.py')
spec = importlib.util.spec_from_file_location('cluster_worker_under_test', module_path)
agent_dir = os.path.join(settings.BASE_DIR, 'containers', 'cluster_node')
spec = importlib.util.spec_from_file_location('cluster_worker_under_test', os.path.join(agent_dir, 'cluster_worker.py'))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# The agent imports speed_limits from its own directory, as in the cluster node image
sys.path.insert(0, agent_dir)
try:
spec.loader.exec_module(module)
finally:
sys.path.remove(agent_dir)
return module
@@ -45,6 +51,9 @@ class FakeNetwork:
def run(self, command, *args, **kwargs):
self.commands.append(command)
stdout = ''
if command[:2] == ['ip', 'link'] or command[0] == 'tc':
# Devices and qdiscs of the speed limits are not part of the routes
return subprocess.CompletedProcess(command, 0, '', '')
if command[:2] == ['wg', 'show']:
stdout = ''.join(f'peer{index}\t{value}\n' for index, value in enumerate(self.allowed_ips))
elif command[0] == 'ip':
@@ -228,7 +237,12 @@ class AgentInterfaceFailureTests(TestCase):
self.config_path = os.path.join(temp_dir.name, 'wg0.conf')
with open(self.config_path, 'w', encoding='utf-8') as config_file:
config_file.write(self.OLD_CONFIG)
for name, value in (('WIREGUARD_DIR', temp_dir.name), ('interface_is_up', lambda interface: True)):
for name, value in (
('WIREGUARD_DIR', temp_dir.name), ('interface_is_up', lambda interface: True),
# Never touch the qdiscs of the interfaces of the machine that runs the tests
('apply_speed_limits', lambda interface, config_path: []),
('remove_speed_limits', lambda interface: None),
):
patcher = patch.object(self.cluster_worker, name, value)
patcher.start()
self.addCleanup(patcher.stop)
+15 -2
View File
@@ -23,9 +23,10 @@ from vpn_invite.models import PeerInvite
from wgwadmlibrary.tools import user_has_access_to_peer
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
from wireguard_tools.functions import (
CLUSTER_WIREGUARD_CONFIG_DIR, WIREGUARD_CONFIG_DIR, get_instance_config_dir, peer_config_lines,
stop_primary_interfaces, sync_interface_routes,
CLUSTER_WIREGUARD_CONFIG_DIR, WIREGUARD_CONFIG_DIR, get_instance_config_dir,
peer_config_lines, stop_primary_interfaces, sync_interface_routes,
)
from wireguard_tools.speed_limits import apply_speed_limits
def clean_command_field(command_field):
@@ -100,6 +101,15 @@ def set_instance_to_include_firewall():
return instance_to_execute_firewall, True
def _apply_speed_limits_with_warning(request, interface_name, config_path):
"""Apply the speed limits of a running interface. A failure is shown as a warning and never stops the interface."""
speed_limit_errors = apply_speed_limits(interface_name, config_path)
if speed_limit_errors:
messages.warning(
request, _('Speed limits not fully applied') + f" {interface_name}|{'; '.join(speed_limit_errors)}"
)
def export_wireguard_configuration(instance_only: WireGuardInstance = None):
cleanup_orphaned = True
instance_to_execute_firewall, force_export_all_instances = set_instance_to_include_firewall()
@@ -197,6 +207,7 @@ def export_wireguard_configuration(instance_only: WireGuardInstance = None):
peers = (
Peer.objects
.filter(wireguard_instance=instance, suspended=False, disabled_by_schedule=False)
.select_related("speed_profile")
.prefetch_related(
Prefetch(
"peerallowedip_set",
@@ -368,6 +379,7 @@ def restart_wireguard_interfaces(request):
error_count += 1
else:
interface_count += 1
_apply_speed_limits_with_warning(request, interface_name, config_path)
else:
if not user_acl.enable_restart:
@@ -387,6 +399,7 @@ def restart_wireguard_interfaces(request):
error_count += 1
else:
interface_count += 1
_apply_speed_limits_with_warning(request, interface_name, os.path.join(config_dir, filename))
if interface_count > 0 and error_count == 0:
if mode == 'reload':