mirror of
https://github.com/eduardogsilva/wireguard_webadmin.git
synced 2026-11-26 22:56:04 +01:00
Add API v2 endpoints to manage cluster workers and the primary WireGuard
This commit is contained in:
@@ -13,6 +13,7 @@ class ApiKeyForm(forms.ModelForm):
|
|||||||
fields = [
|
fields = [
|
||||||
'name',
|
'name',
|
||||||
'allowed_instances',
|
'allowed_instances',
|
||||||
|
'manage_cluster',
|
||||||
#'allow_restart',
|
#'allow_restart',
|
||||||
#'allow_reload',
|
#'allow_reload',
|
||||||
#'allow_export',
|
#'allow_export',
|
||||||
@@ -54,6 +55,10 @@ class ApiKeyForm(forms.ModelForm):
|
|||||||
# Column('allow_export', css_class='form-group col-md-4 mb-0'),
|
# Column('allow_export', css_class='form-group col-md-4 mb-0'),
|
||||||
# css_class='form-row'
|
# css_class='form-row'
|
||||||
#),
|
#),
|
||||||
|
Row(
|
||||||
|
Column('manage_cluster', css_class='form-group col-md-12 mb-0'),
|
||||||
|
css_class='form-row'
|
||||||
|
),
|
||||||
Row(
|
Row(
|
||||||
Column('enabled', css_class='form-group col-md-12 mb-0'),
|
Column('enabled', css_class='form-group col-md-12 mb-0'),
|
||||||
css_class='form-row'
|
css_class='form-row'
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-11-23 17:21
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('api_v2', '0002_alter_apikey_allow_export_alter_apikey_allow_reload_and_more'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='apikey',
|
||||||
|
name='manage_cluster',
|
||||||
|
field=models.BooleanField(default=False, help_text='Allows enabling and disabling cluster workers and WireGuard on the primary server.', verbose_name='Manage Cluster'),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -13,6 +13,10 @@ class ApiKey(models.Model):
|
|||||||
allow_restart = models.BooleanField(default=True, verbose_name=_("Allow Restart"))
|
allow_restart = models.BooleanField(default=True, verbose_name=_("Allow Restart"))
|
||||||
allow_reload = models.BooleanField(default=True, verbose_name=_("Allow Reload"))
|
allow_reload = models.BooleanField(default=True, verbose_name=_("Allow Reload"))
|
||||||
allow_export = models.BooleanField(default=True, verbose_name=_("Allow Export"))
|
allow_export = models.BooleanField(default=True, verbose_name=_("Allow Export"))
|
||||||
|
manage_cluster = models.BooleanField(
|
||||||
|
default=False, verbose_name=_("Manage Cluster"),
|
||||||
|
help_text=_("Allows enabling and disabling cluster workers and WireGuard on the primary server."),
|
||||||
|
)
|
||||||
enabled = models.BooleanField(default=True, verbose_name=_("Enabled"))
|
enabled = models.BooleanField(default=True, verbose_name=_("Enabled"))
|
||||||
|
|
||||||
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
|
uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
|
||||||
|
|||||||
+154
-1
@@ -1,10 +1,13 @@
|
|||||||
import json
|
import json
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
from django.test import TestCase
|
from django.test import TestCase, override_settings
|
||||||
|
|
||||||
from api_v2.models import ApiKey
|
from api_v2.models import ApiKey
|
||||||
|
from cluster.models import ClusterSettings, Worker
|
||||||
|
from cluster.tests import create_instance
|
||||||
from dns.models import DNSSettings, StaticHost
|
from dns.models import DNSSettings, StaticHost
|
||||||
|
from wireguard.models import WireGuardInstance
|
||||||
|
|
||||||
|
|
||||||
class ApiV2ManageDnsRecordTests(TestCase):
|
class ApiV2ManageDnsRecordTests(TestCase):
|
||||||
@@ -138,3 +141,153 @@ class ApiV2ManageDnsRecordTests(TestCase):
|
|||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
self.assertFalse(StaticHost.objects.filter(hostname="del.example.com").exists())
|
self.assertFalse(StaticHost.objects.filter(hostname="del.example.com").exists())
|
||||||
mock_export.assert_not_called()
|
mock_export.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(WIREGUARD_STATUS_CACHE_ENABLED=True, CADDY_ENABLED=True)
|
||||||
|
class ApiV2ManageClusterTests(TestCase):
|
||||||
|
status_url = "/api/v2/manage_cluster/status/"
|
||||||
|
manage_url = "/api/v2/manage_cluster/manage_status/"
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
ClusterSettings.objects.update_or_create(name="cluster_settings", defaults={"enabled": True})
|
||||||
|
self.api_key = ApiKey.objects.create(name="cluster-key", manage_cluster=True)
|
||||||
|
self.node_a = Worker.objects.create(name="node-a")
|
||||||
|
self.node_b = Worker.objects.create(name="node-b", enabled=False)
|
||||||
|
self.instance = create_instance(0)
|
||||||
|
WireGuardInstance.objects.update(pending_changes=False)
|
||||||
|
|
||||||
|
self.calls = []
|
||||||
|
self.stop_errors = []
|
||||||
|
for name, value in (
|
||||||
|
("running_wireguard_interfaces", lambda: ["wg0"]),
|
||||||
|
("start_primary_interfaces", self.record("start")),
|
||||||
|
("stop_primary_interfaces", self.record("stop")),
|
||||||
|
("apply_caddy_config", self.record("export")),
|
||||||
|
):
|
||||||
|
patcher = patch(f"api_v2.views_api.{name}", value)
|
||||||
|
patcher.start()
|
||||||
|
self.addCleanup(patcher.stop)
|
||||||
|
|
||||||
|
def record(self, name):
|
||||||
|
def call():
|
||||||
|
self.calls.append(name)
|
||||||
|
return list(self.stop_errors) if name == "stop" else []
|
||||||
|
return call
|
||||||
|
|
||||||
|
def manage(self, payload, api_key=None, method="put"):
|
||||||
|
return getattr(self.client, method)(
|
||||||
|
self.manage_url, data=json.dumps(payload), content_type="application/json",
|
||||||
|
HTTP_TOKEN=str((api_key or self.api_key).token),
|
||||||
|
)
|
||||||
|
|
||||||
|
def assert_unchanged(self):
|
||||||
|
self.assertTrue(Worker.objects.get(pk=self.node_a.pk).enabled)
|
||||||
|
self.assertFalse(Worker.objects.get(pk=self.node_b.pk).enabled)
|
||||||
|
self.assertTrue(ClusterSettings.objects.get(name="cluster_settings").primary_enable_wireguard)
|
||||||
|
self.assertEqual(self.calls, [])
|
||||||
|
|
||||||
|
def test_api_key_needs_manage_cluster(self):
|
||||||
|
plain_key = ApiKey.objects.create(name="plain-key")
|
||||||
|
self.assertEqual(self.client.get(self.status_url).status_code, 403)
|
||||||
|
self.assertEqual(self.client.get(self.status_url, HTTP_TOKEN=str(plain_key.token)).status_code, 403)
|
||||||
|
response = self.manage({"workers": {str(self.node_a.uuid): False}}, api_key=plain_key)
|
||||||
|
self.assertEqual(response.status_code, 403)
|
||||||
|
self.assertIn("not allowed to manage the cluster", response.json()["error_message"])
|
||||||
|
self.assert_unchanged()
|
||||||
|
|
||||||
|
def test_status_lists_cluster_and_workers_by_uuid(self):
|
||||||
|
response = self.client.get(self.status_url, HTTP_TOKEN=str(self.api_key.token))
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
body = response.json()
|
||||||
|
self.assertEqual(body["cluster"], {
|
||||||
|
"enabled": True, "mode": "mirror", "primary_wireguard": True, "primary_running_interfaces": ["wg0"],
|
||||||
|
})
|
||||||
|
self.assertEqual(body["workers"][str(self.node_a.uuid)]["name"], "node-a")
|
||||||
|
self.assertFalse(body["workers"][str(self.node_b.uuid)]["enabled"])
|
||||||
|
self.assertIsNone(body["workers"][str(self.node_b.uuid)]["sync_state"])
|
||||||
|
|
||||||
|
def test_workers_and_primary_change_in_a_single_request(self):
|
||||||
|
response = self.manage({
|
||||||
|
"workers": {str(self.node_a.uuid): False, str(self.node_b.uuid): True}, "primary_wireguard": False,
|
||||||
|
})
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
body = response.json()
|
||||||
|
self.assertEqual(body["workers"][str(self.node_a.uuid)], {"name": "node-a", "enabled": False, "changed": True})
|
||||||
|
self.assertEqual(body["workers"][str(self.node_b.uuid)], {"name": "node-b", "enabled": True, "changed": True})
|
||||||
|
self.assertEqual(body["primary_wireguard"], {"enabled": False, "changed": True})
|
||||||
|
self.assertTrue(body["apply"]["success"])
|
||||||
|
self.assertFalse(Worker.objects.get(pk=self.node_a.pk).enabled)
|
||||||
|
self.assertTrue(Worker.objects.get(pk=self.node_b.pk).enabled)
|
||||||
|
self.assertFalse(ClusterSettings.primary_serves_clients())
|
||||||
|
self.assertEqual(self.calls, ["export", "stop"])
|
||||||
|
self.instance.refresh_from_db()
|
||||||
|
self.assertFalse(self.instance.pending_changes)
|
||||||
|
|
||||||
|
# The same request again changes nothing
|
||||||
|
self.calls.clear()
|
||||||
|
body = self.manage({"workers": {str(self.node_a.uuid): False}, "primary_wireguard": False}).json()
|
||||||
|
self.assertFalse(body["workers"][str(self.node_a.uuid)]["changed"])
|
||||||
|
self.assertFalse(body["primary_wireguard"]["changed"])
|
||||||
|
self.assertEqual(self.calls, [])
|
||||||
|
|
||||||
|
def test_enabling_the_primary_starts_its_interfaces(self):
|
||||||
|
ClusterSettings.objects.filter(name="cluster_settings").update(primary_enable_wireguard=False)
|
||||||
|
response = self.manage({"primary_wireguard": True}, method="post")
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(self.calls, ["export", "start"])
|
||||||
|
self.assertTrue(ClusterSettings.primary_serves_clients())
|
||||||
|
|
||||||
|
def test_skip_reload_only_marks_the_instances_pending(self):
|
||||||
|
response = self.manage({"primary_wireguard": False, "skip_reload": True})
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(self.calls, [])
|
||||||
|
self.instance.refresh_from_db()
|
||||||
|
self.assertTrue(self.instance.pending_changes)
|
||||||
|
|
||||||
|
def test_worker_changes_do_not_touch_the_primary_interfaces(self):
|
||||||
|
response = self.manage({"workers": {str(self.node_a.uuid): False}})
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertNotIn("primary_wireguard", response.json())
|
||||||
|
self.assertEqual(self.calls, [])
|
||||||
|
|
||||||
|
def test_invalid_requests_change_nothing(self):
|
||||||
|
for payload in (
|
||||||
|
{},
|
||||||
|
{"workers": {}},
|
||||||
|
{"workers": {"00000000-0000-0000-0000-000000000000": False}, "primary_wireguard": False},
|
||||||
|
{"workers": {"node-a": False}},
|
||||||
|
{"workers": {str(self.node_a.uuid): "no"}},
|
||||||
|
{"workers": {str(self.node_b.uuid): True}, "primary_wireguard": 0},
|
||||||
|
):
|
||||||
|
response = self.manage(payload)
|
||||||
|
self.assertEqual(response.status_code, 400, payload)
|
||||||
|
self.assert_unchanged()
|
||||||
|
|
||||||
|
def test_primary_follows_the_cluster_settings_form_rules(self):
|
||||||
|
ClusterSettings.objects.filter(name="cluster_settings").update(cluster_mode="distributed")
|
||||||
|
response = self.manage({"workers": {str(self.node_a.uuid): False}, "primary_wireguard": False})
|
||||||
|
self.assertEqual(response.status_code, 400)
|
||||||
|
self.assertIn("only be disabled in mirror mode", response.json()["error_message"])
|
||||||
|
self.assert_unchanged()
|
||||||
|
|
||||||
|
def test_changes_require_an_enabled_cluster(self):
|
||||||
|
ClusterSettings.objects.filter(name="cluster_settings").update(enabled=False)
|
||||||
|
response = self.manage({"workers": {str(self.node_a.uuid): False}})
|
||||||
|
self.assertEqual(response.status_code, 400)
|
||||||
|
self.assertEqual(response.json()["error_message"], "The cluster is not enabled.")
|
||||||
|
self.assert_unchanged()
|
||||||
|
|
||||||
|
def test_apply_failure_keeps_the_saved_changes_pending(self):
|
||||||
|
self.stop_errors = [("wg0", "device busy")]
|
||||||
|
response = self.manage({"primary_wireguard": False})
|
||||||
|
self.assertEqual(response.status_code, 500)
|
||||||
|
self.assertIn("saved but apply failed: wg0: device busy", response.json()["error_message"])
|
||||||
|
self.assertFalse(ClusterSettings.objects.get(name="cluster_settings").primary_enable_wireguard)
|
||||||
|
self.instance.refresh_from_db()
|
||||||
|
self.assertTrue(self.instance.pending_changes)
|
||||||
|
|
||||||
|
def test_other_methods_are_not_allowed(self):
|
||||||
|
response = self.client.delete(self.manage_url, HTTP_TOKEN=str(self.api_key.token))
|
||||||
|
self.assertEqual(response.status_code, 405)
|
||||||
|
response = self.client.put(self.status_url, HTTP_TOKEN=str(self.api_key.token))
|
||||||
|
self.assertEqual(response.status_code, 405)
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
from django.urls import path
|
from django.urls import path
|
||||||
|
|
||||||
from .views_api import (
|
from .views_api import (
|
||||||
|
api_v2_manage_cluster_manage_status,
|
||||||
|
api_v2_manage_cluster_status,
|
||||||
api_v2_manage_dns_record,
|
api_v2_manage_dns_record,
|
||||||
api_v2_manage_peer,
|
api_v2_manage_peer,
|
||||||
api_v2_peer_detail,
|
api_v2_peer_detail,
|
||||||
@@ -14,4 +16,6 @@ urlpatterns = [
|
|||||||
path('peer_list/', api_v2_peer_list, name='api_v2_peer_list'),
|
path('peer_list/', api_v2_peer_list, name='api_v2_peer_list'),
|
||||||
path('peer_detail/', api_v2_peer_detail, name='api_v2_peer_detail'),
|
path('peer_detail/', api_v2_peer_detail, name='api_v2_peer_detail'),
|
||||||
path('wireguard_status/', api_v2_wireguard_status, name='api_v2_wireguard_status'),
|
path('wireguard_status/', api_v2_wireguard_status, name='api_v2_wireguard_status'),
|
||||||
|
path('manage_cluster/status/', api_v2_manage_cluster_status, name='api_v2_manage_cluster_status'),
|
||||||
|
path('manage_cluster/manage_status/', api_v2_manage_cluster_manage_status, name='api_v2_manage_cluster_manage_status'),
|
||||||
]
|
]
|
||||||
|
|||||||
+254
-1
@@ -4,17 +4,25 @@ import re
|
|||||||
from functools import wraps
|
from functools import wraps
|
||||||
from typing import List, Optional, Tuple
|
from typing import List, Optional, Tuple
|
||||||
|
|
||||||
|
from django.conf import settings as django_settings
|
||||||
|
from django.core.exceptions import ValidationError
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
from django.http import JsonResponse
|
from django.http import JsonResponse
|
||||||
from django.views.decorators.csrf import csrf_exempt
|
from django.views.decorators.csrf import csrf_exempt
|
||||||
|
|
||||||
from api.views import func_get_wireguard_status
|
from api.views import func_get_wireguard_status
|
||||||
|
from app_gateway.caddy_config_export import apply_caddy_config
|
||||||
|
from cluster.forms import ClusterSettingsForm
|
||||||
|
from cluster.models import ClusterSettings, Worker, WorkerStatus
|
||||||
|
from cluster.sync import get_worker_sync_state
|
||||||
from dns.models import DNSSettings, StaticHost
|
from dns.models import DNSSettings, StaticHost
|
||||||
from dns.views import export_dns_configuration
|
from dns.views import export_dns_configuration
|
||||||
from routing_templates.models import RoutingTemplate
|
from routing_templates.models import RoutingTemplate
|
||||||
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
|
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
|
||||||
from wireguard_peer.functions import find_network_in_other_instance, func_create_new_peer
|
from wireguard_peer.functions import find_network_in_other_instance, func_create_new_peer
|
||||||
from wireguard_tools.functions import func_reload_wireguard_interface
|
from wireguard_tools.functions import (
|
||||||
|
func_reload_wireguard_interface, running_wireguard_interfaces, start_primary_interfaces, stop_primary_interfaces,
|
||||||
|
)
|
||||||
from wireguard_tools.views import export_wireguard_configuration
|
from wireguard_tools.views import export_wireguard_configuration
|
||||||
from .models import ApiKey
|
from .models import ApiKey
|
||||||
|
|
||||||
@@ -866,3 +874,248 @@ def api_v2_wireguard_status(request):
|
|||||||
|
|
||||||
data = func_get_wireguard_status()
|
data = func_get_wireguard_status()
|
||||||
return JsonResponse(data)
|
return JsonResponse(data)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_cluster_api_key(request):
|
||||||
|
api_key, api_error = validate_api_key(request)
|
||||||
|
if not api_key:
|
||||||
|
return None, JsonResponse({"status": "error", "error_message": api_error}, status=403)
|
||||||
|
if not api_key.manage_cluster:
|
||||||
|
return None, JsonResponse(
|
||||||
|
{"status": "error", "error_message": "This API key is not allowed to manage the cluster."}, status=403
|
||||||
|
)
|
||||||
|
return api_key, None
|
||||||
|
|
||||||
|
|
||||||
|
def _worker_status_data(worker):
|
||||||
|
worker_status = WorkerStatus.objects.filter(worker=worker).first()
|
||||||
|
operational = worker.enabled and not worker.error_status and worker.is_online
|
||||||
|
return {
|
||||||
|
"name": worker.name,
|
||||||
|
"enabled": worker.enabled,
|
||||||
|
"online": worker.is_online,
|
||||||
|
"last_seen": worker_status.last_seen.isoformat() if worker_status else None,
|
||||||
|
"worker_version": worker_status.worker_version if worker_status else None,
|
||||||
|
"error_status": worker.error_status,
|
||||||
|
# Reported data of disabled, refused or offline workers is only the last known state
|
||||||
|
"sync_state": get_worker_sync_state(worker)["state"] if operational else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@csrf_exempt
|
||||||
|
@api_doc(
|
||||||
|
summary="Cluster status: settings, WireGuard on the primary server and workers",
|
||||||
|
auth="Header token: <ApiKey.token> (the API key must have Manage Cluster enabled)",
|
||||||
|
methods=["GET", "POST"],
|
||||||
|
params=[],
|
||||||
|
returns=[
|
||||||
|
{"status": 200, "body": {
|
||||||
|
"status": "success",
|
||||||
|
"cluster": {"enabled": True, "mode": "mirror", "primary_wireguard": True,
|
||||||
|
"primary_running_interfaces": ["wg0"]},
|
||||||
|
"workers": {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": {
|
||||||
|
"name": "node-a", "enabled": True, "online": True, "last_seen": "2026-01-01T12:00:00+00:00",
|
||||||
|
"worker_version": 15, "error_status": "", "sync_state": "synced"}},
|
||||||
|
}},
|
||||||
|
{"status": 403, "body": {"status": "error", "error_message": "This API key is not allowed to manage the cluster."}},
|
||||||
|
{"status": 405, "body": {"status": "error", "error_message": "Method not allowed."}},
|
||||||
|
],
|
||||||
|
examples={
|
||||||
|
"get_cluster_status": {
|
||||||
|
"method": "GET",
|
||||||
|
"json": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
def api_v2_manage_cluster_status(request):
|
||||||
|
if request.method not in ("GET", "POST"):
|
||||||
|
return JsonResponse({"status": "error", "error_message": "Method not allowed."}, status=405)
|
||||||
|
|
||||||
|
api_key, error_response = _validate_cluster_api_key(request)
|
||||||
|
if error_response:
|
||||||
|
return error_response
|
||||||
|
|
||||||
|
cluster_settings, cluster_settings_created = ClusterSettings.objects.get_or_create(name='cluster_settings')
|
||||||
|
return JsonResponse({
|
||||||
|
"status": "success",
|
||||||
|
"cluster": {
|
||||||
|
"enabled": cluster_settings.enabled,
|
||||||
|
"mode": cluster_settings.cluster_mode,
|
||||||
|
"primary_wireguard": cluster_settings.primary_enable_wireguard,
|
||||||
|
"primary_running_interfaces": running_wireguard_interfaces(),
|
||||||
|
},
|
||||||
|
"workers": {str(worker.uuid): _worker_status_data(worker) for worker in Worker.objects.order_by('name')},
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@csrf_exempt
|
||||||
|
@api_doc(
|
||||||
|
summary="Enable / disable cluster workers and WireGuard on the primary server in a single request",
|
||||||
|
auth="Header token: <ApiKey.token> (the API key must have Manage Cluster enabled)",
|
||||||
|
methods=["PUT", "POST"],
|
||||||
|
params=[
|
||||||
|
{"name": "workers", "in": "json", "type": "object", "required": False,
|
||||||
|
"example": {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": False},
|
||||||
|
"description": "Map of worker UUID to the desired state (true = enabled). Workers apply the change on "
|
||||||
|
"their next synchronization."},
|
||||||
|
{"name": "primary_wireguard", "in": "json", "type": "boolean", "required": False, "example": False,
|
||||||
|
"description": "Enables or disables WireGuard on the primary server. Disabling is only allowed in mirror "
|
||||||
|
"mode: the primary server stops its interfaces and only publishes WireGuard WebAdmin in the "
|
||||||
|
"App Gateway, while the workers serve the clients."},
|
||||||
|
{"name": "skip_reload", "in": "json", "type": "boolean", "required": False, "example": False,
|
||||||
|
"description": "If true, the WireGuard interfaces of the primary server are not started or stopped and "
|
||||||
|
"the instances are marked with pending_changes=True."},
|
||||||
|
],
|
||||||
|
returns=[
|
||||||
|
{"status": 200, "body": {
|
||||||
|
"status": "success", "message": "Cluster updated successfully.",
|
||||||
|
"workers": {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": {"name": "node-a", "enabled": False, "changed": True}},
|
||||||
|
"primary_wireguard": {"enabled": False, "changed": True},
|
||||||
|
"apply": {"success": True, "message": "..."},
|
||||||
|
}},
|
||||||
|
{"status": 400, "body": {"status": "error", "error_message": "The cluster is not enabled."}},
|
||||||
|
{"status": 403, "body": {"status": "error", "error_message": "This API key is not allowed to manage the cluster."}},
|
||||||
|
{"status": 405, "body": {"status": "error", "error_message": "Method not allowed."}},
|
||||||
|
{"status": 500, "body": {"status": "error", "error_message": "Cluster changes were saved but apply failed: ..."}},
|
||||||
|
],
|
||||||
|
examples={
|
||||||
|
"disable_worker_and_primary": {
|
||||||
|
"method": "PUT",
|
||||||
|
"json": {
|
||||||
|
"workers": {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": False},
|
||||||
|
"primary_wireguard": False
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"enable_workers": {
|
||||||
|
"method": "PUT",
|
||||||
|
"json": {
|
||||||
|
"workers": {
|
||||||
|
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx": True,
|
||||||
|
"yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy": True
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
def api_v2_manage_cluster_manage_status(request):
|
||||||
|
if request.method not in ("PUT", "POST"):
|
||||||
|
return JsonResponse({"status": "error", "error_message": "Method not allowed."}, status=405)
|
||||||
|
|
||||||
|
try:
|
||||||
|
payload = json.loads(request.body.decode("utf-8")) if request.body else {}
|
||||||
|
except Exception:
|
||||||
|
return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400)
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
return JsonResponse({"status": "error", "error_message": "Invalid JSON body."}, status=400)
|
||||||
|
|
||||||
|
api_key, error_response = _validate_cluster_api_key(request)
|
||||||
|
if error_response:
|
||||||
|
return error_response
|
||||||
|
|
||||||
|
cluster_settings, cluster_settings_created = ClusterSettings.objects.get_or_create(name='cluster_settings')
|
||||||
|
if not cluster_settings.enabled:
|
||||||
|
return JsonResponse({"status": "error", "error_message": "The cluster is not enabled."}, status=400)
|
||||||
|
|
||||||
|
requested_workers = payload.get("workers")
|
||||||
|
primary_wireguard = payload.get("primary_wireguard")
|
||||||
|
skip_reload = bool(payload.get("skip_reload", False))
|
||||||
|
if requested_workers is None and primary_wireguard is None:
|
||||||
|
return JsonResponse(
|
||||||
|
{"status": "error", "error_message": "Invalid payload: inform workers and/or primary_wireguard."}, status=400
|
||||||
|
)
|
||||||
|
|
||||||
|
# Everything is validated before any change is saved
|
||||||
|
workers = {}
|
||||||
|
if requested_workers is not None:
|
||||||
|
if not isinstance(requested_workers, dict) or not requested_workers:
|
||||||
|
return JsonResponse(
|
||||||
|
{"status": "error", "error_message": "Invalid payload: workers must map worker UUIDs to true or false."},
|
||||||
|
status=400
|
||||||
|
)
|
||||||
|
for worker_uuid, enabled in requested_workers.items():
|
||||||
|
if not isinstance(enabled, bool):
|
||||||
|
return JsonResponse(
|
||||||
|
{"status": "error", "error_message": f"Invalid payload: the state of worker {worker_uuid} must be true or false."},
|
||||||
|
status=400
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
worker = Worker.objects.get(uuid=worker_uuid)
|
||||||
|
except (Worker.DoesNotExist, ValidationError, ValueError):
|
||||||
|
return JsonResponse({"status": "error", "error_message": f"Worker not found: {worker_uuid}"}, status=400)
|
||||||
|
workers[worker] = enabled
|
||||||
|
|
||||||
|
settings_form = None
|
||||||
|
# Validating the form already copies the new value to cluster_settings
|
||||||
|
previous_primary_wireguard = cluster_settings.primary_enable_wireguard
|
||||||
|
if primary_wireguard is not None:
|
||||||
|
if not isinstance(primary_wireguard, bool):
|
||||||
|
return JsonResponse(
|
||||||
|
{"status": "error", "error_message": "Invalid payload: primary_wireguard must be true or false."}, status=400
|
||||||
|
)
|
||||||
|
# Same rules as the cluster settings form
|
||||||
|
settings_form = ClusterSettingsForm(data={
|
||||||
|
"enabled": cluster_settings.enabled,
|
||||||
|
"primary_enable_wireguard": primary_wireguard,
|
||||||
|
"cluster_mode": cluster_settings.cluster_mode,
|
||||||
|
"worker_display": cluster_settings.worker_display,
|
||||||
|
}, instance=cluster_settings)
|
||||||
|
if not settings_form.is_valid():
|
||||||
|
errors = [str(error) for field_errors in settings_form.errors.values() for error in field_errors]
|
||||||
|
return JsonResponse({"status": "error", "error_message": " ".join(errors)}, status=400)
|
||||||
|
|
||||||
|
primary_served_clients = ClusterSettings.primary_serves_clients()
|
||||||
|
worker_results = {}
|
||||||
|
with transaction.atomic():
|
||||||
|
for worker, enabled in workers.items():
|
||||||
|
changed = worker.enabled != enabled
|
||||||
|
if changed:
|
||||||
|
worker.enabled = enabled
|
||||||
|
worker.save(update_fields=["enabled", "updated"])
|
||||||
|
worker_results[str(worker.uuid)] = {"name": worker.name, "enabled": enabled, "changed": changed}
|
||||||
|
|
||||||
|
primary_result = None
|
||||||
|
primary_changed = False
|
||||||
|
if settings_form is not None:
|
||||||
|
primary_changed = previous_primary_wireguard != primary_wireguard
|
||||||
|
settings_form.save()
|
||||||
|
primary_result = {"enabled": primary_wireguard, "changed": primary_changed}
|
||||||
|
if ClusterSettings.primary_serves_clients() != primary_served_clients:
|
||||||
|
WireGuardInstance.objects.update(pending_changes=True)
|
||||||
|
|
||||||
|
apply_success = True
|
||||||
|
if not primary_changed:
|
||||||
|
apply_message = "Workers apply the changes on their next synchronization."
|
||||||
|
elif skip_reload:
|
||||||
|
apply_message = "Changes saved. Apply skipped (pending_changes set to True)."
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
if django_settings.CADDY_ENABLED:
|
||||||
|
apply_caddy_config()
|
||||||
|
except Exception as error:
|
||||||
|
return JsonResponse(
|
||||||
|
{"status": "error", "error_message": f"Cluster changes were saved but apply failed: {error}"}, status=500
|
||||||
|
)
|
||||||
|
if ClusterSettings.primary_serves_clients():
|
||||||
|
errors = start_primary_interfaces()
|
||||||
|
apply_message = "WireGuard interfaces of the primary server started."
|
||||||
|
else:
|
||||||
|
errors = stop_primary_interfaces()
|
||||||
|
apply_message = "WireGuard interfaces of the primary server stopped."
|
||||||
|
if errors:
|
||||||
|
details = "; ".join(f"{interface_name}: {error}" for interface_name, error in errors)
|
||||||
|
return JsonResponse(
|
||||||
|
{"status": "error", "error_message": f"Cluster changes were saved but apply failed: {details}"},
|
||||||
|
status=500
|
||||||
|
)
|
||||||
|
WireGuardInstance.objects.update(pending_changes=False)
|
||||||
|
|
||||||
|
response_data = {
|
||||||
|
"status": "success",
|
||||||
|
"message": "Cluster updated successfully.",
|
||||||
|
"apply": {"success": apply_success, "message": apply_message},
|
||||||
|
}
|
||||||
|
if worker_results:
|
||||||
|
response_data["workers"] = worker_results
|
||||||
|
if primary_result is not None:
|
||||||
|
response_data["primary_wireguard"] = primary_result
|
||||||
|
return JsonResponse(response_data)
|
||||||
|
|||||||
+3
-1
@@ -766,7 +766,9 @@ class PrimaryDisabledTests(ClusterTestMixin, TestCase):
|
|||||||
return type('Result', (), {'returncode': 0, 'stdout': 'wg0 wg1\n', 'stderr': ''})()
|
return type('Result', (), {'returncode': 0, 'stdout': 'wg0 wg1\n', 'stderr': ''})()
|
||||||
|
|
||||||
with patch('wireguard_tools.views.subprocess.run', run), \
|
with patch('wireguard_tools.views.subprocess.run', run), \
|
||||||
patch('wireguard_tools.views.os.path.isfile', lambda path: path.endswith('/wg0.conf')):
|
patch('wireguard_tools.functions.subprocess.run', run), \
|
||||||
|
patch('wireguard_tools.views.os.path.isfile', lambda path: path.endswith('/wg0.conf')), \
|
||||||
|
patch('wireguard_tools.functions.os.path.isfile', lambda path: path.endswith('/wg0.conf')):
|
||||||
self.client.get('/tools/restart_wireguard/?action=dismiss_warning')
|
self.client.get('/tools/restart_wireguard/?action=dismiss_warning')
|
||||||
|
|
||||||
self.assertIn(['wg-quick', 'down', 'wg0'], commands)
|
self.assertIn(['wg-quick', 'down', 'wg0'], commands)
|
||||||
|
|||||||
@@ -12,6 +12,7 @@
|
|||||||
<th class="text-center"><i class="fas fa-power-off" title="{% trans 'Allow Restart' %}"></i></th>
|
<th class="text-center"><i class="fas fa-power-off" title="{% trans 'Allow Restart' %}"></i></th>
|
||||||
<th class="text-center"><i class="fas fa-sync" title="{% trans 'Allow Reload' %}"></i></th>
|
<th class="text-center"><i class="fas fa-sync" title="{% trans 'Allow Reload' %}"></i></th>
|
||||||
<th class="text-center"><i class="fas fa-download" title="{% trans 'Allow Export' %}"></i></th>
|
<th class="text-center"><i class="fas fa-download" title="{% trans 'Allow Export' %}"></i></th>
|
||||||
|
<th class="text-center"><i class="fas fa-server" title="{% trans 'Manage Cluster' %}"></i></th>
|
||||||
<th class="text-center"><i class="far fa-edit"></i></th>
|
<th class="text-center"><i class="far fa-edit"></i></th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -64,6 +65,13 @@
|
|||||||
<i class="fas fa-times text-danger"></i>
|
<i class="fas fa-times text-danger"></i>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</td>
|
</td>
|
||||||
|
<td class="text-center">
|
||||||
|
{% if key.manage_cluster %}
|
||||||
|
<i class="fas fa-check text-success"></i>
|
||||||
|
{% else %}
|
||||||
|
<i class="fas fa-times text-danger"></i>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
<td class="text-center" style="width: 1%; white-space: nowrap;">
|
<td class="text-center" style="width: 1%; white-space: nowrap;">
|
||||||
<a href="/manage_api/v2/manage/?uuid={{ key.uuid }}" title="{% trans 'Edit' %}">
|
<a href="/manage_api/v2/manage/?uuid={{ key.uuid }}" title="{% trans 'Edit' %}">
|
||||||
<i class="far fa-edit"></i>
|
<i class="far fa-edit"></i>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
|
import glob
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
from typing import Union
|
from typing import Union
|
||||||
|
|
||||||
@@ -38,6 +40,40 @@ def get_config_servers(instance: WireGuardInstance) -> list:
|
|||||||
return servers
|
return servers
|
||||||
|
|
||||||
|
|
||||||
|
def running_wireguard_interfaces() -> list:
|
||||||
|
result = subprocess.run(['wg', 'show', 'interfaces'], capture_output=True, text=True)
|
||||||
|
return [interface for interface in result.stdout.split() if re.fullmatch(r'wg[0-9]+', interface)]
|
||||||
|
|
||||||
|
|
||||||
|
def stop_primary_interfaces() -> list:
|
||||||
|
"""Stop every WireGuard interface running on this server. Returns (interface, error) for each failure."""
|
||||||
|
errors = []
|
||||||
|
for interface_name in running_wireguard_interfaces():
|
||||||
|
if os.path.isfile(os.path.join(WIREGUARD_CONFIG_DIR, f'{interface_name}.conf')):
|
||||||
|
command = ['wg-quick', 'down', interface_name]
|
||||||
|
else:
|
||||||
|
# Instances moved to a worker no longer have a configuration on this server
|
||||||
|
command = ['ip', 'link', 'delete', interface_name]
|
||||||
|
result = subprocess.run(command, capture_output=True, text=True)
|
||||||
|
if result.returncode != 0:
|
||||||
|
errors.append((interface_name, result.stderr.strip()))
|
||||||
|
return errors
|
||||||
|
|
||||||
|
|
||||||
|
def start_primary_interfaces() -> list:
|
||||||
|
"""Start the configured WireGuard interfaces that are not running. Returns (interface, error) for each failure."""
|
||||||
|
errors = []
|
||||||
|
running_interfaces = running_wireguard_interfaces()
|
||||||
|
for config_path in sorted(glob.glob(os.path.join(WIREGUARD_CONFIG_DIR, 'wg[0-9]*.conf'))):
|
||||||
|
interface_name = os.path.basename(config_path)[:-len('.conf')]
|
||||||
|
if interface_name in running_interfaces:
|
||||||
|
continue
|
||||||
|
result = subprocess.run(['wg-quick', 'up', interface_name], capture_output=True, text=True)
|
||||||
|
if result.returncode != 0:
|
||||||
|
errors.append((interface_name, result.stderr.strip()))
|
||||||
|
return errors
|
||||||
|
|
||||||
|
|
||||||
def sync_interface_routes(interface_name: str) -> list:
|
def sync_interface_routes(interface_name: str) -> list:
|
||||||
"""
|
"""
|
||||||
Bring the IPv4 routes of a running interface in line with its allowed IPs, as wg-quick does on start.
|
Bring the IPv4 routes of a running interface in line with its allowed IPs, as wg-quick does on start.
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ from vpn_invite.models import PeerInvite
|
|||||||
from wgwadmlibrary.tools import user_has_access_to_peer
|
from wgwadmlibrary.tools import user_has_access_to_peer
|
||||||
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
|
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
|
||||||
from wireguard_tools.functions import (
|
from wireguard_tools.functions import (
|
||||||
CLUSTER_WIREGUARD_CONFIG_DIR, WIREGUARD_CONFIG_DIR, get_instance_config_dir, sync_interface_routes
|
CLUSTER_WIREGUARD_CONFIG_DIR, WIREGUARD_CONFIG_DIR, get_instance_config_dir, stop_primary_interfaces,
|
||||||
|
sync_interface_routes,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -341,11 +342,8 @@ def restart_wireguard_interfaces(request):
|
|||||||
if not (user_acl.enable_reload if mode == 'reload' else user_acl.enable_restart):
|
if not (user_acl.enable_reload if mode == 'reload' else user_acl.enable_restart):
|
||||||
return render(request, 'access_denied.html', {'page_title': 'Access Denied'})
|
return render(request, 'access_denied.html', {'page_title': 'Access Denied'})
|
||||||
# WireGuard is disabled on the primary server in mirror mode: only the cluster workers run the instances
|
# WireGuard is disabled on the primary server in mirror mode: only the cluster workers run the instances
|
||||||
for interface_name in running_interfaces:
|
for interface_name, error in stop_primary_interfaces():
|
||||||
if re.fullmatch(r'wg[0-9]+', interface_name) and os.path.isfile(os.path.join(config_dir, f'{interface_name}.conf')):
|
messages.warning(request, _("Error stopping") + f" {interface_name}|{error}")
|
||||||
stop_result = subprocess.run(['wg-quick', 'down', interface_name], capture_output=True, text=True)
|
|
||||||
if stop_result.returncode != 0:
|
|
||||||
messages.warning(request, _("Error stopping") + f" {interface_name}|{stop_result.stderr}")
|
|
||||||
messages.info(request, _(
|
messages.info(request, _(
|
||||||
"WireGuard disabled on the primary server|The interfaces of this server are stopped. Cluster workers "
|
"WireGuard disabled on the primary server|The interfaces of this server are stopped. Cluster workers "
|
||||||
"keep serving the peers."
|
"keep serving the peers."
|
||||||
|
|||||||
Reference in New Issue
Block a user