mirror of
https://github.com/donaldzou/WGDashboard.git
synced 2025-10-03 07:46:18 +00:00
Update
This commit is contained in:
@@ -1555,7 +1555,6 @@ Index Page
|
|||||||
|
|
||||||
@app.get(f'{APP_PREFIX}/')
|
@app.get(f'{APP_PREFIX}/')
|
||||||
def index():
|
def index():
|
||||||
app.logger.info('hi')
|
|
||||||
return render_template('index.html')
|
return render_template('index.html')
|
||||||
|
|
||||||
def peerInformationBackgroundThread():
|
def peerInformationBackgroundThread():
|
||||||
@@ -1581,7 +1580,7 @@ def peerInformationBackgroundThread():
|
|||||||
c.logPeersHistoryEndpoint()
|
c.logPeersHistoryEndpoint()
|
||||||
c.getRestrictedPeersList()
|
c.getRestrictedPeersList()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[WGDashboard] Background Thread #1 Error: {str(e)}", flush=True)
|
app.logger.error(f"[WGDashboard] Background Thread #1 Error", e)
|
||||||
|
|
||||||
if delay == 6:
|
if delay == 6:
|
||||||
delay = 1
|
delay = 1
|
||||||
@@ -1595,8 +1594,11 @@ def peerJobScheduleBackgroundThread():
|
|||||||
app.logger.info(f"Background Thread #2 PID:" + str(threading.get_native_id()))
|
app.logger.info(f"Background Thread #2 PID:" + str(threading.get_native_id()))
|
||||||
time.sleep(10)
|
time.sleep(10)
|
||||||
while True:
|
while True:
|
||||||
|
try:
|
||||||
AllPeerJobs.runJob()
|
AllPeerJobs.runJob()
|
||||||
time.sleep(180)
|
time.sleep(180)
|
||||||
|
except Exception as e:
|
||||||
|
app.logger.error("Background Thread #2 Error", e)
|
||||||
|
|
||||||
def gunicornConfig():
|
def gunicornConfig():
|
||||||
_, app_ip = DashboardConfig.GetConfig("Server", "app_ip")
|
_, app_ip = DashboardConfig.GetConfig("Server", "app_ip")
|
||||||
@@ -1622,11 +1624,13 @@ def InitWireguardConfigurationsList(startup: bool = False):
|
|||||||
try:
|
try:
|
||||||
if i in WireguardConfigurations.keys():
|
if i in WireguardConfigurations.keys():
|
||||||
if WireguardConfigurations[i].configurationFileChanged():
|
if WireguardConfigurations[i].configurationFileChanged():
|
||||||
|
with app.app_context():
|
||||||
WireguardConfigurations[i] = WireguardConfiguration(DashboardConfig, AllPeerJobs, AllPeerShareLinks, DashboardWebHooks, i)
|
WireguardConfigurations[i] = WireguardConfiguration(DashboardConfig, AllPeerJobs, AllPeerShareLinks, DashboardWebHooks, i)
|
||||||
else:
|
else:
|
||||||
|
with app.app_context():
|
||||||
WireguardConfigurations[i] = WireguardConfiguration(DashboardConfig, AllPeerJobs, AllPeerShareLinks, DashboardWebHooks, i, startup=startup)
|
WireguardConfigurations[i] = WireguardConfiguration(DashboardConfig, AllPeerJobs, AllPeerShareLinks, DashboardWebHooks, i, startup=startup)
|
||||||
except WireguardConfiguration.InvalidConfigurationFileException as e:
|
except WireguardConfiguration.InvalidConfigurationFileException as e:
|
||||||
print(f"{i} have an invalid configuration file.")
|
app.logger.error(f"{i} have an invalid configuration file.")
|
||||||
|
|
||||||
if "awg" in ProtocolsEnabled():
|
if "awg" in ProtocolsEnabled():
|
||||||
confs = os.listdir(DashboardConfig.GetConfig("Server", "awg_conf_path")[1])
|
confs = os.listdir(DashboardConfig.GetConfig("Server", "awg_conf_path")[1])
|
||||||
@@ -1637,11 +1641,13 @@ def InitWireguardConfigurationsList(startup: bool = False):
|
|||||||
try:
|
try:
|
||||||
if i in WireguardConfigurations.keys():
|
if i in WireguardConfigurations.keys():
|
||||||
if WireguardConfigurations[i].configurationFileChanged():
|
if WireguardConfigurations[i].configurationFileChanged():
|
||||||
|
with app.app_context():
|
||||||
WireguardConfigurations[i] = AmneziaWireguardConfiguration(DashboardConfig, AllPeerJobs, AllPeerShareLinks, DashboardWebHooks, i)
|
WireguardConfigurations[i] = AmneziaWireguardConfiguration(DashboardConfig, AllPeerJobs, AllPeerShareLinks, DashboardWebHooks, i)
|
||||||
else:
|
else:
|
||||||
|
with app.app_context():
|
||||||
WireguardConfigurations[i] = AmneziaWireguardConfiguration(DashboardConfig, AllPeerJobs, AllPeerShareLinks, DashboardWebHooks, i, startup=startup)
|
WireguardConfigurations[i] = AmneziaWireguardConfiguration(DashboardConfig, AllPeerJobs, AllPeerShareLinks, DashboardWebHooks, i, startup=startup)
|
||||||
except WireguardConfiguration.InvalidConfigurationFileException as e:
|
except WireguardConfiguration.InvalidConfigurationFileException as e:
|
||||||
print(f"{i} have an invalid configuration file.")
|
app.logger.error(f"{i} have an invalid configuration file.")
|
||||||
|
|
||||||
|
|
||||||
_, app_ip = DashboardConfig.GetConfig("Server", "app_ip")
|
_, app_ip = DashboardConfig.GetConfig("Server", "app_ip")
|
||||||
@@ -1650,17 +1656,14 @@ _, WG_CONF_PATH = DashboardConfig.GetConfig("Server", "wg_conf_path")
|
|||||||
|
|
||||||
WireguardConfigurations: dict[str, WireguardConfiguration] = {}
|
WireguardConfigurations: dict[str, WireguardConfiguration] = {}
|
||||||
|
|
||||||
AllPeerShareLinks: PeerShareLinks = PeerShareLinks(DashboardConfig, WireguardConfigurations)
|
|
||||||
AllPeerJobs: PeerJobs = PeerJobs(DashboardConfig, WireguardConfigurations)
|
|
||||||
DashboardLogger: DashboardLogger = DashboardLogger()
|
|
||||||
DashboardPlugins: DashboardPlugins = DashboardPlugins(app, WireguardConfigurations)
|
|
||||||
DashboardWebHooks: DashboardWebHooks = DashboardWebHooks(DashboardConfig)
|
|
||||||
NewConfigurationTemplates: NewConfigurationTemplates = NewConfigurationTemplates()
|
|
||||||
|
|
||||||
InitWireguardConfigurationsList(startup=True)
|
|
||||||
|
|
||||||
|
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
|
AllPeerShareLinks: PeerShareLinks = PeerShareLinks(DashboardConfig, WireguardConfigurations)
|
||||||
|
AllPeerJobs: PeerJobs = PeerJobs(DashboardConfig, WireguardConfigurations)
|
||||||
|
DashboardLogger: DashboardLogger = DashboardLogger()
|
||||||
|
DashboardPlugins: DashboardPlugins = DashboardPlugins(app, WireguardConfigurations)
|
||||||
|
DashboardWebHooks: DashboardWebHooks = DashboardWebHooks(DashboardConfig)
|
||||||
|
NewConfigurationTemplates: NewConfigurationTemplates = NewConfigurationTemplates()
|
||||||
|
InitWireguardConfigurationsList(startup=True)
|
||||||
DashboardClients: DashboardClients = DashboardClients(WireguardConfigurations)
|
DashboardClients: DashboardClients = DashboardClients(WireguardConfigurations)
|
||||||
app.register_blueprint(createClientBlueprint(WireguardConfigurations, DashboardConfig, DashboardClients))
|
app.register_blueprint(createClientBlueprint(WireguardConfigurations, DashboardConfig, DashboardClients))
|
||||||
|
|
||||||
@@ -1673,5 +1676,5 @@ def startThreads():
|
|||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
startThreads()
|
startThreads()
|
||||||
DashboardPlugins.startThreads()
|
DashboardPlugins.startThreads()
|
||||||
app.logger.addHandler(logging.StreamHandler())
|
# app.logger.addHandler(logging.StreamHandler())
|
||||||
app.run(host=app_ip, debug=False, port=app_port)
|
app.run(host=app_ip, debug=False, port=app_port)
|
@@ -1,5 +1,4 @@
|
|||||||
import os.path
|
import dashboard
|
||||||
import dashboard, configparser
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
global sqldb, cursor, DashboardConfig, WireguardConfigurations, AllPeerJobs, JobLogger, Dash
|
global sqldb, cursor, DashboardConfig, WireguardConfigurations, AllPeerJobs, JobLogger, Dash
|
||||||
app_host, app_port = dashboard.gunicornConfig()
|
app_host, app_port = dashboard.gunicornConfig()
|
||||||
|
@@ -2,7 +2,7 @@
|
|||||||
AmneziaWG Configuration
|
AmneziaWG Configuration
|
||||||
"""
|
"""
|
||||||
import random, sqlalchemy, os, subprocess, re, uuid
|
import random, sqlalchemy, os, subprocess, re, uuid
|
||||||
|
from flask import current_app
|
||||||
from .PeerJobs import PeerJobs
|
from .PeerJobs import PeerJobs
|
||||||
from .AmneziaWGPeer import AmneziaWGPeer
|
from .AmneziaWGPeer import AmneziaWGPeer
|
||||||
from .PeerShareLinks import PeerShareLinks
|
from .PeerShareLinks import PeerShareLinks
|
||||||
@@ -250,10 +250,8 @@ class AmneziaWireguardConfiguration(WireguardConfiguration):
|
|||||||
)
|
)
|
||||||
self.Peers.append(AmneziaWGPeer(tempPeer, self))
|
self.Peers.append(AmneziaWGPeer(tempPeer, self))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if __name__ == '__main__':
|
current_app.logger.error(f"{self.Name} getPeers() Error", e)
|
||||||
print(f"[WGDashboard] {self.Name} getPeers() Error: {str(e)}")
|
|
||||||
else:
|
else:
|
||||||
# checkIfExist = sqlSelect("SELECT * FROM '%s'" % self.Name).fetchall()
|
|
||||||
with self.engine.connect() as conn:
|
with self.engine.connect() as conn:
|
||||||
existingPeers = conn.execute(self.peersTable.select()).mappings().fetchall()
|
existingPeers = conn.execute(self.peersTable.select()).mappings().fetchall()
|
||||||
for i in existingPeers:
|
for i in existingPeers:
|
||||||
|
@@ -1,7 +1,9 @@
|
|||||||
import configparser
|
import configparser
|
||||||
import os
|
import os
|
||||||
from sqlalchemy_utils import database_exists, create_database
|
from sqlalchemy_utils import database_exists, create_database
|
||||||
def ConnectionString(database) -> str or None:
|
from flask import current_app
|
||||||
|
|
||||||
|
def ConnectionString(database) -> str:
|
||||||
parser = configparser.ConfigParser(strict=False)
|
parser = configparser.ConfigParser(strict=False)
|
||||||
parser.read_file(open('wg-dashboard.ini', "r+"))
|
parser.read_file(open('wg-dashboard.ini', "r+"))
|
||||||
sqlitePath = os.path.join("db")
|
sqlitePath = os.path.join("db")
|
||||||
@@ -10,14 +12,14 @@ def ConnectionString(database) -> str or None:
|
|||||||
if parser.get("Database", "type") == "postgresql":
|
if parser.get("Database", "type") == "postgresql":
|
||||||
cn = f'postgresql+psycopg://{parser.get("Database", "username")}:{parser.get("Database", "password")}@{parser.get("Database", "host")}/{database}'
|
cn = f'postgresql+psycopg://{parser.get("Database", "username")}:{parser.get("Database", "password")}@{parser.get("Database", "host")}/{database}'
|
||||||
elif parser.get("Database", "type") == "mysql":
|
elif parser.get("Database", "type") == "mysql":
|
||||||
cn = f'mysql+mysqldb://{parser.get("Database", "username")}:{parser.get("Database", "password")}@{parser.get("Database", "host")}/{database}'
|
cn = f'mysql+pymysql://{parser.get("Database", "username")}:{parser.get("Database", "password")}@{parser.get("Database", "host")}/{database}'
|
||||||
else:
|
else:
|
||||||
cn = f'sqlite:///{os.path.join(sqlitePath, f"{database}.db")}'
|
cn = f'sqlite:///{os.path.join(sqlitePath, f"{database}.db")}'
|
||||||
try:
|
try:
|
||||||
if not database_exists(cn):
|
if not database_exists(cn):
|
||||||
create_database(cn)
|
create_database(cn)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("[WGDashboard] Database error: " + str(e))
|
current_app.logger.error("Database error. Terminating...", e)
|
||||||
exit(1)
|
exit(1)
|
||||||
|
|
||||||
return cn
|
return cn
|
@@ -210,7 +210,6 @@ class DashboardClients:
|
|||||||
if not status:
|
if not status:
|
||||||
return False, "Sign in failed. Reason: " + data
|
return False, "Sign in failed. Reason: " + data
|
||||||
existingClient = self.SignIn_OIDC_UserExistence(data)
|
existingClient = self.SignIn_OIDC_UserExistence(data)
|
||||||
print(data)
|
|
||||||
if not existingClient:
|
if not existingClient:
|
||||||
status, newClientUUID = self.SignUp_OIDC(data)
|
status, newClientUUID = self.SignUp_OIDC(data)
|
||||||
session['ClientID'] = newClientUUID
|
session['ClientID'] = newClientUUID
|
||||||
|
@@ -6,7 +6,7 @@ from sqlalchemy_utils import database_exists, create_database
|
|||||||
import sqlalchemy as db
|
import sqlalchemy as db
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
from flask import current_app
|
||||||
from .ConnectionString import ConnectionString
|
from .ConnectionString import ConnectionString
|
||||||
from .Utilities import (
|
from .Utilities import (
|
||||||
GetRemoteEndpoint, ValidateDNSAddress
|
GetRemoteEndpoint, ValidateDNSAddress
|
||||||
@@ -141,7 +141,7 @@ class DashboardConfig:
|
|||||||
fKeys.append(DashboardAPIKey(k[0], k[1].strftime("%Y-%m-%d %H:%M:%S"), (k[2].strftime("%Y-%m-%d %H:%M:%S") if k[2] else None)))
|
fKeys.append(DashboardAPIKey(k[0], k[1].strftime("%Y-%m-%d %H:%M:%S"), (k[2].strftime("%Y-%m-%d %H:%M:%S") if k[2] else None)))
|
||||||
return fKeys
|
return fKeys
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(e)
|
current_app.logger.error("API Keys error", e)
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def createAPIKeys(self, ExpiredAt = None):
|
def createAPIKeys(self, ExpiredAt = None):
|
||||||
|
@@ -3,7 +3,7 @@ Dashboard Logger Class
|
|||||||
"""
|
"""
|
||||||
import uuid
|
import uuid
|
||||||
import sqlalchemy as db
|
import sqlalchemy as db
|
||||||
|
from flask import current_app
|
||||||
from .ConnectionString import ConnectionString
|
from .ConnectionString import ConnectionString
|
||||||
|
|
||||||
|
|
||||||
@@ -40,5 +40,5 @@ class DashboardLogger:
|
|||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[WGDashboard] Access Log Error: {str(e)}")
|
current_app.logger.error(f"Access Log Error", e)
|
||||||
return False
|
return False
|
@@ -69,10 +69,9 @@ class DashboardOIDC:
|
|||||||
try:
|
try:
|
||||||
tokens = requests.post(oidc_config.get('token_endpoint'), data=data).json()
|
tokens = requests.post(oidc_config.get('token_endpoint'), data=data).json()
|
||||||
if not all([tokens.get('access_token'), tokens.get('id_token')]):
|
if not all([tokens.get('access_token'), tokens.get('id_token')]):
|
||||||
print(oidc_config.get('token_endpoint'), data)
|
|
||||||
return False, tokens.get('error_description', None)
|
return False, tokens.get('error_description', None)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(str(e))
|
current_app.logger.error("Verify token failed", e)
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
|
|
||||||
access_token = tokens.get('access_token')
|
access_token = tokens.get('access_token')
|
||||||
|
@@ -9,6 +9,7 @@ import requests
|
|||||||
from pydantic import BaseModel, field_serializer
|
from pydantic import BaseModel, field_serializer
|
||||||
import sqlalchemy as db
|
import sqlalchemy as db
|
||||||
from .ConnectionString import ConnectionString
|
from .ConnectionString import ConnectionString
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
WebHookActions = ['peer_created', 'peer_deleted', 'peer_updated']
|
WebHookActions = ['peer_created', 'peer_deleted', 'peer_updated']
|
||||||
class WebHook(BaseModel):
|
class WebHook(BaseModel):
|
||||||
@@ -173,19 +174,19 @@ class DashboardWebHooks:
|
|||||||
if action not in WebHookActions:
|
if action not in WebHookActions:
|
||||||
return False
|
return False
|
||||||
self.__getWebHooks()
|
self.__getWebHooks()
|
||||||
subscribedWebHooks = filter(lambda webhook: action in webhook.SubscribedActions and webhook.IsActive, self.WebHooks)
|
subscribedWebHooks = filter(lambda webhook: action in webhook.SubscribedActions and webhook.IsActive,
|
||||||
|
self.WebHooks)
|
||||||
data['action'] = action
|
data['action'] = action
|
||||||
for i in subscribedWebHooks:
|
for i in subscribedWebHooks:
|
||||||
try:
|
try:
|
||||||
ws = WebHookSession(i, data)
|
ws = WebHookSession(i, data)
|
||||||
t = threading.Thread(target=ws.Execute, daemon=True)
|
t = threading.Thread(target=ws.Execute, daemon=True)
|
||||||
t.start()
|
t.start()
|
||||||
print("Spinning threads...")
|
current_app.logger.info(f"Requesting {i.PayloadURL}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(e)
|
current_app.logger.error(f"Requesting {i.PayloadURL} error", e)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(e)
|
current_app.logger.error("Error when running WebHook")
|
||||||
return True
|
|
||||||
|
|
||||||
class WebHookSession:
|
class WebHookSession:
|
||||||
def __init__(self, webHook: WebHook, data: dict[str, str]):
|
def __init__(self, webHook: WebHook, data: dict[str, str]):
|
||||||
|
@@ -3,7 +3,7 @@ Peer Job Logger
|
|||||||
"""
|
"""
|
||||||
import uuid
|
import uuid
|
||||||
import sqlalchemy as db
|
import sqlalchemy as db
|
||||||
|
from flask import current_app
|
||||||
from .ConnectionString import ConnectionString
|
from .ConnectionString import ConnectionString
|
||||||
from .Log import Log
|
from .Log import Log
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ class PeerJobLogger:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[WGDashboard] Peer Job Log Error: {str(e)}")
|
current_app.logger.error(f"Peer Job Log Error", e)
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -54,6 +54,6 @@ class PeerJobLogger:
|
|||||||
logs.append(
|
logs.append(
|
||||||
Log(l.LogID, l.JobID, l.LogDate.strftime("%Y-%m-%d %H:%M:%S"), l.Status, l.Message))
|
Log(l.LogID, l.JobID, l.LogDate.strftime("%Y-%m-%d %H:%M:%S"), l.Status, l.Message))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(e)
|
current_app.logger.error(f"Getting Peer Job Log Error", e)
|
||||||
return logs
|
return logs
|
||||||
return logs
|
return logs
|
@@ -6,6 +6,7 @@ from .PeerJob import PeerJob
|
|||||||
from .PeerJobLogger import PeerJobLogger
|
from .PeerJobLogger import PeerJobLogger
|
||||||
import sqlalchemy as db
|
import sqlalchemy as db
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
class PeerJobs:
|
class PeerJobs:
|
||||||
def __init__(self, DashboardConfig, WireguardConfigurations):
|
def __init__(self, DashboardConfig, WireguardConfigurations):
|
||||||
@@ -140,7 +141,7 @@ class PeerJobs:
|
|||||||
|
|
||||||
|
|
||||||
def runJob(self):
|
def runJob(self):
|
||||||
print("[WGDashboard] Running scheduled jobs")
|
current_app.logger.info("Running scheduled jobs")
|
||||||
needToDelete = []
|
needToDelete = []
|
||||||
self.__getJobs()
|
self.__getJobs()
|
||||||
for job in self.Jobs:
|
for job in self.Jobs:
|
||||||
@@ -166,25 +167,24 @@ class PeerJobs:
|
|||||||
s = fp.resetDataUsage("total")
|
s = fp.resetDataUsage("total")
|
||||||
c.restrictPeers([fp.id])
|
c.restrictPeers([fp.id])
|
||||||
c.allowAccessPeers([fp.id])
|
c.allowAccessPeers([fp.id])
|
||||||
|
|
||||||
if s is True:
|
if s is True:
|
||||||
self.JobLogger.log(job.JobID, s,
|
self.JobLogger.log(job.JobID, s,
|
||||||
f"Peer {fp.id} from {c.Name} is successfully {job.Action}ed."
|
f"Peer {fp.id} from {c.Name} is successfully {job.Action}ed."
|
||||||
)
|
)
|
||||||
print(f"[WGDashboard] Peer {fp.id} from {c.Name} is successfully {job.Action}ed.")
|
current_app.logger.info(f"Peer {fp.id} from {c.Name} is successfully {job.Action}ed.")
|
||||||
needToDelete.append(job)
|
needToDelete.append(job)
|
||||||
else:
|
else:
|
||||||
print(f"[WGDashboard] Peer {fp.id} from {c.Name} is failed {job.Action}ed.")
|
current_app.logger.info(f"Peer {fp.id} from {c.Name} is failed {job.Action}ed.")
|
||||||
self.JobLogger.log(job.JobID, s,
|
self.JobLogger.log(job.JobID, s,
|
||||||
f"Peer {fp.id} from {c.Name} failed {job.Action}ed."
|
f"Peer {fp.id} from {c.Name} failed {job.Action}ed."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
print(f"[WGDashboard] Somehow can't find this peer {job.Peer} from {c.Name} failed {job.Action}ed.")
|
current_app.logger.warning(f"Somehow can't find this peer {job.Peer} from {c.Name} failed {job.Action}ed.")
|
||||||
self.JobLogger.log(job.JobID, False,
|
self.JobLogger.log(job.JobID, False,
|
||||||
f"Somehow can't find this peer {job.Peer} from {c.Name} failed {job.Action}ed."
|
f"Somehow can't find this peer {job.Peer} from {c.Name} failed {job.Action}ed."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
print(f"[WGDashboard] Somehow can't find this peer {job.Peer} from {c.Name} failed {job.Action}ed.")
|
current_app.logger.warning(f"Somehow can't find this peer {job.Peer} from {c.Name} failed {job.Action}ed.")
|
||||||
self.JobLogger.log(job.JobID, False,
|
self.JobLogger.log(job.JobID, False,
|
||||||
f"Somehow can't find this peer {job.Peer} from {job.Configuration} failed {job.Action}ed."
|
f"Somehow can't find this peer {job.Peer} from {job.Configuration} failed {job.Action}ed."
|
||||||
)
|
)
|
||||||
|
@@ -1,8 +1,6 @@
|
|||||||
import shutil
|
import shutil, subprocess, time, threading, psutil
|
||||||
import subprocess
|
from flask import current_app
|
||||||
import time
|
|
||||||
import threading
|
|
||||||
import psutil
|
|
||||||
class SystemStatus:
|
class SystemStatus:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.CPU = CPU()
|
self.CPU = CPU()
|
||||||
@@ -40,28 +38,20 @@ class CPU:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.cpu_percent: float = 0
|
self.cpu_percent: float = 0
|
||||||
self.cpu_percent_per_cpu: list[float] = []
|
self.cpu_percent_per_cpu: list[float] = []
|
||||||
def getData(self):
|
|
||||||
pass
|
|
||||||
# try:
|
|
||||||
# self.cpu_percent_per_cpu = psutil.cpu_percent(interval=1, percpu=True)
|
|
||||||
#
|
|
||||||
# except Exception as e:
|
|
||||||
# pass
|
|
||||||
def getCPUPercent(self):
|
def getCPUPercent(self):
|
||||||
try:
|
try:
|
||||||
self.cpu_percent = psutil.cpu_percent(interval=1)
|
self.cpu_percent = psutil.cpu_percent(interval=1)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
current_app.logger.error("Get CPU Percent error", e)
|
||||||
|
|
||||||
def getPerCPUPercent(self):
|
def getPerCPUPercent(self):
|
||||||
try:
|
try:
|
||||||
self.cpu_percent_per_cpu = psutil.cpu_percent(interval=1, percpu=True)
|
self.cpu_percent_per_cpu = psutil.cpu_percent(interval=1, percpu=True)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
current_app.logger.error("Get Per CPU Percent error", e)
|
||||||
|
|
||||||
def toJson(self):
|
def toJson(self):
|
||||||
self.getData()
|
|
||||||
return self.__dict__
|
return self.__dict__
|
||||||
|
|
||||||
class Memory:
|
class Memory:
|
||||||
@@ -80,7 +70,7 @@ class Memory:
|
|||||||
self.available = memory.available
|
self.available = memory.available
|
||||||
self.percent = memory.percent
|
self.percent = memory.percent
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
current_app.logger.error("Get Memory percent error", e)
|
||||||
def toJson(self):
|
def toJson(self):
|
||||||
self.getData()
|
self.getData()
|
||||||
return self.__dict__
|
return self.__dict__
|
||||||
@@ -92,7 +82,7 @@ class Disks:
|
|||||||
try:
|
try:
|
||||||
self.disks = list(map(lambda x : Disk(x.mountpoint), psutil.disk_partitions()))
|
self.disks = list(map(lambda x : Disk(x.mountpoint), psutil.disk_partitions()))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
current_app.logger.error("Get Disk percent error", e)
|
||||||
def toJson(self):
|
def toJson(self):
|
||||||
self.getData()
|
self.getData()
|
||||||
return self.disks
|
return self.disks
|
||||||
@@ -112,7 +102,7 @@ class Disk:
|
|||||||
self.used = disk.used
|
self.used = disk.used
|
||||||
self.percent = disk.percent
|
self.percent = disk.percent
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
pass
|
current_app.logger.error("Get Disk percent error", e)
|
||||||
def toJson(self):
|
def toJson(self):
|
||||||
self.getData()
|
self.getData()
|
||||||
return self.__dict__
|
return self.__dict__
|
||||||
@@ -149,7 +139,8 @@ class NetworkInterfaces:
|
|||||||
'recv': round((network[i].bytes_recv - self.interfaces[i]['bytes_recv']) / 1024 / 1024, 4)
|
'recv': round((network[i].bytes_recv - self.interfaces[i]['bytes_recv']) / 1024 / 1024, 4)
|
||||||
}
|
}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(str(e))
|
current_app.logger.error("Get network error", e)
|
||||||
|
|
||||||
def toJson(self):
|
def toJson(self):
|
||||||
return self.interfaces
|
return self.interfaces
|
||||||
|
|
||||||
@@ -178,7 +169,8 @@ class Processes:
|
|||||||
key=lambda x : x.percent, reverse=True)[:20]
|
key=lambda x : x.percent, reverse=True)[:20]
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
break
|
current_app.logger.error("Get processes error", e)
|
||||||
|
|
||||||
def toJson(self):
|
def toJson(self):
|
||||||
self.getData()
|
self.getData()
|
||||||
return {
|
return {
|
||||||
|
@@ -8,6 +8,7 @@ import sqlalchemy, random, shutil, configparser, ipaddress, os, subprocess, time
|
|||||||
from zipfile import ZipFile
|
from zipfile import ZipFile
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from itertools import islice
|
from itertools import islice
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
from .ConnectionString import ConnectionString
|
from .ConnectionString import ConnectionString
|
||||||
from .DashboardConfig import DashboardConfig
|
from .DashboardConfig import DashboardConfig
|
||||||
@@ -120,17 +121,17 @@ class WireguardConfiguration:
|
|||||||
self.createDatabase()
|
self.createDatabase()
|
||||||
with open(self.configPath, "w+") as configFile:
|
with open(self.configPath, "w+") as configFile:
|
||||||
self.__parser.write(configFile)
|
self.__parser.write(configFile)
|
||||||
print(f"[WGDashboard] Configuration file {self.configPath} created")
|
current_app.logger.info(f"Configuration file {self.configPath} created")
|
||||||
self.__initPeersList()
|
self.__initPeersList()
|
||||||
|
|
||||||
if not os.path.exists(os.path.join(self.__getProtocolPath(), 'WGDashboard_Backup')):
|
if not os.path.exists(os.path.join(self.__getProtocolPath(), 'WGDashboard_Backup')):
|
||||||
os.mkdir(os.path.join(self.__getProtocolPath(), 'WGDashboard_Backup'))
|
os.mkdir(os.path.join(self.__getProtocolPath(), 'WGDashboard_Backup'))
|
||||||
|
|
||||||
print(f"[WGDashboard] Initialized Configuration: {name}")
|
current_app.logger.info(f"Initialized Configuration: {name}")
|
||||||
self.__dumpDatabase()
|
self.__dumpDatabase()
|
||||||
if self.getAutostartStatus() and not self.getStatus() and startup:
|
if self.getAutostartStatus() and not self.getStatus() and startup:
|
||||||
self.toggleConfiguration()
|
self.toggleConfiguration()
|
||||||
print(f"[WGDashboard] Autostart Configuration: {name}")
|
current_app.logger.info(f"Autostart Configuration: {name}")
|
||||||
|
|
||||||
self.configurationInfo: WireguardConfigurationInfo | None = None
|
self.configurationInfo: WireguardConfigurationInfo | None = None
|
||||||
configurationInfoJson = self.readConfigurationInfo()
|
configurationInfoJson = self.readConfigurationInfo()
|
||||||
@@ -170,7 +171,7 @@ class WireguardConfiguration:
|
|||||||
status, err = self.toggleConfiguration()
|
status, err = self.toggleConfiguration()
|
||||||
if not status:
|
if not status:
|
||||||
restoreStatus = self.restoreBackup(backup['filename'])
|
restoreStatus = self.restoreBackup(backup['filename'])
|
||||||
print(f"Restore status: {restoreStatus}")
|
current_app.logger.error(f"Backup restore status: {restoreStatus}")
|
||||||
self.toggleConfiguration()
|
self.toggleConfiguration()
|
||||||
return False, err
|
return False, err
|
||||||
return True, None
|
return True, None
|
||||||
@@ -228,7 +229,7 @@ class WireguardConfiguration:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("[WGDashboard] Error: Drop table failed - " + str(e))
|
current_app.logger.error("Dropping table failed")
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@@ -403,6 +404,7 @@ class WireguardConfiguration:
|
|||||||
pCounter = -1
|
pCounter = -1
|
||||||
content = configFile.read().split('\n')
|
content = configFile.read().split('\n')
|
||||||
try:
|
try:
|
||||||
|
if "[Peer]" in content:
|
||||||
peerStarts = content.index("[Peer]")
|
peerStarts = content.index("[Peer]")
|
||||||
content = content[peerStarts:]
|
content = content[peerStarts:]
|
||||||
for i in content:
|
for i in content:
|
||||||
@@ -468,8 +470,10 @@ class WireguardConfiguration:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
tmpList.append(Peer(tempPeer, self))
|
tmpList.append(Peer(tempPeer, self))
|
||||||
|
else:
|
||||||
|
current_app.logger.warning(f"{self.Name} is an empty configuration")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[WGDashboard] {self.Name} getPeers() Error: {str(e)}")
|
current_app.logger.error(f"{self.Name} getPeers() Error", e)
|
||||||
else:
|
else:
|
||||||
with self.engine.connect() as conn:
|
with self.engine.connect() as conn:
|
||||||
existingPeers = conn.execute(self.peersTable.select()).mappings().fetchall()
|
existingPeers = conn.execute(self.peersTable.select()).mappings().fetchall()
|
||||||
@@ -1074,7 +1078,7 @@ class WireguardConfiguration:
|
|||||||
check = ipaddress.ip_network(ppip[0])
|
check = ipaddress.ip_network(ppip[0])
|
||||||
existedAddress.add(check)
|
existedAddress.add(check)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[WGDashboard] Error: {self.Name} peer {p.id} have invalid ip")
|
current_app.logger.error(f"{self.Name} peer {p.id} have invalid ip", e)
|
||||||
configurationAddresses = self.Address.split(',')
|
configurationAddresses = self.Address.split(',')
|
||||||
for ca in configurationAddresses:
|
for ca in configurationAddresses:
|
||||||
ca = ca.strip()
|
ca = ca.strip()
|
||||||
@@ -1088,8 +1092,7 @@ class WireguardConfiguration:
|
|||||||
if p.version == network.version and p.subnet_of(network):
|
if p.version == network.version and p.subnet_of(network):
|
||||||
availableAddress[ca] -= 1
|
availableAddress[ca] -= 1
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(e)
|
current_app.logger.error(f"Error: Failed to parse IP address {ca} from {self.Name}", e)
|
||||||
print(f"[WGDashboard] Error: Failed to parse IP address {ca} from {self.Name}")
|
|
||||||
return True, availableAddress
|
return True, availableAddress
|
||||||
|
|
||||||
def getAvailableIP(self, threshold = 255):
|
def getAvailableIP(self, threshold = 255):
|
||||||
@@ -1106,7 +1109,7 @@ class WireguardConfiguration:
|
|||||||
check = ipaddress.ip_network(ppip[0])
|
check = ipaddress.ip_network(ppip[0])
|
||||||
existedAddress.add(check.compressed)
|
existedAddress.add(check.compressed)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[WGDashboard] Error: {self.Name} peer {p.id} have invalid ip")
|
current_app.logger.error(f"{self.Name} peer {p.id} have invalid ip", e)
|
||||||
configurationAddresses = self.Address.split(',')
|
configurationAddresses = self.Address.split(',')
|
||||||
for ca in configurationAddresses:
|
for ca in configurationAddresses:
|
||||||
ca = ca.strip()
|
ca = ca.strip()
|
||||||
@@ -1122,8 +1125,7 @@ class WireguardConfiguration:
|
|||||||
availableAddress[ca] = list(islice(filter(lambda ip : ip not in existedAddress,
|
availableAddress[ca] = list(islice(filter(lambda ip : ip not in existedAddress,
|
||||||
map(lambda iph : ipaddress.ip_network(iph).compressed, network.hosts())), threshold))
|
map(lambda iph : ipaddress.ip_network(iph).compressed, network.hosts())), threshold))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(e)
|
current_app.logger.error(f"Failed to parse IP address {ca} from {self.Name}", e)
|
||||||
print(f"[WGDashboard] Error: Failed to parse IP address {ca} from {self.Name}")
|
|
||||||
return True, availableAddress
|
return True, availableAddress
|
||||||
|
|
||||||
def getRealtimeTrafficUsage(self):
|
def getRealtimeTrafficUsage(self):
|
||||||
|
@@ -19,8 +19,3 @@ class WireguardConfigurationInfo(BaseModel):
|
|||||||
Description: str = ''
|
Description: str = ''
|
||||||
OverridePeerSettings: OverridePeerSettingsClass = OverridePeerSettingsClass(**{})
|
OverridePeerSettings: OverridePeerSettingsClass = OverridePeerSettingsClass(**{})
|
||||||
PeerGroups: dict[str, PeerGroupsClass] = {}
|
PeerGroups: dict[str, PeerGroupsClass] = {}
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
d = WireguardConfigurationInfo.model_validate_json("")
|
|
||||||
print(d.model_dump())
|
|
@@ -11,7 +11,7 @@ tcconfig
|
|||||||
sqlalchemy
|
sqlalchemy
|
||||||
sqlalchemy_utils
|
sqlalchemy_utils
|
||||||
psycopg
|
psycopg
|
||||||
mysqlclient
|
PyMySQL
|
||||||
tzlocal
|
tzlocal
|
||||||
python-jose
|
python-jose
|
||||||
pydantic
|
pydantic
|
Reference in New Issue
Block a user