trying something new

This commit is contained in:
Silversthorn 2022-05-25 15:54:35 +02:00
parent da483b9291
commit 5a1353373a
3 changed files with 91 additions and 108 deletions

View File

@ -66,11 +66,11 @@ class ServerStats(Model):
# Servers_Stats Methods # Servers_Stats Methods
# ********************************************************************************** # **********************************************************************************
class HelperServerStats: class HelperServerStats:
def __init__(self, database): def __init__(self, database, server_id):
self.database = database self.database = database
self.server_id = server_id
@staticmethod def init_database(self, server_id):
def init_database(server_id):
try: try:
server = HelperServers.get_server_data_by_id(server_id) server = HelperServers.get_server_data_by_id(server_id)
db_folder = os.path.join(f"{server['path']}", "db_stats") db_folder = os.path.join(f"{server['path']}", "db_stats")
@ -102,10 +102,9 @@ class HelperServerStats:
f"Error try to look for the db_stats files for server : {ex}" f"Error try to look for the db_stats files for server : {ex}"
) )
@staticmethod def select_database(self):
def select_database(server_id):
try: try:
server = HelperServers.get_server_data_by_id(server_id) server = HelperServers.get_server_data_by_id(self.server_id)
db_file = os.path.join( db_file = os.path.join(
f"{server['path']}", f"{server['path']}",
"db_stats", "db_stats",
@ -120,13 +119,12 @@ class HelperServerStats:
f"Error try to look for the db_stats files for server : {ex}" f"Error try to look for the db_stats files for server : {ex}"
) )
@staticmethod def get_all_servers_stats(self):
def get_all_servers_stats():
servers = HelperServers.get_all_defined_servers() servers = HelperServers.get_all_defined_servers()
server_data = [] server_data = []
try: try:
for s in servers: for s in servers:
HelperServerStats.select_database(s.get("server_id")) # self.select_database(s.get("server_id"))
latest = ( latest = (
ServerStats.select() ServerStats.select()
.where(ServerStats.server_id == s.get("server_id")) .where(ServerStats.server_id == s.get("server_id"))
@ -146,10 +144,9 @@ class HelperServerStats:
) )
return server_data return server_data
@staticmethod def insert_server_stats(self, server):
def insert_server_stats(server):
server_id = server.get("id", 0) server_id = server.get("id", 0)
HelperServerStats.select_database(server_id) # self.select_database(server_id)
if server_id == 0: if server_id == 0:
logger.warning("Stats saving failed with error: Server unknown (id = 0)") logger.warning("Stats saving failed with error: Server unknown (id = 0)")
@ -175,174 +172,158 @@ class HelperServerStats:
} }
).execute() ).execute()
@staticmethod def remove_old_stats(self, last_week):
def remove_old_stats(server_id, last_week): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
ServerStats.delete().where(ServerStats.created < last_week).execute() ServerStats.delete().where(ServerStats.created < last_week).execute()
@staticmethod def get_latest_server_stats(self):
def get_latest_server_stats(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
return ( return (
ServerStats.select() ServerStats.select()
.where(ServerStats.server_id == server_id) .where(ServerStats.server_id == self.server_id)
.order_by(ServerStats.created.desc()) .order_by(ServerStats.created.desc())
.limit(1) .limit(1)
) )
@staticmethod def get_server_stats_by_id(self):
def get_server_stats_by_id(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
stats = ( stats = (
ServerStats.select() ServerStats.select()
.where(ServerStats.server_id == server_id) .where(ServerStats.server_id == self.server_id)
.order_by(ServerStats.created.desc()) .order_by(ServerStats.created.desc())
.limit(1) .limit(1)
) )
return DatabaseShortcuts.return_rows(stats)[0] return DatabaseShortcuts.return_rows(stats)[0]
@staticmethod def server_id_exists(self):
def server_id_exists(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id) if not HelperServers.get_server_data_by_id(self.server_id):
if not HelperServers.get_server_data_by_id(server_id):
return False return False
return True return True
@staticmethod def sever_crashed(self):
def sever_crashed(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
ServerStats.update(crashed=True).where( ServerStats.update(crashed=True).where(
ServerStats.server_id == server_id ServerStats.server_id == self.server_id
).execute() ).execute()
@staticmethod def set_download(self):
def set_download(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
ServerStats.update(downloading=True).where( ServerStats.update(downloading=True).where(
ServerStats.server_id == server_id ServerStats.server_id == self.server_id
).execute() ).execute()
@staticmethod def finish_download(self):
def finish_download(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
ServerStats.update(downloading=False).where( ServerStats.update(downloading=False).where(
ServerStats.server_id == server_id ServerStats.server_id == self.server_id
).execute() ).execute()
@staticmethod def get_download_status(self):
def get_download_status(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
download_status = ( download_status = (
ServerStats.select().where(ServerStats.server_id == server_id).get() ServerStats.select().where(ServerStats.server_id == self.server_id).get()
) )
return download_status.downloading return download_status.downloading
@staticmethod def server_crash_reset(self):
def server_crash_reset(server_id): if self.server_id is None:
if server_id is None:
return return
HelperServerStats.select_database(server_id) # self.select_database(self.server_id)
ServerStats.update(crashed=False).where( ServerStats.update(crashed=False).where(
ServerStats.server_id == server_id ServerStats.server_id == self.server_id
).execute() ).execute()
@staticmethod def is_crashed(self):
def is_crashed(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id) svr = ServerStats.select().where(ServerStats.server_id == self.server_id).get()
svr = ServerStats.select().where(ServerStats.server_id == server_id).get()
# pylint: disable=singleton-comparison # pylint: disable=singleton-comparison
if svr.crashed == True: if svr.crashed == True:
return True return True
else: else:
return False return False
@staticmethod def set_update(self, value):
def set_update(server_id, value): if self.server_id is None:
if server_id is None:
return return
HelperServerStats.select_database(server_id) # self.select_database(self.server_id)
try: try:
# Checks if server even exists # Checks if server even exists
ServerStats.select().where(ServerStats.server_id == server_id) ServerStats.select().where(ServerStats.server_id == self.server_id)
except Exception as ex: except Exception as ex:
logger.error(f"Database entry not found! {ex}") logger.error(f"Database entry not found! {ex}")
ServerStats.update(updating=value).where( ServerStats.update(updating=value).where(
ServerStats.server_id == server_id ServerStats.server_id == self.server_id
).execute() ).execute()
@staticmethod def get_update_status(self):
def get_update_status(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
update_status = ( update_status = (
ServerStats.select().where(ServerStats.server_id == server_id).get() ServerStats.select().where(ServerStats.server_id == self.server_id).get()
) )
return update_status.updating return update_status.updating
@staticmethod def set_first_run(self):
def set_first_run(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
# Sets first run to false # Sets first run to false
try: try:
# Checks if server even exists # Checks if server even exists
ServerStats.select().where(ServerStats.server_id == server_id) ServerStats.select().where(ServerStats.server_id == self.server_id)
except Exception as ex: except Exception as ex:
logger.error(f"Database entry not found! {ex}") logger.error(f"Database entry not found! {ex}")
return return
ServerStats.update(first_run=False).where( ServerStats.update(first_run=False).where(
ServerStats.server_id == server_id ServerStats.server_id == self.server_id
).execute() ).execute()
@staticmethod def get_first_run(self):
def get_first_run(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id) first_run = (
first_run = ServerStats.select().where(ServerStats.server_id == server_id).get() ServerStats.select().where(ServerStats.server_id == self.server_id).get()
)
return first_run.first_run return first_run.first_run
@staticmethod def get_ttl_without_player(self):
def get_ttl_without_player(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
last_stat = ( last_stat = (
ServerStats.select() ServerStats.select()
.where(ServerStats.server_id == server_id) .where(ServerStats.server_id == self.server_id)
.order_by(ServerStats.created.desc()) .order_by(ServerStats.created.desc())
.first() .first()
) )
last_stat_with_player = ( last_stat_with_player = (
ServerStats.select() ServerStats.select()
.where(ServerStats.server_id == server_id) .where(ServerStats.server_id == self.server_id)
.where(ServerStats.online > 0) .where(ServerStats.online > 0)
.order_by(ServerStats.created.desc()) .order_by(ServerStats.created.desc())
.first() .first()
) )
return last_stat.created - last_stat_with_player.created return last_stat.created - last_stat_with_player.created
@staticmethod def can_stop_no_players(self, time_limit):
def can_stop_no_players(server_id, time_limit): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
can = False can = False
ttl_no_players = HelperServerStats.get_ttl_without_player(server_id) ttl_no_players = self.get_ttl_without_player()
if (time_limit == -1) or (ttl_no_players > time_limit): if (time_limit == -1) or (ttl_no_players > time_limit):
can = True can = True
return can return can
@staticmethod def set_waiting_start(self, value):
def set_waiting_start(server_id, value): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
try: try:
# Checks if server even exists # Checks if server even exists
ServerStats.select().where(ServerStats.server_id == server_id) ServerStats.select().where(ServerStats.server_id == self.server_id)
except Exception as ex: except Exception as ex:
logger.error(f"Database entry not found! {ex}") logger.error(f"Database entry not found! {ex}")
ServerStats.update(waiting_start=value).where( ServerStats.update(waiting_start=value).where(
ServerStats.server_id == server_id ServerStats.server_id == self.server_id
).execute() ).execute()
@staticmethod def get_waiting_start(self):
def get_waiting_start(server_id): # self.select_database(self.server_id)
HelperServerStats.select_database(server_id)
waiting_start = ( waiting_start = (
ServerStats.select().where(ServerStats.server_id == server_id).get() ServerStats.select().where(ServerStats.server_id == self.server_id).get()
) )
return waiting_start.waiting_start return waiting_start.waiting_start

View File

@ -16,7 +16,7 @@ from app.classes.models.base_model import BaseModel
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# ********************************************************************************** # **********************************************************************************
# Servers Class # Servers Model
# ********************************************************************************** # **********************************************************************************
class Servers(BaseModel): class Servers(BaseModel):
server_id = AutoField() server_id = AutoField()

View File

@ -111,6 +111,8 @@ class Server:
self.is_crashed = False self.is_crashed = False
self.restart_count = 0 self.restart_count = 0
self.stats = stats self.stats = stats
self.server_object = HelperServers.get_server_obj(self.server_id)
self.stats_helper = HelperServerStats(self.server_id)
tz = get_localzone() tz = get_localzone()
self.server_scheduler = BackgroundScheduler(timezone=str(tz)) self.server_scheduler = BackgroundScheduler(timezone=str(tz))
self.server_scheduler.start() self.server_scheduler.start()
@ -119,8 +121,8 @@ class Server:
) )
self.is_backingup = False self.is_backingup = False
# Reset crash and update at initialization # Reset crash and update at initialization
HelperServerStats.server_crash_reset(self.server_id) self.stats_helper.server_crash_reset(self.server_id)
HelperServerStats.set_update(self.server_id, False) self.stats_helper.set_update(self.server_id, False)
# ********************************************************************************** # **********************************************************************************
# Minecraft Server Management # Minecraft Server Management
@ -143,7 +145,7 @@ class Server:
self.name = server_name self.name = server_name
self.settings = server_data_obj self.settings = server_data_obj
HelperServerStats.init_database(server_id) self.stats_helper.init_database(server_id)
self.record_server_stats() self.record_server_stats()
# build our server run command # build our server run command
@ -165,7 +167,7 @@ class Server:
Console.info(f"Starting server ID: {self.server_id} - {self.name}") Console.info(f"Starting server ID: {self.server_id} - {self.name}")
logger.info(f"Starting server ID: {self.server_id} - {self.name}") logger.info(f"Starting server ID: {self.server_id} - {self.name}")
# Sets waiting start to false since we're attempting to start the server. # Sets waiting start to false since we're attempting to start the server.
HelperServerStats.set_waiting_start(self.server_id, False) self.stats_helper.set_waiting_start(self.server_id, False)
self.run_threaded_server(None) self.run_threaded_server(None)
# remove the scheduled job since it's ran # remove the scheduled job since it's ran
@ -232,7 +234,7 @@ class Server:
else: else:
user_lang = HelperUsers.get_user_lang_by_id(user_id) user_lang = HelperUsers.get_user_lang_by_id(user_id)
if HelperServerStats.get_download_status(self.server_id): if self.stats_helper.get_download_status(self.server_id):
if user_id: if user_id:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user_id, user_id,
@ -405,7 +407,7 @@ class Server:
).start() ).start()
self.is_crashed = False self.is_crashed = False
HelperServerStats.server_crash_reset(self.server_id) self.stats_helper.server_crash_reset(self.server_id)
self.start_time = str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) self.start_time = str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
@ -413,7 +415,7 @@ class Server:
logger.info(f"Server {self.name} running with PID {self.process.pid}") logger.info(f"Server {self.name} running with PID {self.process.pid}")
Console.info(f"Server {self.name} running with PID {self.process.pid}") Console.info(f"Server {self.name} running with PID {self.process.pid}")
self.is_crashed = False self.is_crashed = False
HelperServerStats.server_crash_reset(self.server_id) self.stats_helper.server_crash_reset(self.server_id)
self.record_server_stats() self.record_server_stats()
check_internet_thread = threading.Thread( check_internet_thread = threading.Thread(
target=self.check_internet_thread, target=self.check_internet_thread,
@ -426,9 +428,9 @@ class Server:
) )
check_internet_thread.start() check_internet_thread.start()
# Checks if this is the servers first run. # Checks if this is the servers first run.
if HelperServerStats.get_first_run(self.server_id): if self.stats_helper.get_first_run(self.server_id):
HelperServerStats.set_first_run(self.server_id) self.stats_helper.set_first_run(self.server_id)
loc_server_port = HelperServerStats.get_server_stats_by_id( loc_server_port = self.stats_helper.get_server_stats_by_id(
self.server_id self.server_id
)["server_port"] )["server_port"]
# Sends port reminder message. # Sends port reminder message.
@ -710,7 +712,7 @@ class Server:
self.server_scheduler.remove_job("c_" + str(self.server_id)) self.server_scheduler.remove_job("c_" + str(self.server_id))
return return
HelperServerStats.sever_crashed(self.server_id) self.stats_helper.sever_crashed(self.server_id)
# if we haven't tried to restart more 3 or more times # if we haven't tried to restart more 3 or more times
if self.restart_count <= 3: if self.restart_count <= 3:
@ -734,7 +736,7 @@ class Server:
self.restart_count = 0 self.restart_count = 0
self.is_crashed = True self.is_crashed = True
HelperServerStats.sever_crashed(self.server_id) self.stats_helper.sever_crashed(self.server_id)
# cancel the watcher task # cancel the watcher task
self.server_scheduler.remove_job("c_" + str(self.server_id)) self.server_scheduler.remove_job("c_" + str(self.server_id))
@ -964,7 +966,7 @@ class Server:
return [] return []
def jar_update(self): def jar_update(self):
HelperServerStats.set_update(self.server_id, True) self.stats_helper.set_update(self.server_id, True)
update_thread = threading.Thread( update_thread = threading.Thread(
target=self.a_jar_update, daemon=True, name=f"exe_update_{self.name}" target=self.a_jar_update, daemon=True, name=f"exe_update_{self.name}"
) )
@ -972,7 +974,7 @@ class Server:
def check_update(self): def check_update(self):
if HelperServerStats.get_server_stats_by_id(self.server_id)["updating"]: if self.stats_helper.get_server_stats_by_id(self.server_id)["updating"]:
return True return True
else: else:
return False return False
@ -1045,11 +1047,11 @@ class Server:
self.settings["executable_update_url"], current_executable self.settings["executable_update_url"], current_executable
) )
while HelperServerStats.get_server_stats_by_id(self.server_id)["updating"]: while self.stats_helper.get_server_stats_by_id(self.server_id)["updating"]:
if downloaded and not self.is_backingup: if downloaded and not self.is_backingup:
logger.info("Executable updated successfully. Starting Server") logger.info("Executable updated successfully. Starting Server")
HelperServerStats.set_update(self.server_id, False) self.stats_helper.set_update(self.server_id, False)
if len(self.helper.websocket_helper.clients) > 0: if len(self.helper.websocket_helper.clients) > 0:
# There are clients # There are clients
self.check_update() self.check_update()
@ -1445,11 +1447,11 @@ class Server:
def record_server_stats(self): def record_server_stats(self):
server = self.get_servers_stats() server = self.get_servers_stats()
HelperServerStats.insert_server_stats(server) self.stats_helper.insert_server_stats(server)
# delete old data # delete old data
max_age = self.helper.get_setting("history_max_age") max_age = self.helper.get_setting("history_max_age")
now = datetime.datetime.now() now = datetime.datetime.now()
last_week = now.day - max_age last_week = now.day - max_age
HelperServerStats.remove_old_stats(server.get("id", 0), last_week) self.stats_helper.remove_old_stats(server.get("id", 0), last_week)