Optimized loading speed for peer information

This commit is contained in:
Donald Zou 2025-08-06 17:27:14 +08:00
parent 1c857c0781
commit d96b178a9c
6 changed files with 22 additions and 17 deletions

View File

@ -609,7 +609,7 @@ def API_sharePeer_update():
ShareID: str = data.get("ShareID") ShareID: str = data.get("ShareID")
ExpireDate: str = data.get("ExpireDate") ExpireDate: str = data.get("ExpireDate")
if ShareID is None: if not all([ShareID, ExpireDate]):
return ResponseObject(False, "Please specify ShareID") return ResponseObject(False, "Please specify ShareID")
if len(AllPeerShareLinks.getLinkByID(ShareID)) == 0: if len(AllPeerShareLinks.getLinkByID(ShareID)) == 0:
@ -1348,7 +1348,7 @@ def peerInformationBackgroundThread():
c.getPeersTransfer() c.getPeersTransfer()
c.getPeersLatestHandshake() c.getPeersLatestHandshake()
c.getPeersEndpoint() c.getPeersEndpoint()
c.getPeersList() c.getPeers()
c.getRestrictedPeersList() c.getRestrictedPeersList()
time.sleep(10) time.sleep(10)
@ -1413,7 +1413,7 @@ _, WG_CONF_PATH = DashboardConfig.GetConfig("Server", "wg_conf_path")
WireguardConfigurations: dict[str, WireguardConfiguration] = {} WireguardConfigurations: dict[str, WireguardConfiguration] = {}
AllPeerShareLinks: PeerShareLinks = PeerShareLinks(DashboardConfig) AllPeerShareLinks: PeerShareLinks = PeerShareLinks(DashboardConfig, WireguardConfigurations)
AllPeerJobs: PeerJobs = PeerJobs(DashboardConfig, WireguardConfigurations) AllPeerJobs: PeerJobs = PeerJobs(DashboardConfig, WireguardConfigurations)
DashboardLogger: DashboardLogger = DashboardLogger() DashboardLogger: DashboardLogger = DashboardLogger()

View File

@ -353,7 +353,7 @@ class AmneziaWireguardConfiguration(WireguardConfiguration):
os.remove(uid) os.remove(uid)
subprocess.check_output( subprocess.check_output(
f"{self.Protocol}-quick save {self.Name}", shell=True, stderr=subprocess.STDOUT) f"{self.Protocol}-quick save {self.Name}", shell=True, stderr=subprocess.STDOUT)
self.getPeersList() self.getPeers()
for p in peers: for p in peers:
p = self.searchPeer(p['id']) p = self.searchPeer(p['id'])
if p[0]: if p[0]:

View File

@ -35,8 +35,8 @@ class Peer:
self.getShareLink() self.getShareLink()
def toJson(self): def toJson(self):
self.getJobs() # self.getJobs()
self.getShareLink() # self.getShareLink()
return self.__dict__ return self.__dict__
def __repr__(self): def __repr__(self):
@ -56,8 +56,10 @@ class Peer:
if allowed_ip in existingAllowedIps: if allowed_ip in existingAllowedIps:
return False, "Allowed IP already taken by another peer" return False, "Allowed IP already taken by another peer"
if not ValidateIPAddressesWithRange(endpoint_allowed_ip): if not ValidateIPAddressesWithRange(endpoint_allowed_ip):
return False, f"Endpoint Allowed IPs format is incorrect" return False, f"Endpoint Allowed IPs format is incorrect"
if len(dns_addresses) > 0 and not ValidateDNSAddress(dns_addresses): if len(dns_addresses) > 0 and not ValidateDNSAddress(dns_addresses):
return False, f"DNS format is incorrect" return False, f"DNS format is incorrect"

View File

@ -95,6 +95,7 @@ class PeerJobs:
) )
self.JobLogger.log(Job.JobID, Message=f"Job is updated from if {currentJob[0].Field} {currentJob[0].Operator} {currentJob[0].Value} then {currentJob[0].Action}; to if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}") self.JobLogger.log(Job.JobID, Message=f"Job is updated from if {currentJob[0].Field} {currentJob[0].Operator} {currentJob[0].Value} then {currentJob[0].Action}; to if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
self.__getJobs() self.__getJobs()
self.WireguardConfigurations.get(Job.Configuration).searchPeer(Job.Peer)[1].getJobs()
return True, list( return True, list(
filter(lambda x: x.Configuration == Job.Configuration and x.Peer == Job.Peer and x.JobID == Job.JobID, filter(lambda x: x.Configuration == Job.Configuration and x.Peer == Job.Peer and x.JobID == Job.JobID,
self.Jobs)) self.Jobs))
@ -116,6 +117,7 @@ class PeerJobs:
) )
self.JobLogger.log(Job.JobID, Message=f"Job is removed due to being deleted or finshed.") self.JobLogger.log(Job.JobID, Message=f"Job is removed due to being deleted or finshed.")
self.__getJobs() self.__getJobs()
self.WireguardConfigurations.get(Job.Configuration).searchPeer(Job.Peer)[1].getJobs()
return True, None return True, None
except Exception as e: except Exception as e:
return False, str(e) return False, str(e)

View File

@ -8,7 +8,7 @@ import uuid
Peer Share Links Peer Share Links
""" """
class PeerShareLinks: class PeerShareLinks:
def __init__(self, DashboardConfig): def __init__(self, DashboardConfig, WireguardConfigurations):
self.Links: list[PeerShareLink] = [] self.Links: list[PeerShareLink] = []
self.engine = db.create_engine(ConnectionString("wgdashboard")) self.engine = db.create_engine(ConnectionString("wgdashboard"))
self.metadata = db.MetaData() self.metadata = db.MetaData()
@ -23,6 +23,7 @@ class PeerShareLinks:
) )
self.metadata.create_all(self.engine) self.metadata.create_all(self.engine)
self.__getSharedLinks() self.__getSharedLinks()
self.wireguardConfigurations = WireguardConfigurations
def __getSharedLinks(self): def __getSharedLinks(self):
self.Links.clear() self.Links.clear()
with self.engine.connect() as conn: with self.engine.connect() as conn:
@ -68,18 +69,21 @@ class PeerShareLinks:
) )
) )
self.__getSharedLinks() self.__getSharedLinks()
self.wireguardConfigurations.get(Configuration).searchPeer(Peer)[1].getShareLink()
except Exception as e: except Exception as e:
return False, str(e) return False, str(e)
return True, newShareID return True, newShareID
def updateLinkExpireDate(self, ShareID, ExpireDate: datetime = None) -> tuple[bool, str]: def updateLinkExpireDate(self, ShareID, ExpireDate: datetime = None) -> tuple[bool, str]:
with self.engine.begin() as conn: with self.engine.begin() as conn:
conn.execute( updated = conn.execute(
self.peerShareLinksTable.update().values( self.peerShareLinksTable.update().values(
{ {
"ExpireDate": ExpireDate "ExpireDate": ExpireDate
} }
).where(db.and_(self.peerShareLinksTable.columns.ShareID == ShareID)) ).returning(self.peerShareLinksTable.c.Configuration, self.peerShareLinksTable.c.Peer)
) .where(self.peerShareLinksTable.columns.ShareID == ShareID)
).mappings().fetchone()
self.__getSharedLinks() self.__getSharedLinks()
self.wireguardConfigurations.get(updated.Configuration).searchPeer(updated.Peer)[1].getShareLink()
return True, "" return True, ""

View File

@ -73,9 +73,6 @@ class WireguardConfiguration:
self.__parseConfigurationFile() self.__parseConfigurationFile()
self.__initPeersList() self.__initPeersList()
else: else:
self.Name = data["ConfigurationName"] self.Name = data["ConfigurationName"]
self.configPath = os.path.join(self.__getProtocolPath(), f'{self.Name}.conf') self.configPath = os.path.join(self.__getProtocolPath(), f'{self.Name}.conf')
@ -132,7 +129,7 @@ class WireguardConfiguration:
def __initPeersList(self): def __initPeersList(self):
self.Peers: list[Peer] = [] self.Peers: list[Peer] = []
self.getPeersList() self.getPeers()
self.getRestrictedPeersList() self.getRestrictedPeersList()
def getRawConfigurationFile(self): def getRawConfigurationFile(self):
@ -350,7 +347,6 @@ class WireguardConfiguration:
return changed return changed
def getPeers(self): def getPeers(self):
# self.Peers = []
tmpList = [] tmpList = []
if self.configurationFileChanged(): if self.configurationFileChanged():
with open(self.configPath, 'r') as configFile: with open(self.configPath, 'r') as configFile:
@ -377,6 +373,8 @@ class WireguardConfiguration:
if len(split) == 2: if len(split) == 2:
p[pCounter]["name"] = split[1] p[pCounter]["name"] = split[1]
with self.engine.begin() as conn: with self.engine.begin() as conn:
for i in p: for i in p:
if "PublicKey" in i.keys(): if "PublicKey" in i.keys():
tempPeer = conn.execute(self.peersTable.select().where( tempPeer = conn.execute(self.peersTable.select().where(
@ -475,7 +473,7 @@ class WireguardConfiguration:
os.remove(uid) os.remove(uid)
subprocess.check_output( subprocess.check_output(
f"{self.Protocol}-quick save {self.Name}", shell=True, stderr=subprocess.STDOUT) f"{self.Protocol}-quick save {self.Name}", shell=True, stderr=subprocess.STDOUT)
self.getPeersList() self.getPeers()
for p in peers: for p in peers:
p = self.searchPeer(p['id']) p = self.searchPeer(p['id'])
if p[0]: if p[0]:
@ -758,7 +756,6 @@ class WireguardConfiguration:
return True, None return True, None
def getPeersList(self): def getPeersList(self):
self.getPeers()
return self.Peers return self.Peers
def getRestrictedPeersList(self) -> list: def getRestrictedPeersList(self) -> list: