mirror of
https://gitlab.com/crafty-controller/crafty-4.git
synced 2025-01-19 01:35:28 +01:00
Merge branch 'merge/cleanup-nosquash' into 'dev'
New merge request for cleanup See merge request crafty-controller/crafty-4!268
This commit is contained in:
commit
f01f04ef97
@ -172,7 +172,7 @@ class RolesController:
|
|||||||
|
|
||||||
if role:
|
if role:
|
||||||
server_ids = PermissionsServers.get_server_ids_from_role(role_id)
|
server_ids = PermissionsServers.get_server_ids_from_role(role_id)
|
||||||
role["servers"] = list(server_ids)
|
role["servers"] = server_ids
|
||||||
# logger.debug("role: ({}) {}".format(role_id, role))
|
# logger.debug("role: ({}) {}".format(role_id, role))
|
||||||
return role
|
return role
|
||||||
else:
|
else:
|
||||||
|
@ -149,7 +149,7 @@ class ServersController:
|
|||||||
def get_authorized_servers_stats_api_key(api_key: ApiKeys):
|
def get_authorized_servers_stats_api_key(api_key: ApiKeys):
|
||||||
server_data = []
|
server_data = []
|
||||||
authorized_servers = ServersController.get_authorized_servers(
|
authorized_servers = ServersController.get_authorized_servers(
|
||||||
api_key.user.user_id # TODO: API key authorized servers?
|
api_key.user_id # TODO: API key authorized servers?
|
||||||
)
|
)
|
||||||
|
|
||||||
for server in authorized_servers:
|
for server in authorized_servers:
|
||||||
|
@ -1,7 +1,9 @@
|
|||||||
|
from __future__ import annotations
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import datetime
|
import datetime
|
||||||
import base64
|
import base64
|
||||||
|
import typing as t
|
||||||
import psutil
|
import psutil
|
||||||
|
|
||||||
from app.classes.minecraft.mc_ping import ping
|
from app.classes.minecraft.mc_ping import ping
|
||||||
@ -9,37 +11,77 @@ from app.classes.models.management import HostStats
|
|||||||
from app.classes.models.servers import HelperServers
|
from app.classes.models.servers import HelperServers
|
||||||
from app.classes.shared.helpers import Helpers
|
from app.classes.shared.helpers import Helpers
|
||||||
|
|
||||||
|
if t.TYPE_CHECKING:
|
||||||
|
from app.classes.shared.main_controller import Controller
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class DiskDataDict(t.TypedDict):
|
||||||
|
device: str
|
||||||
|
total_raw: int
|
||||||
|
total: str
|
||||||
|
used_raw: int
|
||||||
|
used: str
|
||||||
|
free_raw: int
|
||||||
|
free: str
|
||||||
|
percent_used: float
|
||||||
|
fs: str
|
||||||
|
mount: str
|
||||||
|
|
||||||
|
|
||||||
|
class NodeStatsDict(t.TypedDict):
|
||||||
|
boot_time: str
|
||||||
|
cpu_usage: float
|
||||||
|
cpu_count: int
|
||||||
|
cpu_cur_freq: float
|
||||||
|
cpu_max_freq: float
|
||||||
|
mem_percent: float
|
||||||
|
mem_usage_raw: int
|
||||||
|
mem_usage: str
|
||||||
|
mem_total_raw: int
|
||||||
|
mem_total: str
|
||||||
|
disk_data: t.List[DiskDataDict]
|
||||||
|
|
||||||
|
|
||||||
|
class NodeStatsReturnDict(t.TypedDict):
|
||||||
|
node_stats: NodeStatsDict
|
||||||
|
|
||||||
|
|
||||||
class Stats:
|
class Stats:
|
||||||
|
helper: Helpers
|
||||||
|
controller: Controller
|
||||||
|
|
||||||
def __init__(self, helper, controller):
|
def __init__(self, helper, controller):
|
||||||
self.helper = helper
|
self.helper = helper
|
||||||
self.controller = controller
|
self.controller = controller
|
||||||
|
|
||||||
def get_node_stats(self):
|
def get_node_stats(self) -> NodeStatsReturnDict:
|
||||||
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
|
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
|
||||||
data = {}
|
|
||||||
try:
|
try:
|
||||||
cpu_freq = psutil.cpu_freq()
|
cpu_freq = psutil.cpu_freq()
|
||||||
except NotImplementedError:
|
except NotImplementedError:
|
||||||
cpu_freq = psutil._common.scpufreq(current=0, min=0, max=0)
|
cpu_freq = psutil._common.scpufreq(current=0, min=0, max=0)
|
||||||
node_stats = {
|
memory = psutil.virtual_memory()
|
||||||
|
node_stats: NodeStatsDict = {
|
||||||
"boot_time": str(boot_time),
|
"boot_time": str(boot_time),
|
||||||
"cpu_usage": psutil.cpu_percent(interval=0.5) / psutil.cpu_count(),
|
"cpu_usage": psutil.cpu_percent(interval=0.5) / psutil.cpu_count(),
|
||||||
"cpu_count": psutil.cpu_count(),
|
"cpu_count": psutil.cpu_count(),
|
||||||
"cpu_cur_freq": round(cpu_freq[0], 2),
|
"cpu_cur_freq": round(cpu_freq[0], 2),
|
||||||
"cpu_max_freq": cpu_freq[2],
|
"cpu_max_freq": cpu_freq[2],
|
||||||
"mem_percent": psutil.virtual_memory()[2],
|
"mem_percent": memory.percent,
|
||||||
"mem_usage": Helpers.human_readable_file_size(psutil.virtual_memory()[3]),
|
"mem_usage_raw": memory.used,
|
||||||
"mem_total": Helpers.human_readable_file_size(psutil.virtual_memory()[0]),
|
"mem_usage": Helpers.human_readable_file_size(memory.used),
|
||||||
|
"mem_total_raw": memory.total,
|
||||||
|
"mem_total": Helpers.human_readable_file_size(memory.total),
|
||||||
"disk_data": self._all_disk_usage(),
|
"disk_data": self._all_disk_usage(),
|
||||||
}
|
}
|
||||||
# server_stats = self.get_servers_stats()
|
# server_stats = self.get_servers_stats()
|
||||||
# data['servers'] = server_stats
|
# data['servers'] = server_stats
|
||||||
data["node_stats"] = node_stats
|
|
||||||
|
|
||||||
return data
|
return {
|
||||||
|
"node_stats": node_stats,
|
||||||
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _get_process_stats(process):
|
def _get_process_stats(process):
|
||||||
@ -82,7 +124,7 @@ class Stats:
|
|||||||
|
|
||||||
# Source: 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() -> t.List[DiskDataDict]:
|
||||||
disk_data = []
|
disk_data = []
|
||||||
# print(templ % ("Device", "Total", "Used", "Free", "Use ", "Type","Mount"))
|
# print(templ % ("Device", "Total", "Used", "Free", "Use ", "Type","Mount"))
|
||||||
|
|
||||||
@ -97,10 +139,13 @@ class Stats:
|
|||||||
disk_data.append(
|
disk_data.append(
|
||||||
{
|
{
|
||||||
"device": part.device,
|
"device": part.device,
|
||||||
|
"total_raw": usage.total,
|
||||||
"total": Helpers.human_readable_file_size(usage.total),
|
"total": Helpers.human_readable_file_size(usage.total),
|
||||||
|
"used_raw": usage.used,
|
||||||
"used": Helpers.human_readable_file_size(usage.used),
|
"used": Helpers.human_readable_file_size(usage.used),
|
||||||
|
"free_raw": usage.free,
|
||||||
"free": Helpers.human_readable_file_size(usage.free),
|
"free": Helpers.human_readable_file_size(usage.free),
|
||||||
"percent_used": int(usage.percent),
|
"percent_used": usage.percent,
|
||||||
"fs": part.fstype,
|
"fs": part.fstype,
|
||||||
"mount": part.mountpoint,
|
"mount": part.mountpoint,
|
||||||
}
|
}
|
||||||
@ -194,7 +239,7 @@ class Stats:
|
|||||||
|
|
||||||
def record_stats(self):
|
def record_stats(self):
|
||||||
stats_to_send = self.get_node_stats()
|
stats_to_send = self.get_node_stats()
|
||||||
node_stats = stats_to_send.get("node_stats")
|
node_stats = stats_to_send["node_stats"]
|
||||||
|
|
||||||
HostStats.insert(
|
HostStats.insert(
|
||||||
{
|
{
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import logging
|
import logging
|
||||||
import typing
|
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from peewee import (
|
from peewee import (
|
||||||
ForeignKeyField,
|
ForeignKeyField,
|
||||||
@ -46,37 +45,26 @@ class PermissionsCrafty:
|
|||||||
# **********************************************************************************
|
# **********************************************************************************
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_permissions_list():
|
def get_permissions_list():
|
||||||
permissions_list: typing.List[EnumPermissionsCrafty] = []
|
return list(EnumPermissionsCrafty.__members__.values())
|
||||||
for member in EnumPermissionsCrafty.__members__.items():
|
|
||||||
permissions_list.append(member[1])
|
|
||||||
return permissions_list
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_permissions(permissions_mask):
|
def get_permissions(permissions_mask):
|
||||||
permissions_list: typing.List[EnumPermissionsCrafty] = []
|
return [
|
||||||
for member in EnumPermissionsCrafty.__members__.items():
|
permission
|
||||||
if PermissionsCrafty.has_permission(permissions_mask, member[1]):
|
for permission in EnumPermissionsCrafty.__members__.values()
|
||||||
permissions_list.append(member[1])
|
if PermissionsCrafty.has_permission(permissions_mask, permission)
|
||||||
return permissions_list
|
]
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def has_permission(
|
def has_permission(permission_mask, permission_tested: EnumPermissionsCrafty):
|
||||||
permission_mask: typing.Mapping[int, str],
|
return permission_mask[permission_tested.value] == "1"
|
||||||
permission_tested: EnumPermissionsCrafty,
|
|
||||||
):
|
|
||||||
result = False
|
|
||||||
if permission_mask[permission_tested.value] == "1":
|
|
||||||
result = True
|
|
||||||
return result
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def set_permission(
|
def set_permission(
|
||||||
permission_mask, permission_tested: EnumPermissionsCrafty, value
|
permission_mask, permission_tested: EnumPermissionsCrafty, value
|
||||||
):
|
):
|
||||||
lst = list(permission_mask)
|
index = permission_tested.value
|
||||||
lst[permission_tested.value] = str(value)
|
return permission_mask[:index] + str(value) + permission_mask[index + 1 :]
|
||||||
permission_mask = "".join(lst)
|
|
||||||
return permission_mask
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_permission(permission_mask, permission_tested: EnumPermissionsCrafty):
|
def get_permission(permission_mask, permission_tested: EnumPermissionsCrafty):
|
||||||
@ -84,19 +72,14 @@ class PermissionsCrafty:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_crafty_permissions_mask(user_id):
|
def get_crafty_permissions_mask(user_id):
|
||||||
permissions_mask = ""
|
# TODO: only get the permissions of the UserCrafty
|
||||||
user_crafty = PermissionsCrafty.get_user_crafty(user_id)
|
user_crafty = PermissionsCrafty.get_user_crafty(user_id)
|
||||||
permissions_mask = user_crafty.permissions
|
permissions_mask = user_crafty.permissions
|
||||||
return permissions_mask
|
return permissions_mask
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_all_permission_quantity_list():
|
def get_all_permission_quantity_list():
|
||||||
quantity_list = {
|
return {name: -1 for name in EnumPermissionsCrafty.__members__.keys()}
|
||||||
EnumPermissionsCrafty.SERVER_CREATION.name: -1,
|
|
||||||
EnumPermissionsCrafty.USER_CONFIG.name: -1,
|
|
||||||
EnumPermissionsCrafty.ROLES_CONFIG.name: -1,
|
|
||||||
}
|
|
||||||
return quantity_list
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_permission_quantity_list(user_id):
|
def get_permission_quantity_list(user_id):
|
||||||
@ -114,7 +97,7 @@ class PermissionsCrafty:
|
|||||||
@staticmethod
|
@staticmethod
|
||||||
def get_user_crafty(user_id):
|
def get_user_crafty(user_id):
|
||||||
try:
|
try:
|
||||||
user_crafty = UserCrafty.select().where(UserCrafty.user_id == user_id).get()
|
user_crafty = UserCrafty.get(UserCrafty.user_id == user_id)
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
user_crafty = UserCrafty.insert(
|
user_crafty = UserCrafty.insert(
|
||||||
{
|
{
|
||||||
@ -146,15 +129,9 @@ class PermissionsCrafty:
|
|||||||
limit_user_creation,
|
limit_user_creation,
|
||||||
limit_role_creation,
|
limit_role_creation,
|
||||||
):
|
):
|
||||||
try:
|
# http://docs.peewee-orm.com/en/latest/peewee/querying.html#upsert
|
||||||
user_crafty = UserCrafty.select().where(UserCrafty.user_id == user_id).get()
|
|
||||||
user_crafty.permissions = permissions_mask
|
UserCrafty.replace(
|
||||||
user_crafty.limit_server_creation = limit_server_creation
|
|
||||||
user_crafty.limit_user_creation = limit_user_creation
|
|
||||||
user_crafty.limit_role_creation = limit_role_creation
|
|
||||||
UserCrafty.save(user_crafty)
|
|
||||||
except:
|
|
||||||
UserCrafty.insert(
|
|
||||||
{
|
{
|
||||||
UserCrafty.user_id: user_id,
|
UserCrafty.user_id: user_id,
|
||||||
UserCrafty.permissions: permissions_mask,
|
UserCrafty.permissions: permissions_mask,
|
||||||
@ -191,19 +168,15 @@ class PermissionsCrafty:
|
|||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def add_server_creation(user_id):
|
def add_server_creation(user_id: int):
|
||||||
"""Increase the "Server Creation" counter for this user
|
"""Increase the "Server Creation" counter for this user
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
user_id (int): The modifiable user's ID
|
user_id (int): The modifiable user's ID
|
||||||
|
|
||||||
Returns:
|
|
||||||
int: The new count of servers created by this user
|
|
||||||
"""
|
"""
|
||||||
user_crafty = PermissionsCrafty.get_user_crafty(user_id)
|
UserCrafty.update(created_server=UserCrafty.created_server + 1).where(
|
||||||
user_crafty.created_server += 1
|
UserCrafty.user_id == user_id
|
||||||
UserCrafty.save(user_crafty)
|
).execute()
|
||||||
return user_crafty.created_server
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def add_user_creation(user_id):
|
def add_user_creation(user_id):
|
||||||
@ -226,8 +199,10 @@ class PermissionsCrafty:
|
|||||||
return PermissionsCrafty.get_permissions_list()
|
return PermissionsCrafty.get_permissions_list()
|
||||||
else:
|
else:
|
||||||
if user["superuser"]:
|
if user["superuser"]:
|
||||||
|
# User is superuser but API key isn't
|
||||||
user_permissions_mask = "111"
|
user_permissions_mask = "111"
|
||||||
else:
|
else:
|
||||||
|
# Not superuser
|
||||||
user_permissions_mask = PermissionsCrafty.get_crafty_permissions_mask(
|
user_permissions_mask = PermissionsCrafty.get_crafty_permissions_mask(
|
||||||
user["user_id"]
|
user["user_id"]
|
||||||
)
|
)
|
||||||
|
@ -269,8 +269,7 @@ class HelpersManagement:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def delete_scheduled_task(schedule_id):
|
def delete_scheduled_task(schedule_id):
|
||||||
sch = Schedules.get(Schedules.schedule_id == schedule_id)
|
return Schedules.delete().where(Schedules.schedule_id == schedule_id).execute()
|
||||||
return Schedules.delete_instance(sch)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def update_scheduled_task(schedule_id, updates):
|
def update_scheduled_task(schedule_id, updates):
|
||||||
@ -329,7 +328,7 @@ class HelpersManagement:
|
|||||||
"backup_path": row.server_id.backup_path,
|
"backup_path": row.server_id.backup_path,
|
||||||
"excluded_dirs": row.excluded_dirs,
|
"excluded_dirs": row.excluded_dirs,
|
||||||
"max_backups": row.max_backups,
|
"max_backups": row.max_backups,
|
||||||
"server_id": row.server_id.server_id,
|
"server_id": row.server_id_id,
|
||||||
"compress": row.compress,
|
"compress": row.compress,
|
||||||
}
|
}
|
||||||
except IndexError:
|
except IndexError:
|
||||||
|
@ -90,6 +90,4 @@ class HelperRoles:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def role_id_exists(role_id) -> bool:
|
def role_id_exists(role_id) -> bool:
|
||||||
if not HelperRoles.get_role(role_id):
|
return Roles.select().where(Roles.role_id == role_id).count() != 0
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
@ -52,18 +52,15 @@ class PermissionsServers:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_permissions_list():
|
def get_permissions_list():
|
||||||
permissions_list: t.List[EnumPermissionsServer] = []
|
return list(EnumPermissionsServer.__members__.values())
|
||||||
for member in EnumPermissionsServer.__members__.items():
|
|
||||||
permissions_list.append(member[1])
|
|
||||||
return permissions_list
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_permissions(permissions_mask):
|
def get_permissions(permissions_mask):
|
||||||
permissions_list: t.List[EnumPermissionsServer] = []
|
return [
|
||||||
for member in EnumPermissionsServer.__members__.items():
|
permission
|
||||||
if PermissionsServers.has_permission(permissions_mask, member[1]):
|
for permission in EnumPermissionsServer.__members__.values()
|
||||||
permissions_list.append(member[1])
|
if PermissionsServers.has_permission(permissions_mask, permission)
|
||||||
return permissions_list
|
]
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def has_permission(permission_mask, permission_tested: EnumPermissionsServer):
|
def has_permission(permission_mask, permission_tested: EnumPermissionsServer):
|
||||||
@ -84,13 +81,13 @@ class PermissionsServers:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_token_permissions(permissions_mask, api_permissions_mask):
|
def get_token_permissions(permissions_mask, api_permissions_mask):
|
||||||
permissions_list = []
|
return [
|
||||||
for member in EnumPermissionsServer.__members__.items():
|
permission
|
||||||
|
for permission in EnumPermissionsServer.__members__.values()
|
||||||
if PermissionHelper.both_have_perm(
|
if PermissionHelper.both_have_perm(
|
||||||
permissions_mask, api_permissions_mask, member[1]
|
permissions_mask, api_permissions_mask, permission
|
||||||
):
|
)
|
||||||
permissions_list.append(member[1])
|
]
|
||||||
return permissions_list
|
|
||||||
|
|
||||||
# **********************************************************************************
|
# **********************************************************************************
|
||||||
# Role_Servers Methods
|
# Role_Servers Methods
|
||||||
@ -160,10 +157,10 @@ class PermissionsServers:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_role_permissions_list(role_id):
|
def get_role_permissions_list(role_id):
|
||||||
permissions_mask = "00000000"
|
|
||||||
role_server = RoleServers.get_or_none(RoleServers.role_id == role_id)
|
role_server = RoleServers.get_or_none(RoleServers.role_id == role_id)
|
||||||
if role_server is not None:
|
permissions_mask = (
|
||||||
permissions_mask = role_server.permissions
|
"00000000" if role_server is None else role_server.permissions
|
||||||
|
)
|
||||||
permissions_list = PermissionsServers.get_permissions(permissions_mask)
|
permissions_list = PermissionsServers.get_permissions(permissions_mask)
|
||||||
return permissions_list
|
return permissions_list
|
||||||
|
|
||||||
@ -181,14 +178,9 @@ class PermissionsServers:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def update_role_permission(role_id, server_id, permissions_mask):
|
def update_role_permission(role_id, server_id, permissions_mask):
|
||||||
role_server = (
|
RoleServers.update(permissions=permissions_mask).where(
|
||||||
RoleServers.select()
|
RoleServers.role_id == role_id, RoleServers.server_id == server_id
|
||||||
.where(RoleServers.role_id == role_id)
|
).execute()
|
||||||
.where(RoleServers.server_id == server_id)
|
|
||||||
.get()
|
|
||||||
)
|
|
||||||
role_server.permissions = permissions_mask
|
|
||||||
RoleServers.save(role_server)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def delete_roles_permissions(
|
def delete_roles_permissions(
|
||||||
@ -232,14 +224,16 @@ class PermissionsServers:
|
|||||||
def get_server_user_list(server_id):
|
def get_server_user_list(server_id):
|
||||||
final_users = []
|
final_users = []
|
||||||
server_roles = RoleServers.select().where(RoleServers.server_id == server_id)
|
server_roles = RoleServers.select().where(RoleServers.server_id == server_id)
|
||||||
super_users = Users.select().where(
|
super_users = Users.select(Users.user_id).where(
|
||||||
Users.superuser == True # pylint: disable=singleton-comparison
|
Users.superuser == True # pylint: disable=singleton-comparison
|
||||||
)
|
)
|
||||||
for role in server_roles:
|
for role in server_roles:
|
||||||
users = UserRoles.select().where(UserRoles.role_id == role.role_id)
|
users = UserRoles.select(UserRoles.user_id).where(
|
||||||
|
UserRoles.role_id == role.role_id
|
||||||
|
)
|
||||||
for user in users:
|
for user in users:
|
||||||
if user.user_id.user_id not in final_users:
|
if user.user_id_id not in final_users:
|
||||||
final_users.append(user.user_id.user_id)
|
final_users.append(user.user_id_id)
|
||||||
for suser in super_users:
|
for suser in super_users:
|
||||||
if suser.user_id not in final_users:
|
if suser.user_id not in final_users:
|
||||||
final_users.append(suser.user_id)
|
final_users.append(suser.user_id)
|
||||||
|
@ -120,7 +120,6 @@ class HelperServers:
|
|||||||
return server_obj.save()
|
return server_obj.save()
|
||||||
|
|
||||||
def remove_server(self, server_id):
|
def remove_server(self, server_id):
|
||||||
with self.database.atomic():
|
|
||||||
Servers.delete().where(Servers.server_id == server_id).execute()
|
Servers.delete().where(Servers.server_id == server_id).execute()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
@ -284,9 +284,7 @@ class HelperUsers:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def user_id_exists(user_id):
|
def user_id_exists(user_id):
|
||||||
if not HelperUsers.get_user(user_id):
|
return Users.select().where(Users.user_id == user_id).count() != 0
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
# **********************************************************************************
|
# **********************************************************************************
|
||||||
# User_Roles Methods
|
# User_Roles Methods
|
||||||
@ -332,10 +330,7 @@ class HelperUsers:
|
|||||||
.join(Roles, JOIN.INNER)
|
.join(Roles, JOIN.INNER)
|
||||||
.where(UserRoles.user_id == user_id)
|
.where(UserRoles.user_id == user_id)
|
||||||
)
|
)
|
||||||
# TODO: this query needs to be narrower
|
roles = {r.role_id_id for r in roles_query}
|
||||||
roles = set()
|
|
||||||
for r in roles_query:
|
|
||||||
roles.add(r.role_id.role_id)
|
|
||||||
|
|
||||||
if isinstance(user, dict):
|
if isinstance(user, dict):
|
||||||
user["roles"] = roles
|
user["roles"] = roles
|
||||||
|
@ -22,9 +22,7 @@ class MainPrompt(cmd.Cmd):
|
|||||||
# overrides the default Prompt
|
# overrides the default Prompt
|
||||||
self.prompt = f"Crafty Controller v{self.helper.get_version_string()} > "
|
self.prompt = f"Crafty Controller v{self.helper.get_version_string()} > "
|
||||||
|
|
||||||
# see MR !233 for pylint exemptino reason
|
def emptyline(self):
|
||||||
@staticmethod
|
|
||||||
def emptyline(): # pylint: disable=arguments-differ
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def do_exit(self, _line):
|
def do_exit(self, _line):
|
||||||
@ -88,11 +86,15 @@ 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: "
|
f"Name: {thread.name}\tIdentifier: "
|
||||||
f"{thread.ident} TID/PID: {thread.native_id}"
|
f"{thread.ident}\tTID/PID: {thread.native_id}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
print(f"Name: {thread.name} Identifier: {thread.ident}")
|
print(f"Name: {thread.name}\tIdentifier: {thread.ident}")
|
||||||
|
|
||||||
|
def print_prompt(self):
|
||||||
|
self.stdout.write(self.prompt)
|
||||||
|
self.stdout.flush()
|
||||||
|
|
||||||
def do_import3(self, _line):
|
def do_import3(self, _line):
|
||||||
Import3.start_import()
|
Import3.start_import()
|
||||||
|
@ -1,8 +1,10 @@
|
|||||||
import datetime
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
|
import locale
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
locale.setlocale(locale.LC_ALL, "") # Get the locale from the environment
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from colorama import init
|
from colorama import init
|
||||||
@ -21,6 +23,11 @@ class Console:
|
|||||||
if "colorama" in sys.modules:
|
if "colorama" in sys.modules:
|
||||||
init()
|
init()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_fmt_date_time():
|
||||||
|
# This will use the local date (%x) and time (%X) formatting
|
||||||
|
return datetime.datetime.now().strftime("%x %X")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def do_print(message, color):
|
def do_print(message, color):
|
||||||
if "termcolor" in sys.modules or "colorama" in sys.modules:
|
if "termcolor" in sys.modules or "colorama" in sys.modules:
|
||||||
@ -54,30 +61,30 @@ class Console:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def debug(message):
|
def debug(message):
|
||||||
date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
|
date_time = Console.get_fmt_date_time()
|
||||||
Console.magenta(f"[+] Crafty: {date_time} - DEBUG:\t{message}")
|
Console.magenta(f"[+] Crafty: {date_time} - DEBUG:\t{message}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def info(message):
|
def info(message):
|
||||||
date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
|
date_time = Console.get_fmt_date_time()
|
||||||
Console.white(f"[+] Crafty: {date_time} - INFO:\t{message}")
|
Console.white(f"[+] Crafty: {date_time} - INFO:\t{message}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def warning(message):
|
def warning(message):
|
||||||
date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
|
date_time = Console.get_fmt_date_time()
|
||||||
Console.cyan(f"[+] Crafty: {date_time} - WARNING:\t{message}")
|
Console.cyan(f"[+] Crafty: {date_time} - WARNING:\t{message}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def error(message):
|
def error(message):
|
||||||
date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
|
date_time = Console.get_fmt_date_time()
|
||||||
Console.yellow(f"[+] Crafty: {date_time} - ERROR:\t{message}")
|
Console.yellow(f"[+] Crafty: {date_time} - ERROR:\t{message}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def critical(message):
|
def critical(message):
|
||||||
date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
|
date_time = Console.get_fmt_date_time()
|
||||||
Console.red(f"[+] Crafty: {date_time} - CRITICAL:\t{message}")
|
Console.red(f"[+] Crafty: {date_time} - CRITICAL:\t{message}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def help(message):
|
def help(message):
|
||||||
date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
|
date_time = Console.get_fmt_date_time()
|
||||||
Console.green(f"[+] Crafty: {date_time} - HELP:\t{message}")
|
Console.green(f"[+] Crafty: {date_time} - HELP:\t{message}")
|
||||||
|
@ -276,13 +276,23 @@ class Controller:
|
|||||||
except:
|
except:
|
||||||
return {"percent": 0, "total_files": 0}
|
return {"percent": 0, "total_files": 0}
|
||||||
|
|
||||||
def get_server_obj(self, server_id: t.Union[str, int]) -> t.Union[bool, Server]:
|
def get_server_obj(self, server_id: t.Union[str, int]) -> Server:
|
||||||
for server in self.servers_list:
|
for server in self.servers_list:
|
||||||
if str(server["server_id"]) == str(server_id):
|
if str(server["server_id"]) == str(server_id):
|
||||||
return server["server_obj"]
|
return server["server_obj"]
|
||||||
|
|
||||||
logger.warning(f"Unable to find server object for server id {server_id}")
|
logger.warning(f"Unable to find server object for server id {server_id}")
|
||||||
return False # TODO: Change to None
|
raise Exception(f"Unable to find server object for server id {server_id}")
|
||||||
|
|
||||||
|
def get_server_obj_optional(
|
||||||
|
self, server_id: t.Union[str, int]
|
||||||
|
) -> t.Optional[Server]:
|
||||||
|
for server in self.servers_list:
|
||||||
|
if str(server["server_id"]) == str(server_id):
|
||||||
|
return server["server_obj"]
|
||||||
|
|
||||||
|
logger.warning(f"Unable to find server object for server id {server_id}")
|
||||||
|
return None
|
||||||
|
|
||||||
def get_server_data(self, server_id: str):
|
def get_server_data(self, server_id: str):
|
||||||
for server in self.servers_list:
|
for server in self.servers_list:
|
||||||
|
@ -263,27 +263,18 @@ class Server:
|
|||||||
|
|
||||||
# Checks for eula. Creates one if none detected.
|
# Checks for eula. Creates one if none detected.
|
||||||
# If EULA is detected and not set to true we offer to set it true.
|
# If EULA is detected and not set to true we offer to set it true.
|
||||||
|
e_flag = False
|
||||||
if Helpers.check_file_exists(os.path.join(self.settings["path"], "eula.txt")):
|
if Helpers.check_file_exists(os.path.join(self.settings["path"], "eula.txt")):
|
||||||
f = open(
|
with 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"
|
||||||
)
|
) as f:
|
||||||
line = f.readline().lower()
|
line = f.readline().lower()
|
||||||
if line == "eula=true":
|
e_flag = line in [
|
||||||
e_flag = True
|
"eula=true",
|
||||||
|
"eula = true",
|
||||||
elif line == "eula = true":
|
"eula= true",
|
||||||
e_flag = True
|
"eula =true",
|
||||||
|
]
|
||||||
elif line == "eula= true":
|
|
||||||
e_flag = True
|
|
||||||
|
|
||||||
elif line == "eula =true":
|
|
||||||
e_flag = True
|
|
||||||
|
|
||||||
else:
|
|
||||||
e_flag = False
|
|
||||||
else:
|
|
||||||
e_flag = False
|
|
||||||
|
|
||||||
if not e_flag:
|
if not e_flag:
|
||||||
if user_id:
|
if user_id:
|
||||||
@ -296,8 +287,6 @@ class Server:
|
|||||||
"Agree not sent due to auto start."
|
"Agree not sent due to auto start."
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
return False
|
|
||||||
f.close()
|
|
||||||
if Helpers.is_os_windows():
|
if Helpers.is_os_windows():
|
||||||
logger.info("Windows Detected")
|
logger.info("Windows Detected")
|
||||||
else:
|
else:
|
||||||
@ -309,15 +298,16 @@ class Server:
|
|||||||
|
|
||||||
# checks to make sure file is openable (downloaded) and exists.
|
# checks to make sure file is openable (downloaded) and exists.
|
||||||
try:
|
try:
|
||||||
f = open(
|
with open(
|
||||||
os.path.join(
|
os.path.join(
|
||||||
self.server_path,
|
self.server_path,
|
||||||
HelperServers.get_server_data_by_id(self.server_id)["executable"],
|
HelperServers.get_server_data_by_id(self.server_id)["executable"],
|
||||||
),
|
),
|
||||||
"r",
|
"r",
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
):
|
||||||
f.close()
|
# Can open the file
|
||||||
|
pass
|
||||||
|
|
||||||
except:
|
except:
|
||||||
if user_id:
|
if user_id:
|
||||||
|
@ -87,10 +87,11 @@ class TasksManager:
|
|||||||
svr = self.controller.get_server_obj(cmd.server_id)
|
svr = self.controller.get_server_obj(cmd.server_id)
|
||||||
except:
|
except:
|
||||||
logger.error(
|
logger.error(
|
||||||
"Server value requested does note exist! "
|
"Server value requested does not exist! "
|
||||||
"Purging item from waiting commands."
|
"Purging item from waiting commands."
|
||||||
)
|
)
|
||||||
HelpersManagement.mark_command_complete(cmd.command_id)
|
HelpersManagement.mark_command_complete(cmd.command_id)
|
||||||
|
continue
|
||||||
|
|
||||||
user_id = cmd.user_id
|
user_id = cmd.user_id
|
||||||
command = cmd.command
|
command = cmd.command
|
||||||
|
@ -181,7 +181,7 @@ class PanelHandler(BaseHandler):
|
|||||||
logger.debug(
|
logger.debug(
|
||||||
f'User {exec_user["user_id"]} does not have permission'
|
f'User {exec_user["user_id"]} does not have permission'
|
||||||
)
|
)
|
||||||
self.redirect("/pandel/error?error=Invalid Server ID")
|
self.redirect("/panel/error?error=Invalid Server ID")
|
||||||
return None
|
return None
|
||||||
return server_id
|
return server_id
|
||||||
|
|
||||||
@ -222,10 +222,9 @@ class PanelHandler(BaseHandler):
|
|||||||
if api_key is not None:
|
if api_key is not None:
|
||||||
superuser = superuser and api_key.superuser
|
superuser = superuser and api_key.superuser
|
||||||
|
|
||||||
exec_user_role = set()
|
|
||||||
if superuser: # TODO: Figure out a better solution
|
if superuser: # TODO: Figure out a better solution
|
||||||
defined_servers = self.controller.list_defined_servers()
|
defined_servers = self.controller.list_defined_servers()
|
||||||
exec_user_role.add("Super User")
|
exec_user_role = {"Super User"}
|
||||||
exec_user_crafty_permissions = (
|
exec_user_crafty_permissions = (
|
||||||
self.controller.crafty_perms.list_defined_crafty_permissions()
|
self.controller.crafty_perms.list_defined_crafty_permissions()
|
||||||
)
|
)
|
||||||
@ -241,6 +240,7 @@ class PanelHandler(BaseHandler):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
logger.debug(exec_user["roles"])
|
logger.debug(exec_user["roles"])
|
||||||
|
exec_user_role = set()
|
||||||
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"])
|
||||||
@ -879,11 +879,16 @@ class PanelHandler(BaseHandler):
|
|||||||
template = "panel/server_schedule_edit.html"
|
template = "panel/server_schedule_edit.html"
|
||||||
|
|
||||||
elif page == "edit_schedule":
|
elif page == "edit_schedule":
|
||||||
server_id = self.get_argument("id", None)
|
server_id = self.check_server_id()
|
||||||
|
if not server_id:
|
||||||
|
return
|
||||||
|
|
||||||
page_data["schedules"] = HelpersManagement.get_schedules_by_server(
|
page_data["schedules"] = HelpersManagement.get_schedules_by_server(
|
||||||
server_id
|
server_id
|
||||||
)
|
)
|
||||||
sch_id = self.get_argument("sch_id", None)
|
sch_id = self.get_argument("sch_id", None)
|
||||||
|
if sch_id is None:
|
||||||
|
self.redirect("/panel/error?error=Invalid Schedule ID")
|
||||||
schedule = self.controller.management.get_scheduled_task_model(sch_id)
|
schedule = self.controller.management.get_scheduled_task_model(sch_id)
|
||||||
page_data["get_players"] = lambda: self.controller.stats.get_server_players(
|
page_data["get_players"] = lambda: self.controller.stats.get_server_players(
|
||||||
server_id
|
server_id
|
||||||
@ -947,9 +952,6 @@ class PanelHandler(BaseHandler):
|
|||||||
difficulty = "advanced"
|
difficulty = "advanced"
|
||||||
page_data["schedule"]["difficulty"] = difficulty
|
page_data["schedule"]["difficulty"] = difficulty
|
||||||
|
|
||||||
if sch_id is None or server_id is None:
|
|
||||||
self.redirect("/panel/error?error=Invalid server ID or Schedule ID")
|
|
||||||
|
|
||||||
if not EnumPermissionsServer.SCHEDULE in page_data["user_permissions"]:
|
if not EnumPermissionsServer.SCHEDULE in page_data["user_permissions"]:
|
||||||
if not superuser:
|
if not superuser:
|
||||||
self.redirect("/panel/error?error=Unauthorized access To Schedules")
|
self.redirect("/panel/error?error=Unauthorized access To Schedules")
|
||||||
@ -961,12 +963,11 @@ class PanelHandler(BaseHandler):
|
|||||||
user_id = self.get_argument("id", None)
|
user_id = self.get_argument("id", None)
|
||||||
role_servers = self.controller.servers.get_authorized_servers(user_id)
|
role_servers = self.controller.servers.get_authorized_servers(user_id)
|
||||||
page_role_servers = []
|
page_role_servers = []
|
||||||
servers = set()
|
|
||||||
for server in role_servers:
|
for server in role_servers:
|
||||||
page_role_servers.append(server["server_id"])
|
page_role_servers.append(server["server_id"])
|
||||||
page_data["new_user"] = False
|
page_data["new_user"] = False
|
||||||
page_data["user"] = self.controller.users.get_user_by_id(user_id)
|
page_data["user"] = self.controller.users.get_user_by_id(user_id)
|
||||||
page_data["servers"] = servers
|
page_data["servers"] = set()
|
||||||
page_data["role-servers"] = page_role_servers
|
page_data["role-servers"] = page_role_servers
|
||||||
page_data["roles_all"] = self.controller.roles.get_all_roles()
|
page_data["roles_all"] = self.controller.roles.get_all_roles()
|
||||||
page_data["servers_all"] = self.controller.list_defined_servers()
|
page_data["servers_all"] = self.controller.list_defined_servers()
|
||||||
@ -1255,10 +1256,9 @@ class PanelHandler(BaseHandler):
|
|||||||
"Config": EnumPermissionsServer.CONFIG,
|
"Config": EnumPermissionsServer.CONFIG,
|
||||||
"Players": EnumPermissionsServer.PLAYERS,
|
"Players": EnumPermissionsServer.PLAYERS,
|
||||||
}
|
}
|
||||||
exec_user_role = set()
|
|
||||||
if superuser:
|
if superuser:
|
||||||
# defined_servers = self.controller.list_defined_servers()
|
# defined_servers = self.controller.list_defined_servers()
|
||||||
exec_user_role.add("Super User")
|
exec_user_role = {"Super User"}
|
||||||
exec_user_crafty_permissions = (
|
exec_user_crafty_permissions = (
|
||||||
self.controller.crafty_perms.list_defined_crafty_permissions()
|
self.controller.crafty_perms.list_defined_crafty_permissions()
|
||||||
)
|
)
|
||||||
@ -1270,6 +1270,7 @@ class PanelHandler(BaseHandler):
|
|||||||
)
|
)
|
||||||
# defined_servers =
|
# defined_servers =
|
||||||
# self.controller.servers.get_authorized_servers(exec_user["user_id"])
|
# self.controller.servers.get_authorized_servers(exec_user["user_id"])
|
||||||
|
exec_user_role = set()
|
||||||
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"])
|
||||||
@ -1366,7 +1367,23 @@ class PanelHandler(BaseHandler):
|
|||||||
|
|
||||||
if page == "server_backup":
|
if page == "server_backup":
|
||||||
logger.debug(self.request.arguments)
|
logger.debug(self.request.arguments)
|
||||||
server_id = self.get_argument("id", None)
|
|
||||||
|
server_id = self.check_server_id()
|
||||||
|
if not server_id:
|
||||||
|
return
|
||||||
|
|
||||||
|
if (
|
||||||
|
not permissions["Backup"]
|
||||||
|
in self.controller.server_perms.get_user_id_permissions_list(
|
||||||
|
exec_user["user_id"], server_id
|
||||||
|
)
|
||||||
|
and not superuser
|
||||||
|
):
|
||||||
|
self.redirect(
|
||||||
|
"/panel/error?error=Unauthorized access: User not authorized"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
server_obj = self.controller.servers.get_server_obj(server_id)
|
server_obj = self.controller.servers.get_server_obj(server_id)
|
||||||
compress = self.get_argument("compress", False)
|
compress = self.get_argument("compress", False)
|
||||||
check_changed = self.get_argument("changed")
|
check_changed = self.get_argument("changed")
|
||||||
@ -1383,25 +1400,6 @@ class PanelHandler(BaseHandler):
|
|||||||
backup_path = server_obj.backup_path
|
backup_path = server_obj.backup_path
|
||||||
max_backups = bleach.clean(self.get_argument("max_backups", None))
|
max_backups = bleach.clean(self.get_argument("max_backups", None))
|
||||||
|
|
||||||
if not permissions[
|
|
||||||
"Backup"
|
|
||||||
] in self.controller.server_perms.get_user_id_permissions_list(
|
|
||||||
exec_user["user_id"], server_id
|
|
||||||
):
|
|
||||||
if not superuser:
|
|
||||||
self.redirect(
|
|
||||||
"/panel/error?error=Unauthorized access: User not authorized"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
elif server_id is None:
|
|
||||||
self.redirect("/panel/error?error=Invalid Server ID")
|
|
||||||
return
|
|
||||||
else:
|
|
||||||
# does this server id exist?
|
|
||||||
if not self.controller.servers.server_id_exists(server_id):
|
|
||||||
self.redirect("/panel/error?error=Invalid Server ID")
|
|
||||||
return
|
|
||||||
|
|
||||||
server_obj = self.controller.servers.get_server_obj(server_id)
|
server_obj = self.controller.servers.get_server_obj(server_id)
|
||||||
server_obj.backup_path = backup_path
|
server_obj.backup_path = backup_path
|
||||||
self.controller.servers.update_server(server_obj)
|
self.controller.servers.update_server(server_obj)
|
||||||
@ -1422,7 +1420,22 @@ class PanelHandler(BaseHandler):
|
|||||||
self.redirect(f"/panel/server_detail?id={server_id}&subpage=backup")
|
self.redirect(f"/panel/server_detail?id={server_id}&subpage=backup")
|
||||||
|
|
||||||
if page == "new_schedule":
|
if page == "new_schedule":
|
||||||
server_id = bleach.clean(self.get_argument("id", None))
|
server_id = self.check_server_id()
|
||||||
|
if not server_id:
|
||||||
|
return
|
||||||
|
|
||||||
|
if (
|
||||||
|
not permissions["Schedule"]
|
||||||
|
in self.controller.server_perms.get_user_id_permissions_list(
|
||||||
|
exec_user["user_id"], server_id
|
||||||
|
)
|
||||||
|
and not superuser
|
||||||
|
):
|
||||||
|
self.redirect(
|
||||||
|
"/panel/error?error=Unauthorized access: User not authorized"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
difficulty = bleach.clean(self.get_argument("difficulty", None))
|
difficulty = bleach.clean(self.get_argument("difficulty", None))
|
||||||
server_obj = self.controller.servers.get_server_obj(server_id)
|
server_obj = self.controller.servers.get_server_obj(server_id)
|
||||||
enabled = bleach.clean(self.get_argument("enabled", "0"))
|
enabled = bleach.clean(self.get_argument("enabled", "0"))
|
||||||
@ -1488,24 +1501,6 @@ class PanelHandler(BaseHandler):
|
|||||||
else:
|
else:
|
||||||
one_time = False
|
one_time = False
|
||||||
|
|
||||||
if not superuser and not permissions[
|
|
||||||
"Schedule"
|
|
||||||
] in self.controller.server_perms.get_user_id_permissions_list(
|
|
||||||
exec_user["user_id"], server_id
|
|
||||||
):
|
|
||||||
self.redirect(
|
|
||||||
"/panel/error?error=Unauthorized access: User not authorized"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
elif server_id is None:
|
|
||||||
self.redirect("/panel/error?error=Invalid Server ID")
|
|
||||||
return
|
|
||||||
else:
|
|
||||||
# does this server id exist?
|
|
||||||
if not self.controller.servers.server_id_exists(server_id):
|
|
||||||
self.redirect("/panel/error?error=Invalid Server ID")
|
|
||||||
return
|
|
||||||
|
|
||||||
if interval_type == "days":
|
if interval_type == "days":
|
||||||
job_data = {
|
job_data = {
|
||||||
"server_id": server_id,
|
"server_id": server_id,
|
||||||
@ -1578,7 +1573,26 @@ class PanelHandler(BaseHandler):
|
|||||||
self.redirect(f"/panel/server_detail?id={server_id}&subpage=schedules")
|
self.redirect(f"/panel/server_detail?id={server_id}&subpage=schedules")
|
||||||
|
|
||||||
if page == "edit_schedule":
|
if page == "edit_schedule":
|
||||||
server_id = bleach.clean(self.get_argument("id", None))
|
server_id = self.check_server_id()
|
||||||
|
if not server_id:
|
||||||
|
return
|
||||||
|
|
||||||
|
if (
|
||||||
|
not permissions["Schedule"]
|
||||||
|
in self.controller.server_perms.get_user_id_permissions_list(
|
||||||
|
exec_user["user_id"], server_id
|
||||||
|
)
|
||||||
|
and not superuser
|
||||||
|
):
|
||||||
|
self.redirect(
|
||||||
|
"/panel/error?error=Unauthorized access: User not authorized"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
sch_id = self.get_argument("sch_id", None)
|
||||||
|
if sch_id is None:
|
||||||
|
self.redirect("/panel/error?error=Invalid Schedule ID")
|
||||||
|
|
||||||
difficulty = bleach.clean(self.get_argument("difficulty", None))
|
difficulty = bleach.clean(self.get_argument("difficulty", None))
|
||||||
server_obj = self.controller.servers.get_server_obj(server_id)
|
server_obj = self.controller.servers.get_server_obj(server_id)
|
||||||
enabled = bleach.clean(self.get_argument("enabled", "0"))
|
enabled = bleach.clean(self.get_argument("enabled", "0"))
|
||||||
@ -1618,7 +1632,6 @@ class PanelHandler(BaseHandler):
|
|||||||
else:
|
else:
|
||||||
interval_type = ""
|
interval_type = ""
|
||||||
cron_string = bleach.clean(self.get_argument("cron", ""))
|
cron_string = bleach.clean(self.get_argument("cron", ""))
|
||||||
sch_id = self.get_argument("sch_id", None)
|
|
||||||
if not croniter.is_valid(cron_string):
|
if not croniter.is_valid(cron_string):
|
||||||
self.redirect(
|
self.redirect(
|
||||||
"/panel/error?error=INVALID FORMAT: Invalid Cron Format."
|
"/panel/error?error=INVALID FORMAT: Invalid Cron Format."
|
||||||
@ -1644,24 +1657,6 @@ class PanelHandler(BaseHandler):
|
|||||||
else:
|
else:
|
||||||
one_time = False
|
one_time = False
|
||||||
|
|
||||||
if not superuser and not permissions[
|
|
||||||
"Schedule"
|
|
||||||
] in self.controller.server_perms.get_user_id_permissions_list(
|
|
||||||
exec_user["user_id"], server_id
|
|
||||||
):
|
|
||||||
self.redirect(
|
|
||||||
"/panel/error?error=Unauthorized access: User not authorized"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
elif server_id is None:
|
|
||||||
self.redirect("/panel/error?error=Invalid Server ID")
|
|
||||||
return
|
|
||||||
else:
|
|
||||||
# does this server id exist?
|
|
||||||
if not self.controller.servers.server_id_exists(server_id):
|
|
||||||
self.redirect("/panel/error?error=Invalid Server ID")
|
|
||||||
return
|
|
||||||
|
|
||||||
if interval_type == "days":
|
if interval_type == "days":
|
||||||
job_data = {
|
job_data = {
|
||||||
"server_id": server_id,
|
"server_id": server_id,
|
||||||
@ -1721,7 +1716,6 @@ class PanelHandler(BaseHandler):
|
|||||||
"one_time": one_time,
|
"one_time": one_time,
|
||||||
"cron_string": "",
|
"cron_string": "",
|
||||||
}
|
}
|
||||||
sch_id = self.get_argument("sch_id", None)
|
|
||||||
self.tasks_manager.update_job(sch_id, job_data)
|
self.tasks_manager.update_job(sch_id, job_data)
|
||||||
|
|
||||||
self.controller.management.add_to_audit_log(
|
self.controller.management.add_to_audit_log(
|
||||||
@ -1906,7 +1900,7 @@ class PanelHandler(BaseHandler):
|
|||||||
|
|
||||||
self.write(
|
self.write(
|
||||||
self.controller.authentication.generate(
|
self.controller.authentication.generate(
|
||||||
key.user_id.user_id, {"token_id": key.token_id}
|
key.user_id_id, {"token_id": key.token_id}
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.finish()
|
self.finish()
|
||||||
|
@ -27,10 +27,9 @@ class ServerHandler(BaseHandler):
|
|||||||
if api_key is not None:
|
if api_key is not None:
|
||||||
superuser = superuser and api_key.superuser
|
superuser = superuser and api_key.superuser
|
||||||
|
|
||||||
exec_user_role = set()
|
|
||||||
if superuser:
|
if superuser:
|
||||||
defined_servers = self.controller.list_defined_servers()
|
defined_servers = self.controller.list_defined_servers()
|
||||||
exec_user_role.add("Super User")
|
exec_user_role = {"Super User"}
|
||||||
exec_user_crafty_permissions = (
|
exec_user_crafty_permissions = (
|
||||||
self.controller.crafty_perms.list_defined_crafty_permissions()
|
self.controller.crafty_perms.list_defined_crafty_permissions()
|
||||||
)
|
)
|
||||||
@ -47,6 +46,7 @@ class ServerHandler(BaseHandler):
|
|||||||
exec_user["user_id"]
|
exec_user["user_id"]
|
||||||
)
|
)
|
||||||
list_roles = []
|
list_roles = []
|
||||||
|
exec_user_role = set()
|
||||||
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"])
|
||||||
|
@ -224,7 +224,7 @@ class Webserver:
|
|||||||
f"is up and ready for connections."
|
f"is up and ready for connections."
|
||||||
)
|
)
|
||||||
|
|
||||||
Console.info("Server Init Complete: Listening For Connections:")
|
Console.info("Server Init Complete: Listening For Connections!")
|
||||||
|
|
||||||
self.ioloop = tornado.ioloop.IOLoop.current()
|
self.ioloop = tornado.ioloop.IOLoop.current()
|
||||||
self.ioloop.start()
|
self.ioloop.start()
|
||||||
|
88
main.py
88
main.py
@ -1,6 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import json
|
import json
|
||||||
|
from threading import Thread
|
||||||
import time
|
import time
|
||||||
import argparse
|
import argparse
|
||||||
import logging.config
|
import logging.config
|
||||||
@ -135,8 +136,17 @@ if __name__ == "__main__":
|
|||||||
tasks_manager = TasksManager(helper, controller)
|
tasks_manager = TasksManager(helper, controller)
|
||||||
tasks_manager.start_webserver()
|
tasks_manager.start_webserver()
|
||||||
|
|
||||||
# slowing down reporting just for a 1/2 second so messages look cleaner
|
def signal_handler(signum, _frame):
|
||||||
time.sleep(0.5)
|
if not args.daemon:
|
||||||
|
print() # for newline after prompt
|
||||||
|
signame = signal.Signals(signum).name
|
||||||
|
logger.info(f"Recieved signal {signame} [{signum}], stopping Crafty...")
|
||||||
|
Console.info(f"Recieved signal {signame} [{signum}], stopping Crafty...")
|
||||||
|
tasks_manager._main_graceful_exit()
|
||||||
|
crafty_prompt.universal_exit()
|
||||||
|
|
||||||
|
signal.signal(signal.SIGTERM, signal_handler)
|
||||||
|
signal.signal(signal.SIGINT, signal_handler)
|
||||||
|
|
||||||
# init servers
|
# init servers
|
||||||
logger.info("Initializing all servers defined")
|
logger.info("Initializing all servers defined")
|
||||||
@ -144,6 +154,7 @@ if __name__ == "__main__":
|
|||||||
controller.init_all_servers()
|
controller.init_all_servers()
|
||||||
servers = controller.list_defined_servers()
|
servers = controller.list_defined_servers()
|
||||||
|
|
||||||
|
def tasks_starter():
|
||||||
# start stats logging
|
# start stats logging
|
||||||
tasks_manager.start_stats_recording()
|
tasks_manager.start_stats_recording()
|
||||||
|
|
||||||
@ -155,58 +166,75 @@ if __name__ == "__main__":
|
|||||||
# for serverjars.com
|
# for serverjars.com
|
||||||
tasks_manager.serverjar_cache_refresher()
|
tasks_manager.serverjar_cache_refresher()
|
||||||
|
|
||||||
|
tasks_starter_thread = Thread(target=tasks_starter, name="tasks_starter")
|
||||||
|
|
||||||
|
def internet_check():
|
||||||
logger.info("Checking Internet. This may take a minute.")
|
logger.info("Checking Internet. This may take a minute.")
|
||||||
Console.info("Checking Internet. This may take a minute.")
|
Console.info("Checking Internet. This may take a minute.")
|
||||||
|
|
||||||
if not helper.check_internet():
|
if not helper.check_internet():
|
||||||
|
logger.warning(
|
||||||
|
"We have detected the machine running Crafty has no "
|
||||||
|
"connection to the internet. Client connections to "
|
||||||
|
"the server may be limited."
|
||||||
|
)
|
||||||
Console.warning(
|
Console.warning(
|
||||||
"We have detected the machine running Crafty has no "
|
"We have detected the machine running Crafty has no "
|
||||||
"connection to the internet. Client connections to "
|
"connection to the internet. Client connections to "
|
||||||
"the server may be limited."
|
"the server may be limited."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
internet_check_thread = Thread(target=internet_check, name="internet_check")
|
||||||
|
|
||||||
|
def controller_setup():
|
||||||
if not controller.check_system_user():
|
if not controller.check_system_user():
|
||||||
controller.add_system_user()
|
controller.add_system_user()
|
||||||
|
|
||||||
Crafty = MainPrompt(helper, tasks_manager, migration_manager, controller)
|
|
||||||
|
|
||||||
project_root = os.path.dirname(__file__)
|
project_root = os.path.dirname(__file__)
|
||||||
controller.set_project_root(project_root)
|
controller.set_project_root(project_root)
|
||||||
controller.clear_unexecuted_commands()
|
controller.clear_unexecuted_commands()
|
||||||
controller.clear_support_status()
|
controller.clear_support_status()
|
||||||
|
|
||||||
def sigterm_handler(*sig):
|
crafty_prompt = MainPrompt(helper, tasks_manager, migration_manager, controller)
|
||||||
print() # for newline
|
|
||||||
logger.info(
|
|
||||||
f"Recieved {signal.Signals(sig[0]).name} [{sig[0]}], stopping Crafty..."
|
|
||||||
)
|
|
||||||
Console.info(
|
|
||||||
f"Recieved {signal.Signals(sig[0]).name} [{sig[0]}], stopping Crafty..."
|
|
||||||
)
|
|
||||||
tasks_manager._main_graceful_exit()
|
|
||||||
Crafty.universal_exit()
|
|
||||||
|
|
||||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
controller_setup_thread = Thread(target=controller_setup, name="controller_setup")
|
||||||
|
|
||||||
|
def setup_starter():
|
||||||
|
if not args.daemon:
|
||||||
|
time.sleep(0.01) # Wait for the prompt to start
|
||||||
|
print() # Make a newline after the prompt so logs are on an empty line
|
||||||
|
else:
|
||||||
|
time.sleep(0.01) # Wait for the daemon info message
|
||||||
|
|
||||||
|
Console.info("Setting up Crafty's internal components...")
|
||||||
|
|
||||||
|
# Start the setup threads
|
||||||
|
tasks_starter_thread.start()
|
||||||
|
internet_check_thread.start()
|
||||||
|
controller_setup_thread.start()
|
||||||
|
|
||||||
|
# Wait for the setup threads to finish
|
||||||
|
tasks_starter_thread.join()
|
||||||
|
internet_check_thread.join()
|
||||||
|
controller_setup_thread.join()
|
||||||
|
|
||||||
|
Console.info("Crafty has fully started and is now ready for use!")
|
||||||
|
|
||||||
if not args.daemon:
|
if not args.daemon:
|
||||||
try:
|
# Put the prompt under the cursor
|
||||||
Crafty.cmdloop()
|
crafty_prompt.print_prompt()
|
||||||
except KeyboardInterrupt:
|
|
||||||
print() # for newline
|
Thread(target=setup_starter, name="setup_starter").start()
|
||||||
logger.info("Recieved SIGINT, stopping Crafty...")
|
|
||||||
Console.info("Recieved SIGINT, stopping Crafty...")
|
if not args.daemon:
|
||||||
tasks_manager._main_graceful_exit()
|
# Start the Crafty prompt
|
||||||
Crafty.universal_exit()
|
crafty_prompt.cmdloop()
|
||||||
else:
|
else:
|
||||||
print("Crafty started in daemon mode, no shell will be printed")
|
Console.info("Crafty started in daemon mode, no shell will be printed")
|
||||||
|
print()
|
||||||
while True:
|
while True:
|
||||||
try:
|
|
||||||
if tasks_manager.get_main_thread_run_status():
|
if tasks_manager.get_main_thread_run_status():
|
||||||
break
|
break
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
except KeyboardInterrupt:
|
|
||||||
logger.info("Recieved SIGINT, stopping Crafty...")
|
|
||||||
Console.info("Recieved SIGINT, stopping Crafty...")
|
|
||||||
break
|
|
||||||
tasks_manager._main_graceful_exit()
|
tasks_manager._main_graceful_exit()
|
||||||
Crafty.universal_exit()
|
crafty_prompt.universal_exit()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user