I'm breaking/fixing stuff

This commit is contained in:
Silversthorn 2022-05-26 14:50:20 +02:00
parent 5a1353373a
commit 8423cc24c1
14 changed files with 424 additions and 317 deletions

View File

@ -1,4 +1,5 @@
import logging
from app.classes.controllers.servers_controller import ServersController
from app.classes.models.server_permissions import (
PermissionsServers,
@ -8,7 +9,9 @@ from app.classes.models.users import HelperUsers, ApiKeys
from app.classes.models.roles import HelperRoles
from app.classes.models.servers import HelperServers
from app.classes.models.server_stats import HelperServerStats
from app.classes.shared.main_models import DatabaseShortcuts
from app.classes.shared.server import Server
logger = logging.getLogger(__name__)
@ -107,7 +110,10 @@ class ServerPermsController:
)
for server in authorized_servers:
latest = HelperServerStats.get_latest_server_stats(server.get("server_id"))
srv: Server = ServersController().get_server_instance_by_id(
server.get("server_id")
)
latest = srv.stats_helper.get_latest_server_stats()
server_data.append(
{
"server_data": server,

View File

@ -1,9 +1,23 @@
from gettext import install
from inspect import _void
import os
import logging
from pydoc import Helper
import time
import json
import typing as t
from typing_extensions import Self
from app.classes.controllers.roles_controller import RolesController
from app.classes.shared.server import Server
from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers
from app.classes.shared.main_models import DatabaseShortcuts
from app.classes.minecraft.server_props import ServerProps
from app.classes.minecraft.stats import Stats
from app.classes.models.servers import HelperServers
from app.classes.models.server_stats import HelperServerStats
from app.classes.models.users import HelperUsers, ApiKeys
@ -11,15 +25,20 @@ from app.classes.models.server_permissions import (
PermissionsServers,
EnumPermissionsServer,
)
from app.classes.shared.helpers import Helpers
from app.classes.shared.main_models import DatabaseShortcuts
from app.classes.shared.singleton import Singleton
logger = logging.getLogger(__name__)
class ServersController:
def __init__(self, servers_helper):
self.servers_helper = servers_helper
class ServersController(metaclass=Singleton):
servers_list: Server
def __init__(self, helper, servers_helper, management_helper):
self.helper: Helper = helper
self.servers_helper: HelperServers = servers_helper
self.management_helper = management_helper
self.servers_list = []
self.stats = Stats(self.helper, self)
# **********************************************************************************
# Generic Servers Methods
@ -83,15 +102,18 @@ class ServersController:
@staticmethod
def set_download(server_id):
return HelperServerStats.set_download(server_id)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.set_download(server_id)
@staticmethod
def finish_download(server_id):
return HelperServerStats.finish_download(server_id)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.finish_download(server_id)
@staticmethod
def get_download_status(server_id):
return HelperServerStats.get_download_status(server_id)
server: Server = ServersController().get_server_instance_by_id(server_id)
return server.stats_helper.get_download_status()
def remove_server(self, server_id):
roles_list = PermissionsServers.get_roles_from_server(server_id)
@ -110,6 +132,105 @@ class ServersController:
# **********************************************************************************
# Servers Methods
# **********************************************************************************
def get_server_instance_by_id(self, server_id):
for server in self.servers_list:
if server["server_id"] == int(server_id):
return server["server_obj"]
return None
def init_all_servers(self):
servers = self.get_all_defined_servers()
for server in servers:
server_id = server.get("server_id")
# if we have already initialized this server, let's skip it.
if self.check_server_loaded(server_id):
continue
# if this server path no longer exists - let's warn and bomb out
if not Helpers.check_path_exists(
Helpers.get_os_understandable_path(server["path"])
):
logger.warning(
f"Unable to find server "
f"{server['server_name']} at path {server['path']}. "
f"Skipping this server"
)
Console.warning(
f"Unable to find server "
f"{server['server_name']} at path {server['path']}. "
f"Skipping this server"
)
continue
settings_file = os.path.join(
Helpers.get_os_understandable_path(server["path"]), "server.properties"
)
# if the properties file isn't there, let's warn
if not Helpers.check_file_exists(settings_file):
logger.error(f"Unable to find {settings_file}. Skipping this server.")
Console.error(f"Unable to find {settings_file}. Skipping this server.")
continue
settings = ServerProps(settings_file)
temp_server_dict = {
"server_id": server.get("server_id"),
"server_data_obj": server,
"server_obj": Server(
server.get("server_id"),
self.helper,
self.management_helper,
self.stats,
),
"server_settings": settings.props,
}
# setup the server, do the auto start and all that jazz
temp_server_dict["server_obj"].do_server_setup(server)
# add this temp object to the list of init servers
self.servers_list.append(temp_server_dict)
if server["auto_start"]:
self.servers.set_waiting_start(server["server_id"], True)
self.refresh_server_settings(server["server_id"])
Console.info(
f"Loaded Server: ID {server['server_id']}"
f" | Name: {server['server_name']}"
f" | Autostart: {server['auto_start']}"
f" | Delay: {server['auto_start_delay']}"
)
def check_server_loaded(self, server_id_to_check: int):
logger.info(f"Checking to see if we already registered {server_id_to_check}")
for server in self.servers_list:
known_server = server.get("server_id")
if known_server is None:
return False
if known_server == server_id_to_check:
logger.info(
f"skipping initialization of server {server_id_to_check} "
f"because it is already loaded"
)
return True
return False
def refresh_server_settings(self, server_id: int):
server_obj = self.get_server_obj(server_id)
server_obj.reload_server_settings()
@staticmethod
def get_all_defined_servers():
return HelperServers.get_all_defined_servers()
@ -141,9 +262,26 @@ class ServersController:
return user_ids
@staticmethod
def get_all_servers_stats():
return HelperServerStats.get_all_servers_stats()
def get_all_servers_stats(self):
server_data = []
try:
for server in self.servers_list:
srv: Server = ServersController().get_server_instance_by_id(
server.get("server_id")
)
latest = srv.stats_helper.get_latest_server_stats()
server_data.append(
{
"server_data": server["server_data_obj"],
"stats": latest,
"user_command_permission": True,
}
)
except IndexError as ex:
logger.error(
f"Stats collection failed with error: {ex}. Was a server just created?"
)
return server_data
@staticmethod
def get_authorized_servers_stats_api_key(api_key: ApiKeys):
@ -153,7 +291,8 @@ class ServersController:
)
for server in authorized_servers:
latest = HelperServerStats.get_latest_server_stats(server.get("server_id"))
srv: Server = server
latest = srv.stats_helper.get_latest_server_stats()
key_permissions = PermissionsServers.get_api_key_permissions_list(
api_key, server.get("server_id")
)
@ -176,7 +315,8 @@ class ServersController:
authorized_servers = ServersController.get_authorized_servers(user_id)
for server in authorized_servers:
latest = HelperServerStats.get_latest_server_stats(server.get("server_id"))
srv: Server = server
latest = srv.stats_helper.get_latest_server_stats()
# TODO
user_permissions = PermissionsServers.get_user_id_permissions_list(
user_id, server.get("server_id")
@ -199,16 +339,111 @@ class ServersController:
def get_server_friendly_name(server_id):
return HelperServers.get_server_friendly_name(server_id)
def get_server_settings(self, server_id):
for server in self.servers_list:
if int(server["server_id"]) == int(server_id):
return server["server_settings"]
logger.warning(f"Unable to find server object for server id {server_id}")
return False
def crash_detection(self, server_obj):
svr = self.get_server_obj(server_obj.server_id)
# start or stop crash detection depending upon user preference
# The below functions check to see if the server is running.
# They only execute if it's running.
if server_obj.crash_detection == 1:
svr.start_crash_detection()
else:
svr.stop_crash_detection()
def get_server_obj(self, server_id: t.Union[str, int]) -> Server:
for server in self.servers_list:
if str(server["server_id"]) == str(server_id):
return server["server_obj"]
logger.warning(f"Unable to find server object for server id {server_id}")
raise Exception(f"Unable to find server object for server id {server_id}")
def get_server_obj_optional(
self, server_id: t.Union[str, int]
) -> t.Optional[Server]:
for server in self.servers_list:
if str(server["server_id"]) == str(server_id):
return server["server_obj"]
logger.warning(f"Unable to find server object for server id {server_id}")
return None
def get_server_data(self, server_id: str):
for server in self.servers_list:
if str(server["server_id"]) == str(server_id):
return server["server_data_obj"]
logger.warning(f"Unable to find server object for server id {server_id}")
return False
@staticmethod
def list_defined_servers():
servers = HelperServers.get_all_defined_servers()
return servers
@staticmethod
def get_all_server_ids() -> t.List[int]:
return HelperServers.get_all_server_ids()
def list_running_servers(self):
running_servers = []
# for each server
for servers in self.servers_list:
# is the server running?
srv_obj = servers["server_obj"]
running = srv_obj.check_running()
# if so, let's add a dictionary to the list of running servers
if running:
running_servers.append({"id": srv_obj.server_id, "name": srv_obj.name})
return running_servers
def stop_all_servers(self):
servers = self.list_running_servers()
logger.info(f"Found {len(servers)} running server(s)")
Console.info(f"Found {len(servers)} running server(s)")
logger.info("Stopping All Servers")
Console.info("Stopping All Servers")
for server in servers:
logger.info(f"Stopping Server ID {server['id']} - {server['name']}")
Console.info(f"Stopping Server ID {server['id']} - {server['name']}")
self.stop_server(server["id"])
# let's wait 2 seconds to let everything flush out
time.sleep(2)
logger.info("All Servers Stopped")
Console.info("All Servers Stopped")
def stop_server(self, server_id):
# issue the stop command
svr_obj = self.get_server_obj(server_id)
svr_obj.stop_threaded_server()
# **********************************************************************************
# Servers_Stats Methods
# **********************************************************************************
@staticmethod
def get_server_stats_by_id(server_id):
return HelperServerStats.get_server_stats_by_id(server_id)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.get_latest_server_stats()
@staticmethod
def server_id_exists(server_id):
return HelperServerStats.server_id_exists(server_id)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.server_id_exists()
@staticmethod
def get_server_type_by_id(server_id):
@ -227,7 +462,8 @@ class ServersController:
@staticmethod
def is_crashed(server_id):
return HelperServerStats.is_crashed(server_id)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.is_crashed()
@staticmethod
def server_id_authorized_api_key(server_id: str, api_key: ApiKeys) -> bool:
@ -238,34 +474,41 @@ class ServersController:
@staticmethod
def set_update(server_id, value):
return HelperServerStats.set_update(server_id, value)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.set_update(value)
@staticmethod
def get_ttl_without_player(server_id):
return HelperServerStats.get_ttl_without_player(server_id)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.get_ttl_without_player()
@staticmethod
def can_stop_no_players(server_id, time_limit):
return HelperServerStats.can_stop_no_players(server_id, time_limit)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.can_stop_no_players(time_limit)
@staticmethod
def set_waiting_start(server_id, value):
HelperServerStats.set_waiting_start(server_id, value)
srv: Server = ServersController().get_server_instance_by_id(server_id)
srv.stats_helper.set_waiting_start(value)
@staticmethod
def get_waiting_start(server_id):
return HelperServerStats.get_waiting_start(server_id)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.get_waiting_start()
@staticmethod
def get_update_status(server_id):
return HelperServerStats.get_update_status(server_id)
srv: Server = ServersController().get_server_instance_by_id(server_id)
return srv.stats_helper.get_update_status()
# **********************************************************************************
# Servers Helpers Methods
# **********************************************************************************
@staticmethod
def get_banned_players(server_id):
stats = HelperServerStats.get_server_stats_by_id(server_id)
srv: Server = ServersController().get_server_instance_by_id(server_id)
stats = srv.stats_helper.get_server_stats()
server_path = stats["server_id"]["path"]
path = os.path.join(server_path, "banned-players.json")

View File

@ -2,6 +2,12 @@ import os
import logging
import datetime
import typing as t
from peewee import DoesNotExist
from playhouse.shortcuts import model_to_dict
from app.classes.models.servers import Servers, HelperServers
from app.classes.shared.helpers import Helpers
from app.classes.shared.main_models import DatabaseShortcuts
@ -27,7 +33,7 @@ except ModuleNotFoundError as e:
logger = logging.getLogger(__name__)
peewee_logger = logging.getLogger("peewee")
peewee_logger.setLevel(logging.INFO)
database_stats_proxy = DatabaseProxy()
# database_stats_proxy = DatabaseProxy()
# **********************************************************************************
@ -59,16 +65,19 @@ class ServerStats(Model):
class Meta:
table_name = "server_stats"
database = database_stats_proxy
# database = database_stats_proxy
# **********************************************************************************
# Servers_Stats Methods
# **********************************************************************************
class HelperServerStats:
def __init__(self, database, server_id):
self.database = database
self.server_id = server_id
server_id: int
database = None
def __init__(self, server_id):
self.server_id = int(server_id)
self.init_database(self.server_id)
def init_database(self, server_id):
try:
@ -78,7 +87,7 @@ class HelperServerStats:
db_folder,
"crafty_server_stats.sqlite",
)
database = SqliteDatabase(
self.database = SqliteDatabase(
db_file, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
)
if not os.path.exists(db_file):
@ -93,10 +102,10 @@ class HelperServerStats:
f"{helper_stats.migration_dir}", "stats"
)
helper_stats.db_path = db_file
database_stats_proxy.initialize(database)
migration_manager = MigrationManager(database, helper_stats)
# database_stats_proxy.initialize(self.database)
migration_manager = MigrationManager(self.database, helper_stats)
migration_manager.up() # Automatically runs migrations
database_stats_proxy.initialize(database)
# database_stats_proxy.initialize(self.database)
except Exception as ex:
logger.warning(
f"Error try to look for the db_stats files for server : {ex}"
@ -110,10 +119,10 @@ class HelperServerStats:
"db_stats",
"crafty_server_stats.sqlite",
)
database = SqliteDatabase(
self.database = SqliteDatabase(
db_file, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
)
database_stats_proxy.initialize(database)
# database_stats_proxy.initialize(self.database)
except Exception as ex:
logger.warning(
f"Error try to look for the db_stats files for server : {ex}"
@ -131,6 +140,7 @@ class HelperServerStats:
.order_by(ServerStats.created.desc())
.limit(1)
)
latest._database = self.database
server_data.append(
{
"server_data": s,
@ -170,30 +180,37 @@ class HelperServerStats:
ServerStats.desc: server.get("desc", False),
ServerStats.version: server.get("version", False),
}
).execute()
).execute(self.database)
def remove_old_stats(self, last_week):
# self.select_database(self.server_id)
ServerStats.delete().where(ServerStats.created < last_week).execute()
ServerStats.delete().where(ServerStats.created < last_week).execute(
self.database
)
def get_latest_server_stats(self):
# self.select_database(self.server_id)
return (
latest = (
ServerStats.select()
.where(ServerStats.server_id == self.server_id)
.order_by(ServerStats.created.desc())
.limit(1)
.get(self.database)
)
try:
return model_to_dict(latest)
except IndexError:
return {}
def get_server_stats_by_id(self):
def get_server_stats(self):
# self.select_database(self.server_id)
stats = (
ServerStats.select()
.where(ServerStats.server_id == self.server_id)
.order_by(ServerStats.created.desc())
.limit(1)
.get(self.database)
)
return DatabaseShortcuts.return_rows(stats)[0]
return model_to_dict(stats)
def server_id_exists(self):
# self.select_database(self.server_id)
@ -205,24 +222,26 @@ class HelperServerStats:
# self.select_database(self.server_id)
ServerStats.update(crashed=True).where(
ServerStats.server_id == self.server_id
).execute()
).execute(self.database)
def set_download(self):
# self.select_database(self.server_id)
ServerStats.update(downloading=True).where(
ServerStats.server_id == self.server_id
).execute()
).execute(self.database)
def finish_download(self):
# self.select_database(self.server_id)
ServerStats.update(downloading=False).where(
ServerStats.server_id == self.server_id
).execute()
).execute(self.database)
def get_download_status(self):
# self.select_database(self.server_id)
download_status = (
ServerStats.select().where(ServerStats.server_id == self.server_id).get()
ServerStats.select()
.where(ServerStats.server_id == self.server_id)
.get(self.database)
)
return download_status.downloading
@ -233,11 +252,15 @@ class HelperServerStats:
# self.select_database(self.server_id)
ServerStats.update(crashed=False).where(
ServerStats.server_id == self.server_id
).execute()
).execute(self.database)
def is_crashed(self):
# self.select_database(self.server_id)
svr = ServerStats.select().where(ServerStats.server_id == self.server_id).get()
svr: ServerStats = (
ServerStats.select()
.where(ServerStats.server_id == self.server_id)
.get(self.database)
)
# pylint: disable=singleton-comparison
if svr.crashed == True:
return True
@ -251,17 +274,21 @@ class HelperServerStats:
# self.select_database(self.server_id)
try:
# Checks if server even exists
ServerStats.select().where(ServerStats.server_id == self.server_id)
ServerStats.select().where(ServerStats.server_id == self.server_id).execute(
self.database
)
except Exception as ex:
logger.error(f"Database entry not found! {ex}")
ServerStats.update(updating=value).where(
ServerStats.server_id == self.server_id
).execute()
).execute(self.database)
def get_update_status(self):
# self.select_database(self.server_id)
update_status = (
ServerStats.select().where(ServerStats.server_id == self.server_id).get()
ServerStats.select()
.where(ServerStats.server_id == self.server_id)
.get(self.database)
)
return update_status.updating
@ -270,18 +297,22 @@ class HelperServerStats:
# Sets first run to false
try:
# Checks if server even exists
ServerStats.select().where(ServerStats.server_id == self.server_id)
ServerStats.select().where(ServerStats.server_id == self.server_id).execute(
self.database
)
except Exception as ex:
logger.error(f"Database entry not found! {ex}")
return
ServerStats.update(first_run=False).where(
ServerStats.server_id == self.server_id
).execute()
).execute(self.database)
def get_first_run(self):
# self.select_database(self.server_id)
first_run = (
ServerStats.select().where(ServerStats.server_id == self.server_id).get()
ServerStats.select()
.where(ServerStats.server_id == self.server_id)
.get(self.database)
)
return first_run.first_run
@ -291,14 +322,14 @@ class HelperServerStats:
ServerStats.select()
.where(ServerStats.server_id == self.server_id)
.order_by(ServerStats.created.desc())
.first()
.first(self.database)
)
last_stat_with_player = (
ServerStats.select()
.where(ServerStats.server_id == self.server_id)
.where(ServerStats.online > 0)
.order_by(ServerStats.created.desc())
.first()
.first(self.database)
)
return last_stat.created - last_stat_with_player.created
@ -319,11 +350,13 @@ class HelperServerStats:
logger.error(f"Database entry not found! {ex}")
ServerStats.update(waiting_start=value).where(
ServerStats.server_id == self.server_id
).execute()
).execute(self.database)
def get_waiting_start(self):
# self.select_database(self.server_id)
waiting_start = (
ServerStats.select().where(ServerStats.server_id == self.server_id).get()
ServerStats.select()
.where(ServerStats.server_id == self.server_id)
.get(self.database)
)
return waiting_start.waiting_start

View File

@ -26,11 +26,8 @@ from app.classes.models.servers import HelperServers
from app.classes.shared.authentication import Authentication
from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers
from app.classes.shared.server import Server
from app.classes.shared.file_helpers import FileHelpers
from app.classes.minecraft.server_props import ServerProps
from app.classes.minecraft.serverjars import ServerJars
from app.classes.minecraft.stats import Stats
logger = logging.getLogger(__name__)
@ -44,13 +41,13 @@ class Controller:
self.servers_helper = HelperServers(database)
self.management_helper = HelpersManagement(database, self.helper)
self.authentication = Authentication(self.helper)
self.servers_list = []
self.stats = Stats(self.helper, self)
self.crafty_perms = CraftyPermsController()
self.management = ManagementController(self.management_helper)
self.roles = RolesController(self.users_helper, self.roles_helper)
self.server_perms = ServerPermsController()
self.servers = ServersController(self.servers_helper)
self.servers = ServersController(
self.helper, self.servers_helper, self.management_helper
)
self.users = UsersController(
self.helper, self.users_helper, self.authentication
)
@ -58,93 +55,6 @@ class Controller:
self.support_scheduler = BackgroundScheduler(timezone=str(tz))
self.support_scheduler.start()
def check_server_loaded(self, server_id_to_check: int):
logger.info(f"Checking to see if we already registered {server_id_to_check}")
for server in self.servers_list:
known_server = server.get("server_id")
if known_server is None:
return False
if known_server == server_id_to_check:
logger.info(
f"skipping initialization of server {server_id_to_check} "
f"because it is already loaded"
)
return True
return False
def init_all_servers(self):
servers = self.servers.get_all_defined_servers()
for server in servers:
server_id = server.get("server_id")
# if we have already initialized this server, let's skip it.
if self.check_server_loaded(server_id):
continue
# if this server path no longer exists - let's warn and bomb out
if not Helpers.check_path_exists(
Helpers.get_os_understandable_path(server["path"])
):
logger.warning(
f"Unable to find server "
f"{server['server_name']} at path {server['path']}. "
f"Skipping this server"
)
Console.warning(
f"Unable to find server "
f"{server['server_name']} at path {server['path']}. "
f"Skipping this server"
)
continue
settings_file = os.path.join(
Helpers.get_os_understandable_path(server["path"]), "server.properties"
)
# if the properties file isn't there, let's warn
if not Helpers.check_file_exists(settings_file):
logger.error(f"Unable to find {settings_file}. Skipping this server.")
Console.error(f"Unable to find {settings_file}. Skipping this server.")
continue
settings = ServerProps(settings_file)
temp_server_dict = {
"server_id": server.get("server_id"),
"server_data_obj": server,
"server_obj": Server(self.helper, self.management_helper, self.stats),
"server_settings": settings.props,
}
# setup the server, do the auto start and all that jazz
temp_server_dict["server_obj"].do_server_setup(server)
# add this temp object to the list of init servers
self.servers_list.append(temp_server_dict)
if server["auto_start"]:
self.servers.set_waiting_start(server["server_id"], True)
self.refresh_server_settings(server["server_id"])
Console.info(
f"Loaded Server: ID {server['server_id']}"
f" | Name: {server['server_name']}"
f" | Autostart: {server['auto_start']}"
f" | Delay: {server['auto_start_delay']}"
)
def refresh_server_settings(self, server_id: int):
server_obj = self.get_server_obj(server_id)
server_obj.reload_server_settings()
@staticmethod
def check_system_user():
if HelperUsers.get_user_id_by_name("system") is not None:
@ -243,24 +153,6 @@ class Controller:
False,
)
def get_server_settings(self, server_id):
for server in self.servers_list:
if int(server["server_id"]) == int(server_id):
return server["server_settings"]
logger.warning(f"Unable to find server object for server id {server_id}")
return False
def crash_detection(self, server_obj):
svr = self.get_server_obj(server_obj.server_id)
# start or stop crash detection depending upon user preference
# The below functions check to see if the server is running.
# They only execute if it's running.
if server_obj.crash_detection == 1:
svr.start_crash_detection()
else:
svr.stop_crash_detection()
def log_status(self, source_path, dest_path, exec_user):
results = Helpers.calc_percent(source_path, dest_path)
self.log_stats = results
@ -276,81 +168,6 @@ class Controller:
except:
return {"percent": 0, "total_files": 0}
def get_server_obj(self, server_id: t.Union[str, int]) -> Server:
for server in self.servers_list:
if str(server["server_id"]) == str(server_id):
return server["server_obj"]
logger.warning(f"Unable to find server object for server id {server_id}")
raise Exception(f"Unable to find server object for server id {server_id}")
def get_server_obj_optional(
self, server_id: t.Union[str, int]
) -> t.Optional[Server]:
for server in self.servers_list:
if str(server["server_id"]) == str(server_id):
return server["server_obj"]
logger.warning(f"Unable to find server object for server id {server_id}")
return None
def get_server_data(self, server_id: str):
for server in self.servers_list:
if str(server["server_id"]) == str(server_id):
return server["server_data_obj"]
logger.warning(f"Unable to find server object for server id {server_id}")
return False
@staticmethod
def list_defined_servers():
servers = HelperServers.get_all_defined_servers()
return servers
@staticmethod
def get_all_server_ids() -> t.List[int]:
return HelperServers.get_all_server_ids()
def list_running_servers(self):
running_servers = []
# for each server
for servers in self.servers_list:
# is the server running?
srv_obj = servers["server_obj"]
running = srv_obj.check_running()
# if so, let's add a dictionary to the list of running servers
if running:
running_servers.append({"id": srv_obj.server_id, "name": srv_obj.name})
return running_servers
def stop_all_servers(self):
servers = self.list_running_servers()
logger.info(f"Found {len(servers)} running server(s)")
Console.info(f"Found {len(servers)} running server(s)")
logger.info("Stopping All Servers")
Console.info("Stopping All Servers")
for server in servers:
logger.info(f"Stopping Server ID {server['id']} - {server['name']}")
Console.info(f"Stopping Server ID {server['id']} - {server['name']}")
self.stop_server(server["id"])
# let's wait 2 seconds to let everything flush out
time.sleep(2)
logger.info("All Servers Stopped")
Console.info("All Servers Stopped")
def stop_server(self, server_id):
# issue the stop command
svr_obj = self.get_server_obj(server_id)
svr_obj.stop_threaded_server()
def create_api_server(self, data: dict):
server_fs_uuid = Helpers.create_uuid()
new_server_path = os.path.join(self.helper.servers_dir, server_fs_uuid)
@ -981,13 +798,13 @@ class Controller:
return False
# let's re-init all servers
self.init_all_servers()
self.servers.init_all_servers()
return new_id
def remove_server(self, server_id, files):
counter = 0
for server in self.servers_list:
for server in self.servers.servers_list:
# if this is the droid... im mean server we are looking for...
if str(server["server_id"]) == str(server_id):
@ -1035,7 +852,7 @@ class Controller:
self.servers.remove_server(server_id)
# remove the server from servers list
self.servers_list.pop(counter)
self.servers.servers_list.pop(counter)
counter += 1

View File

@ -17,7 +17,7 @@ from apscheduler.schedulers.background import BackgroundScheduler
from app.classes.minecraft.stats import Stats
from app.classes.minecraft.mc_ping import ping, ping_bedrock
from app.classes.models.servers import HelperServers
from app.classes.models.servers import HelperServers, Servers
from app.classes.models.server_stats import HelperServerStats
from app.classes.models.management import HelpersManagement
from app.classes.models.users import HelperUsers
@ -93,7 +93,10 @@ class ServerOutBuf:
# Minecraft Server Class
# **********************************************************************************
class Server:
def __init__(self, helper, management_helper, stats):
server_object: Servers
stats_helper: HelperServerStats
def __init__(self, server_id, helper, management_helper, stats):
self.helper = helper
self.management_helper = management_helper
# holders for our process
@ -105,7 +108,7 @@ class Server:
self.server_thread = None
self.settings = None
self.updating = False
self.server_id = None
self.server_id = server_id
self.jar_update_url = None
self.name = None
self.is_crashed = False
@ -121,8 +124,8 @@ class Server:
)
self.is_backingup = False
# Reset crash and update at initialization
self.stats_helper.server_crash_reset(self.server_id)
self.stats_helper.set_update(self.server_id, False)
self.stats_helper.server_crash_reset()
self.stats_helper.set_update(False)
# **********************************************************************************
# Minecraft Server Management
@ -167,7 +170,7 @@ class Server:
Console.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.
self.stats_helper.set_waiting_start(self.server_id, False)
self.stats_helper.set_waiting_start(False)
self.run_threaded_server(None)
# remove the scheduled job since it's ran
@ -234,7 +237,7 @@ class Server:
else:
user_lang = HelperUsers.get_user_lang_by_id(user_id)
if self.stats_helper.get_download_status(self.server_id):
if self.stats_helper.get_download_status():
if user_id:
self.helper.websocket_helper.broadcast_user(
user_id,
@ -407,7 +410,7 @@ class Server:
).start()
self.is_crashed = False
self.stats_helper.server_crash_reset(self.server_id)
self.stats_helper.server_crash_reset()
self.start_time = str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
@ -415,7 +418,7 @@ class Server:
logger.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.stats_helper.server_crash_reset(self.server_id)
self.stats_helper.server_crash_reset()
self.record_server_stats()
check_internet_thread = threading.Thread(
target=self.check_internet_thread,
@ -428,11 +431,9 @@ class Server:
)
check_internet_thread.start()
# Checks if this is the servers first run.
if self.stats_helper.get_first_run(self.server_id):
self.stats_helper.set_first_run(self.server_id)
loc_server_port = self.stats_helper.get_server_stats_by_id(
self.server_id
)["server_port"]
if self.stats_helper.get_first_run():
self.stats_helper.set_first_run()
loc_server_port = self.stats_helper.get_server_stats()["server_port"]
# Sends port reminder message.
self.helper.websocket_helper.broadcast_user(
user_id,
@ -712,7 +713,7 @@ class Server:
self.server_scheduler.remove_job("c_" + str(self.server_id))
return
self.stats_helper.sever_crashed(self.server_id)
self.stats_helper.sever_crashed()
# if we haven't tried to restart more 3 or more times
if self.restart_count <= 3:
@ -736,7 +737,7 @@ class Server:
self.restart_count = 0
self.is_crashed = True
self.stats_helper.sever_crashed(self.server_id)
self.stats_helper.sever_crashed()
# cancel the watcher task
self.server_scheduler.remove_job("c_" + str(self.server_id))
@ -966,7 +967,7 @@ class Server:
return []
def jar_update(self):
self.stats_helper.set_update(self.server_id, True)
self.stats_helper.set_update(True)
update_thread = threading.Thread(
target=self.a_jar_update, daemon=True, name=f"exe_update_{self.name}"
)
@ -974,7 +975,7 @@ class Server:
def check_update(self):
if self.stats_helper.get_server_stats_by_id(self.server_id)["updating"]:
if self.stats_helper.get_server_stats()["updating"]:
return True
else:
return False
@ -1047,11 +1048,11 @@ class Server:
self.settings["executable_update_url"], current_executable
)
while self.stats_helper.get_server_stats_by_id(self.server_id)["updating"]:
while self.stats_helper.get_server_stats()["updating"]:
if downloaded and not self.is_backingup:
logger.info("Executable updated successfully. Starting Server")
self.stats_helper.set_update(self.server_id, False)
self.stats_helper.set_update(False)
if len(self.helper.websocket_helper.clients) > 0:
# There are clients
self.check_update()
@ -1454,4 +1455,4 @@ class Server:
now = datetime.datetime.now()
last_week = now.day - max_age
self.stats_helper.remove_old_stats(server.get("id", 0), last_week)
self.stats_helper.remove_old_stats(last_week)

View File

@ -0,0 +1,7 @@
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]

View File

@ -84,7 +84,7 @@ class TasksManager:
commands = HelpersManagement.get_unactioned_commands()
for cmd in commands:
try:
svr = self.controller.get_server_obj(cmd.server_id)
svr = self.controller.servers.get_server_obj(cmd.server_id)
except:
logger.error(
"Server value requested does not exist! "
@ -516,10 +516,10 @@ class TasksManager:
)
# one for now,
self.controller.stats.record_stats()
self.controller.servers.stats.record_stats()
# one for later
self.scheduler.add_job(
self.controller.stats.record_stats,
self.controller.servers.stats.record_stats,
"interval",
seconds=stats_update_frequency,
id="stats",

View File

@ -286,7 +286,7 @@ class AjaxHandler(BaseHandler):
logger.warning("Server ID not found in send_command ajax call")
Console.warning("Server ID not found in send_command ajax call")
srv_obj = self.controller.get_server_obj(server_id)
srv_obj = self.controller.servers.get_server_obj(server_id)
if command == srv_obj.settings["stop_command"]:
logger.info(
@ -334,7 +334,7 @@ class AjaxHandler(BaseHandler):
logger.error("Server ID is none. Canceling backup!")
return
server = self.controller.get_server_obj(server_id)
server = self.controller.servers.get_server_obj(server_id)
self.controller.management.add_to_audit_log_raw(
self.controller.users.get_user_by_id(exec_user["user_id"])["username"],
exec_user["user_id"],
@ -356,7 +356,7 @@ class AjaxHandler(BaseHandler):
self.redirect("/panel/error?error=Unauthorized access to Commands")
return
server_id = self.get_argument("id", None)
svr = self.controller.get_server_obj(server_id)
svr = self.controller.servers.get_server_obj(server_id)
try:
svr.kill()
time.sleep(5)
@ -369,7 +369,7 @@ class AjaxHandler(BaseHandler):
return
elif page == "eula":
server_id = self.get_argument("id", None)
svr = self.controller.get_server_obj(server_id)
svr = self.controller.servers.get_server_obj(server_id)
svr.agree_eula(exec_user["user_id"])
elif page == "restore_backup":

View File

@ -127,7 +127,7 @@ class NodeStats(ApiHandler):
return
# Get node stats
node_stats = self.controller.stats.get_node_stats()
node_stats = self.controller.servers.stats.get_node_stats()
self.return_response(200, {"code": node_stats["node_stats"]})
@ -161,7 +161,7 @@ class SendCommand(ApiHandler):
command = self.get_argument("command", default=None, strip=True)
server_id = self.get_argument("id")
if command:
server = self.controller.get_server_obj(server_id)
server = self.controller.servers.get_server_obj(server_id)
if server.check_running:
server.send_command(command)
self.return_response(200, {"run": True})
@ -198,7 +198,7 @@ class ServerBackup(ApiHandler):
self.access_denied(user)
return
server = self.controller.get_server_obj(server_id)
server = self.controller.servers.get_server_obj(server_id)
server.backup_server()
@ -232,7 +232,7 @@ class StartServer(ApiHandler):
self.access_denied("unknown")
return
server = self.controller.get_server_obj(server_id)
server = self.controller.servers.get_server_obj(server_id)
if not server.check_running():
self.controller.management.send_command(
@ -270,7 +270,7 @@ class StopServer(ApiHandler):
self.access_denied(user)
return
server = self.controller.get_server_obj(server_id)
server = self.controller.servers.get_server_obj(server_id)
if server.check_running():
self.controller.management.send_command(

View File

@ -180,7 +180,7 @@ class BaseHandler(tornado.web.RequestHandler):
exec_user_role = set()
if superuser:
authorized_servers = self.controller.list_defined_servers()
authorized_servers = self.controller.servers.list_defined_servers()
exec_user_role.add("Super User")
exec_user_crafty_permissions = (
self.controller.crafty_perms.list_defined_crafty_permissions()

View File

@ -42,7 +42,7 @@ class PanelHandler(BaseHandler):
def get_role_servers(self) -> t.Set[int]:
servers = set()
for server in self.controller.list_defined_servers():
for server in self.controller.servers.list_defined_servers():
argument = self.get_argument(f"server_{server['server_id']}_access", "0")
if argument == "0":
continue
@ -191,7 +191,7 @@ class PanelHandler(BaseHandler):
total_players = 0
for server in page_data["servers"]:
total_players += len(
self.controller.stats.get_server_players(
self.controller.servers.stats.get_server_players(
server["server_data"]["server_id"]
)
)
@ -223,7 +223,7 @@ class PanelHandler(BaseHandler):
superuser = superuser and api_key.superuser
if superuser: # TODO: Figure out a better solution
defined_servers = self.controller.list_defined_servers()
defined_servers = self.controller.servers.list_defined_servers()
exec_user_role = {"Super User"}
exec_user_crafty_permissions = (
self.controller.crafty_perms.list_defined_crafty_permissions()
@ -285,10 +285,10 @@ class PanelHandler(BaseHandler):
},
"server_stats": {
"total": len(defined_servers),
"running": len(self.controller.list_running_servers()),
"running": len(self.controller.servers.list_running_servers()),
"stopped": (
len(self.controller.list_defined_servers())
- len(self.controller.list_running_servers())
len(self.controller.servers.list_defined_servers())
- len(self.controller.servers.list_running_servers())
),
},
"menu_servers": defined_servers,
@ -398,7 +398,7 @@ class PanelHandler(BaseHandler):
"servers"
] = self.controller.servers.get_all_servers_stats()
except IndexError:
self.controller.stats.record_stats()
self.controller.servers.stats.record_stats()
page_data[
"servers"
] = self.controller.servers.get_all_servers_stats()
@ -408,7 +408,7 @@ class PanelHandler(BaseHandler):
exec_user["user_id"]
)
except IndexError:
self.controller.stats.record_stats()
self.controller.servers.stats.record_stats()
user_auth = self.controller.servers.get_authorized_servers_stats(
exec_user["user_id"]
)
@ -491,7 +491,7 @@ class PanelHandler(BaseHandler):
"schedules",
]
server = self.controller.get_server_obj(server_id)
server = self.controller.servers.get_server_obj(server_id)
# server_data isn't needed since the server_stats also pulls server data
page_data["server_data"] = self.controller.servers.get_server_data_by_id(
server_id
@ -509,9 +509,9 @@ class PanelHandler(BaseHandler):
except Exception as e:
logger.error(f"Failed to get server waiting to start: {e}")
page_data["waiting_start"] = False
page_data["get_players"] = lambda: self.controller.stats.get_server_players(
server_id
)
page_data[
"get_players"
] = lambda: self.controller.servers.stats.get_server_players(server_id)
page_data["active_link"] = subpage
page_data["permissions"] = {
"Commands": EnumPermissionsServer.COMMANDS,
@ -639,10 +639,10 @@ class PanelHandler(BaseHandler):
page_data[
"exclusions"
] = self.controller.management.get_excluded_backup_dirs(server_id)
page_data["backing_up"] = self.controller.get_server_obj(
page_data["backing_up"] = self.controller.servers.get_server_obj(
server_id
).is_backingup
page_data["backup_stats"] = self.controller.get_server_obj(
page_data["backup_stats"] = self.controller.servers.get_server_obj(
server_id
).send_backup_status()
# makes it so relative path is the only thing shown
@ -652,7 +652,7 @@ class PanelHandler(BaseHandler):
else:
exclusions.append(file.replace(server_info["path"] + "/", ""))
page_data["exclusions"] = exclusions
self.controller.refresh_server_settings(server_id)
self.controller.servers.refresh_server_settings(server_id)
try:
page_data["backup_list"] = server.list_backups()
except:
@ -792,7 +792,7 @@ class PanelHandler(BaseHandler):
page_data["roles_all"] = self.controller.roles.get_all_roles()
page_data["servers"] = []
page_data["servers_all"] = self.controller.list_defined_servers()
page_data["servers_all"] = self.controller.servers.list_defined_servers()
page_data["role-servers"] = []
page_data[
"permissions_all"
@ -826,9 +826,9 @@ class PanelHandler(BaseHandler):
page_data["schedules"] = HelpersManagement.get_schedules_by_server(
server_id
)
page_data["get_players"] = lambda: self.controller.stats.get_server_players(
server_id
)
page_data[
"get_players"
] = lambda: self.controller.servers.stats.get_server_players(server_id)
page_data["active_link"] = "schedules"
page_data["permissions"] = {
"Commands": EnumPermissionsServer.COMMANDS,
@ -890,9 +890,9 @@ class PanelHandler(BaseHandler):
if sch_id is None:
self.redirect("/panel/error?error=Invalid Schedule ID")
schedule = self.controller.management.get_scheduled_task_model(sch_id)
page_data["get_players"] = lambda: self.controller.stats.get_server_players(
server_id
)
page_data[
"get_players"
] = lambda: self.controller.servers.stats.get_server_players(server_id)
page_data["active_link"] = "schedules"
page_data["permissions"] = {
"Commands": EnumPermissionsServer.COMMANDS,
@ -970,7 +970,7 @@ class PanelHandler(BaseHandler):
page_data["servers"] = set()
page_data["role-servers"] = page_role_servers
page_data["roles_all"] = self.controller.roles.get_all_roles()
page_data["servers_all"] = self.controller.list_defined_servers()
page_data["servers_all"] = self.controller.servers.list_defined_servers()
page_data["superuser"] = superuser
page_data[
"permissions_all"
@ -1098,7 +1098,7 @@ class PanelHandler(BaseHandler):
)
return
page_data["servers_all"] = self.controller.list_defined_servers()
page_data["servers_all"] = self.controller.servers.list_defined_servers()
page_data[
"permissions_all"
] = self.controller.server_perms.list_defined_permissions()
@ -1110,7 +1110,7 @@ class PanelHandler(BaseHandler):
page_data["new_role"] = False
role_id = self.get_argument("id", None)
page_data["role"] = self.controller.roles.get_role_with_servers(role_id)
page_data["servers_all"] = self.controller.list_defined_servers()
page_data["servers_all"] = self.controller.servers.list_defined_servers()
page_data[
"permissions_all"
] = self.controller.server_perms.list_defined_permissions()
@ -1257,7 +1257,7 @@ class PanelHandler(BaseHandler):
"Players": EnumPermissionsServer.PLAYERS,
}
if superuser:
# defined_servers = self.controller.list_defined_servers()
# defined_servers = self.controller.servers.list_defined_servers()
exec_user_role = {"Super User"}
exec_user_crafty_permissions = (
self.controller.crafty_perms.list_defined_crafty_permissions()
@ -1354,7 +1354,7 @@ class PanelHandler(BaseHandler):
self.controller.servers.update_server(server_obj)
self.controller.crash_detection(server_obj)
self.controller.refresh_server_settings(server_id)
self.controller.servers.refresh_server_settings(server_id)
self.controller.management.add_to_audit_log(
exec_user["user_id"],

View File

@ -688,7 +688,7 @@ class ApiServersIndexHandler(BaseApiHandler):
# Increase the server creation counter
self.controller.crafty_perms.add_server_creation(user["user_id"])
self.controller.stats.record_stats()
self.controller.servers.stats.record_stats()
self.controller.management.add_to_audit_log(
user["user_id"],

View File

@ -28,7 +28,7 @@ class ServerHandler(BaseHandler):
superuser = superuser and api_key.superuser
if superuser:
defined_servers = self.controller.list_defined_servers()
defined_servers = self.controller.servers.list_defined_servers()
exec_user_role = {"Super User"}
exec_user_crafty_permissions = (
self.controller.crafty_perms.list_defined_crafty_permissions()
@ -66,11 +66,11 @@ class ServerHandler(BaseHandler):
"Roles_Config": EnumPermissionsCrafty.ROLES_CONFIG,
},
"server_stats": {
"total": len(self.controller.list_defined_servers()),
"running": len(self.controller.list_running_servers()),
"total": len(self.controller.servers.list_defined_servers()),
"running": len(self.controller.servers.list_running_servers()),
"stopped": (
len(self.controller.list_defined_servers())
- len(self.controller.list_running_servers())
len(self.controller.servers.list_defined_servers())
- len(self.controller.servers.list_running_servers())
),
},
"hosts_data": self.controller.management.get_latest_hosts_stats(),
@ -370,7 +370,7 @@ class ServerHandler(BaseHandler):
new_server_id, role_id, "11111111"
)
self.controller.stats.record_stats()
self.controller.servers.stats.record_stats()
self.redirect("/panel/dashboard")
if page == "bedrock_step1":
@ -487,7 +487,7 @@ class ServerHandler(BaseHandler):
new_server_id, role_id, "11111111"
)
self.controller.stats.record_stats()
self.controller.servers.stats.record_stats()
self.redirect("/panel/dashboard")
try:

View File

@ -151,8 +151,8 @@ if __name__ == "__main__":
# init servers
logger.info("Initializing all servers defined")
Console.info("Initializing all servers defined")
controller.init_all_servers()
servers = controller.list_defined_servers()
controller.servers.init_all_servers()
servers = controller.servers.list_defined_servers()
def tasks_starter():
# start stats logging