1
0
mirror of https://github.com/donaldzou/WGDashboard.git synced 2024-11-22 15:20:09 +01:00

No longer reading configuration file every few seconds

Only when the file is changed
This commit is contained in:
Donald Zou 2024-08-15 18:26:20 -04:00
parent 42fa89db7a
commit c98d851cd2
2 changed files with 88 additions and 75 deletions

View File

@ -40,6 +40,8 @@
- Rewrote the backend into a REST API structure - Rewrote the backend into a REST API structure
- Improved SQL query efficient - Improved SQL query efficient
- Removed all templates, except for `index.html` where it will load the Vue.js app. - Removed all templates, except for `index.html` where it will load the Vue.js app.
- Parsing names in `.conf`
- Minimized the need to read `.conf`, only when any `.conf` is modified
- **🥘 New Experimental Features** - **🥘 New Experimental Features**
- **Cross-Server Access**: Now you can access other servers that installed `v4` of WGDashboard through API key. - **Cross-Server Access**: Now you can access other servers that installed `v4` of WGDashboard through API key.

View File

@ -5,6 +5,7 @@ import configparser
import hashlib import hashlib
import ipaddress import ipaddress
import json import json
import traceback
# Python Built-in Library # Python Built-in Library
import os import os
import secrets import secrets
@ -421,6 +422,7 @@ class WireguardConfiguration:
def __init__(self, name: str = None, data: dict = None): def __init__(self, name: str = None, data: dict = None):
self.__parser: configparser.ConfigParser = configparser.ConfigParser(strict=False) self.__parser: configparser.ConfigParser = configparser.ConfigParser(strict=False)
self.__parser.optionxform = str self.__parser.optionxform = str
self.__configFileModifiedTime = None
self.Status: bool = False self.Status: bool = False
self.Name: str = "" self.Name: str = ""
@ -565,79 +567,83 @@ class WireguardConfiguration:
self.RestrictedPeers.append(Peer(i, self)) self.RestrictedPeers.append(Peer(i, self))
def __getPeers(self): def __getPeers(self):
self.Peers = []
with open(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'), 'r') as configFile: mt = os.path.getmtime(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'))
p = [] if self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt:
pCounter = -1 self.Peers = []
content = configFile.read().split('\n') with open(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'), 'r') as configFile:
try: p = []
peerStarts = content.index("[Peer]") pCounter = -1
content = content[peerStarts:] content = configFile.read().split('\n')
for i in content: try:
if not regex_match("#(.*)", i) and not regex_match(";(.*)", i): peerStarts = content.index("[Peer]")
if i == "[Peer]": content = content[peerStarts:]
pCounter += 1 for i in content:
p.append({}) if not regex_match("#(.*)", i) and not regex_match(";(.*)", i):
p[pCounter]["name"] = "" if i == "[Peer]":
else: pCounter += 1
if len(i) > 0: p.append({})
split = re.split(r'\s*=\s*', i, 1) p[pCounter]["name"] = ""
if len(split) == 2: else:
p[pCounter][split[0]] = split[1] if len(i) > 0:
split = re.split(r'\s*=\s*', i, 1)
if len(split) == 2:
p[pCounter][split[0]] = split[1]
if regex_match("#Name# = (.*)", i):
split = re.split(r'\s*=\s*', i, 1)
print(split)
if len(split) == 2:
p[pCounter]["name"] = split[1]
if regex_match("#Name# = (.*)", i): for i in p:
split = re.split(r'\s*=\s*', i, 1) if "PublicKey" in i.keys():
print(split) checkIfExist = sqldb.cursor().execute("SELECT * FROM '%s' WHERE id = ?" % self.Name,
if len(split) == 2: ((i['PublicKey']),)).fetchone()
p[pCounter]["name"] = split[1] if checkIfExist is None:
print(i)
for i in p: newPeer = {
if "PublicKey" in i.keys(): "id": i['PublicKey'],
checkIfExist = sqldb.cursor().execute("SELECT * FROM '%s' WHERE id = ?" % self.Name, "private_key": "",
((i['PublicKey']),)).fetchone() "DNS": DashboardConfig.GetConfig("Peers", "peer_global_DNS")[1],
if checkIfExist is None: "endpoint_allowed_ip": DashboardConfig.GetConfig("Peers", "peer_endpoint_allowed_ip")[
print(i) 1],
newPeer = { "name": i.get("name"),
"id": i['PublicKey'], "total_receive": 0,
"private_key": "", "total_sent": 0,
"DNS": DashboardConfig.GetConfig("Peers", "peer_global_DNS")[1], "total_data": 0,
"endpoint_allowed_ip": DashboardConfig.GetConfig("Peers", "peer_endpoint_allowed_ip")[ "endpoint": "N/A",
1], "status": "stopped",
"name": i.get("name"), "latest_handshake": "N/A",
"total_receive": 0, "allowed_ip": i.get("AllowedIPs", "N/A"),
"total_sent": 0, "cumu_receive": 0,
"total_data": 0, "cumu_sent": 0,
"endpoint": "N/A", "cumu_data": 0,
"status": "stopped", "traffic": [],
"latest_handshake": "N/A", "mtu": DashboardConfig.GetConfig("Peers", "peer_mtu")[1],
"allowed_ip": i.get("AllowedIPs", "N/A"), "keepalive": DashboardConfig.GetConfig("Peers", "peer_keep_alive")[1],
"cumu_receive": 0, "remote_endpoint": DashboardConfig.GetConfig("Peers", "remote_endpoint")[1],
"cumu_sent": 0, "preshared_key": i["PresharedKey"] if "PresharedKey" in i.keys() else ""
"cumu_data": 0, }
"traffic": [], print(newPeer)
"mtu": DashboardConfig.GetConfig("Peers", "peer_mtu")[1], sqldb.cursor().execute(
"keepalive": DashboardConfig.GetConfig("Peers", "peer_keep_alive")[1], """
"remote_endpoint": DashboardConfig.GetConfig("Peers", "remote_endpoint")[1], INSERT INTO '%s'
"preshared_key": i["PresharedKey"] if "PresharedKey" in i.keys() else "" VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent,
} :total_data, :endpoint, :status, :latest_handshake, :allowed_ip, :cumu_receive, :cumu_sent,
print(newPeer) :cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key);
sqldb.cursor().execute( """ % self.Name
""" , newPeer)
INSERT INTO '%s' sqldb.commit()
VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent, self.Peers.append(Peer(newPeer, self))
:total_data, :endpoint, :status, :latest_handshake, :allowed_ip, :cumu_receive, :cumu_sent, else:
:cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key); sqldb.cursor().execute("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name,
""" % self.Name (i.get("AllowedIPs", "N/A"), i['PublicKey'],))
, newPeer) sqldb.commit()
sqldb.commit() self.Peers.append(Peer(checkIfExist, self))
self.Peers.append(Peer(newPeer, self)) except Exception as e:
else: print(f"[WGDashboard] {self.Name} Error: {str(e)}")
sqldb.cursor().execute("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name, self.__configFileModifiedTime = mt
(i.get("AllowedIPs", "N/A"), i['PublicKey'],))
sqldb.commit()
self.Peers.append(Peer(checkIfExist, self))
except Exception as e:
print(f"[WGDashboard] {self.Name} Error: {str(e)}")
def addPeers(self, peers: list): def addPeers(self, peers: list):
for p in peers: for p in peers:
@ -782,7 +788,8 @@ class WireguardConfiguration:
, (status, latestHandshake[count],)) , (status, latestHandshake[count],))
sqldb.commit() sqldb.commit()
count += 2 count += 2
def getPeersTransfer(self): def getPeersTransfer(self):
if not self.getStatus(): if not self.getStatus():
self.toggleConfiguration() self.toggleConfiguration()
@ -797,6 +804,7 @@ class WireguardConfiguration:
"SELECT total_receive, total_sent, cumu_receive, cumu_sent, status FROM '%s' WHERE id= ? " "SELECT total_receive, total_sent, cumu_receive, cumu_sent, status FROM '%s' WHERE id= ? "
% self.Name, (data_usage[i][0],)).fetchone() % self.Name, (data_usage[i][0],)).fetchone()
if cur_i is not None: if cur_i is not None:
cur_i = dict(cur_i)
total_sent = cur_i['total_sent'] total_sent = cur_i['total_sent']
total_receive = cur_i['total_receive'] total_receive = cur_i['total_receive']
cur_total_sent = float(data_usage[i][2]) / (1024 ** 3) cur_total_sent = float(data_usage[i][2]) / (1024 ** 3)
@ -812,17 +820,20 @@ class WireguardConfiguration:
self.Name, (cumulative_receive, cumulative_sent, self.Name, (cumulative_receive, cumulative_sent,
cumulative_sent + cumulative_receive, cumulative_sent + cumulative_receive,
data_usage[i][0],)) data_usage[i][0],))
sqldb.commit()
total_sent = 0 total_sent = 0
total_receive = 0 total_receive = 0
print(data_usage[i][0])
_, p = self.searchPeer(data_usage[i][0]) _, p = self.searchPeer(data_usage[i][0])
if p.total_receive != total_receive or p.total_sent != total_sent: if p.total_receive != total_receive or p.total_sent != total_sent:
sqldb.cursor().execute( sqldb.cursor().execute(
"UPDATE '%s' SET total_receive = ?, total_sent = ?, total_data = ? WHERE id = ?" "UPDATE '%s' SET total_receive = ?, total_sent = ?, total_data = ? WHERE id = ?"
% self.Name, (total_receive, total_sent, % self.Name, (total_receive, total_sent,
total_receive + total_sent, data_usage[i][0],)) total_receive + total_sent, data_usage[i][0],))
sqldb.commit()
except Exception as e: except Exception as e:
print("Error: " + str(e)) traceback.print_exc()
print(f"[WGDashboard] {self.Name} Error: {str(e)} {str(e.__traceback__)}")
def getPeersEndpoint(self): def getPeersEndpoint(self):
if not self.getStatus(): if not self.getStatus():