diff --git a/api_v2/views_api.py b/api_v2/views_api.py index 5473abf..0f03f63 100644 --- a/api_v2/views_api.py +++ b/api_v2/views_api.py @@ -21,6 +21,7 @@ from cluster.sync import get_worker_sync_state from dns.models import DNSSettings, StaticHost 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 wgwadmlibrary.tools import create_peer_invite, get_peer_invite_data, send_email from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance @@ -256,6 +257,9 @@ def _validate_dns_hostname(hostname: str) -> Tuple[Optional[str], Optional[str]] {"name": "active_worker_uuid", "in": "json", "type": "string", "required": False, "description": "Cluster worker that connects to the endpoint in the mirror mode (create/update). Null or " "empty means the primary server."}, + {"name": "speed_profile_uuid", "in": "json", "type": "string", "required": False, + "description": "Speed profile of the peer (create/update). Null or empty removes the limit. When omitted on " + "create, the default speed profile of the instance is used."}, ], returns=[ {"status": 200, "body": {"status": "success", "message": "Peer updated successfully.", "peer_uuid": "...", "public_key": "...", "main_addresses": ["..."], "reload": {"success": True, "message": "..."}}}, @@ -358,6 +362,15 @@ def api_v2_manage_peer(request): if not new_active_worker: return JsonResponse({"status": "error", "error_message": "Invalid active_worker_uuid."}, status=400) + new_speed_profile = None + if payload.get("speed_profile_uuid"): + try: + new_speed_profile = SpeedProfile.objects.filter(uuid=payload.get("speed_profile_uuid")).first() + except (ValidationError, ValueError): + new_speed_profile = None + if not new_speed_profile: + return JsonResponse({"status": "error", "error_message": "Invalid speed_profile_uuid."}, status=400) + with transaction.atomic(): # CREATE if request.method == "POST": @@ -393,6 +406,8 @@ def api_v2_manage_peer(request): if routing_template is not None: create_overrides["default_routing_template"] = routing_template + if "speed_profile_uuid" in payload: + create_overrides["speed_profile"] = new_speed_profile created_peer, create_message = func_create_new_peer(wireguard_instance=wireguard_instance, overrides=create_overrides) if not created_peer: @@ -495,6 +510,8 @@ def api_v2_manage_peer(request): peer_for_action.endpoint = new_endpoint if "active_worker_uuid" in payload: peer_for_action.active_worker = new_active_worker + if "speed_profile_uuid" in payload: + peer_for_action.speed_profile = new_speed_profile if not peer_for_action.endpoint: peer_for_action.active_worker = None @@ -724,7 +741,7 @@ def api_v2_manage_dns_record(request): "description": "Required. Target instance name in the format wg{instance_id} (e.g. wg0, wg1)."}, ], returns=[ - {"status": 200, "body": {"status": "success", "instance": "wg2", "peers": [{"uuid": "...", "name": "...", "public_key": "...", "suspended": False, "suspend_reason": "...", "disabled_by_schedule": False, "main_addresses": ["..."]}]}}, + {"status": 200, "body": {"status": "success", "instance": "wg2", "peers": [{"uuid": "...", "name": "...", "public_key": "...", "suspended": False, "suspend_reason": "...", "disabled_by_schedule": False, "main_addresses": ["..."], "endpoint": "", "speed_profile_uuid": ""}]}}, {"status": 400, "body": {"status": "error", "error_message": "Invalid or missing WireGuard instance."}}, {"status": 403, "body": {"status": "error", "error_message": "Invalid API key."}}, ], @@ -762,6 +779,7 @@ def api_v2_peer_list(request): peer_qs = ( Peer.objects .filter(wireguard_instance=wireguard_instance) + .select_related("speed_profile") .prefetch_related("peerallowedip_set") .order_by("sort_order", "name", "public_key") ) @@ -777,6 +795,7 @@ def api_v2_peer_list(request): "disabled_by_schedule": bool(current_peer.disabled_by_schedule), "main_addresses": current_peer.main_addresses, "endpoint": current_peer.endpoint, + "speed_profile_uuid": str(current_peer.speed_profile.uuid) if current_peer.speed_profile else "", }) return JsonResponse( @@ -803,7 +822,7 @@ def api_v2_peer_list(request): "description": "Peer public key selector."}, ], returns=[ - {"status": 200, "body": {"status": "success", "peer": {"uuid": "...", "name": "...", "public_key": "...", "pre_shared_key": "...", "private_key": "...", "persistent_keepalive": 25, "routing_template_uuid": "...", "suspended": False, "suspend_reason": "...", "disabled_by_schedule": False, "enabled": True, "main_addresses": ["..."], "announced_networks": ["..."], "client_routes": ["..."], "endpoint": "", "active_worker_uuid": "", "instance": "...", "instance_uuid": "..."}}}, + {"status": 200, "body": {"status": "success", "peer": {"uuid": "...", "name": "...", "public_key": "...", "pre_shared_key": "...", "private_key": "...", "persistent_keepalive": 25, "routing_template_uuid": "...", "suspended": False, "suspend_reason": "...", "disabled_by_schedule": False, "enabled": True, "main_addresses": ["..."], "announced_networks": ["..."], "client_routes": ["..."], "endpoint": "", "active_worker_uuid": "", "speed_profile_uuid": "", "instance": "...", "instance_uuid": "..."}}}, {"status": 400, "body": {"status": "error", "error_message": "Missing peer selector (peer_uuid or peer_public_key)."}}, {"status": 404, "body": {"status": "error", "error_message": "Peer not found."}}, {"status": 403, "body": {"status": "error", "error_message": "Invalid API key."}}, @@ -881,6 +900,7 @@ def api_v2_peer_detail(request): "client_routes": current_peer.client_routes, "endpoint": current_peer.endpoint, "active_worker_uuid": str(current_peer.active_worker.uuid) if current_peer.active_worker else "", + "speed_profile_uuid": str(current_peer.speed_profile.uuid) if current_peer.speed_profile else "", "instance": f"wg{wireguard_instance.instance_id}", "instance_uuid": str(wireguard_instance.uuid), } diff --git a/cluster/cluster_api.py b/cluster/cluster_api.py index 7f83da8..70a6fa7 100644 --- a/cluster/cluster_api.py +++ b/cluster/cluster_api.py @@ -125,6 +125,8 @@ def _clean_section_report(sections): 'hash': str(report.get('hash', ''))[:64], 'status': status, 'message': str(report.get('message', ''))[:1000], + # Problems that did not stop the section, such as speed limits that could not be applied + 'warning': str(report.get('warning', ''))[:1000] if status == 'ok' else '', 'updated': timezone.now().isoformat(), } return cleaned_sections diff --git a/cluster/sync.py b/cluster/sync.py index 4eecdae..afb5b3e 100644 --- a/cluster/sync.py +++ b/cluster/sync.py @@ -107,6 +107,7 @@ def _mirror_endpoint_peers(content, content_sha256, filename, worker): suspended=False, disabled_by_schedule=False, ) .exclude(endpoint='') + .select_related('speed_profile') .prefetch_related(Prefetch('peerallowedip_set', queryset=PeerAllowedIP.objects.filter(config_file='server'))) ) worker_lines = [line for peer in endpoint_peers for line in peer_config_lines(peer)] @@ -203,12 +204,15 @@ def build_manifest(worker): CERTIFICATE_EXPIRATION_WARNING_DAYS = 14 -def get_worker_warnings(worker): - """Stopped services and certificates that are not trusted or expire soon, as reported by the worker.""" +def get_worker_warnings(worker, sync_state=None): + """ + Stopped services, certificates that are not trusted or expire soon and sections applied with warnings, as + reported by the worker. sync_state avoids building the manifest again when it is already known. + """ try: worker_status = worker.workerstatus except WorkerStatus.DoesNotExist: - return {'stopped_services': [], 'certificate_issues': []} + return {'stopped_services': [], 'certificate_issues': [], 'section_warnings': []} stopped_services = sorted( service for service, state in (worker_status.services_status or {}).items() if state != 'running' @@ -221,7 +225,15 @@ def get_worker_warnings(worker): certificate_issues.append(hostname) elif certificate.get('status') == 'trusted' and not_after and not_after < expiration_limit: certificate_issues.append(hostname) - return {'stopped_services': stopped_services, 'certificate_issues': certificate_issues} + # Only warnings of the content currently applied: a newer version replaces them once it is reported + sync_state = sync_state or get_worker_sync_state(worker) + section_warnings = sorted( + section_name for section_name, section in sync_state['sections'].items() if section.get('warning') + ) + return { + 'stopped_services': stopped_services, 'certificate_issues': certificate_issues, + 'section_warnings': section_warnings, + } def get_worker_sync_state(worker, manifest=None): @@ -244,7 +256,7 @@ def get_worker_sync_state(worker, manifest=None): elif reported.get('status') == 'error': sections[section_name] = {'state': 'error', 'message': reported.get('message', '')} else: - sections[section_name] = {'state': 'synced', 'message': ''} + sections[section_name] = {'state': 'synced', 'message': '', 'warning': reported.get('warning', '')} states = {section['state'] for section in sections.values()} if 'error' in states: diff --git a/cluster/views.py b/cluster/views.py index f99d5c3..209ce98 100644 --- a/cluster/views.py +++ b/cluster/views.py @@ -35,7 +35,7 @@ def describe_worker(worker): f"{section_name}: {section['message']}" for section_name, section in worker.sync_state['sections'].items() if section['state'] == 'error' and section['message'] ] - worker.warnings = get_worker_warnings(worker) + worker.warnings = get_worker_warnings(worker, worker.sync_state) # Reported data of disabled, refused or offline workers is only the last known state worker.operational = worker.enabled and not worker.error_status and worker.is_online worker_status = get_worker_status(worker) @@ -84,7 +84,7 @@ def cluster_main(request): 'attention': sum( 1 for worker in enabled_workers if worker.sync_state['state'] == 'error' or worker.error_status or worker.warnings['stopped_services'] - or worker.warnings['certificate_issues'] or not worker.is_online + or worker.warnings['certificate_issues'] or worker.warnings['section_warnings'] or not worker.is_online ), }, 'cache_refresh_interval': settings.WIREGUARD_STATUS_CACHE_REFRESH_INTERVAL, @@ -112,6 +112,7 @@ def worker_details(request): 'name': section_name, 'state': section_state.get('state', 'pending'), 'message': section_state.get('message', ''), + 'warning': section_state.get('warning', ''), 'updated': parse_datetime(reported.get('updated', '')) if reported.get('updated') else None, }) diff --git a/containers/cluster_node/Dockerfile-cluster_node b/containers/cluster_node/Dockerfile-cluster_node index b34ff6a..71840bf 100644 --- a/containers/cluster_node/Dockerfile-cluster_node +++ b/containers/cluster_node/Dockerfile-cluster_node @@ -22,7 +22,7 @@ COPY requirements.txt /app/requirements.txt RUN pip install --no-cache-dir -r requirements.txt # Copy the application code -COPY cluster_worker.py entrypoint.sh /app/ +COPY cluster_worker.py speed_limits.py entrypoint.sh /app/ # Set execution permissions on scripts RUN chmod +x /app/entrypoint.sh diff --git a/containers/cluster_node/cluster_worker.py b/containers/cluster_node/cluster_worker.py index 8756ad0..bb4eecd 100644 --- a/containers/cluster_node/cluster_worker.py +++ b/containers/cluster_node/cluster_worker.py @@ -14,12 +14,14 @@ from datetime import datetime, timezone import requests +from speed_limits import apply_speed_limits, remove_speed_limits + logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) MASTER_SERVER_ADDRESS = os.environ.get('MASTER_SERVER_ADDRESS', '') TOKEN = os.environ.get('TOKEN', '') -WORKER_VERSION = 15 +WORKER_VERSION = 16 REQUEST_TIMEOUT = 30 MANIFEST_INTERVAL = 60 DEFAULT_STATS_INTERVAL = 60 @@ -242,6 +244,8 @@ class ClusterNodeAgent: }) # Nothing is persisted: after a restart interfaces and firewall rules are gone, so every section is applied again self.applied_hashes = {} + # Problems that did not stop a section, reported with it + self.section_warnings = {} self.stats_interval = DEFAULT_STATS_INTERVAL self.wireguard_active = False # Applications left in the gateway directory by an earlier run are only removed when the worker is refused @@ -303,9 +307,11 @@ class ClusterNodeAgent: interface = filename[:-len('.conf')] if interface_is_up(interface): run_command(['wg-quick', 'down', interface], check=False) + remove_speed_limits(interface) os.remove(config_path) logger.info('Removed WireGuard interface %s', interface) + speed_limit_warnings = [] for filename, content in sorted(desired_files.items()): interface = filename[:-len('.conf')] config_path = os.path.join(WIREGUARD_DIR, filename) @@ -322,6 +328,12 @@ class ClusterNodeAgent: elif previous_content != content: self.sync_peers(interface, config_path) logger.info('Synchronized peers of WireGuard interface %s', interface) + else: + continue + # A failure in the speed limits never keeps the interface down: it is reported as a warning + for speed_limit_error in apply_speed_limits(interface, config_path): + logger.warning('%s: speed limits not fully applied: %s', interface, speed_limit_error) + speed_limit_warnings.append(f'{interface}: speed limits not fully applied: {speed_limit_error}') except SectionError as error: errors.append(str(error)) # Back to the content actually applied, so the next attempt sees the change again @@ -329,6 +341,7 @@ class ClusterNodeAgent: write_file(config_path, previous_content) self.wireguard_active = True + self.section_warnings['wireguard'] = '; '.join(speed_limit_warnings) if errors: raise SectionError('; '.join(errors)) @@ -402,7 +415,9 @@ class ClusterNodeAgent: return logger.warning('Shutting down WireGuard interfaces and firewall rules') for config_path in glob.glob(os.path.join(WIREGUARD_DIR, 'wg[0-9]*.conf')): - run_command(['wg-quick', 'down', os.path.basename(config_path)[:-len('.conf')]], check=False) + interface = os.path.basename(config_path)[:-len('.conf')] + run_command(['wg-quick', 'down', interface], check=False) + remove_speed_limits(interface) for table, chain in FIREWALL_CHAINS: run_command(['iptables', '-t', table, '-F', chain], check=False) self.applied_hashes.pop('wireguard', None) @@ -459,6 +474,9 @@ class ClusterNodeAgent: self.SECTION_HANDLERS[section_name](self, section) self.applied_hashes[section_name] = section['hash'] reports[section_name] = {'hash': section['hash'], 'status': 'ok'} + warning = self.section_warnings.pop(section_name, '') + if warning: + reports[section_name]['warning'] = warning logger.info('Section %s applied', section_name) except (SectionError, OSError, ValueError) as error: # Forget the last applied content: the next version must be applied and reported even if it diff --git a/containers/cluster_node/speed_limits.py b/containers/cluster_node/speed_limits.py new file mode 100644 index 0000000..65669bc --- /dev/null +++ b/containers/cluster_node/speed_limits.py @@ -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 +""" +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]} ', 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) diff --git a/init.sh b/init.sh index 5bcadad..209053b 100644 --- a/init.sh +++ b/init.sh @@ -23,7 +23,10 @@ config_files=(/etc/wireguard/*.conf) if [ ${#config_files[@]} -gt 0 ]; then if python manage.py primary_wireguard_enabled; then for f in "${config_files[@]}"; do - wg-quick up "$(basename "${f}" .conf)" + interface_name="$(basename "${f}" .conf)" + # A failure in the speed limits only prints a warning and never keeps the interface down + wg-quick up "${interface_name}" + python wireguard_tools/speed_limits.py "${interface_name}" "${f}" || true done else echo "WireGuard is disabled on the primary server, interfaces not started." diff --git a/speed_profiles/__init__.py b/speed_profiles/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/speed_profiles/apps.py b/speed_profiles/apps.py new file mode 100644 index 0000000..20f715d --- /dev/null +++ b/speed_profiles/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class SpeedProfilesConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'speed_profiles' diff --git a/speed_profiles/forms.py b/speed_profiles/forms.py new file mode 100644 index 0000000..60b1ed1 --- /dev/null +++ b/speed_profiles/forms.py @@ -0,0 +1,69 @@ +from decimal import Decimal + +from crispy_forms.helper import FormHelper +from crispy_forms.layout import Button, Div, Layout, Submit +from django import forms +from django.utils.translation import gettext_lazy as _ + +from speed_profiles.models import SpeedProfile + +MIN_LIMIT = Decimal('0.001') + + +class SpeedProfileForm(forms.ModelForm): + class Meta: + model = SpeedProfile + fields = ['name', 'download_limit', 'download_burst', 'upload_limit', 'upload_burst'] + labels = { + 'name': _('Name'), + 'download_limit': _('Download (Mbit/s)'), + 'download_burst': _('Download burst (MB)'), + 'upload_limit': _('Upload (Mbit/s)'), + 'upload_burst': _('Upload burst (MB)'), + } + help_texts = { + 'download_limit': _('Traffic that reaches the peer. Leave empty for no download limit.'), + 'upload_limit': _('Traffic that the peer sends. Leave empty for no upload limit.'), + 'download_burst': _('Optional. Data that may pass at full speed before the limit applies.'), + 'upload_burst': _('Optional. Data that may pass at full speed before the limit applies.'), + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'): + self.fields[field_name].widget.attrs.update({'min': str(MIN_LIMIT), 'step': 'any'}) + self.helper = FormHelper() + self.helper.form_method = 'post' + self.helper.layout = Layout( + Div('name', css_class='col-md-12'), + Div( + Div('download_limit', css_class='col-md-6'), + Div('download_burst', css_class='col-md-6'), + css_class='row', + ), + Div( + Div('upload_limit', css_class='col-md-6'), + Div('upload_burst', css_class='col-md-6'), + css_class='row', + ), + Div( + Submit('submit', _('Save'), css_class='btn btn-success'), + Button('cancel', _('Back'), css_class='btn btn-secondary', onclick="window.location.href='/speed_profiles/'"), + css_class='col-md-12', + ), + ) + + def clean(self): + cleaned_data = super().clean() + for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'): + value = cleaned_data.get(field_name) + if value is not None and value < MIN_LIMIT: + self.add_error(field_name, _('Enter a value greater than zero.')) + + if cleaned_data.get('download_limit') is None and cleaned_data.get('upload_limit') is None: + raise forms.ValidationError(_('Set at least a download or an upload limit.')) + if cleaned_data.get('download_burst') and cleaned_data.get('download_limit') is None: + self.add_error('download_burst', _('The burst requires a download limit.')) + if cleaned_data.get('upload_burst') and cleaned_data.get('upload_limit') is None: + self.add_error('upload_burst', _('The burst requires an upload limit.')) + return cleaned_data diff --git a/speed_profiles/migrations/0001_initial.py b/speed_profiles/migrations/0001_initial.py new file mode 100644 index 0000000..1a54fbf --- /dev/null +++ b/speed_profiles/migrations/0001_initial.py @@ -0,0 +1,33 @@ +# Generated by Django 5.2.19 on 2026-11-24 15:57 + +import uuid + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='SpeedProfile', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=64, unique=True)), + ('download_limit', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)), + ('upload_limit', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)), + ('download_burst', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)), + ('upload_burst', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)), + ('created', models.DateTimeField(auto_now_add=True)), + ('updated', models.DateTimeField(auto_now=True)), + ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), + ], + options={ + 'ordering': ['name'], + }, + ), + ] diff --git a/speed_profiles/migrations/__init__.py b/speed_profiles/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/speed_profiles/models.py b/speed_profiles/models.py new file mode 100644 index 0000000..24e2c20 --- /dev/null +++ b/speed_profiles/models.py @@ -0,0 +1,77 @@ +import uuid +from decimal import Decimal + +from django.db import models + + +def mbit_to_kbit(value): + return int((Decimal(value) * 1000).to_integral_value()) + + +def megabytes_to_bytes(value): + return int((Decimal(value) * 1_000_000).to_integral_value()) + + +class SpeedProfile(models.Model): + """Bandwidth limit applied to each peer that uses the profile. Empty limits mean no limit in that direction.""" + name = models.CharField(max_length=64, unique=True) + # Mbit/s. Download is the traffic that reaches the peer, upload the traffic the peer sends. + download_limit = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True) + upload_limit = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True) + # MB that may pass at full speed before the limit applies. Empty means the automatic minimum. + download_burst = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True) + upload_burst = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True) + + created = models.DateTimeField(auto_now_add=True) + updated = models.DateTimeField(auto_now=True) + uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) + + class Meta: + ordering = ['name'] + + def __str__(self): + return self.name + + @staticmethod + def _format(value): + # 10.000 -> "10", 0.500 -> "0.5" + return f'{Decimal(value).normalize():f}' + + @property + def download_display(self): + return self._format(self.download_limit) if self.download_limit else '' + + @property + def upload_display(self): + return self._format(self.upload_limit) if self.upload_limit else '' + + @property + def download_burst_display(self): + return self._format(self.download_burst) if self.download_burst else '' + + @property + def upload_burst_display(self): + return self._format(self.upload_burst) if self.upload_burst else '' + + @property + def summary(self): + """Short description used in peer pages, e.g. "↓ 10 Mbit/s · ↑ 5 Mbit/s".""" + parts = [] + if self.download_limit: + parts.append(f'↓ {self.download_display} Mbit/s') + if self.upload_limit: + parts.append(f'↑ {self.upload_display} Mbit/s') + return ' · '.join(parts) + + def config_comment(self): + """Settings written to the WireGuard configuration of each peer, read when the limits are applied.""" + values = [] + if self.download_limit: + values.append(f'download_kbit={mbit_to_kbit(self.download_limit)}') + if self.download_burst: + values.append(f'download_burst={megabytes_to_bytes(self.download_burst)}') + if self.upload_limit: + values.append(f'upload_kbit={mbit_to_kbit(self.upload_limit)}') + if self.upload_burst: + values.append(f'upload_burst={megabytes_to_bytes(self.upload_burst)}') + return ' '.join(values) diff --git a/speed_profiles/tests.py b/speed_profiles/tests.py new file mode 100644 index 0000000..af9a899 --- /dev/null +++ b/speed_profiles/tests.py @@ -0,0 +1,523 @@ +import json +import os +import subprocess +import tempfile +from decimal import Decimal +from unittest.mock import patch + +from django.conf import settings +from django.contrib.auth.models import User +from django.db.models import ProtectedError +from django.test import TestCase, override_settings + +from api_v2.models import ApiKey +from cluster import sync +from cluster.models import ClusterSettings, Worker, WorkerStatus +from cluster.tests import ClusterTestMixin, create_instance +from speed_profiles.forms import SpeedProfileForm +from speed_profiles.models import SpeedProfile +from user_manager.models import UserAcl +from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance +from wireguard_peer.functions import func_create_new_peer +from wireguard_tools import functions +from wireguard_tools.speed_limits import apply_speed_limits, build_tc_commands, parse_speed_limits +from wireguard_tools.tests import FakeNetwork, load_cluster_worker +from wireguard_tools.views import export_wireguard_configuration + + +def create_peer(instance, number, speed_profile=None, networks=(), endpoint=''): + peer = Peer.objects.create( + name=f'peer-{number}', public_key=f'peer-public-{number}', pre_shared_key='', private_key=f'private-{number}', + wireguard_instance=instance, speed_profile=speed_profile, endpoint=endpoint, + ) + PeerAllowedIP.objects.create( + peer=peer, priority=0, allowed_ip=f'10.188.{instance.instance_id}.{number}', netmask=32, config_file='server' + ) + for priority, network in enumerate(networks, start=1): + address, netmask = network.split('/') + PeerAllowedIP.objects.create( + peer=peer, priority=priority, allowed_ip=address, netmask=int(netmask), config_file='server' + ) + return peer + + +class SpeedProfileFormTests(TestCase): + def form(self, **data): + return SpeedProfileForm(data={'name': 'Basic', **data}) + + def test_accepts_optional_and_decimal_limits(self): + self.assertTrue(self.form(download_limit='0.5').is_valid()) + self.assertTrue(self.form(upload_limit='10').is_valid()) + form = self.form(download_limit='10', download_burst='5', upload_limit='2.5', upload_burst='0.25') + self.assertTrue(form.is_valid(), form.errors) + + def test_refuses_zero_and_negative_values(self): + for field_name in ('download_limit', 'upload_limit'): + for value in ('0', '-1'): + form = self.form(**{field_name: value}) + self.assertFalse(form.is_valid()) + self.assertIn(field_name, form.errors) + form = self.form(download_limit='10', download_burst='0') + self.assertIn('download_burst', form.errors) + + def test_refuses_repeated_name(self): + SpeedProfile.objects.create(name='Basic', download_limit=10) + form = self.form(download_limit='20') + self.assertFalse(form.is_valid()) + self.assertIn('name', form.errors) + + def test_refuses_profile_without_limits(self): + form = self.form() + self.assertFalse(form.is_valid()) + self.assertIn('__all__', form.errors) + + def test_refuses_burst_without_the_limit_of_its_direction(self): + form = self.form(download_limit='10', upload_burst='5') + self.assertFalse(form.is_valid()) + self.assertIn('upload_burst', form.errors) + + +class SpeedProfileViewMixin: + def setUp(self): + super().setUp() + user = User.objects.create_user(username='admin', password='unused') + UserAcl.objects.create(user=user, user_level=50) + self.client.force_login(user) + self.instance = create_instance(0) + self.other_instance = create_instance(1) + self.profile = SpeedProfile.objects.create(name='Basic', download_limit=10, upload_limit=5) + + +class SpeedProfileDeleteTests(SpeedProfileViewMixin, TestCase): + def test_profile_in_use_is_protected(self): + create_peer(self.instance, 10, self.profile) + with self.assertRaises(ProtectedError): + self.profile.delete() + + def test_delete_page_lists_peers_and_instances(self): + create_peer(self.instance, 10, self.profile) + WireGuardInstance.objects.filter(pk=self.other_instance.pk).update(default_speed_profile=self.profile) + response = self.client.get('/speed_profiles/delete/', {'uuid': str(self.profile.uuid)}) + self.assertContains(response, 'peer-10') + self.assertContains(response, 'wg1') + self.assertContains(response, 'unlink_and_delete') + + @patch('speed_profiles.views._auto_apply', return_value=False) + def test_unlink_and_delete(self, auto_apply): + peer = create_peer(self.instance, 10, self.profile) + WireGuardInstance.objects.filter(pk=self.other_instance.pk).update(default_speed_profile=self.profile) + + # Without the unlink action nothing is deleted + self.client.post(f'/speed_profiles/delete/?uuid={self.profile.uuid}', {'action': 'delete'}) + self.assertTrue(SpeedProfile.objects.filter(pk=self.profile.pk).exists()) + + response = self.client.post(f'/speed_profiles/delete/?uuid={self.profile.uuid}', {'action': 'unlink_and_delete'}) + self.assertRedirects(response, '/speed_profiles/', fetch_redirect_response=False) + self.assertFalse(SpeedProfile.objects.filter(pk=self.profile.pk).exists()) + peer.refresh_from_db() + self.assertIsNone(peer.speed_profile) + self.other_instance.refresh_from_db() + self.assertIsNone(self.other_instance.default_speed_profile) + # The instance whose peer lost the limit is applied again (pending without auto apply) + auto_apply.assert_called_once() + self.instance.refresh_from_db() + self.assertTrue(self.instance.pending_changes) + + +class SpeedProfileEditTests(SpeedProfileViewMixin, TestCase): + def edit(self): + return self.client.post( + f'/speed_profiles/manage/?uuid={self.profile.uuid}', {'name': 'Basic', 'download_limit': '20', 'upload_limit': '5'} + ) + + @patch('speed_profiles.views._auto_apply', return_value=True) + def test_edit_applies_the_instances_using_the_profile(self, auto_apply): + create_peer(self.instance, 10, self.profile) + create_peer(self.instance, 11, self.profile) + create_peer(self.other_instance, 12) + self.edit() + self.assertEqual([call.args[1] for call in auto_apply.call_args_list], [self.instance]) + + @patch('speed_profiles.views._auto_apply', return_value=False) + def test_edit_marks_instances_pending_without_auto_apply(self, auto_apply): + WireGuardInstance.objects.update(pending_changes=False) + create_peer(self.instance, 10, self.profile) + self.edit() + self.instance.refresh_from_db() + self.other_instance.refresh_from_db() + self.assertTrue(self.instance.pending_changes) + self.assertFalse(self.other_instance.pending_changes) + + +class DefaultSpeedProfileTests(TestCase): + def setUp(self): + self.default_profile = SpeedProfile.objects.create(name='Default', download_limit=10) + self.other_profile = SpeedProfile.objects.create(name='Other', upload_limit=5) + self.instance = create_instance(0) + WireGuardInstance.objects.filter(pk=self.instance.pk).update(default_speed_profile=self.default_profile) + self.instance.refresh_from_db() + self.api_key = ApiKey.objects.create(name='key', enabled=True) + + def test_new_peer_gets_the_default_profile(self): + peer, message = func_create_new_peer(self.instance) + self.assertEqual(peer.speed_profile, self.default_profile) + + def test_override_replaces_the_default_profile(self): + peer, message = func_create_new_peer(self.instance, {'speed_profile': None}) + self.assertIsNone(peer.speed_profile) + + def api_create(self, **payload): + return self.client.post( + '/api/v2/manage_peer/', data=json.dumps({'instance': 'wg0', 'skip_reload': True, **payload}), + content_type='application/json', HTTP_TOKEN=str(self.api_key.token), + ) + + def test_api_uses_the_default_profile_when_none_is_informed(self): + response = self.api_create(name='from-api') + self.assertEqual(response.status_code, 201, response.content) + self.assertEqual(Peer.objects.get(uuid=response.json()['peer_uuid']).speed_profile, self.default_profile) + + def test_api_informed_profile_replaces_the_default(self): + response = self.api_create(name='other', speed_profile_uuid=str(self.other_profile.uuid)) + self.assertEqual(Peer.objects.get(uuid=response.json()['peer_uuid']).speed_profile, self.other_profile) + response = self.api_create(name='unlimited', speed_profile_uuid='') + self.assertIsNone(Peer.objects.get(uuid=response.json()['peer_uuid']).speed_profile) + + +class ExportedConfigMixin: + """Exports the WireGuard configuration of the instances to a temporary directory.""" + + def setUp(self): + super().setUp() + temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(temp_dir.cleanup) + self.wireguard_dir = temp_dir.name + cluster_dir = os.path.join(self.wireguard_dir, 'cluster') + # Every module that resolves the configuration directory must point to the temporary one + for target, value in ( + ('wireguard_tools.functions.WIREGUARD_CONFIG_DIR', self.wireguard_dir), + ('wireguard_tools.functions.CLUSTER_WIREGUARD_CONFIG_DIR', cluster_dir), + ('wireguard_tools.views.WIREGUARD_CONFIG_DIR', self.wireguard_dir), + ('wireguard_tools.views.CLUSTER_WIREGUARD_CONFIG_DIR', cluster_dir), + ): + patcher = patch(target, value) + patcher.start() + self.addCleanup(patcher.stop) + + def exported_limits(self, instance_id=0): + export_wireguard_configuration() + with open(os.path.join(self.wireguard_dir, f'wg{instance_id}.conf')) as config_file: + return parse_speed_limits(config_file.read()) + + +class SpeedLimitRuleTests(ExportedConfigMixin, TestCase): + def setUp(self): + super().setUp() + self.instance = create_instance(0) + + def test_each_limited_peer_gets_its_own_rules_covering_all_its_networks(self): + profile = SpeedProfile.objects.create(name='Basic', download_limit=10, upload_limit=Decimal('2.5')) + create_peer(self.instance, 10, profile, networks=['192.168.50.0/24']) + create_peer(self.instance, 11, profile) + create_peer(self.instance, 12) + + limits = self.exported_limits() + self.assertEqual( + [sorted(str(network) for network in peer['networks']) for peer in limits], + [['10.188.0.10/32', '192.168.50.0/24'], ['10.188.0.11/32']], + ) + commands = build_tc_commands('wg0', limits) + # One download class on the interface and one upload class on its ifb per peer + self.assertEqual(len([command for command in commands if command.startswith('class add dev wg0 ')]), 2) + self.assertEqual(len([command for command in commands if command.startswith('class add dev ifbwg0 ')]), 2) + # Only the networks of limited peers are redirected to the ifb + redirects = [command for command in commands if 'action mirred egress redirect dev ifbwg0' in command] + self.assertEqual(len(redirects), 3) + upload_filters = [command for command in commands if command.startswith('filter add dev ifbwg0 ')] + self.assertEqual(len(upload_filters), 3) + # Both networks of the first peer go to the same class, so the limit covers the peer as a whole + self.assertEqual({command.split('flowid ')[1] for command in upload_filters[:2]}, {'1:1'}) + self.assertTrue(all('10.188.0.12' not in command for command in commands)) + + def test_profile_with_one_direction_only_limits_that_direction(self): + create_peer(self.instance, 10, SpeedProfile.objects.create(name='Down', download_limit=10)) + create_peer(self.instance, 11, SpeedProfile.objects.create(name='Up', upload_limit=5)) + commands = build_tc_commands('wg0', self.exported_limits()) + download_filters = [command for command in commands if 'match ip dst' in command] + upload_filters = [command for command in commands if command.startswith('filter add dev ifbwg0 ')] + self.assertEqual([command.split('ip dst ')[1].split()[0] for command in download_filters], ['10.188.0.10/32']) + self.assertEqual([command.split('ip src ')[1].split()[0] for command in upload_filters], ['10.188.0.11/32']) + + def test_burst_is_used_when_informed(self): + create_peer(self.instance, 10, SpeedProfile.objects.create( + name='Burst', download_limit=10, download_burst=5, upload_limit=10, upload_burst=Decimal('0.5'), + )) + create_peer(self.instance, 11, SpeedProfile.objects.create(name='Auto', download_limit=10, upload_limit=8)) + commands = build_tc_commands('wg0', self.exported_limits()) + download_classes = [command for command in commands if command.startswith('class add dev wg0 ')] + upload_classes = [command for command in commands if command.startswith('class add dev ifbwg0 ')] + self.assertIn('burst 5000000b cburst 5000000b', download_classes[0]) + self.assertIn('burst 500000b cburst 500000b', upload_classes[0]) + # Without a burst, htb uses its automatic value + self.assertNotIn('burst', download_classes[1]) + self.assertNotIn('burst', upload_classes[1]) + + def test_peer_with_endpoint_gets_the_same_rules(self): + profile = SpeedProfile.objects.create(name='Basic', download_limit=10, upload_limit=5) + create_peer(self.instance, 10, profile, networks=['192.168.70.0/24'], endpoint='remote.example.test:51820') + limits = self.exported_limits() + self.assertEqual(len(limits), 1) + self.assertEqual(limits[0]['download_kbit'], 10000) + self.assertEqual(limits[0]['upload_kbit'], 5000) + + +class FakeTc: + def __init__(self, fail=False, ifb=True): + self.fail = fail + self.ifb = ifb + self.batches = [] + self.commands = [] + + def run(self, command, *args, input=None, **kwargs): + self.commands.append(command) + if command[:2] == ['tc', '-batch']: + self.batches.append(input.splitlines()) + if self.fail: + return subprocess.CompletedProcess(command, 1, '', 'Error: Specified qdisc kind is unknown.') + if command[:3] == ['ip', 'link', 'add'] and not self.ifb: + return subprocess.CompletedProcess(command, 2, '', 'Error: Unknown device type.') + return subprocess.CompletedProcess(command, 0, '', '') + + +class ApplySpeedLimitsTests(TestCase): + def setUp(self): + temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(temp_dir.cleanup) + self.config_path = os.path.join(temp_dir.name, 'wg0.conf') + + def write_config(self, *peers): + blocks = ['[Interface]\nListenPort = 51820\n'] + for address, limit in peers: + blocks.append(f'[Peer]\nPublicKey = {address}\n# Speed limit: {limit}\nAllowedIPs = {address}/32\n') + with open(self.config_path, 'w') as config_file: + config_file.write('\n'.join(blocks)) + + def test_limits_are_replaced_on_each_application(self): + tc = FakeTc() + self.write_config(('10.188.0.2', 'download_kbit=10000'), ('10.188.0.3', 'upload_kbit=5000')) + self.assertEqual(apply_speed_limits('wg0', self.config_path, run=tc.run), []) + self.assertTrue(any('10.188.0.3/32' in command for command in tc.batches[0])) + + # Changed limit and a peer that lost its profile + self.write_config(('10.188.0.2', 'download_kbit=20000')) + apply_speed_limits('wg0', self.config_path, run=tc.run) + self.assertIn(['tc', 'qdisc', 'del', 'dev', 'wg0', 'root'], tc.commands) + self.assertIn(['tc', 'qdisc', 'del', 'dev', 'wg0', 'ingress'], tc.commands) + self.assertTrue(any('rate 20000kbit' in command for command in tc.batches[1])) + self.assertFalse(any('10.188.0.3' in command for command in tc.batches[1])) + + # Without limited peers the previous limits and the ifb are only removed + self.write_config() + apply_speed_limits('wg0', self.config_path, run=tc.run) + self.assertEqual(len(tc.batches), 2) + self.assertEqual(tc.commands[-3:], [ + ['tc', 'qdisc', 'del', 'dev', 'wg0', 'root'], ['tc', 'qdisc', 'del', 'dev', 'wg0', 'ingress'], + ['ip', 'link', 'delete', 'ifbwg0'], + ]) + + def test_upload_limits_create_the_ifb(self): + tc = FakeTc() + self.write_config(('10.188.0.2', 'upload_kbit=5000')) + self.assertEqual(apply_speed_limits('wg0', self.config_path, run=tc.run), []) + self.assertIn(['ip', 'link', 'add', 'ifbwg0', 'type', 'ifb'], tc.commands) + self.assertIn(['ip', 'link', 'set', 'ifbwg0', 'up', 'txqueuelen', '1000'], tc.commands) + self.assertIn('class add dev ifbwg0 parent 1: classid 1:1 htb rate 5000kbit ceil 5000kbit', tc.batches[0]) + + def test_without_ifb_only_download_limits_are_applied(self): + tc = FakeTc(ifb=False) + self.write_config(('10.188.0.2', 'download_kbit=10000 upload_kbit=5000')) + errors = apply_speed_limits('wg0', self.config_path, run=tc.run) + self.assertEqual(len(errors), 1) + self.assertIn('upload limits need the ifb kernel module', errors[0]) + self.assertTrue(any('rate 10000kbit' in command for command in tc.batches[0])) + self.assertFalse(any('ifbwg0' in command for command in tc.batches[0])) + + def test_failure_is_returned_and_partial_limits_are_removed(self): + tc = FakeTc(fail=True) + self.write_config(('10.188.0.2', 'download_kbit=10000')) + errors = apply_speed_limits('wg0', self.config_path, run=tc.run) + self.assertEqual(errors, ['Error: Specified qdisc kind is unknown.']) + self.assertEqual(tc.commands[-1], ['ip', 'link', 'delete', 'ifbwg0']) + + def test_failure_does_not_fail_the_reload(self): + self.write_config(('10.188.0.2', 'download_kbit=10000')) + network = FakeNetwork('wg0', ['10.188.0.2/32'], {'10.188.0.0/24': True}) + tc = FakeTc(fail=True) + + def run(command, *args, **kwargs): + if command[0] == 'tc': + return tc.run(command, *args, **kwargs) + if command[:2] == ['wg-quick', 'strip']: + return subprocess.CompletedProcess(command, 0, '[Interface]\n', '') + return network.run(command) + + with patch('wireguard_tools.functions.subprocess.run', side_effect=run): + success, message = functions.func_reload_wireguard_interface('wg0', os.path.dirname(self.config_path)) + self.assertTrue(success) + self.assertIn(functions.SPEED_LIMIT_WARNING, message) + self.assertIn('qdisc kind is unknown', message) + + def test_agent_ships_the_same_module(self): + agent_copy = os.path.join(settings.BASE_DIR, 'containers', 'cluster_node', 'speed_limits.py') + primary_copy = os.path.join(settings.BASE_DIR, 'wireguard_tools', 'speed_limits.py') + with open(agent_copy) as agent_file, open(primary_copy) as primary_file: + self.assertEqual(agent_file.read(), primary_file.read()) + + +@override_settings(CLUSTER_WORKER_MINIMUM_VERSION=12, WIREGUARD_STATUS_CACHE_ENABLED=True) +class ClusterSpeedLimitTests(ClusterTestMixin, TestCase): + def setUp(self): + super().setUp() + cluster_dir = os.path.join(self.wireguard_dir, 'cluster') + for target, value in ( + ('cluster.sync.CLUSTER_WIREGUARD_CONFIG_DIR', cluster_dir), + ('wireguard_tools.functions.WIREGUARD_CONFIG_DIR', self.wireguard_dir), + ('wireguard_tools.functions.CLUSTER_WIREGUARD_CONFIG_DIR', cluster_dir), + ('wireguard_tools.views.WIREGUARD_CONFIG_DIR', self.wireguard_dir), + ('wireguard_tools.views.CLUSTER_WIREGUARD_CONFIG_DIR', cluster_dir), + ): + patcher = patch(target, value) + patcher.start() + self.addCleanup(patcher.stop) + self.worker_b = Worker.objects.create(name='node-b', hostname='node-b.example.test') + profile = SpeedProfile.objects.create(name='Basic', download_limit=10) + self.primary_instance = create_instance(0) + self.worker_instance = create_instance(1, worker=self.worker) + create_peer(self.primary_instance, 10, profile) + create_peer(self.worker_instance, 11, profile) + + def section_limits(self, worker): + files = sync.build_section('wireguard', worker).files + return {filename: parse_speed_limits(content) for filename, content in files.items()} + + def test_mirror_workers_receive_the_limits_of_every_instance(self): + ClusterSettings.objects.filter(name='cluster_settings').update(cluster_mode='mirror') + export_wireguard_configuration() + limits = self.section_limits(self.worker_b) + self.assertEqual(sorted(limits), ['wg0.conf', 'wg1.conf']) + self.assertTrue(all(len(peers) == 1 for peers in limits.values())) + + def test_distributed_worker_only_receives_the_limits_of_its_instance(self): + ClusterSettings.objects.filter(name='cluster_settings').update(cluster_mode='distributed') + export_wireguard_configuration() + limits = self.section_limits(self.worker) + self.assertEqual(list(limits), ['wg1.conf']) + self.assertEqual(str(limits['wg1.conf'][0]['networks'][0]), '10.188.1.11/32') + self.assertEqual(self.section_limits(self.worker_b), {}) + + def test_report_warning_is_stored_and_shown(self): + ClusterSettings.objects.filter(name='cluster_settings').update(cluster_mode='mirror') + export_wireguard_configuration() + wireguard_hash = sync.build_manifest(self.worker)['wireguard'] + report = {'sections': {'wireguard': { + 'hash': wireguard_hash, 'status': 'ok', 'warning': 'wg0: speed limits not fully applied: no htb', + }}} + self.client.post('/api/cluster/v2/report/', data=json.dumps(report), content_type='application/json', **self.headers) + self.assertEqual( + WorkerStatus.objects.get(worker=self.worker).section_status['wireguard']['warning'], + 'wg0: speed limits not fully applied: no htb', + ) + self.assertEqual(sync.get_worker_warnings(self.worker)['section_warnings'], ['wireguard']) + + user = User.objects.create_user(username='admin', password='unused') + UserAcl.objects.create(user=user, user_level=50) + self.client.force_login(user) + response = self.client.get('/cluster/worker/view/', {'uuid': str(self.worker.uuid)}) + self.assertContains(response, 'Synchronized with warnings') + self.assertContains(response, 'speed limits not fully applied: no htb') + + +class AgentSpeedLimitTests(TestCase): + CONFIG = '[Interface]\nListenPort = 51820\n\n[Peer]\nPublicKey = a\n# Speed limit: download_kbit=1000\nAllowedIPs = 10.188.0.2/32\n' + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.cluster_worker = load_cluster_worker() + + def setUp(self): + temp_dir = tempfile.TemporaryDirectory() + self.addCleanup(temp_dir.cleanup) + for name, value in (('WIREGUARD_DIR', temp_dir.name), ('interface_is_up', lambda interface: False)): + patcher = patch.object(self.cluster_worker, name, value) + patcher.start() + self.addCleanup(patcher.stop) + self.agent = self.cluster_worker.ClusterNodeAgent() + + def test_speed_limit_failure_keeps_the_interface_and_is_reported(self): + with patch.object(self.cluster_worker, 'run_command') as run_command, \ + patch.object(self.cluster_worker, 'apply_speed_limits', return_value=['no htb']) as apply_limits: + self.agent.apply_wireguard({'files': {'wg0.conf': self.CONFIG}}) + run_command.assert_called_once_with(['wg-quick', 'up', 'wg0']) + apply_limits.assert_called_once() + self.assertEqual(self.agent.section_warnings['wireguard'], 'wg0: speed limits not fully applied: no htb') + + manifest = {'sections': {'wireguard': 'hash-1'}} + section = {'hash': 'hash-1', 'files': {'wg0.conf': self.CONFIG}} + responses = {'manifest/': manifest, 'section/wireguard/': section} + reports = [] + + def request(method, path, **kwargs): + if method == 'POST': + reports.append(kwargs['json']) + return None + return type('Response', (), {'status_code': 200, 'json': lambda self: responses[path], 'text': ''})() + + with patch.object(self.agent, 'request', side_effect=request), \ + patch.object(self.agent, 'response_json', side_effect=lambda response, path: responses[path]), \ + patch.object(self.cluster_worker, 'run_command'), \ + patch.object(self.cluster_worker, 'apply_speed_limits', return_value=['no htb']): + self.agent.sync_configuration() + self.assertEqual(reports[0]['sections']['wireguard']['status'], 'ok') + self.assertEqual(reports[0]['sections']['wireguard']['warning'], 'wg0: speed limits not fully applied: no htb') + + +class ApiSpeedProfileTests(TestCase): + def setUp(self): + self.instance = create_instance(0) + self.profile = SpeedProfile.objects.create(name='Basic', download_limit=10) + self.peer = create_peer(self.instance, 10) + self.api_key = ApiKey.objects.create(name='key', enabled=True) + + def post(self, path, method='post', **payload): + return getattr(self.client, method)( + path, data=json.dumps({'instance': 'wg0', **payload}), content_type='application/json', + HTTP_TOKEN=str(self.api_key.token), + ) + + def update(self, value): + return self.post('/api/v2/manage_peer/', method='put', peer_uuid=str(self.peer.uuid), skip_reload=True, + speed_profile_uuid=value) + + def test_manage_peer_sets_and_clears_the_profile(self): + response = self.update(str(self.profile.uuid)) + self.assertEqual(response.status_code, 200, response.content) + self.peer.refresh_from_db() + self.assertEqual(self.peer.speed_profile, self.profile) + + self.update('') + self.peer.refresh_from_db() + self.assertIsNone(self.peer.speed_profile) + + def test_manage_peer_refuses_an_invalid_profile(self): + for value in ('00000000-0000-0000-0000-000000000000', 'not-a-uuid'): + response = self.update(value) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()['error_message'], 'Invalid speed_profile_uuid.') + + def test_peer_detail_and_list_return_the_profile(self): + Peer.objects.filter(pk=self.peer.pk).update(speed_profile=self.profile) + detail = self.post('/api/v2/peer_detail/', peer_uuid=str(self.peer.uuid)).json() + self.assertEqual(detail['peer']['speed_profile_uuid'], str(self.profile.uuid)) + peers = self.post('/api/v2/peer_list/').json()['peers'] + self.assertEqual(peers[0]['speed_profile_uuid'], str(self.profile.uuid)) diff --git a/speed_profiles/urls.py b/speed_profiles/urls.py new file mode 100644 index 0000000..323c306 --- /dev/null +++ b/speed_profiles/urls.py @@ -0,0 +1,9 @@ +from django.urls import path + +from speed_profiles.views import view_delete_speed_profile, view_manage_speed_profile, view_speed_profile_list + +urlpatterns = [ + path('', view_speed_profile_list, name='speed_profile_list'), + path('manage/', view_manage_speed_profile, name='manage_speed_profile'), + path('delete/', view_delete_speed_profile, name='delete_speed_profile'), +] diff --git a/speed_profiles/views.py b/speed_profiles/views.py new file mode 100644 index 0000000..6936eff --- /dev/null +++ b/speed_profiles/views.py @@ -0,0 +1,109 @@ +from django.contrib import messages +from django.contrib.auth.decorators import login_required +from django.db import transaction +from django.db.models import Count +from django.shortcuts import get_object_or_404, redirect, render +from django.utils.translation import gettext as _ + +from speed_profiles.forms import SpeedProfileForm +from speed_profiles.models import SpeedProfile +from user_manager.models import UserAcl +from wireguard.models import Peer, WireGuardInstance +from wireguard_peer.views import _auto_apply + + +def _can_manage(request): + return UserAcl.objects.filter(user=request.user, user_level__gte=30).exists() + + +def apply_instances(request, instances): + """Apply the configuration of the instances whose peers changed limits, or mark them as pending.""" + for instance in instances: + if not _auto_apply(request, instance): + WireGuardInstance.objects.filter(pk=instance.pk).update(pending_changes=True) + + +def instances_using(profile): + return list(WireGuardInstance.objects.filter(peer__speed_profile=profile).distinct().order_by('instance_id')) + + +@login_required +def view_speed_profile_list(request): + profiles = SpeedProfile.objects.annotate(peer_count=Count('peers')).order_by('name') + return render(request, 'speed_profiles/speed_profile_list.html', { + 'page_title': _('Speed Profiles'), 'profiles': profiles, + }) + + +@login_required +def view_manage_speed_profile(request): + if not _can_manage(request): + return render(request, 'access_denied.html', {'page_title': _('Access Denied')}) + + profile = None + if request.GET.get('uuid'): + profile = get_object_or_404(SpeedProfile, uuid=request.GET.get('uuid')) + + form = SpeedProfileForm(request.POST or None, instance=profile) + if form.is_valid(): + changed = profile is not None and form.has_changed() + profile = form.save() + messages.success(request, _('Speed profile saved|Speed profile saved successfully.')) + if changed: + apply_instances(request, instances_using(profile)) + return redirect('speed_profile_list') + + form_description = { + 'size': 'col-lg-6', + 'content': _(''' +
Speed profile
+

Each peer that uses this profile gets its own limit: a profile of 10 Mbit/s does not share 10 Mbit/s among + its peers. Peers without a profile have no limit.

+ +
Download and upload
+

Download is the traffic that reaches the peer and upload the traffic that + it sends. Each limit is optional, so a profile may limit only one direction. The limit covers all the + addresses and networks of the peer.

+ +
Burst
+

The amount of data that may pass at full speed before the limit applies, refilled while the peer uses less + than its limit. A burst of a few MB keeps browsing fast without allowing large downloads at full speed. For + reference, 10 Mbit/s is about 1.25 MB per second. Leave it empty for the automatic minimum.

+ '''), + } + return render(request, 'generic_form.html', { + 'page_title': _('Edit Speed Profile') if profile else _('Add Speed Profile'), + 'form': form, + 'form_description': form_description, + }) + + +@login_required +def view_delete_speed_profile(request): + if not _can_manage(request): + return render(request, 'access_denied.html', {'page_title': _('Access Denied')}) + + profile = get_object_or_404(SpeedProfile, uuid=request.GET.get('uuid')) + peers = list(Peer.objects.filter(speed_profile=profile).select_related('wireguard_instance').order_by( + 'wireguard_instance__instance_id', 'name' + )) + default_for_instances = list(profile.default_for_instances.order_by('instance_id')) + + if request.method == 'POST': + if (peers or default_for_instances) and request.POST.get('action') != 'unlink_and_delete': + return redirect(f"{request.path}?uuid={profile.uuid}") + affected_instances = instances_using(profile) + with transaction.atomic(): + Peer.objects.filter(speed_profile=profile).update(speed_profile=None) + WireGuardInstance.objects.filter(default_speed_profile=profile).update(default_speed_profile=None) + profile.delete() + messages.success(request, _('Speed profile deleted|Speed profile deleted successfully.')) + apply_instances(request, affected_instances) + return redirect('speed_profile_list') + + return render(request, 'speed_profiles/speed_profile_delete.html', { + 'page_title': _('Delete Speed Profile'), + 'profile': profile, + 'peers': peers, + 'default_for_instances': default_for_instances, + }) diff --git a/templates/cluster/worker_details.html b/templates/cluster/worker_details.html index b456f66..71071e1 100644 --- a/templates/cluster/worker_details.html +++ b/templates/cluster/worker_details.html @@ -78,7 +78,9 @@ {{ section.name }} - {% if section.state == 'synced' %}{% trans 'Synchronized' %} + {% if section.state == 'synced' and section.warning %}{% trans 'Synchronized with warnings' %} +
{{ section.warning|truncatechars:300 }} + {% elif section.state == 'synced' %}{% trans 'Synchronized' %} {% elif section.state == 'error' %}{% trans 'Error' %} {% else %}{% trans 'Pending' %}{% endif %} {% if section.message %}
{{ section.message|truncatechars:300 }}{% endif %} diff --git a/templates/cluster/workers_list.html b/templates/cluster/workers_list.html index 32c8c00..55455e4 100644 --- a/templates/cluster/workers_list.html +++ b/templates/cluster/workers_list.html @@ -150,6 +150,11 @@ {% empty %} - {% endfor %} + {% if worker.operational and worker.warnings.section_warnings %} +
+ {% trans 'Synchronized with warnings' %} + + {% endif %} {% if worker.operational and worker.warnings.certificate_issues %}
{% trans 'Certificates unavailable or expiring soon' %} diff --git a/templates/speed_profiles/speed_profile_delete.html b/templates/speed_profiles/speed_profile_delete.html new file mode 100644 index 0000000..230cf0d --- /dev/null +++ b/templates/speed_profiles/speed_profile_delete.html @@ -0,0 +1,51 @@ +{% extends "base.html" %} +{% load i18n %} + +{% block content %} +
+
+

{% trans 'Delete Speed Profile' %}

+
+
+ {% csrf_token %} +
+ {% if peers or default_for_instances %} +

{% blocktrans with name=profile.name %}The profile "{{ name }}" is in use.{% endblocktrans %}

+ {% if peers %} +

{% trans 'Peers using this profile' %}

+
    + {% for peer in peers %} +
  • {{ peer }} (wg{{ peer.wireguard_instance.instance_id }})
  • + {% endfor %} +
+ {% endif %} + {% if default_for_instances %} +

{% trans 'Default profile of the instances' %}

+
    + {% for instance in default_for_instances %} +
  • wg{{ instance.instance_id }}{% if instance.name %} ({{ instance.name }}){% endif %}
  • + {% endfor %} +
+ {% endif %} +
+ {% trans 'Unlinking removes the profile from these peers and instances. The peers will have no speed limit.' %} +
+ {% else %} +

{% blocktrans with name=profile.name %}Are you sure you want to delete the profile "{{ name }}"?{% endblocktrans %}

+ {% endif %} +
+ +
+
+{% endblock %} diff --git a/templates/speed_profiles/speed_profile_list.html b/templates/speed_profiles/speed_profile_list.html new file mode 100644 index 0000000..bcfb14e --- /dev/null +++ b/templates/speed_profiles/speed_profile_list.html @@ -0,0 +1,83 @@ +{% extends "base.html" %} +{% load i18n %} + +{% block content %} +
+
+

{% trans 'Speed Profiles' %}

+
+
+ + + + + + + + + + + + {% for profile in profiles %} + + + + + + + + {% empty %} + + + + {% endfor %} + +
{% trans 'Name' %}{% trans 'Download' %}{% trans 'Upload' %}{% trans 'Peers' %}{% trans 'Actions' %}
{{ profile.name }} + {% if profile.download_limit %} + {{ profile.download_display }} Mbit/s + {% if profile.download_burst %}({% trans 'burst' %} {{ profile.download_burst_display }} MB){% endif %} + {% else %} + {% trans 'No limit' %} + {% endif %} + + {% if profile.upload_limit %} + {{ profile.upload_display }} Mbit/s + {% if profile.upload_burst %}({% trans 'burst' %} {{ profile.upload_burst_display }} MB){% endif %} + {% else %} + {% trans 'No limit' %} + {% endif %} + {{ profile.peer_count }} + = 30 %} + href="{% url 'manage_speed_profile' %}?uuid={{ profile.uuid }}" class="btn btn-sm btn-info" + {% else %} + href="#" class="btn btn-sm btn-info disabled" + {% endif %} + title="{% trans 'Edit' %}"> + + + = 30 %} + href="{% url 'delete_speed_profile' %}?uuid={{ profile.uuid }}" class="btn btn-sm btn-danger" + {% else %} + href="#" class="btn btn-sm btn-danger disabled" + {% endif %} + title="{% trans 'Delete' %}"> + + +
{% trans 'No speed profiles found.' %}
+
+ +
+{% endblock %} diff --git a/templates/wireguard/wireguard_manage_peer.html b/templates/wireguard/wireguard_manage_peer.html index 2de6094..60fb090 100644 --- a/templates/wireguard/wireguard_manage_peer.html +++ b/templates/wireguard/wireguard_manage_peer.html @@ -111,6 +111,25 @@ + +
+ +
+ + {% if current_peer.speed_profile %} + {{ current_peer.speed_profile.name }} +
{{ current_peer.speed_profile.summary }} + {% else %} + {% trans 'No limit' %} + {% endif %} +
+ + + +
+
+
diff --git a/templates/wireguard/wireguard_peer_list.html b/templates/wireguard/wireguard_peer_list.html index 365a38f..f91a402 100644 --- a/templates/wireguard/wireguard_peer_list.html +++ b/templates/wireguard/wireguard_peer_list.html @@ -48,6 +48,9 @@ {% trans 'Disabled Peers' %} {% endif %} + + {% trans 'Speed Profiles' %} +
diff --git a/wireguard/forms.py b/wireguard/forms.py index 7f76ca7..9b11f04 100644 --- a/wireguard/forms.py +++ b/wireguard/forms.py @@ -9,6 +9,7 @@ from django.urls import reverse_lazy from django.utils.translation import gettext_lazy as _ from cluster.models import ClusterSettings, Worker +from speed_profiles.models import SpeedProfile from wgwadmlibrary.tools import is_valid_ip_or_hostname from .models import NETMASK_CHOICES, WireGuardInstance @@ -30,13 +31,17 @@ class WireGuardInstanceForm(forms.ModelForm): help_text=_('Optional. One or more domains separated by commas (e.g. vpn, example.com).') ) enforce_route_policy = forms.BooleanField(label=_('Enforce Route Policy'), required=False) + default_speed_profile = forms.ModelChoiceField( + queryset=SpeedProfile.objects.order_by('name'), label=_('Default Speed Profile'), required=False, + empty_label=_('No limit'), help_text=_('Speed profile given to the peers created in this instance.'), + ) class Meta: model = WireGuardInstance fields = [ 'name', 'instance_id', 'private_key', 'public_key','hostname', 'listen_port', 'address', 'netmask', 'peer_list_refresh_interval', 'dns_primary', 'dns_secondary', 'dns_search_domains', 'enforce_route_policy', - 'worker' + 'default_speed_profile', 'worker' ] def __init__(self, *args, **kwargs): @@ -115,6 +120,10 @@ class WireGuardInstanceForm(forms.ModelForm): Column('enforce_route_policy', css_class='form-group col-md-12 mb-0'), css_class='form-row' ), + Row( + Column('default_speed_profile', css_class='form-group col-md-12 mb-0'), + css_class='form-row' + ), Row( Column('worker', css_class='form-group col-md-12 mb-0'), css_class='form-row' diff --git a/wireguard/migrations/0036_speed_profile.py b/wireguard/migrations/0036_speed_profile.py new file mode 100644 index 0000000..aff4943 --- /dev/null +++ b/wireguard/migrations/0036_speed_profile.py @@ -0,0 +1,25 @@ +# Generated by Django 5.2.19 on 2026-11-24 15:57 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('speed_profiles', '0001_initial'), + ('wireguard', '0035_peer_endpoint'), + ] + + operations = [ + migrations.AddField( + model_name='peer', + name='speed_profile', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='peers', to='speed_profiles.speedprofile'), + ), + migrations.AddField( + model_name='wireguardinstance', + name='default_speed_profile', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='default_for_instances', to='speed_profiles.speedprofile'), + ), + ] diff --git a/wireguard/models.py b/wireguard/models.py index d58af5f..34203c4 100644 --- a/wireguard/models.py +++ b/wireguard/models.py @@ -73,6 +73,10 @@ class WireGuardInstance(models.Model): worker = models.ForeignKey( 'cluster.Worker', on_delete=models.PROTECT, blank=True, null=True, related_name='wireguard_instances' ) + # Speed profile given to the peers created in this instance + default_speed_profile = models.ForeignKey( + 'speed_profiles.SpeedProfile', on_delete=models.PROTECT, blank=True, null=True, related_name='default_for_instances' + ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) @@ -210,6 +214,9 @@ class Peer(models.Model): routing_template = models.ForeignKey( 'routing_templates.RoutingTemplate', on_delete=models.SET_NULL, blank=True, null=True, related_name='peers' ) + speed_profile = models.ForeignKey( + 'speed_profiles.SpeedProfile', on_delete=models.PROTECT, blank=True, null=True, related_name='peers' + ) # Remote address (host:port) for peers that this server connects to, instead of waiting for them to connect endpoint = models.CharField(max_length=255, blank=True, default='') diff --git a/wireguard_peer/forms.py b/wireguard_peer/forms.py index 9c9ad5a..44a861f 100644 --- a/wireguard_peer/forms.py +++ b/wireguard_peer/forms.py @@ -14,6 +14,7 @@ from django.utils.translation import gettext_lazy as _ from cluster.models import ClusterSettings, Worker from scheduler.models import PeerScheduling +from speed_profiles.models import SpeedProfile from wireguard.models import NETMASK_CHOICES, Peer, PeerAllowedIP from wireguard_peer.functions import find_network_in_other_instance @@ -92,6 +93,18 @@ def normalize_endpoint(value): return f'{host.lower()}:{int(port)}' +class PeerSpeedProfileForm(PeerModelForm): + speed_profile = forms.ModelChoiceField( + queryset=SpeedProfile.objects.order_by('name'), label=_('Speed profile'), required=False, + empty_label=_('No limit'), + help_text=_('Download and upload limits of this peer. Speed profiles are managed from the peer list.'), + ) + + class Meta: + model = Peer + fields = ['speed_profile'] + + class PeerEndpointForm(PeerModelForm): endpoint = forms.CharField( label=_('Endpoint'), required=False, diff --git a/wireguard_peer/functions.py b/wireguard_peer/functions.py index 3ec6109..196ff83 100644 --- a/wireguard_peer/functions.py +++ b/wireguard_peer/functions.py @@ -66,6 +66,7 @@ def func_create_new_peer( - allowed_ip_netmask (defaults to 32) - endpoint - active_worker + - speed_profile (when absent, the default speed profile of the instance; None for no profile) """ new_peer_data = generate_peer_default(wireguard_instance) @@ -105,6 +106,10 @@ def func_create_new_peer( routing_template=new_peer_data.get('default_routing_template'), endpoint=new_peer_data.get('endpoint') or '', active_worker=new_peer_data.get('active_worker') if new_peer_data.get('endpoint') else None, + speed_profile=( + new_peer_data['speed_profile'] if 'speed_profile' in new_peer_data + else wireguard_instance.default_speed_profile + ), ) PeerAllowedIP.objects.create( diff --git a/wireguard_peer/views.py b/wireguard_peer/views.py index 36b8878..2a18851 100644 --- a/wireguard_peer/views.py +++ b/wireguard_peer/views.py @@ -14,8 +14,8 @@ from wgwadmlibrary.tools import check_sort_order_conflict, deduplicate_sort_orde user_allowed_instances, user_allowed_peers, user_has_access_to_instance, user_has_access_to_peer from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance from wireguard_peer.forms import PeerAllowedIPForm, PeerEndpointForm, PeerNameForm, PeerKeepaliveForm, PeerKeysForm, \ - PeerSuspensionForm, PeerScheduleProfileForm -from wireguard_tools.functions import func_reload_wireguard_interface, get_config_servers + PeerSpeedProfileForm, PeerSuspensionForm, PeerScheduleProfileForm +from wireguard_tools.functions import SPEED_LIMIT_WARNING, func_reload_wireguard_interface, get_config_servers from wireguard_tools.views import export_wireguard_configuration from .functions import func_create_new_peer @@ -37,7 +37,11 @@ def _auto_apply(request, instance): )) return True success, message = func_reload_wireguard_interface(instance) - if success: + if success and SPEED_LIMIT_WARNING in message: + messages.warning(request, _('wg%(id)s reloaded automatically, but the speed limits were not fully applied: ') % { + 'id': instance.instance_id + } + message.split(f'{SPEED_LIMIT_WARNING}: ', 1)[-1]) + elif success: messages.info(request, _('wg%(id)s reloaded automatically.') % {'id': instance.instance_id}) else: messages.warning(request, _('Auto-apply failed for wg%(id)s: ') % {'id': instance.instance_id} + message) @@ -236,6 +240,7 @@ def view_wireguard_peer_edit_field(request): 'keepalive': PeerKeepaliveForm, 'keys': PeerKeysForm, 'endpoint': PeerEndpointForm, + 'speed': PeerSpeedProfileForm, } if group not in form_classes: @@ -261,6 +266,8 @@ def view_wireguard_peer_edit_field(request): page_title = _('Edit Keys') elif group == 'endpoint': page_title = _('Edit Endpoint') + elif group == 'speed': + page_title = _('Edit Speed Limit') context = { 'page_title': page_title, diff --git a/wireguard_tools/functions.py b/wireguard_tools/functions.py index a71c103..f50d986 100644 --- a/wireguard_tools/functions.py +++ b/wireguard_tools/functions.py @@ -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: diff --git a/wireguard_tools/speed_limits.py b/wireguard_tools/speed_limits.py new file mode 100644 index 0000000..65669bc --- /dev/null +++ b/wireguard_tools/speed_limits.py @@ -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 +""" +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]} ', 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) diff --git a/wireguard_tools/tests.py b/wireguard_tools/tests.py index ea212f9..6eedcef 100644 --- a/wireguard_tools/tests.py +++ b/wireguard_tools/tests.py @@ -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) diff --git a/wireguard_tools/views.py b/wireguard_tools/views.py index 690117d..cca904f 100644 --- a/wireguard_tools/views.py +++ b/wireguard_tools/views.py @@ -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': diff --git a/wireguard_webadmin/settings.py b/wireguard_webadmin/settings.py index b71941f..67e68a8 100644 --- a/wireguard_webadmin/settings.py +++ b/wireguard_webadmin/settings.py @@ -50,6 +50,7 @@ INSTALLED_APPS = [ 'api', 'routing_templates', 'scheduler.apps.SchedulerConfig', + 'speed_profiles', 'api_v2', 'gatekeeper', 'app_gateway', @@ -178,7 +179,7 @@ DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' WIREGUARD_WEBADMIN_VERSION = 9982 -CLUSTER_WORKER_CURRENT_VERSION = 15 +CLUSTER_WORKER_CURRENT_VERSION = 16 CLUSTER_WORKER_MINIMUM_VERSION = 12 CADDY_ENABLED = os.getenv("CADDY_ENABLED", "false").lower() == "true" diff --git a/wireguard_webadmin/urls.py b/wireguard_webadmin/urls.py index d27d6a1..b41b693 100644 --- a/wireguard_webadmin/urls.py +++ b/wireguard_webadmin/urls.py @@ -25,6 +25,7 @@ urlpatterns = [ path('gatekeeper/', include('gatekeeper.urls')), path('app_gateway/', include('app_gateway.urls')), path('scheduler/', include('scheduler.urls')), + path('speed_profiles/', include('speed_profiles.urls')), path('server/', include('wireguard.urls')), path('tools/', include('wireguard_tools.urls')), path('vpn_invite/', include('vpn_invite.urls')),