mirror of
https://github.com/eduardogsilva/wireguard_webadmin.git
synced 2026-01-17 13:06:18 +00:00
refactor func_process_wireguard_status to improve data handling and parsing
This commit is contained in:
79
api/views.py
79
api/views.py
@@ -4,6 +4,7 @@ import os
|
|||||||
import subprocess
|
import subprocess
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
from typing import Dict, Any
|
||||||
|
|
||||||
import pytz
|
import pytz
|
||||||
import requests
|
import requests
|
||||||
@@ -211,55 +212,49 @@ def api_instance_info(request):
|
|||||||
return JsonResponse(data)
|
return JsonResponse(data)
|
||||||
|
|
||||||
|
|
||||||
def func_process_wireguard_status():
|
def func_process_wireguard_status() -> Dict[str, Any]:
|
||||||
# Query WireGuard status from the system and construct the data dictionary
|
command = "wg show all dump"
|
||||||
commands = {
|
|
||||||
'latest-handshakes': "wg show all latest-handshakes | expand | tr -s ' '",
|
|
||||||
'allowed-ips': "wg show all allowed-ips | expand | tr -s ' '",
|
|
||||||
'transfer': "wg show all transfer | expand | tr -s ' '",
|
|
||||||
'endpoints': "wg show all endpoints | expand | tr -s ' '",
|
|
||||||
}
|
|
||||||
|
|
||||||
data = {}
|
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||||
|
stdout, stderr = process.communicate()
|
||||||
|
|
||||||
for key, command in commands.items():
|
if process.returncode != 0:
|
||||||
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
return {"message": stderr, "status": "error"}
|
||||||
stdout, stderr = process.communicate()
|
|
||||||
|
|
||||||
if process.returncode != 0:
|
data: Dict[str, Dict[str, Dict[str, Any]]] = {}
|
||||||
return JsonResponse({'error': stderr}, status=400)
|
|
||||||
|
|
||||||
current_interface = None
|
# wg dump format is tab-separated.
|
||||||
for line in stdout.strip().split('\n'):
|
# There are two kinds of lines:
|
||||||
parts = line.split()
|
# - Interface line: interface \t private_key \t public_key \t listen_port \t fwmark
|
||||||
if len(parts) >= 3:
|
# - Peer line: interface \t peer_public_key \t preshared_key \t endpoint \t allowed_ips \t latest_handshake \t transfer_rx \t transfer_tx \t persistent_keepalive
|
||||||
interface, peer, value = parts[0], parts[1], " ".join(parts[2:])
|
for line in stdout.strip().split("\n"):
|
||||||
current_interface = interface
|
parts = line.split("\t")
|
||||||
elif len(parts) == 2 and current_interface:
|
if len(parts) < 5:
|
||||||
peer, value = parts
|
continue
|
||||||
else:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if interface not in data:
|
interface = parts[0]
|
||||||
data[interface] = {}
|
|
||||||
|
|
||||||
if peer not in data[interface]:
|
# Peer lines are expected to have at least 9 fields
|
||||||
data[interface][peer] = {
|
if len(parts) < 9:
|
||||||
'allowed-ips': [],
|
# interface line, ignore
|
||||||
'latest-handshakes': '',
|
continue
|
||||||
'transfer': {'tx': 0, 'rx': 0},
|
|
||||||
'endpoints': '',
|
|
||||||
}
|
|
||||||
|
|
||||||
if key == 'allowed-ips':
|
peer_public_key = parts[1]
|
||||||
data[interface][peer]['allowed-ips'].append(value)
|
endpoint = parts[3]
|
||||||
elif key == 'transfer':
|
allowed_ips_raw = parts[4]
|
||||||
rx, tx = value.split()[-2:]
|
latest_handshake = parts[5]
|
||||||
data[interface][peer]['transfer'] = {'tx': int(tx), 'rx': int(rx)}
|
transfer_rx = parts[6]
|
||||||
elif key == 'endpoints':
|
transfer_tx = parts[7]
|
||||||
data[interface][peer]['endpoints'] = value
|
|
||||||
else:
|
if interface not in data:
|
||||||
data[interface][peer][key] = value
|
data[interface] = {}
|
||||||
|
|
||||||
|
data[interface][peer_public_key] = {
|
||||||
|
"allowed-ips": [ip for ip in allowed_ips_raw.split(",") if ip] if allowed_ips_raw else [],
|
||||||
|
"latest-handshakes": latest_handshake or "",
|
||||||
|
"transfer": {"tx": int(transfer_tx or 0), "rx": int(transfer_rx or 0)},
|
||||||
|
"endpoints": endpoint or "",
|
||||||
|
}
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import logging
|
|||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import time
|
import time
|
||||||
|
from typing import Dict, Any
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
@@ -40,55 +41,50 @@ class ClusterWorker:
|
|||||||
self.base_url = f"{MASTER_SERVER_ADDRESS}/api/cluster"
|
self.base_url = f"{MASTER_SERVER_ADDRESS}/api/cluster"
|
||||||
|
|
||||||
|
|
||||||
def func_process_wireguard_status(self):
|
def func_process_wireguard_status(self) -> Dict[str, Any]:
|
||||||
# Query WireGuard status from the system and construct the data dictionary
|
command = "wg show all dump"
|
||||||
commands = {
|
|
||||||
'latest-handshakes': "wg show all latest-handshakes | expand | tr -s ' '",
|
|
||||||
'allowed-ips': "wg show all allowed-ips | expand | tr -s ' '",
|
|
||||||
'transfer': "wg show all transfer | expand | tr -s ' '",
|
|
||||||
'endpoints': "wg show all endpoints | expand | tr -s ' '",
|
|
||||||
}
|
|
||||||
|
|
||||||
data = {}
|
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||||
|
stdout, stderr = process.communicate()
|
||||||
|
|
||||||
for key, command in commands.items():
|
if process.returncode != 0:
|
||||||
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
return {"message": stderr, "status": "error"}
|
||||||
stdout, stderr = process.communicate()
|
|
||||||
|
|
||||||
if process.returncode != 0:
|
data: Dict[str, Dict[str, Dict[str, Any]]] = {}
|
||||||
return {'error': stderr}
|
|
||||||
|
|
||||||
current_interface = None
|
# wg dump format is tab-separated.
|
||||||
for line in stdout.strip().split('\n'):
|
# There are two kinds of lines:
|
||||||
parts = line.split()
|
# - Interface line: interface \t private_key \t public_key \t listen_port \t fwmark
|
||||||
if len(parts) >= 3:
|
# - Peer line: interface \t peer_public_key \t preshared_key \t endpoint \t allowed_ips \t latest_handshake \t transfer_rx \t transfer_tx \t persistent_keepalive
|
||||||
interface, peer, value = parts[0], parts[1], " ".join(parts[2:])
|
for line in stdout.strip().split("\n"):
|
||||||
current_interface = interface
|
parts = line.split("\t")
|
||||||
elif len(parts) == 2 and current_interface:
|
if len(parts) < 5:
|
||||||
peer, value = parts
|
continue
|
||||||
else:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if interface not in data:
|
interface = parts[0]
|
||||||
data[interface] = {}
|
|
||||||
|
|
||||||
if peer not in data[interface]:
|
# Peer lines are expected to have at least 9 fields
|
||||||
data[interface][peer] = {
|
if len(parts) < 9:
|
||||||
'allowed-ips': [],
|
# interface line, ignore
|
||||||
'latest-handshakes': '',
|
continue
|
||||||
'transfer': {'tx': 0, 'rx': 0},
|
|
||||||
'endpoints': '',
|
peer_public_key = parts[1]
|
||||||
}
|
endpoint = parts[3]
|
||||||
|
allowed_ips_raw = parts[4]
|
||||||
|
latest_handshake = parts[5]
|
||||||
|
transfer_rx = parts[6]
|
||||||
|
transfer_tx = parts[7]
|
||||||
|
|
||||||
|
if interface not in data:
|
||||||
|
data[interface] = {}
|
||||||
|
|
||||||
|
data[interface][peer_public_key] = {
|
||||||
|
"allowed-ips": [ip for ip in allowed_ips_raw.split(",") if ip] if allowed_ips_raw else [],
|
||||||
|
"latest-handshakes": latest_handshake or "",
|
||||||
|
"transfer": {"tx": int(transfer_tx or 0), "rx": int(transfer_rx or 0)},
|
||||||
|
"endpoints": endpoint or "",
|
||||||
|
}
|
||||||
|
|
||||||
if key == 'allowed-ips':
|
|
||||||
data[interface][peer]['allowed-ips'].append(value)
|
|
||||||
elif key == 'transfer':
|
|
||||||
rx, tx = value.split()[-2:]
|
|
||||||
data[interface][peer]['transfer'] = {'tx': int(tx), 'rx': int(rx)}
|
|
||||||
elif key == 'endpoints':
|
|
||||||
data[interface][peer]['endpoints'] = value
|
|
||||||
else:
|
|
||||||
data[interface][peer][key] = value
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -593,7 +593,9 @@
|
|||||||
};
|
};
|
||||||
|
|
||||||
const checkAllowedIps = (allowedIpsElement, allowedIpsApiResponse) => {
|
const checkAllowedIps = (allowedIpsElement, allowedIpsApiResponse) => {
|
||||||
const apiIps = allowedIpsApiResponse[0].split(' ');
|
const apiIps = Array.isArray(allowedIpsApiResponse)
|
||||||
|
? allowedIpsApiResponse.filter(Boolean)
|
||||||
|
: (allowedIpsApiResponse || '').split(/\s+/).filter(Boolean);
|
||||||
const htmlIpsText = allowedIpsElement.textContent.trim();
|
const htmlIpsText = allowedIpsElement.textContent.trim();
|
||||||
const htmlIpsArray = htmlIpsText.match(/\b(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}\b/g) || [];
|
const htmlIpsArray = htmlIpsText.match(/\b(?:\d{1,3}\.){3}\d{1,3}\/\d{1,2}\b/g) || [];
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user