mirror of
https://gitlab.com/crafty-controller/crafty-4.git
synced 2024-08-30 18:23:09 +00:00
Fix files to conform with new ⚫Black pylintrc
Mostly just breaking up strings and comments into new lines Some strings dont require 'f' but keeping in for readability with the rest of the concatinated string
This commit is contained in:
parent
9b2161d450
commit
2a512d7273
@ -36,15 +36,19 @@ class Crafty_Perms_Controller:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def can_add_user(): # Add back argument 'user_id' when you work on this
|
def can_add_user(): # Add back argument 'user_id' when you work on this
|
||||||
# TODO: Complete if we need a User Addition limit
|
|
||||||
# return crafty_permissions.can_add_in_crafty(user_id, Enum_Permissions_Crafty.User_Config)
|
|
||||||
return True
|
return True
|
||||||
|
# TODO: Complete if we need a User Addition limit
|
||||||
|
# return crafty_permissions.can_add_in_crafty(
|
||||||
|
# user_id, Enum_Permissions_Crafty.User_Config
|
||||||
|
# )
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def can_add_role(): # Add back argument 'user_id' when you work on this
|
def can_add_role(): # Add back argument 'user_id' when you work on this
|
||||||
# TODO: Complete if we need a Role Addition limit
|
|
||||||
# return crafty_permissions.can_add_in_crafty(user_id, Enum_Permissions_Crafty.Roles_Config)
|
|
||||||
return True
|
return True
|
||||||
|
# TODO: Complete if we need a Role Addition limit
|
||||||
|
# return crafty_permissions.can_add_in_crafty(
|
||||||
|
# user_id, Enum_Permissions_Crafty.Roles_Config
|
||||||
|
# )
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def list_all_crafty_permissions_quantity_limits():
|
def list_all_crafty_permissions_quantity_limits():
|
||||||
|
@ -8,16 +8,16 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class Management_Controller:
|
class Management_Controller:
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Host_Stats Methods
|
# Host_Stats Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_latest_hosts_stats():
|
def get_latest_hosts_stats():
|
||||||
return management_helper.get_latest_hosts_stats()
|
return management_helper.get_latest_hosts_stats()
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Commands Methods
|
# Commands Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_unactioned_commands():
|
def get_unactioned_commands():
|
||||||
return management_helper.get_unactioned_commands()
|
return management_helper.get_unactioned_commands()
|
||||||
@ -39,9 +39,9 @@ class Management_Controller:
|
|||||||
def mark_command_complete(command_id=None):
|
def mark_command_complete(command_id=None):
|
||||||
return management_helper.mark_command_complete(command_id)
|
return management_helper.mark_command_complete(command_id)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Audit_Log Methods
|
# Audit_Log Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_actity_log():
|
def get_actity_log():
|
||||||
return management_helper.get_actity_log()
|
return management_helper.get_actity_log()
|
||||||
@ -58,9 +58,9 @@ class Management_Controller:
|
|||||||
user_name, user_id, server_id, log_msg, source_ip
|
user_name, user_id, server_id, log_msg, source_ip
|
||||||
)
|
)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Schedules Methods
|
# Schedules Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def create_scheduled_task(
|
def create_scheduled_task(
|
||||||
server_id,
|
server_id,
|
||||||
@ -115,9 +115,9 @@ class Management_Controller:
|
|||||||
def get_schedules_enabled():
|
def get_schedules_enabled():
|
||||||
return management_helper.get_schedules_enabled()
|
return management_helper.get_schedules_enabled()
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Backups Methods
|
# Backups Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_backup_config(server_id):
|
def get_backup_config(server_id):
|
||||||
return management_helper.get_backup_config(server_id)
|
return management_helper.get_backup_config(server_id)
|
||||||
|
@ -45,7 +45,8 @@ class Roles_Controller:
|
|||||||
server_permissions.get_or_create(role_id, server, permissions_mask)
|
server_permissions.get_or_create(role_id, server, permissions_mask)
|
||||||
for server in base_data["servers"]:
|
for server in base_data["servers"]:
|
||||||
server_permissions.update_role_permission(role_id, server, permissions_mask)
|
server_permissions.update_role_permission(role_id, server, permissions_mask)
|
||||||
# TODO: This is horribly inefficient and we should be using bulk queries but im going for functionality at this point
|
# TODO: This is horribly inefficient and we should be using bulk queries
|
||||||
|
# but im going for functionality at this point
|
||||||
server_permissions.delete_roles_permissions(role_id, removed_servers)
|
server_permissions.delete_roles_permissions(role_id, removed_servers)
|
||||||
if up_data:
|
if up_data:
|
||||||
roles_helper.update_role(role_id, up_data)
|
roles_helper.update_role(role_id, up_data)
|
||||||
|
@ -51,11 +51,11 @@ class Server_Perms_Controller:
|
|||||||
int(role.role_id), int(old_server_id)
|
int(role.role_id), int(old_server_id)
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
# server_permissions.add_role_server(new_server_id, role.role_id, '00001000')
|
# server_permissions.add_role_server(new_server_id, role.role_id,"00001000")
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers Permissions Methods
|
# Servers Permissions Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_permissions_mask(role_id, server_id):
|
def get_permissions_mask(role_id, server_id):
|
||||||
return server_permissions.get_permissions_mask(role_id, server_id)
|
return server_permissions.get_permissions_mask(role_id, server_id)
|
||||||
|
@ -17,9 +17,9 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class Servers_Controller:
|
class Servers_Controller:
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Generic Servers Methods
|
# Generic Servers Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def create_server(
|
def create_server(
|
||||||
name: str,
|
name: str,
|
||||||
@ -81,9 +81,9 @@ class Servers_Controller:
|
|||||||
def get_server_data_by_id(server_id):
|
def get_server_data_by_id(server_id):
|
||||||
return servers_helper.get_server_data_by_id(server_id)
|
return servers_helper.get_server_data_by_id(server_id)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers Methods
|
# Servers Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_all_defined_servers():
|
def get_all_defined_servers():
|
||||||
return servers_helper.get_all_defined_servers()
|
return servers_helper.get_all_defined_servers()
|
||||||
@ -157,9 +157,9 @@ class Servers_Controller:
|
|||||||
def get_server_friendly_name(server_id):
|
def get_server_friendly_name(server_id):
|
||||||
return servers_helper.get_server_friendly_name(server_id)
|
return servers_helper.get_server_friendly_name(server_id)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers_Stats Methods
|
# Servers_Stats Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_server_stats_by_id(server_id):
|
def get_server_stats_by_id(server_id):
|
||||||
return servers_helper.get_server_stats_by_id(server_id)
|
return servers_helper.get_server_stats_by_id(server_id)
|
||||||
@ -218,9 +218,9 @@ class Servers_Controller:
|
|||||||
def get_update_status(server_id):
|
def get_update_status(server_id):
|
||||||
return servers_helper.get_update_status(server_id)
|
return servers_helper.get_update_status(server_id)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers Helpers Methods
|
# Servers Helpers Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_banned_players(server_id):
|
def get_banned_players(server_id):
|
||||||
stats = servers_helper.get_server_stats_by_id(server_id)
|
stats = servers_helper.get_server_stats_by_id(server_id)
|
||||||
|
@ -14,9 +14,9 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class Users_Controller:
|
class Users_Controller:
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Users Methods
|
# Users Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_all_users():
|
def get_all_users():
|
||||||
return users_helper.get_all_users()
|
return users_helper.get_all_users()
|
||||||
@ -163,9 +163,9 @@ class Users_Controller:
|
|||||||
_, user = authentication.check(token)
|
_, user = authentication.check(token)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# User Roles Methods
|
# User Roles Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_user_roles_id(user_id):
|
def get_user_roles_id(user_id):
|
||||||
@ -187,9 +187,9 @@ class Users_Controller:
|
|||||||
def user_role_query(user_id):
|
def user_role_query(user_id):
|
||||||
return users_helper.user_role_query(user_id)
|
return users_helper.user_role_query(user_id)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Api Keys Methods
|
# Api Keys Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_user_api_keys(user_id: str):
|
def get_user_api_keys(user_id: str):
|
||||||
|
@ -1,66 +1,67 @@
|
|||||||
import pprint
|
import pprint
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
|
||||||
class ServerProps:
|
class ServerProps:
|
||||||
def __init__(self, filepath):
|
def __init__(self, filepath):
|
||||||
self.filepath = filepath
|
self.filepath = filepath
|
||||||
self.props = self._parse()
|
self.props = self._parse()
|
||||||
|
|
||||||
def _parse(self):
|
def _parse(self):
|
||||||
"""Loads and parses the file specified in self.filepath"""
|
# Loads and parses the file specified in self.filepath
|
||||||
with open(self.filepath, encoding="utf-8") as fp:
|
with open(self.filepath, encoding="utf-8") as fp:
|
||||||
line = fp.readline()
|
line = fp.readline()
|
||||||
d = {}
|
d = {}
|
||||||
if os.path.exists(".header"):
|
if os.path.exists(".header"):
|
||||||
os.remove(".header")
|
os.remove(".header")
|
||||||
while line:
|
while line:
|
||||||
if "#" != line[0]:
|
if "#" != line[0]:
|
||||||
s = line
|
s = line
|
||||||
s1 = s[: s.find("=")]
|
s1 = s[: s.find("=")]
|
||||||
if "\n" in s:
|
if "\n" in s:
|
||||||
s2 = s[s.find("=") + 1 : s.find("\n")]
|
s2 = s[s.find("=") + 1 : s.find("\n")]
|
||||||
else:
|
else:
|
||||||
s2 = s[s.find("=") + 1 :]
|
s2 = s[s.find("=") + 1 :]
|
||||||
d[s1] = s2
|
d[s1] = s2
|
||||||
else:
|
else:
|
||||||
with open(".header", "a+", encoding="utf-8") as h:
|
with open(".header", "a+", encoding="utf-8") as h:
|
||||||
h.write(line)
|
h.write(line)
|
||||||
line = fp.readline()
|
line = fp.readline()
|
||||||
return d
|
return d
|
||||||
|
|
||||||
def print(self):
|
def print(self):
|
||||||
"""Prints the properties dictionary (using pprint)"""
|
# Prints the properties dictionary (using pprint)
|
||||||
pprint.pprint(self.props)
|
pprint.pprint(self.props)
|
||||||
|
|
||||||
def get(self):
|
def get(self):
|
||||||
"""Returns the properties dictionary"""
|
# Returns the properties dictionary
|
||||||
return self.props
|
return self.props
|
||||||
|
|
||||||
def update(self, key, val):
|
def update(self, key, val):
|
||||||
"""Updates property in the properties dictionary [ update("pvp", "true") ] and returns boolean condition"""
|
# Updates property in the properties dictionary [ update("pvp", "true") ]
|
||||||
if key in self.props.keys():
|
# and returns boolean condition
|
||||||
self.props[key] = val
|
if key in self.props.keys():
|
||||||
return True
|
self.props[key] = val
|
||||||
else:
|
return True
|
||||||
return False
|
else:
|
||||||
|
return False
|
||||||
def save(self):
|
|
||||||
"""Writes to the new file"""
|
def save(self):
|
||||||
with open(self.filepath, "a+", encoding="utf-8") as f:
|
# Writes to the new file
|
||||||
f.truncate(0)
|
with open(self.filepath, "a+", encoding="utf-8") as f:
|
||||||
with open(".header", encoding="utf-8") as header:
|
f.truncate(0)
|
||||||
line = header.readline()
|
with open(".header", encoding="utf-8") as header:
|
||||||
while line:
|
line = header.readline()
|
||||||
f.write(line)
|
while line:
|
||||||
line = header.readline()
|
f.write(line)
|
||||||
header.close()
|
line = header.readline()
|
||||||
for key, value in self.props.items():
|
header.close()
|
||||||
f.write(key + "=" + value + "\n")
|
for key, value in self.props.items():
|
||||||
if os.path.exists(".header"):
|
f.write(key + "=" + value + "\n")
|
||||||
os.remove(".header")
|
if os.path.exists(".header"):
|
||||||
|
os.remove(".header")
|
||||||
@staticmethod
|
|
||||||
def cleanup():
|
@staticmethod
|
||||||
if os.path.exists(".header"):
|
def cleanup():
|
||||||
os.remove(".header")
|
if os.path.exists(".header"):
|
||||||
|
os.remove(".header")
|
||||||
|
@ -137,7 +137,8 @@ class ServerJars:
|
|||||||
# jar versions for this server
|
# jar versions for this server
|
||||||
versions = self._get_jar_details(s)
|
versions = self._get_jar_details(s)
|
||||||
|
|
||||||
# add these versions (a list) to the dict with a key of the server type
|
# add these versions (a list) to the dict with
|
||||||
|
# a key of the server type
|
||||||
data["servers"].update({s: versions})
|
data["servers"].update({s: versions})
|
||||||
|
|
||||||
# save our cache
|
# save our cache
|
||||||
@ -177,7 +178,8 @@ class ServerJars:
|
|||||||
fetch_url = f"{self.base_url}/api/fetchJar/{server}/{version}"
|
fetch_url = f"{self.base_url}/api/fetchJar/{server}/{version}"
|
||||||
server_users = server_permissions.get_server_user_list(server_id)
|
server_users = server_permissions.get_server_user_list(server_id)
|
||||||
|
|
||||||
# We need to make sure the server is registered before we submit a db update for it's stats.
|
# We need to make sure the server is registered before
|
||||||
|
# we submit a db update for it's stats.
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
Servers_Controller.set_download(server_id)
|
Servers_Controller.set_download(server_id)
|
||||||
|
@ -67,7 +67,7 @@ class Stats:
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(
|
logger.error(
|
||||||
f"Unable to get process details for pid: {process_pid} due to error: {e}"
|
f"Unable to get process details for pid: {process_pid} Error: {e}"
|
||||||
)
|
)
|
||||||
|
|
||||||
# Dummy Data
|
# Dummy Data
|
||||||
@ -77,7 +77,7 @@ class Stats:
|
|||||||
}
|
}
|
||||||
return process_stats
|
return process_stats
|
||||||
|
|
||||||
# shamelessly stolen from https://github.com/giampaolo/psutil/blob/master/scripts/disk_usage.py
|
# Source: https://github.com/giampaolo/psutil/blob/master/scripts/disk_usage.py
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _all_disk_usage():
|
def _all_disk_usage():
|
||||||
disk_data = []
|
disk_data = []
|
||||||
@ -207,26 +207,29 @@ class Stats:
|
|||||||
}
|
}
|
||||||
).execute()
|
).execute()
|
||||||
|
|
||||||
# server_stats = stats_to_send.get('servers')#
|
# server_stats = stats_to_send.get("servers")
|
||||||
#
|
# for server in server_stats:
|
||||||
# for server in server_stats:
|
# Server_Stats.insert(
|
||||||
# Server_Stats.insert({
|
# {
|
||||||
# Server_Stats.server_id: server.get('id', 0),
|
# Server_Stats.server_id: server.get("id", 0),
|
||||||
# Server_Stats.started: server.get('started', ""),
|
# Server_Stats.started: server.get("started", ""),
|
||||||
# Server_Stats.running: server.get('running', False),
|
# Server_Stats.running: server.get("running", False),
|
||||||
# Server_Stats.cpu: server.get('cpu', 0),
|
# Server_Stats.cpu: server.get("cpu", 0),
|
||||||
# Server_Stats.mem: server.get('mem', 0),
|
# Server_Stats.mem: server.get("mem", 0),
|
||||||
# Server_Stats.mem_percent: server.get('mem_percent', 0),
|
# Server_Stats.mem_percent: server.get("mem_percent", 0),
|
||||||
# Server_Stats.world_name: server.get('world_name', ""),
|
# Server_Stats.world_name: server.get("world_name", ""),
|
||||||
# Server_Stats.world_size: server.get('world_size', ""),
|
# Server_Stats.world_size: server.get("world_size", ""),
|
||||||
# Server_Stats.server_port: server.get('server_port', ""),
|
# Server_Stats.server_port: server.get("server_port", ""),
|
||||||
# Server_Stats.int_ping_results: server.get('int_ping_results', False),
|
# Server_Stats.int_ping_results: server.get(
|
||||||
# Server_Stats.online: server.get("online", False),
|
# "int_ping_results", False
|
||||||
# Server_Stats.max: server.get("max", False),
|
# ),
|
||||||
# Server_Stats.players: server.get("players", False),
|
# Server_Stats.online: server.get("online", False),
|
||||||
# Server_Stats.desc: server.get("desc", False),
|
# Server_Stats.max: server.get("max", False),
|
||||||
# Server_Stats.version: server.get("version", False)
|
# Server_Stats.players: server.get("players", False),
|
||||||
# }).execute()
|
# Server_Stats.desc: server.get("desc", False),
|
||||||
|
# Server_Stats.version: server.get("version", False),
|
||||||
|
# }
|
||||||
|
# ).execute()
|
||||||
|
|
||||||
# delete old data
|
# delete old data
|
||||||
max_age = helper.get_setting("history_max_age")
|
max_age = helper.get_setting("history_max_age")
|
||||||
|
@ -26,9 +26,9 @@ database = SqliteDatabase(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# User_Crafty Class
|
# User_Crafty Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class User_Crafty(Model):
|
class User_Crafty(Model):
|
||||||
user_id = ForeignKeyField(Users, backref="users_crafty")
|
user_id = ForeignKeyField(Users, backref="users_crafty")
|
||||||
permissions = CharField(default="00000000")
|
permissions = CharField(default="00000000")
|
||||||
@ -44,9 +44,9 @@ class User_Crafty(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Crafty Permissions Class
|
# Crafty Permissions Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Enum_Permissions_Crafty(Enum):
|
class Enum_Permissions_Crafty(Enum):
|
||||||
Server_Creation = 0
|
Server_Creation = 0
|
||||||
User_Config = 1
|
User_Config = 1
|
||||||
@ -54,10 +54,9 @@ class Enum_Permissions_Crafty(Enum):
|
|||||||
|
|
||||||
|
|
||||||
class Permissions_Crafty:
|
class Permissions_Crafty:
|
||||||
|
# **********************************************************************************
|
||||||
# ************************************************************************************************
|
|
||||||
# Crafty Permissions Methods
|
# Crafty Permissions Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_permissions_list():
|
def get_permissions_list():
|
||||||
permissions_list = []
|
permissions_list = []
|
||||||
@ -113,15 +112,15 @@ class Permissions_Crafty:
|
|||||||
def get_permission_quantity_list(user_id):
|
def get_permission_quantity_list(user_id):
|
||||||
user_crafty = crafty_permissions.get_User_Crafty(user_id)
|
user_crafty = crafty_permissions.get_User_Crafty(user_id)
|
||||||
quantity_list = {
|
quantity_list = {
|
||||||
Enum_Permissions_Crafty.Server_Creation.name: user_crafty.limit_server_creation,
|
Enum_Permissions_Crafty.Server_Creation.name: user_crafty.limit_server_creation, # pylint: disable=line-too-long
|
||||||
Enum_Permissions_Crafty.User_Config.name: user_crafty.limit_user_creation,
|
Enum_Permissions_Crafty.User_Config.name: user_crafty.limit_user_creation,
|
||||||
Enum_Permissions_Crafty.Roles_Config.name: user_crafty.limit_role_creation,
|
Enum_Permissions_Crafty.Roles_Config.name: user_crafty.limit_role_creation,
|
||||||
}
|
}
|
||||||
return quantity_list
|
return quantity_list
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# User_Crafty Methods
|
# User_Crafty Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_User_Crafty(user_id):
|
def get_User_Crafty(user_id):
|
||||||
try:
|
try:
|
||||||
|
@ -33,9 +33,9 @@ database = SqliteDatabase(
|
|||||||
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
||||||
)
|
)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Audit_Log Class
|
# Audit_Log Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Audit_Log(Model):
|
class Audit_Log(Model):
|
||||||
audit_id = AutoField()
|
audit_id = AutoField()
|
||||||
created = DateTimeField(default=datetime.datetime.now)
|
created = DateTimeField(default=datetime.datetime.now)
|
||||||
@ -51,9 +51,9 @@ class Audit_Log(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Host_Stats Class
|
# Host_Stats Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Host_Stats(Model):
|
class Host_Stats(Model):
|
||||||
time = DateTimeField(default=datetime.datetime.now, index=True)
|
time = DateTimeField(default=datetime.datetime.now, index=True)
|
||||||
boot_time = CharField(default="")
|
boot_time = CharField(default="")
|
||||||
@ -71,9 +71,9 @@ class Host_Stats(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Commands Class
|
# Commands Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Commands(Model):
|
class Commands(Model):
|
||||||
command_id = AutoField()
|
command_id = AutoField()
|
||||||
created = DateTimeField(default=datetime.datetime.now)
|
created = DateTimeField(default=datetime.datetime.now)
|
||||||
@ -88,9 +88,9 @@ class Commands(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Webhooks Class
|
# Webhooks Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Webhooks(Model):
|
class Webhooks(Model):
|
||||||
id = AutoField()
|
id = AutoField()
|
||||||
name = CharField(max_length=64, unique=True, index=True)
|
name = CharField(max_length=64, unique=True, index=True)
|
||||||
@ -104,9 +104,9 @@ class Webhooks(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Schedules Class
|
# Schedules Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Schedules(Model):
|
class Schedules(Model):
|
||||||
schedule_id = IntegerField(unique=True, primary_key=True)
|
schedule_id = IntegerField(unique=True, primary_key=True)
|
||||||
server_id = ForeignKeyField(Servers, backref="schedule_server")
|
server_id = ForeignKeyField(Servers, backref="schedule_server")
|
||||||
@ -127,9 +127,9 @@ class Schedules(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Backups Class
|
# Backups Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Backups(Model):
|
class Backups(Model):
|
||||||
excluded_dirs = CharField(null=True)
|
excluded_dirs = CharField(null=True)
|
||||||
max_backups = IntegerField()
|
max_backups = IntegerField()
|
||||||
@ -143,18 +143,18 @@ class Backups(Model):
|
|||||||
|
|
||||||
class helpers_management:
|
class helpers_management:
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Host_Stats Methods
|
# Host_Stats Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_latest_hosts_stats():
|
def get_latest_hosts_stats():
|
||||||
# pylint: disable=no-member
|
# pylint: disable=no-member
|
||||||
query = Host_Stats.select().order_by(Host_Stats.id.desc()).get()
|
query = Host_Stats.select().order_by(Host_Stats.id.desc()).get()
|
||||||
return model_to_dict(query)
|
return model_to_dict(query)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Commands Methods
|
# Commands Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def add_command(server_id, user_id, remote_ip, command):
|
def add_command(server_id, user_id, remote_ip, command):
|
||||||
Commands.insert(
|
Commands.insert(
|
||||||
@ -179,9 +179,9 @@ class helpers_management:
|
|||||||
Commands.command_id == command_id
|
Commands.command_id == command_id
|
||||||
).execute()
|
).execute()
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Audit_Log Methods
|
# Audit_Log Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_actity_log():
|
def get_actity_log():
|
||||||
q = Audit_Log.select()
|
q = Audit_Log.select()
|
||||||
@ -243,9 +243,9 @@ class helpers_management:
|
|||||||
else:
|
else:
|
||||||
return
|
return
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Schedules Methods
|
# Schedules Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def create_scheduled_task(
|
def create_scheduled_task(
|
||||||
server_id,
|
server_id,
|
||||||
@ -325,9 +325,9 @@ class helpers_management:
|
|||||||
# pylint: disable=singleton-comparison
|
# pylint: disable=singleton-comparison
|
||||||
return Schedules.select().where(Schedules.enabled == True).execute()
|
return Schedules.select().where(Schedules.enabled == True).execute()
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Backups Methods
|
# Backups Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_backup_config(server_id):
|
def get_backup_config(server_id):
|
||||||
try:
|
try:
|
||||||
|
@ -24,9 +24,9 @@ database = SqliteDatabase(
|
|||||||
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
||||||
)
|
)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Roles Class
|
# Roles Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Roles(Model):
|
class Roles(Model):
|
||||||
role_id = AutoField()
|
role_id = AutoField()
|
||||||
created = DateTimeField(default=datetime.datetime.now)
|
created = DateTimeField(default=datetime.datetime.now)
|
||||||
@ -38,9 +38,9 @@ class Roles(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Roles Helpers
|
# Roles Helpers
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class helper_roles:
|
class helper_roles:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_all_roles():
|
def get_all_roles():
|
||||||
|
@ -27,9 +27,9 @@ database = SqliteDatabase(
|
|||||||
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
||||||
)
|
)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Role Servers Class
|
# Role Servers Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Role_Servers(Model):
|
class Role_Servers(Model):
|
||||||
role_id = ForeignKeyField(Roles, backref="role_server")
|
role_id = ForeignKeyField(Roles, backref="role_server")
|
||||||
server_id = ForeignKeyField(Servers, backref="role_server")
|
server_id = ForeignKeyField(Servers, backref="role_server")
|
||||||
@ -41,9 +41,9 @@ class Role_Servers(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers Permissions Class
|
# Servers Permissions Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Enum_Permissions_Server(Enum):
|
class Enum_Permissions_Server(Enum):
|
||||||
Commands = 0
|
Commands = 0
|
||||||
Terminal = 1
|
Terminal = 1
|
||||||
@ -104,9 +104,9 @@ class Permissions_Servers:
|
|||||||
permissions_list.append(member[1])
|
permissions_list.append(member[1])
|
||||||
return permissions_list
|
return permissions_list
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Role_Servers Methods
|
# Role_Servers Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_role_servers_from_role_id(roleid):
|
def get_role_servers_from_role_id(roleid):
|
||||||
return Role_Servers.select().where(Role_Servers.role_id == roleid)
|
return Role_Servers.select().where(Role_Servers.role_id == roleid)
|
||||||
|
@ -27,9 +27,9 @@ database = SqliteDatabase(
|
|||||||
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
||||||
)
|
)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers Class
|
# Servers Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Servers(Model):
|
class Servers(Model):
|
||||||
server_id = AutoField()
|
server_id = AutoField()
|
||||||
created = DateTimeField(default=datetime.datetime.now)
|
created = DateTimeField(default=datetime.datetime.now)
|
||||||
@ -55,9 +55,9 @@ class Servers(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers Stats Class
|
# Servers Stats Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Server_Stats(Model):
|
class Server_Stats(Model):
|
||||||
stats_id = AutoField()
|
stats_id = AutoField()
|
||||||
created = DateTimeField(default=datetime.datetime.now)
|
created = DateTimeField(default=datetime.datetime.now)
|
||||||
@ -87,14 +87,14 @@ class Server_Stats(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers Class
|
# Servers Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class helper_servers:
|
class helper_servers:
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Generic Servers Methods
|
# Generic Servers Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def create_server(
|
def create_server(
|
||||||
name: str,
|
name: str,
|
||||||
@ -152,9 +152,9 @@ class helper_servers:
|
|||||||
except IndexError:
|
except IndexError:
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers Methods
|
# Servers Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_all_defined_servers():
|
def get_all_defined_servers():
|
||||||
query = Servers.select()
|
query = Servers.select()
|
||||||
@ -188,12 +188,15 @@ class helper_servers:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def get_server_friendly_name(server_id):
|
def get_server_friendly_name(server_id):
|
||||||
server_data = servers_helper.get_server_data_by_id(server_id)
|
server_data = servers_helper.get_server_data_by_id(server_id)
|
||||||
friendly_name = f"{server_data.get('server_name', None)} with ID: {server_data.get('server_id', 0)}"
|
friendly_name = (
|
||||||
|
f"{server_data.get('server_name', None)} "
|
||||||
|
f"with ID: {server_data.get('server_id', 0)}"
|
||||||
|
)
|
||||||
return friendly_name
|
return friendly_name
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Servers_Stats Methods
|
# Servers_Stats Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_latest_server_stats(server_id):
|
def get_latest_server_stats(server_id):
|
||||||
return (
|
return (
|
||||||
|
@ -30,9 +30,9 @@ database = SqliteDatabase(
|
|||||||
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
|
||||||
)
|
)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Users Class
|
# Users Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Users(Model):
|
class Users(Model):
|
||||||
user_id = AutoField()
|
user_id = AutoField()
|
||||||
created = DateTimeField(default=datetime.datetime.now)
|
created = DateTimeField(default=datetime.datetime.now)
|
||||||
@ -55,9 +55,9 @@ class Users(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# API Keys Class
|
# API Keys Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class ApiKeys(Model):
|
class ApiKeys(Model):
|
||||||
token_id = AutoField()
|
token_id = AutoField()
|
||||||
name = CharField(default="", unique=True, index=True)
|
name = CharField(default="", unique=True, index=True)
|
||||||
@ -72,9 +72,9 @@ class ApiKeys(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# User Roles Class
|
# User Roles Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class User_Roles(Model):
|
class User_Roles(Model):
|
||||||
user_id = ForeignKeyField(Users, backref="user_role")
|
user_id = ForeignKeyField(Users, backref="user_role")
|
||||||
role_id = ForeignKeyField(Roles, backref="user_role")
|
role_id = ForeignKeyField(Roles, backref="user_role")
|
||||||
@ -85,9 +85,9 @@ class User_Roles(Model):
|
|||||||
database = database
|
database = database
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Users Helpers
|
# Users Helpers
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class helper_users:
|
class helper_users:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_by_id(user_id):
|
def get_by_id(user_id):
|
||||||
@ -260,9 +260,9 @@ class helper_users:
|
|||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# User_Roles Methods
|
# User_Roles Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_or_create(user_id, role_id):
|
def get_or_create(user_id, role_id):
|
||||||
@ -335,9 +335,9 @@ class helper_users:
|
|||||||
def remove_roles_from_role_id(role_id):
|
def remove_roles_from_role_id(role_id):
|
||||||
User_Roles.delete().where(User_Roles.role_id == role_id).execute()
|
User_Roles.delete().where(User_Roles.role_id == role_id).execute()
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# ApiKeys Methods
|
# ApiKeys Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_user_api_keys(user_id: str):
|
def get_user_api_keys(user_id: str):
|
||||||
|
@ -63,7 +63,8 @@ class Authentication:
|
|||||||
return None
|
return None
|
||||||
user_id: str = data["user_id"]
|
user_id: str = data["user_id"]
|
||||||
user = users_helper.get_user(user_id)
|
user = users_helper.get_user(user_id)
|
||||||
# TODO: Have a cache or something so we don't constantly have to query the database
|
# TODO: Have a cache or something so we don't constantly
|
||||||
|
# have to query the database
|
||||||
if int(user.get("valid_tokens_from").timestamp()) < iat:
|
if int(user.get("valid_tokens_from").timestamp()) < iat:
|
||||||
# Success!
|
# Success!
|
||||||
return key, data, user
|
return key, data, user
|
||||||
|
@ -56,7 +56,8 @@ class MainPrompt(cmd.Cmd):
|
|||||||
for thread in threading.enumerate():
|
for thread in threading.enumerate():
|
||||||
if sys.version_info >= (3, 8):
|
if sys.version_info >= (3, 8):
|
||||||
print(
|
print(
|
||||||
f"Name: {thread.name} Identifier: {thread.ident} TID/PID: {thread.native_id}"
|
f"Name: {thread.name} Identifier: "
|
||||||
|
f"{thread.ident} TID/PID: {thread.native_id}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
print(f"Name: {thread.name} Identifier: {thread.ident}")
|
print(f"Name: {thread.name} Identifier: {thread.ident}")
|
||||||
|
@ -76,7 +76,8 @@ class FileHelpers:
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Error backing up: {os.path.join(root, file)}! - Error was: {e}"
|
f"Error backing up: {os.path.join(root, file)}!"
|
||||||
|
f" - Error was: {e}"
|
||||||
)
|
)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
@ -104,7 +105,8 @@ class FileHelpers:
|
|||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Error backing up: {os.path.join(root, file)}! - Error was: {e}"
|
f"Error backing up: {os.path.join(root, file)}!"
|
||||||
|
f" - Error was: {e}"
|
||||||
)
|
)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
@ -142,28 +142,26 @@ class Helpers:
|
|||||||
ci = -1 # command index - pointer to the argument we're building in cmd_out
|
ci = -1 # command index - pointer to the argument we're building in cmd_out
|
||||||
np = True # whether we're creating a new argument/parameter
|
np = True # whether we're creating a new argument/parameter
|
||||||
esc = False # whether an escape character was encountered
|
esc = False # whether an escape character was encountered
|
||||||
stch = None # if we're dealing with a quote, save the quote type here. Nested quotes to be dealt with by the command
|
stch = None # if we're dealing with a quote, save the quote type here.
|
||||||
|
# Nested quotes to be dealt with by the command
|
||||||
for c in cmd_in: # for character in string
|
for c in cmd_in: # for character in string
|
||||||
if (
|
if np: # if set, begin a new argument and increment the command index.
|
||||||
np
|
# Continue the loop.
|
||||||
): # if set, begin a new argument and increment the command index. Continue the loop.
|
|
||||||
if c == " ":
|
if c == " ":
|
||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
ci += 1
|
ci += 1
|
||||||
cmd_out.append("")
|
cmd_out.append("")
|
||||||
np = False
|
np = False
|
||||||
if (
|
if esc: # if we encountered an escape character on the last loop,
|
||||||
esc
|
# append this char regardless of what it is
|
||||||
): # if we encountered an escape character on the last loop, append this char regardless of what it is
|
|
||||||
if c not in Helpers.allowed_quotes:
|
if c not in Helpers.allowed_quotes:
|
||||||
cmd_out[ci] += "\\"
|
cmd_out[ci] += "\\"
|
||||||
cmd_out[ci] += c
|
cmd_out[ci] += c
|
||||||
esc = False
|
esc = False
|
||||||
else:
|
else:
|
||||||
if (
|
if c == "\\": # if the current character is an escape character,
|
||||||
c == "\\"
|
# set the esc flag and continue to next loop
|
||||||
): # if the current character is an escape character, set the esc flag and continue to next loop
|
|
||||||
esc = True
|
esc = True
|
||||||
elif (
|
elif (
|
||||||
c == " " and stch is None
|
c == " " and stch is None
|
||||||
@ -172,12 +170,13 @@ class Helpers:
|
|||||||
np = True
|
np = True
|
||||||
elif (
|
elif (
|
||||||
c == stch
|
c == stch
|
||||||
): # if we encounter the character that matches our start quote, end the quote and continue to next loop
|
): # if we encounter the character that matches our start quote,
|
||||||
|
# end the quote and continue to next loop
|
||||||
stch = None
|
stch = None
|
||||||
elif stch is None and (
|
elif stch is None and (
|
||||||
c in Helpers.allowed_quotes
|
c in Helpers.allowed_quotes
|
||||||
): # if we're not in the middle of a quote and we get a quotable character,
|
): # if we're not in the middle of a quote and we get a quotable
|
||||||
# start a quote and proceed to the next loop
|
# character, start a quote and proceed to the next loop
|
||||||
stch = c
|
stch = c
|
||||||
else: # else, just store the character in the current arg
|
else: # else, just store the character in the current arg
|
||||||
cmd_out[ci] += c
|
cmd_out[ci] += c
|
||||||
@ -236,8 +235,9 @@ class Helpers:
|
|||||||
def get_announcements():
|
def get_announcements():
|
||||||
r = requests.get("https://craftycontrol.com/notify.json", timeout=2)
|
r = requests.get("https://craftycontrol.com/notify.json", timeout=2)
|
||||||
data = (
|
data = (
|
||||||
'[{"id":"1","date":"Unknown","title":"Error getting Announcements","desc":"Error getting '
|
'[{"id":"1","date":"Unknown",'
|
||||||
'Announcements","link":""}] '
|
'"title":"Error getting Announcements",'
|
||||||
|
'"desc":"Error getting Announcements","link":""}]'
|
||||||
)
|
)
|
||||||
|
|
||||||
if r.status_code in [200, 201]:
|
if r.status_code in [200, 201]:
|
||||||
@ -337,7 +337,8 @@ class Helpers:
|
|||||||
# get file size
|
# get file size
|
||||||
fsize = f.tell()
|
fsize = f.tell()
|
||||||
|
|
||||||
# set pos @ last n chars (buffer from above = number of lines * avg_line_length)
|
# set pos @ last n chars
|
||||||
|
# (buffer from above = number of lines * avg_line_length)
|
||||||
f.seek(max(fsize - line_buffer, 0), 0)
|
f.seek(max(fsize - line_buffer, 0), 0)
|
||||||
|
|
||||||
# read file til the end
|
# read file til the end
|
||||||
@ -455,7 +456,8 @@ class Helpers:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def calc_percent(source_path, dest_path):
|
def calc_percent(source_path, dest_path):
|
||||||
# calculates percentable of zip from drive. Not with compression. For backups and support logs
|
# calculates percentable of zip from drive. Not with compression.
|
||||||
|
# (For backups and support logs)
|
||||||
source_size = 0
|
source_size = 0
|
||||||
files_count = 0
|
files_count = 0
|
||||||
for path, _dirs, files in os.walk(source_path):
|
for path, _dirs, files in os.walk(source_path):
|
||||||
@ -539,13 +541,15 @@ class Helpers:
|
|||||||
started = data.get("started")
|
started = data.get("started")
|
||||||
if psutil.pid_exists(pid):
|
if psutil.pid_exists(pid):
|
||||||
console.critical(
|
console.critical(
|
||||||
f"Another Crafty Controller agent seems to be running...\npid: {pid} \nstarted on: {started}"
|
f"Another Crafty Controller agent seems to be running..."
|
||||||
|
f"\npid: {pid} \nstarted on: {started}"
|
||||||
)
|
)
|
||||||
logger.critical("Found running crafty process. Exiting.")
|
logger.critical("Found running crafty process. Exiting.")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
else:
|
else:
|
||||||
logger.info(
|
logger.info(
|
||||||
"No process found for pid. Assuming crafty crashed. Deleting stale session.lock"
|
"No process found for pid. Assuming "
|
||||||
|
"crafty crashed. Deleting stale session.lock"
|
||||||
)
|
)
|
||||||
os.remove(self.session_file)
|
os.remove(self.session_file)
|
||||||
|
|
||||||
@ -564,7 +568,8 @@ class Helpers:
|
|||||||
with open(self.session_file, "w", encoding="utf-8") as f:
|
with open(self.session_file, "w", encoding="utf-8") as f:
|
||||||
json.dump(session_data, f, indent=True)
|
json.dump(session_data, f, indent=True)
|
||||||
|
|
||||||
# because this is a recursive function, we will return bytes, and set human readable later
|
# because this is a recursive function, we will return bytes,
|
||||||
|
# and set human readable later
|
||||||
def get_dir_size(self, path: str):
|
def get_dir_size(self, path: str):
|
||||||
total = 0
|
total = 0
|
||||||
for entry in os.scandir(path):
|
for entry in os.scandir(path):
|
||||||
@ -610,7 +615,8 @@ class Helpers:
|
|||||||
"""
|
"""
|
||||||
ensures a directory exists
|
ensures a directory exists
|
||||||
|
|
||||||
Checks for the existence of a directory, if the directory isn't there, this function creates the directory
|
Checks for the existence of a directory, if the directory isn't there,
|
||||||
|
this function creates the directory
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
path (string): the path you are checking for
|
path (string): the path you are checking for
|
||||||
@ -769,7 +775,8 @@ class Helpers:
|
|||||||
class="tree-nested d-block tree-ctx-item tree-file tree-item"
|
class="tree-nested d-block tree-ctx-item tree-file tree-item"
|
||||||
data-path="{dpath}"
|
data-path="{dpath}"
|
||||||
data-name="{filename}"
|
data-name="{filename}"
|
||||||
onclick="clickOnFile(event)"><span style="margin-right: 6px;"><i class="far fa-file"></i></span>{filename}</li>"""
|
onclick="clickOnFile(event)"><span style="margin-right: 6px;">
|
||||||
|
<i class="far fa-file"></i></span>{filename}</li>"""
|
||||||
return output
|
return output
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@ -805,7 +812,8 @@ class Helpers:
|
|||||||
class="tree-nested d-block tree-ctx-item tree-file tree-item"
|
class="tree-nested d-block tree-ctx-item tree-file tree-item"
|
||||||
data-path="{dpath}"
|
data-path="{dpath}"
|
||||||
data-name="{filename}"
|
data-name="{filename}"
|
||||||
onclick="clickOnFile(event)"><span style="margin-right: 6px;"><i class="far fa-file"></i></span>{filename}</li>"""
|
onclick="clickOnFile(event)"><span style="margin-right: 6px;">
|
||||||
|
<i class="far fa-file"></i></span>{filename}</li>"""
|
||||||
output += "</ul>\n"
|
output += "</ul>\n"
|
||||||
return output
|
return output
|
||||||
|
|
||||||
@ -883,13 +891,16 @@ class Helpers:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def in_path(parent_path, child_path):
|
def in_path(parent_path, child_path):
|
||||||
# Smooth out relative path names, note: if you are concerned about symbolic links, you should use os.path.realpath too
|
# Smooth out relative path names, note: if you are concerned about
|
||||||
|
# symbolic links, you should use os.path.realpath too
|
||||||
parent_path = os.path.abspath(parent_path)
|
parent_path = os.path.abspath(parent_path)
|
||||||
child_path = os.path.abspath(child_path)
|
child_path = os.path.abspath(child_path)
|
||||||
|
|
||||||
# Compare the common path of the parent and child path with the common path of just the parent path.
|
# Compare the common path of the parent and child path with the
|
||||||
# Using the commonpath method on just the parent path will regularise the path name in the same way
|
# common path of just the parent path. Using the commonpath method
|
||||||
# as the comparison that deals with both paths, removing any trailing path separator
|
# on just the parent path will regularise the path name in the same way
|
||||||
|
# as the comparison that deals with both paths, removing any trailing
|
||||||
|
# path separator
|
||||||
return os.path.commonpath([parent_path]) == os.path.commonpath(
|
return os.path.commonpath([parent_path]) == os.path.commonpath(
|
||||||
[parent_path, child_path]
|
[parent_path, child_path]
|
||||||
)
|
)
|
||||||
|
@ -1,87 +1,95 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from app.classes.controllers.users_controller import users_helper
|
from app.classes.controllers.users_controller import users_helper
|
||||||
from app.classes.shared.main_controller import Controller
|
from app.classes.shared.main_controller import Controller
|
||||||
from app.classes.shared.console import console
|
from app.classes.shared.console import console
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
class import3:
|
class import3:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.controller = Controller()
|
self.controller = Controller()
|
||||||
|
|
||||||
def start_import(self):
|
def start_import(self):
|
||||||
folder = os.path.normpath(
|
folder = os.path.normpath(
|
||||||
input(
|
input(
|
||||||
"Please input the path to the migrations folder in your installation of Crafty 3: "
|
"Please input the path to the migrations folder "
|
||||||
)
|
"in your installation of Crafty 3: "
|
||||||
)
|
)
|
||||||
if not os.path.exists(folder):
|
)
|
||||||
console.info(
|
if not os.path.exists(folder):
|
||||||
"Crafty cannot find the path you entered. Does Crafty's user have permission to access it?"
|
console.info(
|
||||||
)
|
"Crafty cannot find the path you entered. "
|
||||||
console.info("Please run the import3 command again and enter a valid path.")
|
"Does Crafty's user have permission to access it?"
|
||||||
else:
|
)
|
||||||
with open(os.path.join(folder, "users.json"), encoding="utf-8") as f:
|
console.info("Please run the import3 command again and enter a valid path.")
|
||||||
user_json = json.loads(f.read())
|
else:
|
||||||
with open(os.path.join(folder, "mc_settings.json"), encoding="utf-8") as f:
|
with open(os.path.join(folder, "users.json"), encoding="utf-8") as f:
|
||||||
servers_json = json.loads(f.read())
|
user_json = json.loads(f.read())
|
||||||
self.import_users(user_json)
|
with open(os.path.join(folder, "mc_settings.json"), encoding="utf-8") as f:
|
||||||
self.import_servers(servers_json, self.controller)
|
servers_json = json.loads(f.read())
|
||||||
|
self.import_users(user_json)
|
||||||
@staticmethod
|
self.import_servers(servers_json, self.controller)
|
||||||
def import_users(json_data):
|
|
||||||
# If there is only one user to import json needs to call the data differently
|
@staticmethod
|
||||||
if isinstance(json_data, list):
|
def import_users(json_data):
|
||||||
for user in json_data:
|
# If there is only one user to import json needs to call the data differently
|
||||||
users_helper.add_rawpass_user(user["username"], user["password"])
|
if isinstance(json_data, list):
|
||||||
console.info(f"Imported user {user['username']} from Crafty 3")
|
for user in json_data:
|
||||||
logger.info(f"Imported user {user['username']} from Crafty 3")
|
users_helper.add_rawpass_user(user["username"], user["password"])
|
||||||
else:
|
console.info(f"Imported user {user['username']} from Crafty 3")
|
||||||
console.info(
|
logger.info(f"Imported user {user['username']} from Crafty 3")
|
||||||
"There is only one user detected. Cannot create duplicate Admin account."
|
else:
|
||||||
)
|
console.info(
|
||||||
logger.info(
|
"There is only one user detected. "
|
||||||
"There is only one user detected. Cannot create duplicate Admin account."
|
"Cannot create duplicate Admin account."
|
||||||
)
|
)
|
||||||
|
logger.info(
|
||||||
@staticmethod
|
"There is only one user detected. "
|
||||||
def import_servers(json_data, controller):
|
"Cannot create duplicate Admin account."
|
||||||
# If there is only one server to import json needs to call the data differently
|
)
|
||||||
if isinstance(json_data, list):
|
|
||||||
for server in json_data:
|
@staticmethod
|
||||||
new_server_id = controller.import_jar_server(
|
def import_servers(json_data, controller):
|
||||||
server_name=server["server_name"],
|
# If there is only one server to import json needs to call the data differently
|
||||||
server_path=server["server_path"],
|
if isinstance(json_data, list):
|
||||||
server_jar=server["server_jar"],
|
for server in json_data:
|
||||||
min_mem=(int(server["memory_min"]) / 1000),
|
new_server_id = controller.import_jar_server(
|
||||||
max_mem=(int(server["memory_max"]) / 1000),
|
server_name=server["server_name"],
|
||||||
port=server["server_port"],
|
server_path=server["server_path"],
|
||||||
)
|
server_jar=server["server_jar"],
|
||||||
console.info(
|
min_mem=(int(server["memory_min"]) / 1000),
|
||||||
f"Imported server {server['server_name']}[{server['id']}] from Crafty 3 to new server id {new_server_id}"
|
max_mem=(int(server["memory_max"]) / 1000),
|
||||||
)
|
port=server["server_port"],
|
||||||
logger.info(
|
)
|
||||||
f"Imported server {server['server_name']}[{server['id']}] from Crafty 3 to new server id {new_server_id}"
|
console.info(
|
||||||
)
|
f"Imported server {server['server_name']}[{server['id']}] "
|
||||||
else:
|
f"from Crafty 3 to new server id {new_server_id}"
|
||||||
new_server_id = controller.import_jar_server(
|
)
|
||||||
server_name=json_data["server_name"],
|
logger.info(
|
||||||
server_path=json_data["server_path"],
|
f"Imported server {server['server_name']}[{server['id']}] "
|
||||||
server_jar=json_data["server_jar"],
|
f"from Crafty 3 to new server id {new_server_id}"
|
||||||
min_mem=(int(json_data["memory_min"]) / 1000),
|
)
|
||||||
max_mem=(int(json_data["memory_max"]) / 1000),
|
else:
|
||||||
port=json_data["server_port"],
|
new_server_id = controller.import_jar_server(
|
||||||
)
|
server_name=json_data["server_name"],
|
||||||
console.info(
|
server_path=json_data["server_path"],
|
||||||
f"Imported server {json_data['server_name']}[{json_data['id']}] from Crafty 3 to new server id {new_server_id}"
|
server_jar=json_data["server_jar"],
|
||||||
)
|
min_mem=(int(json_data["memory_min"]) / 1000),
|
||||||
logger.info(
|
max_mem=(int(json_data["memory_max"]) / 1000),
|
||||||
f"Imported server {json_data['server_name']}[{json_data['id']}] from Crafty 3 to new server id {new_server_id}"
|
port=json_data["server_port"],
|
||||||
)
|
)
|
||||||
|
console.info(
|
||||||
|
f"Imported server {json_data['server_name']}[{json_data['id']}] "
|
||||||
import3 = import3()
|
f"from Crafty 3 to new server id {new_server_id}"
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f"Imported server {json_data['server_name']}[{json_data['id']}] "
|
||||||
|
f"from Crafty 3 to new server id {new_server_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
import3 = import3()
|
||||||
|
@ -64,7 +64,8 @@ class Controller:
|
|||||||
|
|
||||||
if known_server == server_id_to_check:
|
if known_server == server_id_to_check:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"skipping initialization of server {server_id_to_check} because it is already loaded"
|
f"skipping initialization of server {server_id_to_check} "
|
||||||
|
f"because it is already loaded"
|
||||||
)
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
@ -86,11 +87,13 @@ class Controller:
|
|||||||
helper.get_os_understandable_path(s["path"])
|
helper.get_os_understandable_path(s["path"])
|
||||||
):
|
):
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Unable to find server {s['server_name']} at path {s['path']}. Skipping this server"
|
f"Unable to find server {s['server_name']} at path {s['path']}. "
|
||||||
|
f"Skipping this server"
|
||||||
)
|
)
|
||||||
|
|
||||||
console.warning(
|
console.warning(
|
||||||
f"Unable to find server {s['server_name']} at path {s['path']}. Skipping this server"
|
f"Unable to find server {s['server_name']} at path {s['path']}. "
|
||||||
|
f"Skipping this server"
|
||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@ -180,7 +183,8 @@ class Controller:
|
|||||||
auth_servers.append(server)
|
auth_servers.append(server)
|
||||||
else:
|
else:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Logs permission not available for server {server['server_name']}. Skipping."
|
f"Logs permission not available for server "
|
||||||
|
f"{server['server_name']}. Skipping."
|
||||||
)
|
)
|
||||||
# we'll iterate through our list of log paths from auth servers.
|
# we'll iterate through our list of log paths from auth servers.
|
||||||
for server in auth_servers:
|
for server in auth_servers:
|
||||||
@ -242,7 +246,8 @@ class Controller:
|
|||||||
def crash_detection(self, server_obj):
|
def crash_detection(self, server_obj):
|
||||||
svr = self.get_server_obj(server_obj.server_id)
|
svr = self.get_server_obj(server_obj.server_id)
|
||||||
# start or stop crash detection depending upon user preference
|
# 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.
|
# The below functions check to see if the server is running.
|
||||||
|
# They only execute if it's running.
|
||||||
if server_obj.crash_detection == 1:
|
if server_obj.crash_detection == 1:
|
||||||
svr.start_crash_detection()
|
svr.start_crash_detection()
|
||||||
else:
|
else:
|
||||||
@ -366,11 +371,18 @@ class Controller:
|
|||||||
logger.error(f"Unable to create required server files due to :{e}")
|
logger.error(f"Unable to create required server files due to :{e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# must remain non-fstring due to string addtion
|
|
||||||
if helper.is_os_windows():
|
if helper.is_os_windows():
|
||||||
server_command = f'java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar "{full_jar_path}" nogui'
|
server_command = (
|
||||||
|
f"java -Xms{helper.float_to_string(min_mem)}M "
|
||||||
|
f"-Xmx{helper.float_to_string(max_mem)}M "
|
||||||
|
f'-jar "{full_jar_path}" nogui'
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
server_command = f"java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar {full_jar_path} nogui"
|
server_command = (
|
||||||
|
f"java -Xms{helper.float_to_string(min_mem)}M "
|
||||||
|
f"-Xmx{helper.float_to_string(max_mem)}M "
|
||||||
|
f"-jar {full_jar_path} nogui"
|
||||||
|
)
|
||||||
server_log_file = f"{server_dir}/logs/latest.log"
|
server_log_file = f"{server_dir}/logs/latest.log"
|
||||||
server_stop = "stop"
|
server_stop = "stop"
|
||||||
|
|
||||||
@ -441,7 +453,8 @@ class Controller:
|
|||||||
has_properties = True
|
has_properties = True
|
||||||
if not has_properties:
|
if not has_properties:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"No server.properties found on zip file import. Creating one with port selection of {str(port)}"
|
f"No server.properties found on zip file import. "
|
||||||
|
f"Creating one with port selection of {str(port)}"
|
||||||
)
|
)
|
||||||
with open(
|
with open(
|
||||||
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
|
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
|
||||||
@ -451,11 +464,18 @@ class Controller:
|
|||||||
|
|
||||||
full_jar_path = os.path.join(new_server_dir, server_jar)
|
full_jar_path = os.path.join(new_server_dir, server_jar)
|
||||||
|
|
||||||
# due to adding strings this must not be an fstring
|
|
||||||
if helper.is_os_windows():
|
if helper.is_os_windows():
|
||||||
server_command = f'java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar "{full_jar_path}" nogui'
|
server_command = (
|
||||||
|
f"java -Xms{helper.float_to_string(min_mem)}M "
|
||||||
|
f"-Xmx{helper.float_to_string(max_mem)}M "
|
||||||
|
f'-jar "{full_jar_path}" nogui'
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
server_command = f"java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar {full_jar_path} nogui"
|
server_command = (
|
||||||
|
f"java -Xms{helper.float_to_string(min_mem)}M "
|
||||||
|
f"-Xmx{helper.float_to_string(max_mem)}M "
|
||||||
|
f"-jar {full_jar_path} nogui"
|
||||||
|
)
|
||||||
server_log_file = f"{new_server_dir}/logs/latest.log"
|
server_log_file = f"{new_server_dir}/logs/latest.log"
|
||||||
server_stop = "stop"
|
server_stop = "stop"
|
||||||
|
|
||||||
@ -512,7 +532,8 @@ class Controller:
|
|||||||
logger.error(f"ERROR IN ZIP IMPORT: {ex}")
|
logger.error(f"ERROR IN ZIP IMPORT: {ex}")
|
||||||
if not has_properties:
|
if not has_properties:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"No server.properties found on zip file import. Creating one with port selection of {str(port)}"
|
f"No server.properties found on zip file import. "
|
||||||
|
f"Creating one with port selection of {str(port)}"
|
||||||
)
|
)
|
||||||
with open(
|
with open(
|
||||||
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
|
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
|
||||||
@ -522,11 +543,18 @@ class Controller:
|
|||||||
|
|
||||||
full_jar_path = os.path.join(new_server_dir, server_jar)
|
full_jar_path = os.path.join(new_server_dir, server_jar)
|
||||||
|
|
||||||
# due to strings being added we need to leave this as not an fstring
|
|
||||||
if helper.is_os_windows():
|
if helper.is_os_windows():
|
||||||
server_command = f'java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar "{full_jar_path}" nogui'
|
server_command = (
|
||||||
|
f"java -Xms{helper.float_to_string(min_mem)}M "
|
||||||
|
f"-Xmx{helper.float_to_string(max_mem)}M "
|
||||||
|
f'-jar "{full_jar_path}" nogui'
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
server_command = f"java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar {full_jar_path} nogui"
|
server_command = (
|
||||||
|
f"java -Xms{helper.float_to_string(min_mem)}M "
|
||||||
|
f"-Xmx{helper.float_to_string(max_mem)}M "
|
||||||
|
f"-jar {full_jar_path} nogui"
|
||||||
|
)
|
||||||
logger.debug("command: " + server_command)
|
logger.debug("command: " + server_command)
|
||||||
server_log_file = f"{new_server_dir}/logs/latest.log"
|
server_log_file = f"{new_server_dir}/logs/latest.log"
|
||||||
server_stop = "stop"
|
server_stop = "stop"
|
||||||
@ -545,9 +573,9 @@ class Controller:
|
|||||||
)
|
)
|
||||||
return new_id
|
return new_id
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# BEDROCK IMPORTS
|
# BEDROCK IMPORTS
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
|
|
||||||
def import_bedrock_server(
|
def import_bedrock_server(
|
||||||
self, server_name: str, server_path: str, server_exe: str, port: int
|
self, server_name: str, server_path: str, server_exe: str, port: int
|
||||||
@ -575,7 +603,8 @@ class Controller:
|
|||||||
has_properties = True
|
has_properties = True
|
||||||
if not has_properties:
|
if not has_properties:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"No server.properties found on zip file import. Creating one with port selection of {str(port)}"
|
f"No server.properties found on zip file import. "
|
||||||
|
f"Creating one with port selection of {str(port)}"
|
||||||
)
|
)
|
||||||
with open(
|
with open(
|
||||||
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
|
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
|
||||||
@ -585,7 +614,6 @@ class Controller:
|
|||||||
|
|
||||||
full_jar_path = os.path.join(new_server_dir, server_exe)
|
full_jar_path = os.path.join(new_server_dir, server_exe)
|
||||||
|
|
||||||
# due to adding strings this must not be an fstring
|
|
||||||
if helper.is_os_windows():
|
if helper.is_os_windows():
|
||||||
server_command = f'"{full_jar_path}"'
|
server_command = f'"{full_jar_path}"'
|
||||||
else:
|
else:
|
||||||
@ -644,7 +672,8 @@ class Controller:
|
|||||||
logger.error(f"ERROR IN ZIP IMPORT: {ex}")
|
logger.error(f"ERROR IN ZIP IMPORT: {ex}")
|
||||||
if not has_properties:
|
if not has_properties:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"No server.properties found on zip file import. Creating one with port selection of {str(port)}"
|
f"No server.properties found on zip file import. "
|
||||||
|
f"Creating one with port selection of {str(port)}"
|
||||||
)
|
)
|
||||||
with open(
|
with open(
|
||||||
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
|
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
|
||||||
@ -654,7 +683,6 @@ class Controller:
|
|||||||
|
|
||||||
full_jar_path = os.path.join(new_server_dir, server_exe)
|
full_jar_path = os.path.join(new_server_dir, server_exe)
|
||||||
|
|
||||||
# due to strings being added we need to leave this as not an fstring
|
|
||||||
if helper.is_os_windows():
|
if helper.is_os_windows():
|
||||||
server_command = f'"{full_jar_path}"'
|
server_command = f'"{full_jar_path}"'
|
||||||
else:
|
else:
|
||||||
@ -681,9 +709,9 @@ class Controller:
|
|||||||
|
|
||||||
return new_id
|
return new_id
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# BEDROCK IMPORTS END
|
# BEDROCK IMPORTS END
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
|
|
||||||
def rename_backup_dir(self, old_server_id, new_server_id, new_uuid):
|
def rename_backup_dir(self, old_server_id, new_server_id, new_uuid):
|
||||||
server_data = self.servers.get_server_data_by_id(old_server_id)
|
server_data = self.servers.get_server_data_by_id(old_server_id)
|
||||||
@ -743,7 +771,8 @@ class Controller:
|
|||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
) as f:
|
) as f:
|
||||||
f.write(
|
f.write(
|
||||||
"The server is managed by Crafty Controller.\n Leave this directory/files alone please"
|
"The server is managed by Crafty Controller.\n "
|
||||||
|
"Leave this directory/files alone please"
|
||||||
)
|
)
|
||||||
f.close()
|
f.close()
|
||||||
|
|
||||||
@ -782,7 +811,8 @@ class Controller:
|
|||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(
|
logger.error(
|
||||||
f"Unable to delete server files for server with ID: {server_id} with error logged: {e}"
|
f"Unable to delete server files for server with ID: "
|
||||||
|
f"{server_id} with error logged: {e}"
|
||||||
)
|
)
|
||||||
if helper.check_path_exists(
|
if helper.check_path_exists(
|
||||||
self.servers.get_server_data_by_id(server_id)["backup_path"]
|
self.servers.get_server_data_by_id(server_id)["backup_path"]
|
||||||
|
@ -53,9 +53,9 @@ class db_builder:
|
|||||||
|
|
||||||
class db_shortcuts:
|
class db_shortcuts:
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Generic Databse Methods
|
# Generic Databse Methods
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def return_rows(query):
|
def return_rows(query):
|
||||||
rows = []
|
rows = []
|
||||||
@ -75,8 +75,8 @@ class db_shortcuts:
|
|||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Static Accessors
|
# Static Accessors
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
installer = db_builder()
|
installer = db_builder()
|
||||||
db_helper = db_shortcuts()
|
db_helper = db_shortcuts()
|
||||||
|
@ -67,7 +67,8 @@ class ServerOutBuf:
|
|||||||
while True:
|
while True:
|
||||||
if self.proc.poll() is None:
|
if self.proc.poll() is None:
|
||||||
char = self.proc.stdout.read(1).decode("utf-8", "ignore")
|
char = self.proc.stdout.read(1).decode("utf-8", "ignore")
|
||||||
# TODO: we may want to benchmark reading in blocks and userspace processing it later, reads are kind of expensive as a syscall
|
# TODO: we may want to benchmark reading in blocks and userspace
|
||||||
|
# processing it later, reads are kind of expensive as a syscall
|
||||||
self.process_byte(char)
|
self.process_byte(char)
|
||||||
else:
|
else:
|
||||||
flush = self.proc.stdout.read().decode("utf-8", "ignore")
|
flush = self.proc.stdout.read().decode("utf-8", "ignore")
|
||||||
@ -82,7 +83,8 @@ class ServerOutBuf:
|
|||||||
|
|
||||||
logger.debug("Broadcasting new virtual terminal line")
|
logger.debug("Broadcasting new virtual terminal line")
|
||||||
|
|
||||||
# TODO: Do not send data to clients who do not have permission to view this server's console
|
# TODO: Do not send data to clients who do not have permission to view
|
||||||
|
# this server's console
|
||||||
websocket_helper.broadcast_page_params(
|
websocket_helper.broadcast_page_params(
|
||||||
"/panel/server_detail",
|
"/panel/server_detail",
|
||||||
{"id": self.server_id},
|
{"id": self.server_id},
|
||||||
@ -91,9 +93,9 @@ class ServerOutBuf:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Minecraft Server Class
|
# Minecraft Server Class
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
class Server:
|
class Server:
|
||||||
def __init__(self, stats):
|
def __init__(self, stats):
|
||||||
# holders for our process
|
# holders for our process
|
||||||
@ -122,9 +124,9 @@ class Server:
|
|||||||
servers_helper.server_crash_reset(self.server_id)
|
servers_helper.server_crash_reset(self.server_id)
|
||||||
servers_helper.set_update(self.server_id, False)
|
servers_helper.set_update(self.server_id, False)
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Minecraft Server Management
|
# Minecraft Server Management
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
def reload_server_settings(self):
|
def reload_server_settings(self):
|
||||||
server_data = servers_helper.get_server_data_by_id(self.server_id)
|
server_data = servers_helper.get_server_data_by_id(self.server_id)
|
||||||
self.settings = server_data
|
self.settings = server_data
|
||||||
@ -135,7 +137,9 @@ class Server:
|
|||||||
autoStart = server_data_obj["auto_start"]
|
autoStart = server_data_obj["auto_start"]
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Creating Server object: {serverId} | Server Name: {serverName} | Auto Start: {autoStart}"
|
f"Creating Server object: {serverId} | "
|
||||||
|
f"Server Name: {serverName} | "
|
||||||
|
f"Auto Start: {autoStart}"
|
||||||
)
|
)
|
||||||
self.server_id = serverId
|
self.server_id = serverId
|
||||||
self.name = serverName
|
self.name = serverName
|
||||||
@ -259,7 +263,7 @@ class Server:
|
|||||||
console.info(f"Launching Server {self.name} with command {self.server_command}")
|
console.info(f"Launching Server {self.name} with command {self.server_command}")
|
||||||
|
|
||||||
# Checks for eula. Creates one if none detected.
|
# Checks for eula. Creates one if none detected.
|
||||||
# If EULA is detected and not set to one of these true vaiants we offer to set it true.
|
# If EULA is detected and not set to true we offer to set it true.
|
||||||
if helper.check_file_exists(os.path.join(self.settings["path"], "eula.txt")):
|
if helper.check_file_exists(os.path.join(self.settings["path"], "eula.txt")):
|
||||||
f = open(
|
f = open(
|
||||||
os.path.join(self.settings["path"], "eula.txt"), "r", encoding="utf-8"
|
os.path.join(self.settings["path"], "eula.txt"), "r", encoding="utf-8"
|
||||||
@ -289,7 +293,8 @@ class Server:
|
|||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.error(
|
logger.error(
|
||||||
"Autostart failed due to EULA being false. Agree not sent due to auto start."
|
"Autostart failed due to EULA being false. "
|
||||||
|
"Agree not sent due to auto start."
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
return False
|
return False
|
||||||
@ -334,7 +339,8 @@ class Server:
|
|||||||
== "minecraft-bedrock"
|
== "minecraft-bedrock"
|
||||||
):
|
):
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Bedrock and Unix detected for server {self.name}. Switching to appropriate execution string"
|
f"Bedrock and Unix detected for server {self.name}. "
|
||||||
|
f"Switching to appropriate execution string"
|
||||||
)
|
)
|
||||||
my_env = os.environ
|
my_env = os.environ
|
||||||
my_env["LD_LIBRARY_PATH"] = self.server_path
|
my_env["LD_LIBRARY_PATH"] = self.server_path
|
||||||
@ -456,18 +462,22 @@ class Server:
|
|||||||
websocket_helper.broadcast_user(user, "send_start_reload", {})
|
websocket_helper.broadcast_user(user, "send_start_reload", {})
|
||||||
else:
|
else:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Server PID {self.process.pid} died right after starting - is this a server config issue?"
|
f"Server PID {self.process.pid} died right after starting "
|
||||||
|
f"- is this a server config issue?"
|
||||||
)
|
)
|
||||||
console.warning(
|
console.warning(
|
||||||
f"Server PID {self.process.pid} died right after starting - is this a server config issue?"
|
f"Server PID {self.process.pid} died right after starting "
|
||||||
|
f"- is this a server config issue?"
|
||||||
)
|
)
|
||||||
|
|
||||||
if self.settings["crash_detection"]:
|
if self.settings["crash_detection"]:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Server {self.name} has crash detection enabled - starting watcher task"
|
f"Server {self.name} has crash detection enabled "
|
||||||
|
f"- starting watcher task"
|
||||||
)
|
)
|
||||||
console.info(
|
console.info(
|
||||||
f"Server {self.name} has crash detection enabled - starting watcher task"
|
f"Server {self.name} has crash detection enabled "
|
||||||
|
f"- starting watcher task"
|
||||||
)
|
)
|
||||||
|
|
||||||
self.server_scheduler.add_job(
|
self.server_scheduler.add_job(
|
||||||
@ -484,24 +494,29 @@ class Server:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def stop_crash_detection(self):
|
def stop_crash_detection(self):
|
||||||
# This is only used if the crash detection settings change while the server is running.
|
# This is only used if the crash detection settings change
|
||||||
|
# while the server is running.
|
||||||
if self.check_running():
|
if self.check_running():
|
||||||
logger.info(f"Detected crash detection shut off for server {self.name}")
|
logger.info(f"Detected crash detection shut off for server {self.name}")
|
||||||
try:
|
try:
|
||||||
self.server_scheduler.remove_job("c_" + str(self.server_id))
|
self.server_scheduler.remove_job("c_" + str(self.server_id))
|
||||||
except:
|
except:
|
||||||
logger.error(
|
logger.error(
|
||||||
f"Removing crash watcher for server {self.name} failed. Assuming it was never started."
|
f"Removing crash watcher for server {self.name} failed. "
|
||||||
|
f"Assuming it was never started."
|
||||||
)
|
)
|
||||||
|
|
||||||
def start_crash_detection(self):
|
def start_crash_detection(self):
|
||||||
# This is only used if the crash detection settings change while the server is running.
|
# This is only used if the crash detection settings change
|
||||||
|
# while the server is running.
|
||||||
if self.check_running():
|
if self.check_running():
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Server {self.name} has crash detection enabled - starting watcher task"
|
f"Server {self.name} has crash detection enabled "
|
||||||
|
f"- starting watcher task"
|
||||||
)
|
)
|
||||||
console.info(
|
console.info(
|
||||||
f"Server {self.name} has crash detection enabled - starting watcher task"
|
f"Server {self.name} has crash detection enabled "
|
||||||
|
"- starting watcher task"
|
||||||
)
|
)
|
||||||
self.server_scheduler.add_job(
|
self.server_scheduler.add_job(
|
||||||
self.detect_crash, "interval", seconds=30, id=f"c_{self.server_id}"
|
self.detect_crash, "interval", seconds=30, id=f"c_{self.server_id}"
|
||||||
@ -523,7 +538,8 @@ class Server:
|
|||||||
self.server_scheduler.remove_job("c_" + str(self.server_id))
|
self.server_scheduler.remove_job("c_" + str(self.server_id))
|
||||||
except:
|
except:
|
||||||
logger.error(
|
logger.error(
|
||||||
f"Removing crash watcher for server {self.name} failed. Assuming it was never started."
|
f"Removing crash watcher for server {self.name} failed. "
|
||||||
|
f"Assuming it was never started."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# windows will need to be handled separately for Ctrl+C
|
# windows will need to be handled separately for Ctrl+C
|
||||||
@ -541,7 +557,11 @@ class Server:
|
|||||||
|
|
||||||
while running:
|
while running:
|
||||||
x = x + 1
|
x = x + 1
|
||||||
logstr = f"Server {server_name} is still running - waiting 2s to see if it stops ({int(60-(x*2))} seconds until force close)"
|
logstr = (
|
||||||
|
f"Server {server_name} is still running "
|
||||||
|
f"- waiting 2s to see if it stops ({int(60-(x*2))} "
|
||||||
|
f"seconds until force close)"
|
||||||
|
)
|
||||||
logger.info(logstr)
|
logger.info(logstr)
|
||||||
console.info(logstr)
|
console.info(logstr)
|
||||||
running = self.check_running()
|
running = self.check_running()
|
||||||
@ -624,19 +644,23 @@ class Server:
|
|||||||
|
|
||||||
if self.settings["crash_detection"]:
|
if self.settings["crash_detection"]:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"The server {name} has crashed and will be restarted. Restarting server"
|
f"The server {name} has crashed and will be restarted. "
|
||||||
|
f"Restarting server"
|
||||||
)
|
)
|
||||||
console.warning(
|
console.warning(
|
||||||
f"The server {name} has crashed and will be restarted. Restarting server"
|
f"The server {name} has crashed and will be restarted. "
|
||||||
|
f"Restarting server"
|
||||||
)
|
)
|
||||||
self.run_threaded_server(None)
|
self.run_threaded_server(None)
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
logger.critical(
|
logger.critical(
|
||||||
f"The server {name} has crashed, crash detection is disabled and it will not be restarted"
|
f"The server {name} has crashed, "
|
||||||
|
f"crash detection is disabled and it will not be restarted"
|
||||||
)
|
)
|
||||||
console.critical(
|
console.critical(
|
||||||
f"The server {name} has crashed, crash detection is disabled and it will not be restarted"
|
f"The server {name} has crashed, "
|
||||||
|
f"crash detection is disabled and it will not be restarted"
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
@ -646,7 +670,7 @@ class Server:
|
|||||||
|
|
||||||
# for every sub process...
|
# for every sub process...
|
||||||
for proc in process.children(recursive=True):
|
for proc in process.children(recursive=True):
|
||||||
# kill all the child processes - it sounds too wrong saying kill all the children (kevdagoat: lol!)
|
# kill all the child processes
|
||||||
logger.info(f"Sending SIGKILL to server {proc.name}")
|
logger.info(f"Sending SIGKILL to server {proc.name}")
|
||||||
proc.kill()
|
proc.kill()
|
||||||
# kill the main process we are after
|
# kill the main process we are after
|
||||||
@ -678,8 +702,9 @@ class Server:
|
|||||||
# check the exit code -- This could be a fix for /stop
|
# check the exit code -- This could be a fix for /stop
|
||||||
if self.process.returncode == 0:
|
if self.process.returncode == 0:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"Process {self.process.pid} exited with code {self.process.returncode}. This is considered a clean exit"
|
f"Process {self.process.pid} exited with code "
|
||||||
+ " supressing crash handling."
|
f"{self.process.returncode}. This is considered a clean exit"
|
||||||
|
f" supressing crash handling."
|
||||||
)
|
)
|
||||||
# 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))
|
||||||
@ -699,10 +724,12 @@ class Server:
|
|||||||
# we have tried to restart 4 times...
|
# we have tried to restart 4 times...
|
||||||
elif self.restart_count == 4:
|
elif self.restart_count == 4:
|
||||||
logger.critical(
|
logger.critical(
|
||||||
f"Server {self.name} has been restarted {self.restart_count} times. It has crashed, not restarting."
|
f"Server {self.name} has been restarted {self.restart_count}"
|
||||||
|
f" times. It has crashed, not restarting."
|
||||||
)
|
)
|
||||||
console.critical(
|
console.critical(
|
||||||
f"Server {self.name} has been restarted {self.restart_count} times. It has crashed, not restarting."
|
f"Server {self.name} has been restarted {self.restart_count}"
|
||||||
|
f" times. It has crashed, not restarting."
|
||||||
)
|
)
|
||||||
|
|
||||||
self.restart_count = 0
|
self.restart_count = 0
|
||||||
@ -740,7 +767,8 @@ class Server:
|
|||||||
if self.server_path is None:
|
if self.server_path is None:
|
||||||
self.server_path = helper.get_os_understandable_path(self.settings["path"])
|
self.server_path = helper.get_os_understandable_path(self.settings["path"])
|
||||||
logger.info(
|
logger.info(
|
||||||
"Backup Thread - Local server path not defined. Setting local server path variable."
|
"Backup Thread - Local server path not defined. "
|
||||||
|
"Setting local server path variable."
|
||||||
)
|
)
|
||||||
# checks if the backup thread is currently alive for this server
|
# checks if the backup thread is currently alive for this server
|
||||||
if not self.is_backingup:
|
if not self.is_backingup:
|
||||||
@ -752,7 +780,8 @@ class Server:
|
|||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
logger.error(
|
logger.error(
|
||||||
f"Backup is already being processed for server {self.settings['server_name']}. Canceling backup request"
|
f"Backup is already being processed for server "
|
||||||
|
f"{self.settings['server_name']}. Canceling backup request"
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
logger.info(f"Backup Thread started for server {self.settings['server_name']}.")
|
logger.info(f"Backup Thread started for server {self.settings['server_name']}.")
|
||||||
@ -779,10 +808,14 @@ class Server:
|
|||||||
conf = management_helper.get_backup_config(self.server_id)
|
conf = management_helper.get_backup_config(self.server_id)
|
||||||
helper.ensure_dir_exists(self.settings["backup_path"])
|
helper.ensure_dir_exists(self.settings["backup_path"])
|
||||||
try:
|
try:
|
||||||
backup_filename = f"{self.settings['backup_path']}/{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}"
|
backup_filename = (
|
||||||
|
f"{self.settings['backup_path']}/"
|
||||||
|
f"{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}"
|
||||||
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Creating backup of server '{self.settings['server_name']}'"
|
f"Creating backup of server '{self.settings['server_name']}'"
|
||||||
+ f" (ID#{self.server_id}, path={self.server_path}) at '{backup_filename}'"
|
f" (ID#{self.server_id}, path={self.server_path}) "
|
||||||
|
f"at '{backup_filename}'"
|
||||||
)
|
)
|
||||||
|
|
||||||
tempDir = tempfile.mkdtemp()
|
tempDir = tempfile.mkdtemp()
|
||||||
@ -799,14 +832,17 @@ class Server:
|
|||||||
server_dir = helper.get_os_understandable_path(self.settings["path"])
|
server_dir = helper.get_os_understandable_path(self.settings["path"])
|
||||||
|
|
||||||
for my_dir in excluded_dirs:
|
for my_dir in excluded_dirs:
|
||||||
# Take the full path of the excluded dir and replace the server path with the temp path
|
# Take the full path of the excluded dir and replace the
|
||||||
# This is so that we're only deleting excluded dirs from the temp path and not the server path
|
# server path with the temp path, this is so that we're
|
||||||
|
# only deleting excluded dirs from the temp path
|
||||||
|
# and not the server path
|
||||||
excluded_dir = helper.get_os_understandable_path(my_dir).replace(
|
excluded_dir = helper.get_os_understandable_path(my_dir).replace(
|
||||||
server_dir, helper.get_os_understandable_path(tempDir)
|
server_dir, helper.get_os_understandable_path(tempDir)
|
||||||
)
|
)
|
||||||
# Next, check to see if it is a directory
|
# Next, check to see if it is a directory
|
||||||
if os.path.isdir(excluded_dir):
|
if os.path.isdir(excluded_dir):
|
||||||
# If it is a directory, recursively delete the entire directory from the backup
|
# If it is a directory,
|
||||||
|
# recursively delete the entire directory from the backup
|
||||||
file_helper.del_dirs(excluded_dir)
|
file_helper.del_dirs(excluded_dir)
|
||||||
else:
|
else:
|
||||||
# If not, just remove the file
|
# If not, just remove the file
|
||||||
@ -945,7 +981,8 @@ class Server:
|
|||||||
if self.check_running():
|
if self.check_running():
|
||||||
wasStarted = True
|
wasStarted = True
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Server with PID {self.process.pid} is running. Sending shutdown command"
|
f"Server with PID {self.process.pid} is running. "
|
||||||
|
f"Sending shutdown command"
|
||||||
)
|
)
|
||||||
self.stop_threaded_server()
|
self.stop_threaded_server()
|
||||||
else:
|
else:
|
||||||
@ -976,7 +1013,8 @@ class Server:
|
|||||||
backup_executable = os.path.join(backup_dir, "old_server.jar")
|
backup_executable = os.path.join(backup_dir, "old_server.jar")
|
||||||
else:
|
else:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Executable backup directory not found for Server: {self.name}. Creating one."
|
f"Executable backup directory not found for Server: {self.name}."
|
||||||
|
f" Creating one."
|
||||||
)
|
)
|
||||||
os.mkdir(backup_dir)
|
os.mkdir(backup_dir)
|
||||||
backup_executable = os.path.join(backup_dir, "old_server.jar")
|
backup_executable = os.path.join(backup_dir, "old_server.jar")
|
||||||
@ -1062,9 +1100,9 @@ class Server:
|
|||||||
)
|
)
|
||||||
logger.error("Executable download failed.")
|
logger.error("Executable download failed.")
|
||||||
|
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
# Minecraft Servers Statistics
|
# Minecraft Servers Statistics
|
||||||
# ************************************************************************************************
|
# **********************************************************************************
|
||||||
|
|
||||||
def realtime_stats(self):
|
def realtime_stats(self):
|
||||||
total_players = 0
|
total_players = 0
|
||||||
@ -1180,7 +1218,8 @@ class Server:
|
|||||||
ping_data = Stats.parse_server_RakNet_ping(int_mc_ping)
|
ping_data = Stats.parse_server_RakNet_ping(int_mc_ping)
|
||||||
else:
|
else:
|
||||||
ping_data = Stats.parse_server_ping(int_mc_ping)
|
ping_data = Stats.parse_server_ping(int_mc_ping)
|
||||||
# Makes sure we only show stats when a server is online otherwise people have gotten confused.
|
# Makes sure we only show stats when a server is online
|
||||||
|
# otherwise people have gotten confused.
|
||||||
if self.check_running():
|
if self.check_running():
|
||||||
server_stats = {
|
server_stats = {
|
||||||
"id": server_id,
|
"id": server_id,
|
||||||
@ -1302,7 +1341,8 @@ class Server:
|
|||||||
|
|
||||||
int_data = False
|
int_data = False
|
||||||
ping_data = {}
|
ping_data = {}
|
||||||
# Makes sure we only show stats when a server is online otherwise people have gotten confused.
|
# Makes sure we only show stats when a server is online
|
||||||
|
# otherwise people have gotten confused.
|
||||||
if self.check_running():
|
if self.check_running():
|
||||||
# if we got a good ping return, let's parse it
|
# if we got a good ping return, let's parse it
|
||||||
if servers_helper.get_server_type_by_id(server_id) != "minecraft-bedrock":
|
if servers_helper.get_server_type_by_id(server_id) != "minecraft-bedrock":
|
||||||
|
@ -92,7 +92,8 @@ class TasksManager:
|
|||||||
svr = self.controller.get_server_obj(c.server_id)
|
svr = self.controller.get_server_obj(c.server_id)
|
||||||
except:
|
except:
|
||||||
logger.error(
|
logger.error(
|
||||||
"Server value requested does note exist purging item from waiting commands."
|
"Server value requested does note exist! "
|
||||||
|
"Purging item from waiting commands."
|
||||||
)
|
)
|
||||||
management_helper.mark_command_complete(c.command_id)
|
management_helper.mark_command_complete(c.command_id)
|
||||||
|
|
||||||
@ -162,7 +163,9 @@ class TasksManager:
|
|||||||
def scheduler_thread(self):
|
def scheduler_thread(self):
|
||||||
schedules = management_helper.get_schedules_enabled()
|
schedules = management_helper.get_schedules_enabled()
|
||||||
self.scheduler.add_listener(self.schedule_watcher, mask=EVENT_JOB_EXECUTED)
|
self.scheduler.add_listener(self.schedule_watcher, mask=EVENT_JOB_EXECUTED)
|
||||||
# self.scheduler.add_job(self.scheduler.print_jobs, 'interval', seconds=10, id='-1')
|
# self.scheduler.add_job(
|
||||||
|
# self.scheduler.print_jobs, "interval", seconds=10, id="-1"
|
||||||
|
# )
|
||||||
|
|
||||||
# load schedules from DB
|
# load schedules from DB
|
||||||
for schedule in schedules:
|
for schedule in schedules:
|
||||||
@ -254,7 +257,8 @@ class TasksManager:
|
|||||||
job_data["parent"],
|
job_data["parent"],
|
||||||
job_data["delay"],
|
job_data["delay"],
|
||||||
)
|
)
|
||||||
# Checks to make sure some doofus didn't actually make the newly created task a child of itself.
|
# Checks to make sure some doofus didn't actually make the newly
|
||||||
|
# created task a child of itself.
|
||||||
if str(job_data["parent"]) == str(sch_id):
|
if str(job_data["parent"]) == str(sch_id):
|
||||||
management_helper.update_scheduled_task(sch_id, {"parent": None})
|
management_helper.update_scheduled_task(sch_id, {"parent": None})
|
||||||
# Check to see if it's enabled and is not a chain reaction.
|
# Check to see if it's enabled and is not a chain reaction.
|
||||||
@ -349,12 +353,14 @@ class TasksManager:
|
|||||||
else:
|
else:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Job with ID {sch_id} was deleted from DB, but was not enabled."
|
f"Job with ID {sch_id} was deleted from DB, but was not enabled."
|
||||||
+ "Not going to try removing something that doesn't exist from active schedules."
|
f"Not going to try removing something "
|
||||||
|
f"that doesn't exist from active schedules."
|
||||||
)
|
)
|
||||||
|
|
||||||
def update_job(self, sch_id, job_data):
|
def update_job(self, sch_id, job_data):
|
||||||
management_helper.update_scheduled_task(sch_id, job_data)
|
management_helper.update_scheduled_task(sch_id, job_data)
|
||||||
# Checks to make sure some doofus didn't actually make the newly created task a child of itself.
|
# Checks to make sure some doofus didn't actually make the newly
|
||||||
|
# created task a child of itself.
|
||||||
if str(job_data["parent"]) == str(sch_id):
|
if str(job_data["parent"]) == str(sch_id):
|
||||||
management_helper.update_scheduled_task(sch_id, {"parent": None})
|
management_helper.update_scheduled_task(sch_id, {"parent": None})
|
||||||
try:
|
try:
|
||||||
@ -362,7 +368,8 @@ class TasksManager:
|
|||||||
self.scheduler.remove_job(str(sch_id))
|
self.scheduler.remove_job(str(sch_id))
|
||||||
except:
|
except:
|
||||||
logger.info(
|
logger.info(
|
||||||
"No job found in update job. Assuming it was previously disabled. Starting new job."
|
"No job found in update job. "
|
||||||
|
"Assuming it was previously disabled. Starting new job."
|
||||||
)
|
)
|
||||||
|
|
||||||
if job_data["enabled"]:
|
if job_data["enabled"]:
|
||||||
@ -436,7 +443,8 @@ class TasksManager:
|
|||||||
self.scheduler.remove_job(str(sch_id))
|
self.scheduler.remove_job(str(sch_id))
|
||||||
except:
|
except:
|
||||||
logger.info(
|
logger.info(
|
||||||
f"APScheduler found no scheduled job on schedule update for schedule with id: {sch_id} Assuming it was already disabled."
|
f"APScheduler found no scheduled job on schedule update for "
|
||||||
|
f"schedule with id: {sch_id} Assuming it was already disabled."
|
||||||
)
|
)
|
||||||
|
|
||||||
def schedule_watcher(self, event):
|
def schedule_watcher(self, event):
|
||||||
@ -454,11 +462,14 @@ class TasksManager:
|
|||||||
if task.one_time:
|
if task.one_time:
|
||||||
self.remove_job(task.schedule_id)
|
self.remove_job(task.schedule_id)
|
||||||
logger.info("one time task detected. Deleting...")
|
logger.info("one time task detected. Deleting...")
|
||||||
# check for any child tasks for this. It's kind of backward, but this makes DB management a lot easier. One to one instead of one to many.
|
# check for any child tasks for this. It's kind of backward,
|
||||||
|
# but this makes DB management a lot easier. One to one
|
||||||
|
# instead of one to many.
|
||||||
for schedule in management_helper.get_child_schedules_by_server(
|
for schedule in management_helper.get_child_schedules_by_server(
|
||||||
task.schedule_id, task.server_id
|
task.schedule_id, task.server_id
|
||||||
):
|
):
|
||||||
# event job ID's are strings so we need to look at this as the same data type.
|
# event job ID's are strings so we need to look at
|
||||||
|
# this as the same data type.
|
||||||
if str(schedule.parent) == str(event.job_id):
|
if str(schedule.parent) == str(event.job_id):
|
||||||
if schedule.enabled:
|
if schedule.enabled:
|
||||||
delaytime = datetime.datetime.now() + datetime.timedelta(
|
delaytime = datetime.datetime.now() + datetime.timedelta(
|
||||||
@ -478,7 +489,8 @@ class TasksManager:
|
|||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.info(
|
logger.info(
|
||||||
"Event job ID is not numerical. Assuming it's stats - not stored in DB. Moving on."
|
"Event job ID is not numerical. Assuming it's stats "
|
||||||
|
"- not stored in DB. Moving on."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
logger.error(f"Task failed with error: {event.exception}")
|
logger.error(f"Task failed with error: {event.exception}")
|
||||||
|
@ -173,7 +173,8 @@ class AjaxHandler(BaseHandler):
|
|||||||
data-path="{dpath}"
|
data-path="{dpath}"
|
||||||
data-name="{filename}"
|
data-name="{filename}"
|
||||||
onclick=""><input type='checkbox' class="checkBoxClass" name='root_path' value="{dpath}">
|
onclick=""><input type='checkbox' class="checkBoxClass" name='root_path' value="{dpath}">
|
||||||
<span style="margin-right: 6px;"><i class="far fa-file"></i></span></input>{filename}</li>"""
|
<span style="margin-right: 6px;"><i class="far fa-file">
|
||||||
|
</i></span></input>{filename}</li>"""
|
||||||
self.write(helper.get_os_understandable_path(folder) + "\n" + output)
|
self.write(helper.get_os_understandable_path(folder) + "\n" + output)
|
||||||
self.finish()
|
self.finish()
|
||||||
|
|
||||||
@ -236,7 +237,8 @@ class AjaxHandler(BaseHandler):
|
|||||||
data-path="{dpath}"
|
data-path="{dpath}"
|
||||||
data-name="{filename}"
|
data-name="{filename}"
|
||||||
onclick=""><input type='checkbox' name='root_path' value='{dpath}'>
|
onclick=""><input type='checkbox' name='root_path' value='{dpath}'>
|
||||||
<span style="margin-right: 6px;"><i class="far fa-file"></i></span></input>{filename}</li>"""
|
<span style="margin-right: 6px;"><i class="far fa-file">
|
||||||
|
</i></span></input>{filename}</li>"""
|
||||||
|
|
||||||
self.write(helper.get_os_understandable_path(folder) + "\n" + output)
|
self.write(helper.get_os_understandable_path(folder) + "\n" + output)
|
||||||
self.finish()
|
self.finish()
|
||||||
@ -320,7 +322,9 @@ class AjaxHandler(BaseHandler):
|
|||||||
|
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f"Sent command to {self.controller.servers.get_server_friendly_name(server_id)} terminal: {command}",
|
f"Sent command to "
|
||||||
|
f"{self.controller.servers.get_server_friendly_name(server_id)} "
|
||||||
|
f"terminal: {command}",
|
||||||
server_id,
|
server_id,
|
||||||
self.get_remote_ip(),
|
self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
@ -516,7 +520,8 @@ class AjaxHandler(BaseHandler):
|
|||||||
return
|
return
|
||||||
server_id = self.get_argument("id", None)
|
server_id = self.get_argument("id", None)
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Removing server from panel for server: {self.controller.servers.get_server_friendly_name(server_id)}"
|
f"Removing server from panel for server: "
|
||||||
|
f"{self.controller.servers.get_server_friendly_name(server_id)}"
|
||||||
)
|
)
|
||||||
|
|
||||||
server_data = self.controller.get_server_data(server_id)
|
server_data = self.controller.get_server_data(server_id)
|
||||||
@ -539,7 +544,8 @@ class AjaxHandler(BaseHandler):
|
|||||||
return
|
return
|
||||||
server_id = self.get_argument("id", None)
|
server_id = self.get_argument("id", None)
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Removing server and all associated files for server: {self.controller.servers.get_server_friendly_name(server_id)}"
|
f"Removing server and all associated files for server: "
|
||||||
|
f"{self.controller.servers.get_server_friendly_name(server_id)}"
|
||||||
)
|
)
|
||||||
|
|
||||||
server_data = self.controller.get_server_data(server_id)
|
server_data = self.controller.get_server_data(server_id)
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
# pylint: disable=too-many-lines
|
||||||
import time
|
import time
|
||||||
import datetime
|
import datetime
|
||||||
import os
|
import os
|
||||||
@ -36,7 +37,8 @@ class PanelHandler(BaseHandler):
|
|||||||
user_roles = {}
|
user_roles = {}
|
||||||
for user in self.controller.users.get_all_users():
|
for user in self.controller.users.get_all_users():
|
||||||
user_roles_list = self.controller.users.get_user_roles_names(user.user_id)
|
user_roles_list = self.controller.users.get_user_roles_names(user.user_id)
|
||||||
# user_servers = self.controller.servers.get_authorized_servers(user.user_id)
|
# user_servers =
|
||||||
|
# self.controller.servers.get_authorized_servers(user.user_id)
|
||||||
user_roles[user.user_id] = user_roles_list
|
user_roles[user.user_id] = user_roles_list
|
||||||
return user_roles
|
return user_roles
|
||||||
|
|
||||||
@ -142,7 +144,8 @@ class PanelHandler(BaseHandler):
|
|||||||
api_key, _, exec_user = self.current_user
|
api_key, _, exec_user = self.current_user
|
||||||
superuser = exec_user["superuser"]
|
superuser = exec_user["superuser"]
|
||||||
|
|
||||||
# Commented out because there is no server access control for API keys, they just inherit from the host user
|
# Commented out because there is no server access control for API keys,
|
||||||
|
# they just inherit from the host user
|
||||||
# if api_key is not None:
|
# if api_key is not None:
|
||||||
# superuser = superuser and api_key.superuser
|
# superuser = superuser and api_key.superuser
|
||||||
|
|
||||||
@ -162,7 +165,8 @@ class PanelHandler(BaseHandler):
|
|||||||
server_id, api_key
|
server_id, api_key
|
||||||
):
|
):
|
||||||
print(
|
print(
|
||||||
f"API key {api_key.name} (id: {api_key.token_id}) does not have permission"
|
f"API key {api_key.name} (id: {api_key.token_id}) "
|
||||||
|
f"does not have permission"
|
||||||
)
|
)
|
||||||
self.redirect("/panel/error?error=Invalid Server ID")
|
self.redirect("/panel/error?error=Invalid Server ID")
|
||||||
return None
|
return None
|
||||||
@ -434,7 +438,8 @@ class PanelHandler(BaseHandler):
|
|||||||
page_servers.append(server)
|
page_servers.append(server)
|
||||||
un_used_servers.remove(server)
|
un_used_servers.remove(server)
|
||||||
user_order.remove(server_id)
|
user_order.remove(server_id)
|
||||||
# we only want to set these server stats values once. We need to update the flag so it only hits that if once.
|
# we only want to set these server stats values once.
|
||||||
|
# We need to update the flag so it only hits that if once.
|
||||||
flag += 1
|
flag += 1
|
||||||
|
|
||||||
for server in un_used_servers:
|
for server in un_used_servers:
|
||||||
@ -447,7 +452,8 @@ class PanelHandler(BaseHandler):
|
|||||||
user_order.remove(server_id)
|
user_order.remove(server_id)
|
||||||
page_data["servers"] = page_servers
|
page_data["servers"] = page_servers
|
||||||
|
|
||||||
# num players is set to zero here. If we poll all servers while dashboard is loading it takes FOREVER. We leave this to the
|
# num players is set to zero here. If we poll all servers while
|
||||||
|
# dashboard is loading it takes FOREVER. We leave this to the
|
||||||
# async polling once dashboard is served.
|
# async polling once dashboard is served.
|
||||||
page_data["num_players"] = 0
|
page_data["num_players"] = 0
|
||||||
|
|
||||||
@ -778,7 +784,7 @@ class PanelHandler(BaseHandler):
|
|||||||
page_data[
|
page_data[
|
||||||
"quantity_server"
|
"quantity_server"
|
||||||
] = (
|
] = (
|
||||||
self.controller.crafty_perms.list_all_crafty_permissions_quantity_limits()
|
self.controller.crafty_perms.list_all_crafty_permissions_quantity_limits() # pylint: disable=line-too-long
|
||||||
)
|
)
|
||||||
page_data["languages"] = []
|
page_data["languages"] = []
|
||||||
page_data["languages"].append(
|
page_data["languages"].append(
|
||||||
@ -843,7 +849,8 @@ class PanelHandler(BaseHandler):
|
|||||||
page_data["schedule"]["cron_string"] = ""
|
page_data["schedule"]["cron_string"] = ""
|
||||||
page_data["schedule"]["time"] = ""
|
page_data["schedule"]["time"] = ""
|
||||||
page_data["schedule"]["interval"] = ""
|
page_data["schedule"]["interval"] = ""
|
||||||
# we don't need to check difficulty here. We'll just default to basic for new schedules
|
# we don't need to check difficulty here.
|
||||||
|
# We'll just default to basic for new schedules
|
||||||
page_data["schedule"]["difficulty"] = "basic"
|
page_data["schedule"]["difficulty"] = "basic"
|
||||||
page_data["schedule"]["interval_type"] = "days"
|
page_data["schedule"]["interval_type"] = "days"
|
||||||
|
|
||||||
@ -898,7 +905,8 @@ class PanelHandler(BaseHandler):
|
|||||||
"children"
|
"children"
|
||||||
] = self.controller.management.get_child_schedules(sch_id)
|
] = self.controller.management.get_child_schedules(sch_id)
|
||||||
# We check here to see if the command is any of the default ones.
|
# We check here to see if the command is any of the default ones.
|
||||||
# We do not want a user changing to a custom command and seeing our command there.
|
# We do not want a user changing to a custom command
|
||||||
|
# and seeing our command there.
|
||||||
if (
|
if (
|
||||||
schedule.action != "start"
|
schedule.action != "start"
|
||||||
or schedule.action != "stop"
|
or schedule.action != "stop"
|
||||||
@ -1192,7 +1200,8 @@ class PanelHandler(BaseHandler):
|
|||||||
|
|
||||||
elif page == "support_logs":
|
elif page == "support_logs":
|
||||||
logger.info(
|
logger.info(
|
||||||
f"Support logs requested. Packinging logs for user with ID: {exec_user['user_id']}"
|
f"Support logs requested. "
|
||||||
|
f"Packinging logs for user with ID: {exec_user['user_id']}"
|
||||||
)
|
)
|
||||||
logs_thread = threading.Thread(
|
logs_thread = threading.Thread(
|
||||||
target=self.controller.package_support_logs,
|
target=self.controller.package_support_logs,
|
||||||
@ -1243,7 +1252,8 @@ class PanelHandler(BaseHandler):
|
|||||||
exec_user["user_id"]
|
exec_user["user_id"]
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
# defined_servers = self.controller.servers.get_authorized_servers(exec_user["user_id"])
|
# defined_servers =
|
||||||
|
# self.controller.servers.get_authorized_servers(exec_user["user_id"])
|
||||||
for r in exec_user["roles"]:
|
for r in exec_user["roles"]:
|
||||||
role = self.controller.roles.get_role(r)
|
role = self.controller.roles.get_role(r)
|
||||||
exec_user_role.add(role["role_name"])
|
exec_user_role.add(role["role_name"])
|
||||||
@ -1289,7 +1299,8 @@ class PanelHandler(BaseHandler):
|
|||||||
|
|
||||||
server_obj = self.controller.servers.get_server_obj(server_id)
|
server_obj = self.controller.servers.get_server_obj(server_id)
|
||||||
stale_executable = server_obj.executable
|
stale_executable = server_obj.executable
|
||||||
# Compares old jar name to page data being passed. If they are different we replace the executable name in the
|
# Compares old jar name to page data being passed.
|
||||||
|
# If they are different we replace the executable name in the
|
||||||
if str(stale_executable) != str(executable):
|
if str(stale_executable) != str(executable):
|
||||||
execution_command = execution_command.replace(
|
execution_command = execution_command.replace(
|
||||||
str(stale_executable), str(executable)
|
str(stale_executable), str(executable)
|
||||||
@ -1711,7 +1722,8 @@ class PanelHandler(BaseHandler):
|
|||||||
elif page == "edit_user":
|
elif page == "edit_user":
|
||||||
if bleach.clean(self.get_argument("username", None)) == "system":
|
if bleach.clean(self.get_argument("username", None)) == "system":
|
||||||
self.redirect(
|
self.redirect(
|
||||||
"/panel/error?error=Unauthorized access: system user is not editable"
|
"/panel/error?error=Unauthorized access: "
|
||||||
|
"system user is not editable"
|
||||||
)
|
)
|
||||||
user_id = bleach.clean(self.get_argument("id", None))
|
user_id = bleach.clean(self.get_argument("id", None))
|
||||||
username = bleach.clean(self.get_argument("username", None))
|
username = bleach.clean(self.get_argument("username", None))
|
||||||
@ -1724,8 +1736,9 @@ class PanelHandler(BaseHandler):
|
|||||||
)
|
)
|
||||||
|
|
||||||
if superuser:
|
if superuser:
|
||||||
# Checks if user is trying to change super user status of self. We don't want that.
|
# Checks if user is trying to change super user status of self.
|
||||||
# Automatically make them stay super user since we know they are.
|
# We don't want that. Automatically make them stay super user
|
||||||
|
# since we know they are.
|
||||||
if str(exec_user["user_id"]) != str(user_id):
|
if str(exec_user["user_id"]) != str(user_id):
|
||||||
superuser = bleach.clean(self.get_argument("superuser", "0"))
|
superuser = bleach.clean(self.get_argument("superuser", "0"))
|
||||||
else:
|
else:
|
||||||
@ -1800,7 +1813,8 @@ class PanelHandler(BaseHandler):
|
|||||||
|
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f"Edited user {username} (UID:{user_id}) with roles {roles} and permissions {permissions_mask}",
|
f"Edited user {username} (UID:{user_id}) with roles {roles} "
|
||||||
|
f"and permissions {permissions_mask}",
|
||||||
server_id=0,
|
server_id=0,
|
||||||
source_ip=self.get_remote_ip(),
|
source_ip=self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
@ -1836,8 +1850,9 @@ class PanelHandler(BaseHandler):
|
|||||||
|
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f"Added API key {name} with crafty permissions {crafty_permissions_mask}"
|
f"Added API key {name} with crafty permissions "
|
||||||
+ f" and {server_permissions_mask} for user with UID: {user_id}",
|
f"{crafty_permissions_mask}"
|
||||||
|
f" and {server_permissions_mask} for user with UID: {user_id}",
|
||||||
server_id=0,
|
server_id=0,
|
||||||
source_ip=self.get_remote_ip(),
|
source_ip=self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
@ -1858,7 +1873,8 @@ class PanelHandler(BaseHandler):
|
|||||||
|
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f"Generated a new API token for the key {key.name} from user with UID: {key.user.user_id}",
|
f"Generated a new API token for the key {key.name} "
|
||||||
|
f"from user with UID: {key.user.user_id}",
|
||||||
server_id=0,
|
server_id=0,
|
||||||
source_ip=self.get_remote_ip(),
|
source_ip=self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
@ -1871,8 +1887,9 @@ class PanelHandler(BaseHandler):
|
|||||||
elif page == "add_user":
|
elif page == "add_user":
|
||||||
if bleach.clean(self.get_argument("username", None)).lower() == "system":
|
if bleach.clean(self.get_argument("username", None)).lower() == "system":
|
||||||
self.redirect(
|
self.redirect(
|
||||||
"/panel/error?error=Unauthorized access: username system is reserved for the Crafty system."
|
"/panel/error?error=Unauthorized access: "
|
||||||
+ " Please choose a different username."
|
"username system is reserved for the Crafty system."
|
||||||
|
" Please choose a different username."
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
username = bleach.clean(self.get_argument("username", None))
|
username = bleach.clean(self.get_argument("username", None))
|
||||||
@ -2074,7 +2091,8 @@ class PanelHandler(BaseHandler):
|
|||||||
|
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f"Removed API key {target_key} (ID: {key_id}) from user {exec_user['user_id']}",
|
f"Removed API key {target_key} "
|
||||||
|
f"(ID: {key_id}) from user {exec_user['user_id']}",
|
||||||
server_id=0,
|
server_id=0,
|
||||||
source_ip=self.get_remote_ip(),
|
source_ip=self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
|
@ -127,7 +127,10 @@ class PublicHandler(BaseHandler):
|
|||||||
|
|
||||||
# if they are disabled
|
# if they are disabled
|
||||||
if not user_data.enabled:
|
if not user_data.enabled:
|
||||||
error_msg = "User account disabled. Please contact your system administrator for more info."
|
error_msg = (
|
||||||
|
"User account disabled. Please contact "
|
||||||
|
"your system administrator for more info."
|
||||||
|
)
|
||||||
# self.clear_cookie("user")
|
# self.clear_cookie("user")
|
||||||
# self.clear_cookie("user_data")
|
# self.clear_cookie("user_data")
|
||||||
self.clear_cookie("token")
|
self.clear_cookie("token")
|
||||||
|
@ -126,7 +126,8 @@ class ServerHandler(BaseHandler):
|
|||||||
exec_user["user_id"]
|
exec_user["user_id"]
|
||||||
):
|
):
|
||||||
self.redirect(
|
self.redirect(
|
||||||
"/panel/error?error=Unauthorized access: not a server creator or server limit reached"
|
"/panel/error?error=Unauthorized access: "
|
||||||
|
"not a server creator or server limit reached"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
@ -141,7 +142,8 @@ class ServerHandler(BaseHandler):
|
|||||||
exec_user["user_id"]
|
exec_user["user_id"]
|
||||||
):
|
):
|
||||||
self.redirect(
|
self.redirect(
|
||||||
"/panel/error?error=Unauthorized access: not a server creator or server limit reached"
|
"/panel/error?error=Unauthorized access: "
|
||||||
|
"not a server creator or server limit reached"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
@ -286,7 +288,7 @@ class ServerHandler(BaseHandler):
|
|||||||
)
|
)
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f'imported a jar server named "{server_name}"', # Example: Admin imported a server named "old creative"
|
f'imported a jar server named "{server_name}"',
|
||||||
new_server_id,
|
new_server_id,
|
||||||
self.get_remote_ip(),
|
self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
@ -303,13 +305,15 @@ class ServerHandler(BaseHandler):
|
|||||||
)
|
)
|
||||||
if new_server_id == "false":
|
if new_server_id == "false":
|
||||||
self.redirect(
|
self.redirect(
|
||||||
"/panel/error?error=Zip file not accessible! You can fix this permissions issue with"
|
f"/panel/error?error=Zip file not accessible! "
|
||||||
+ f"sudo chown -R crafty:crafty {import_server_path} And sudo chmod 2775 -R {import_server_path}"
|
f"You can fix this permissions issue with "
|
||||||
|
f"sudo chown -R crafty:crafty {import_server_path} "
|
||||||
|
f"And sudo chmod 2775 -R {import_server_path}"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f'imported a zip server named "{server_name}"', # Example: Admin imported a server named "old creative"
|
f'imported a zip server named "{server_name}"',
|
||||||
new_server_id,
|
new_server_id,
|
||||||
self.get_remote_ip(),
|
self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
@ -320,20 +324,23 @@ class ServerHandler(BaseHandler):
|
|||||||
self.redirect("/panel/error?error=Invalid server data")
|
self.redirect("/panel/error?error=Invalid server data")
|
||||||
return
|
return
|
||||||
server_type, server_version = server_parts
|
server_type, server_version = server_parts
|
||||||
# TODO: add server type check here and call the correct server add functions if not a jar
|
# TODO: add server type check here and call the correct server
|
||||||
|
# add functions if not a jar
|
||||||
role_ids = self.controller.users.get_user_roles_id(exec_user["user_id"])
|
role_ids = self.controller.users.get_user_roles_id(exec_user["user_id"])
|
||||||
new_server_id = self.controller.create_jar_server(
|
new_server_id = self.controller.create_jar_server(
|
||||||
server_type, server_version, server_name, min_mem, max_mem, port
|
server_type, server_version, server_name, min_mem, max_mem, port
|
||||||
)
|
)
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f'created a {server_version} {str(server_type).capitalize()} server named "{server_name}"',
|
f"created a {server_version} {str(server_type).capitalize()}"
|
||||||
|
f' server named "{server_name}"',
|
||||||
# Example: Admin created a 1.16.5 Bukkit server named "survival"
|
# Example: Admin created a 1.16.5 Bukkit server named "survival"
|
||||||
new_server_id,
|
new_server_id,
|
||||||
self.get_remote_ip(),
|
self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
|
|
||||||
# These lines create a new Role for the Server with full permissions and add the user to it if he's not a superuser
|
# These lines create a new Role for the Server with full permissions
|
||||||
|
# and add the user to it if he's not a superuser
|
||||||
if len(captured_roles) == 0:
|
if len(captured_roles) == 0:
|
||||||
if not superuser:
|
if not superuser:
|
||||||
new_server_uuid = self.controller.servers.get_server_data_by_id(
|
new_server_uuid = self.controller.servers.get_server_data_by_id(
|
||||||
@ -399,7 +406,7 @@ class ServerHandler(BaseHandler):
|
|||||||
)
|
)
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f'imported a jar server named "{server_name}"', # Example: Admin imported a server named "old creative"
|
f'imported a jar server named "{server_name}"',
|
||||||
new_server_id,
|
new_server_id,
|
||||||
self.get_remote_ip(),
|
self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
@ -416,13 +423,15 @@ class ServerHandler(BaseHandler):
|
|||||||
)
|
)
|
||||||
if new_server_id == "false":
|
if new_server_id == "false":
|
||||||
self.redirect(
|
self.redirect(
|
||||||
"/panel/error?error=Zip file not accessible! You can fix this permissions issue with"
|
f"/panel/error?error=Zip file not accessible! "
|
||||||
+ f"sudo chown -R crafty:crafty {import_server_path} And sudo chmod 2775 -R {import_server_path}"
|
f"You can fix this permissions issue with"
|
||||||
|
f"sudo chown -R crafty:crafty {import_server_path} "
|
||||||
|
f"And sudo chmod 2775 -R {import_server_path}"
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f'imported a zip server named "{server_name}"', # Example: Admin imported a server named "old creative"
|
f'imported a zip server named "{server_name}"',
|
||||||
new_server_id,
|
new_server_id,
|
||||||
self.get_remote_ip(),
|
self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
@ -433,20 +442,23 @@ class ServerHandler(BaseHandler):
|
|||||||
self.redirect("/panel/error?error=Invalid server data")
|
self.redirect("/panel/error?error=Invalid server data")
|
||||||
return
|
return
|
||||||
server_type, server_version = server_parts
|
server_type, server_version = server_parts
|
||||||
# TODO: add server type check here and call the correct server add functions if not a jar
|
# TODO: add server type check here and call the correct server
|
||||||
|
# add functions if not a jar
|
||||||
role_ids = self.controller.users.get_user_roles_id(exec_user["user_id"])
|
role_ids = self.controller.users.get_user_roles_id(exec_user["user_id"])
|
||||||
new_server_id = self.controller.create_jar_server(
|
new_server_id = self.controller.create_jar_server(
|
||||||
server_type, server_version, server_name, min_mem, max_mem, port
|
server_type, server_version, server_name, min_mem, max_mem, port
|
||||||
)
|
)
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
exec_user["user_id"],
|
exec_user["user_id"],
|
||||||
f'created a {server_version} {str(server_type).capitalize()} server named "{server_name}"',
|
f"created a {server_version} {str(server_type).capitalize()} "
|
||||||
|
f'server named "{server_name}"',
|
||||||
# Example: Admin created a 1.16.5 Bukkit server named "survival"
|
# Example: Admin created a 1.16.5 Bukkit server named "survival"
|
||||||
new_server_id,
|
new_server_id,
|
||||||
self.get_remote_ip(),
|
self.get_remote_ip(),
|
||||||
)
|
)
|
||||||
|
|
||||||
# These lines create a new Role for the Server with full permissions and add the user to it if he's not a superuser
|
# These lines create a new Role for the Server with full permissions
|
||||||
|
# and add the user to it if he's not a superuser
|
||||||
if len(captured_roles) == 0:
|
if len(captured_roles) == 0:
|
||||||
if not superuser:
|
if not superuser:
|
||||||
new_server_uuid = self.controller.servers.get_server_data_by_id(
|
new_server_uuid = self.controller.servers.get_server_data_by_id(
|
||||||
|
@ -61,12 +61,15 @@ class Webserver:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def _asyncio_patch():
|
def _asyncio_patch():
|
||||||
"""
|
"""
|
||||||
As of Python 3.8 (on Windows), the asyncio default event handler has changed to "proactor",
|
As of Python 3.8 (on Windows),
|
||||||
|
the asyncio default event handler has changed to "proactor",
|
||||||
where tornado expects the "selector" handler.
|
where tornado expects the "selector" handler.
|
||||||
|
|
||||||
This function checks if the platform is windows and changes the event handler to suit.
|
This function checks if the platform is windows and
|
||||||
|
changes the event handler to suit.
|
||||||
|
|
||||||
(Taken from https://github.com/mkdocs/mkdocs/commit/cf2b136d4257787c0de51eba2d9e30ded5245b31)
|
(Taken from
|
||||||
|
https://github.com/mkdocs/mkdocs/commit/cf2b136d4257787c0de51eba2d9e30ded5245b31)
|
||||||
"""
|
"""
|
||||||
logger.debug("Checking if asyncio patch is required")
|
logger.debug("Checking if asyncio patch is required")
|
||||||
if sys.platform.startswith("win") and sys.version_info >= (3, 8):
|
if sys.platform.startswith("win") and sys.version_info >= (3, 8):
|
||||||
@ -189,10 +192,12 @@ class Webserver:
|
|||||||
self.HTTPS_Server.listen(https_port)
|
self.HTTPS_Server.listen(https_port)
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
f"https://{helper.get_local_ip()}:{https_port} is up and ready for connections."
|
f"https://{helper.get_local_ip()}:{https_port} "
|
||||||
|
f"is up and ready for connections."
|
||||||
)
|
)
|
||||||
console.info(
|
console.info(
|
||||||
f"https://{helper.get_local_ip()}:{https_port} is up and ready for connections."
|
f"https://{helper.get_local_ip()}:{https_port} "
|
||||||
|
f"is up and ready for connections."
|
||||||
)
|
)
|
||||||
|
|
||||||
console.info("Server Init Complete: Listening For Connections:")
|
console.info("Server Init Complete: Listening For Connections:")
|
||||||
|
@ -75,10 +75,12 @@ class UploadHandler(BaseHandler):
|
|||||||
|
|
||||||
if Enum_Permissions_Server.Files not in exec_user_server_permissions:
|
if Enum_Permissions_Server.Files not in exec_user_server_permissions:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"User {user_id} tried to upload a file to {server_id} without permissions!"
|
f"User {user_id} tried to upload a file to "
|
||||||
|
f"{server_id} without permissions!"
|
||||||
)
|
)
|
||||||
console.warning(
|
console.warning(
|
||||||
f"User {user_id} tried to upload a file to {server_id} without permissions!"
|
f"User {user_id} tried to upload a file to "
|
||||||
|
f"{server_id} without permissions!"
|
||||||
)
|
)
|
||||||
self.do_upload = False
|
self.do_upload = False
|
||||||
|
|
||||||
@ -101,10 +103,12 @@ class UploadHandler(BaseHandler):
|
|||||||
full_path,
|
full_path,
|
||||||
)
|
)
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f"User {user_id} tried to upload a file to {server_id} but the path is not inside of the server!"
|
f"User {user_id} tried to upload a file to {server_id} "
|
||||||
|
f"but the path is not inside of the server!"
|
||||||
)
|
)
|
||||||
console.warning(
|
console.warning(
|
||||||
f"User {user_id} tried to upload a file to {server_id} but the path is not inside of the server!"
|
f"User {user_id} tried to upload a file to {server_id} "
|
||||||
|
f"but the path is not inside of the server!"
|
||||||
)
|
)
|
||||||
self.do_upload = False
|
self.do_upload = False
|
||||||
|
|
||||||
|
@ -24,14 +24,16 @@ class WebSocketHelper:
|
|||||||
|
|
||||||
def broadcast(self, event_type: str, data):
|
def broadcast(self, event_type: str, data):
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"Sending to {len(self.clients)} clients: {json.dumps({'event': event_type, 'data': data})}"
|
f"Sending to {len(self.clients)} clients: "
|
||||||
|
f"{json.dumps({'event': event_type, 'data': data})}"
|
||||||
)
|
)
|
||||||
for client in self.clients:
|
for client in self.clients:
|
||||||
try:
|
try:
|
||||||
self.send_message(client, event_type, data)
|
self.send_message(client, event_type, data)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception(
|
logger.exception(
|
||||||
f"Error caught while sending WebSocket message to {client.get_remote_ip()} {e}"
|
f"Error caught while sending WebSocket message to "
|
||||||
|
f"{client.get_remote_ip()} {e}"
|
||||||
)
|
)
|
||||||
|
|
||||||
def broadcast_page(self, page: str, event_type: str, data):
|
def broadcast_page(self, page: str, event_type: str, data):
|
||||||
@ -85,7 +87,8 @@ class WebSocketHelper:
|
|||||||
def broadcast_with_fn(self, filter_fn, event_type: str, data):
|
def broadcast_with_fn(self, filter_fn, event_type: str, data):
|
||||||
clients = list(filter(filter_fn, self.clients))
|
clients = list(filter(filter_fn, self.clients))
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"Sending to {len(clients)} out of {len(self.clients)} clients: {json.dumps({'event': event_type, 'data': data})}"
|
f"Sending to {len(clients)} out of {len(self.clients)} "
|
||||||
|
f"clients: {json.dumps({'event': event_type, 'data': data})}"
|
||||||
)
|
)
|
||||||
|
|
||||||
for client in clients:
|
for client in clients:
|
||||||
@ -93,7 +96,8 @@ class WebSocketHelper:
|
|||||||
self.send_message(client, event_type, data)
|
self.send_message(client, event_type, data)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception(
|
logger.exception(
|
||||||
f"Error catched while sending WebSocket message to {client.get_remote_ip()} {e}"
|
f"Error catched while sending WebSocket message to "
|
||||||
|
f"{client.get_remote_ip()} {e}"
|
||||||
)
|
)
|
||||||
|
|
||||||
def disconnect_all(self):
|
def disconnect_all(self):
|
||||||
|
Loading…
Reference in New Issue
Block a user