изменение yaml и systemd
This commit is contained in:
parent
f8624f741f
commit
3658f059aa
130
hlna.py
130
hlna.py
@ -175,7 +175,7 @@ def ports_array():
|
||||
query_p = []
|
||||
rcon_p = []
|
||||
for k in list_config:
|
||||
data_port = read_yaml(k, game="ARK")
|
||||
data_port = read_yaml(k, g="ark")
|
||||
port_s.append(data_port['Port'])
|
||||
query_p.append(data_port['QueryPort'])
|
||||
rcon_p.append(data_port['RCONPort'])
|
||||
@ -191,7 +191,7 @@ def ports(port, ports_arr, flag):
|
||||
elif flag == 1:
|
||||
port = 27015
|
||||
elif flag == 2:
|
||||
port = 27044
|
||||
port = 23331
|
||||
print_line("Port=", port)
|
||||
return port
|
||||
else:
|
||||
@ -371,12 +371,13 @@ def config_ark(list_config=list_config):
|
||||
create_dir(dir_server_ark)
|
||||
create_dir(dir_maps_ark)
|
||||
|
||||
id_mods_ark = ""
|
||||
cluster_server, cluster_id, cluster_dir_override = config_cluster()
|
||||
|
||||
if list_config:
|
||||
print("Уже установленные карты: ")
|
||||
for i in list_config:
|
||||
data = read_yaml(i, game="ARK")
|
||||
data = read_yaml(i, g="ark")
|
||||
print(f"{i} : {data['map']}")
|
||||
count_maps = config_nummap()
|
||||
print_line(count_maps)
|
||||
@ -393,12 +394,9 @@ def config_ark(list_config=list_config):
|
||||
max_players = config_players()
|
||||
listen_server = config_listen()
|
||||
|
||||
print_line(cluster_server, map_s, list_config[-1], port_server, query_port,
|
||||
yaml_create("ark", "", cluster_server, map_s, list_config[-1], port_server, query_port,
|
||||
rcon_enabled, rcon_port, adminpassword_server, password_server, max_players,
|
||||
cluster_id, cluster_dir_override, listen_server)
|
||||
yaml_create("ARK", "", cluster_server, map_s, list_config[-1], port_server, query_port,
|
||||
rcon_enabled, rcon_port, adminpassword_server, password_server, max_players,
|
||||
cluster_id, cluster_dir_override, listen_server)
|
||||
id_mods_ark, cluster_id, cluster_dir_override, listen_server)
|
||||
|
||||
|
||||
def config_7daystodie():
|
||||
@ -422,11 +420,14 @@ def xml_parser():
|
||||
print("Я пока не умею парсить xml))", flag=False)
|
||||
|
||||
|
||||
def yaml_create(game, dir_server="", cluster_server="", map_s="", name_server="", port_server="", query_port="",
|
||||
def yaml_create(g, dir_server="", cluster_server="", map_s="", name_server="", port_server="", query_port="",
|
||||
rcon_enabled="", rcon_port="", adminpassword_server="", password_server="", max_players="",
|
||||
id_mods_ark="", cluster_id="", cluster_dir_override="", listen_server=""):
|
||||
"""Создаёт на основании собранных данных yaml конфиг"""
|
||||
if game == "ARK":
|
||||
if g == "ark":
|
||||
print_line(type(id_mods_ark))
|
||||
print_line(id_mods_ark)
|
||||
print_line(name_server)
|
||||
path_yaml = dir_maps_ark + name_server
|
||||
settings = [
|
||||
{
|
||||
@ -447,7 +448,7 @@ def yaml_create(game, dir_server="", cluster_server="", map_s="", name_server=""
|
||||
'clusterdir': cluster_dir_override
|
||||
}
|
||||
]
|
||||
elif game == "path_server":
|
||||
elif g == "path_server":
|
||||
path_yaml = dir_config + "config"
|
||||
settings = [
|
||||
{
|
||||
@ -458,21 +459,20 @@ def yaml_create(game, dir_server="", cluster_server="", map_s="", name_server=""
|
||||
with open(path_yaml, 'w') as yamlfile:
|
||||
yaml.dump(settings, yamlfile)
|
||||
print(colorama.Fore.GREEN + f"Конфиг {path_yaml} создан" + colorama.Style.RESET_ALL)
|
||||
if game != "path_server":
|
||||
systemd_unit_create(game)
|
||||
if g != "path_server":
|
||||
systemd_unit_create(g, name_server)
|
||||
|
||||
|
||||
def systemd_unit_create(game, config_7days="", name_server=list_config):
|
||||
def systemd_unit_create(g, name_server=list_config, config_7days=""):
|
||||
"""Создаёт на основании yaml конфига systemd юнит"""
|
||||
if game == "ARK":
|
||||
if g == "ark":
|
||||
id_game = "376030"
|
||||
for i in name_server:
|
||||
data = read_yaml(i, game="ARK")
|
||||
data = read_yaml(name_server, g="ark")
|
||||
ntff = "" if not data['Cluster'] else "-NoTransferFromFiltering"
|
||||
unit_dir_server = dir_server_ark
|
||||
systemd_unit_exec = f"{dir_server_exec}ShooterGameServer {data['map']}?listen={data['Listen']}?SessionName={data['SessionName']}?Port={data['Port']}?QueryPort={data['QueryPort']}?RCONEnabled={data['RCONEnabled']}?RCONPort={data['RCONPort']}?ServerAdminPassword={data['ServerAdminPassword']}??MaxPlayers={data['MaxPlayers']} -clusterid={data['clusterid']} -ClusterDirOverride={data['clusterdir']} {ntff}"
|
||||
systemd_unit_exec = f"{dir_server_exec}ShooterGameServer {data['map']}?listen={data['Listen']}?SessionName={data['SessionName']}?ModsId={data['ModsId']}?Port={data['Port']}?QueryPort={data['QueryPort']}?RCONEnabled={data['RCONEnabled']}?RCONPort={data['RCONPort']}?ServerAdminPassword={data['ServerAdminPassword']}?MaxPlayers={data['MaxPlayers']} -clusterid={data['clusterid']} -ClusterDirOverride={data['clusterdir']} {ntff}"
|
||||
unit_file = f"{dir_unit}ark_{data['SessionName']}.service".lower()
|
||||
elif game == "7Days":
|
||||
elif g == "7Days":
|
||||
id_game = "294420"
|
||||
# сюда дописать обращение к xml_parser для получения уникального имени сервера
|
||||
unit_dir_server = dir_server_7days
|
||||
@ -480,7 +480,7 @@ def systemd_unit_create(game, config_7days="", name_server=list_config):
|
||||
unit_file = f"{dir_unit}7days.service".lower()
|
||||
|
||||
unit_text = f'''[Unit]
|
||||
Description={game}: Server
|
||||
Description={g}: Server
|
||||
Wants=network-online.target
|
||||
After=syslog.target network.target nss-lookup.target network-online.target
|
||||
|
||||
@ -498,7 +498,7 @@ WantedBy=default.target
|
||||
with open(unit_file, 'w') as systemd_unit:
|
||||
systemd_unit.write(unit_text)
|
||||
unit_name = unit_file.split("/")[-1]
|
||||
os.system(f"systemctl --user unmask {unit_name}")
|
||||
print(colorama.Fore.GREEN + f"Юнит {unit_name} создан" + colorama.Style.RESET_ALL)
|
||||
os.system('systemctl --user daemon-reload')
|
||||
os.system(f"systemctl --user enable {unit_name}")
|
||||
|
||||
@ -510,11 +510,15 @@ WantedBy=default.target
|
||||
@click.argument('id_mods_ark', nargs=-1)
|
||||
def mod(g, m, i, id_mods_ark):
|
||||
if g == "ark":
|
||||
check_exist_servers(g)
|
||||
if not os.path.isdir(dir_mods_ark):
|
||||
create_dir(dir_mods_ark)
|
||||
id_mods_ark = id_mods_ark[0].split(',')
|
||||
if id_mods_ark[1] != "":
|
||||
id_mods = ""
|
||||
for id_mod in id_mods_ark:
|
||||
id_mods += ","+id_mod
|
||||
id_mods = id_mods[1:]
|
||||
dir_mod_ark = f"{dir_mods_ark}/{id_mod}"
|
||||
if not os.path.isfile(f"{dir_mod_ark}.mod"):
|
||||
if i:
|
||||
@ -528,6 +532,13 @@ def mod(g, m, i, id_mods_ark):
|
||||
else:
|
||||
print_line(f"Мод уже установлен")
|
||||
modupdate(g, m, id_mod, dir_mod_ark)
|
||||
name_server = choose_map(g, m)
|
||||
id_mods_ark = id_mods
|
||||
for i in name_server:
|
||||
data = read_yaml(i, g="ark")
|
||||
yaml_create("ark", data['ServerPath'], data['Cluster'], data['map'], data['SessionName'], data['Port'], data['QueryPort'],
|
||||
data['RCONEnabled'], data['RCONPort'], data['ServerAdminPassword'], data['ServerPassword'],
|
||||
data['MaxPlayers'], id_mods_ark, data['clusterid'], data['clusterdir'], data['Listen'])
|
||||
else:
|
||||
print_line("Введите id модов через запятую без пробелов")
|
||||
else:
|
||||
@ -671,10 +682,10 @@ def switch(g, m, e): #добавить all
|
||||
data['Port'] = ports(data['Port'], port_s, e)
|
||||
data['QueryPort'] = ports(data['QueryPort'], port_s, e)
|
||||
data['RCONPort'] = ports(data['RCONPort'], port_s, e)
|
||||
yaml_create("ARK", data['map'], data['Cluster'], data['SessionName'], data['Port'], data['QueryPort'],
|
||||
data['RCONEnabled'], data['RCONPort'], data['ServerAdminPassword'], data['ServerPassword'],
|
||||
data['MaxPlayers'], data['ModsId'], data['Listen'], data['ServerPath'], data['clusterid'],
|
||||
data['clusterdir'])
|
||||
yaml_create("ark", data['ServerPath'], data['Cluster'], data['map'], data['SessionName'], data['Port'],
|
||||
data['QueryPort'], data['RCONEnabled'], data['RCONPort'], data['ServerAdminPassword'],
|
||||
data['ServerPassword'], data['MaxPlayers'], data['ModsId'], data['clusterid'], data['clusterdir'],
|
||||
data['Listen'])
|
||||
x = os.system(
|
||||
f"rm {dir_deactivated}{i} >> {dir_logs}{date} 2>&1")
|
||||
with open(f"{dir_logs}{date}.log", "a") as f:
|
||||
@ -700,7 +711,7 @@ def status(list_config=list_config):
|
||||
print_line("Сервера не сконфигурированы", flag=False)
|
||||
else:
|
||||
for i in list_config:
|
||||
data = read_yaml(i, game="ARK")
|
||||
data = read_yaml(i, g="ark")
|
||||
x = os.system(f"lsof -w -i :{data['Port']}")
|
||||
if x == 0:
|
||||
print_line("Сервер запущен")
|
||||
@ -781,28 +792,13 @@ def check_exist_servers(g):
|
||||
print_line("7Days")
|
||||
|
||||
|
||||
def start_stop(action, g, m, list_config=list_config):
|
||||
def start_stop(action, g, m):
|
||||
"""Функция изменения статусов сервера"""
|
||||
if g == "ark":
|
||||
check_exist_servers(g)
|
||||
dict_mapname = {}
|
||||
dict_allmapname = []
|
||||
for i in list_config:
|
||||
data = read_yaml(i, game="ARK")
|
||||
dict_mapname[data['SessionName']] = data['map']
|
||||
dict_allmapname.append(data['SessionName'])
|
||||
names_serverstart = []
|
||||
for ns, v in dict_mapname.items():
|
||||
if v in m:
|
||||
names_serverstart.append(ns)
|
||||
if list_config != []: # Перенести выше для проверки наличия конфигов
|
||||
if m == "all":
|
||||
names_serverstart = dict_allmapname
|
||||
print(f"Выполняется для карт(-ы) {names_serverstart}")
|
||||
else:
|
||||
names_serverstart = choose_map(names_serverstart)
|
||||
for i in names_serverstart:
|
||||
data = read_yaml(i, game="ARK")
|
||||
name_servers = choose_map(g, m)
|
||||
for i in name_servers:
|
||||
data = read_yaml(i, g="ark", flag=True)
|
||||
if action == "stop" or action == "restart":
|
||||
rcon_local(i, "SaveWorld")
|
||||
x = os.system(f"systemctl --user {action} ark_{data['SessionName'].lower()}.service")
|
||||
@ -818,24 +814,41 @@ def start_stop(action, g, m, list_config=list_config):
|
||||
return
|
||||
|
||||
|
||||
def read_yaml(list_config=list_config, flag=True, game=""):
|
||||
def read_yaml(list_config=list_config, flag=True, m="", g=""):
|
||||
"""Читает конфиги и отдаёт данные туда где их запросили"""
|
||||
# Читаем конфиги активных или неактивных карт в зависимости от флага
|
||||
if game == "ARK":
|
||||
if g == "ark":
|
||||
if m == "all":
|
||||
list_config=list_config
|
||||
path_yaml = f"{dir_maps_ark}{list_config}" if flag else f"{dir_deactivated}{list_config}"
|
||||
elif game == "path_server":
|
||||
elif g == "path_server":
|
||||
path_yaml = dir_config + "config"
|
||||
with open(path_yaml, "r") as yamlfile:
|
||||
data = yaml.load(yamlfile, Loader=yaml.FullLoader)
|
||||
return data[0] # возвращаем словарь со всеми значениями
|
||||
|
||||
|
||||
def choose_map(arr):
|
||||
def choose_map(g, m, list_config=list_config):
|
||||
"""Функция выбора карт"""
|
||||
new_arr = []
|
||||
arr = sorted(arr)
|
||||
if g == "ark":
|
||||
dict_mapname = {}
|
||||
dict_allmapname = []
|
||||
for i in list_config:
|
||||
data = read_yaml(i, g="ark")
|
||||
dict_mapname[data['SessionName']] = data['map']
|
||||
dict_allmapname.append(data['SessionName'])
|
||||
name_servers = []
|
||||
for ns, v in dict_mapname.items():
|
||||
if v in m:
|
||||
name_servers.append(ns)
|
||||
if list_config != []: # Перенести выше для проверки наличия конфигов
|
||||
if m == "all":
|
||||
name_servers = dict_allmapname
|
||||
print(f"Выполняется для карт(-ы) {name_servers}")
|
||||
else:
|
||||
name_servers = sorted(name_servers)
|
||||
print('Найдены сервера с этой картой')
|
||||
for i, map in enumerate(arr):
|
||||
for i, map in enumerate(name_servers):
|
||||
print(f"{i + 1}) {map}")
|
||||
while True:
|
||||
try:
|
||||
@ -843,13 +856,12 @@ def choose_map(arr):
|
||||
x = [int(i) for i in x]
|
||||
break
|
||||
except:
|
||||
print_line("Неправильный ввод",flag=False)
|
||||
|
||||
print_line("Неправильный ввод", flag=False)
|
||||
for i in x:
|
||||
new_arr.append(arr[i - 1])
|
||||
print('Выбранные сервера:', new_arr)
|
||||
name_servers.append(name_servers[i - 1])
|
||||
print('Выбранные сервера:', name_servers)
|
||||
|
||||
return new_arr
|
||||
return name_servers
|
||||
|
||||
|
||||
@hlna.command(help='Отправка команд на игровой сервер через rcon <rcon SaveWorld -m all>')
|
||||
@ -866,7 +878,7 @@ def rcon_local(m, c):
|
||||
if list_config:
|
||||
rcon_ports = []
|
||||
for i in list_config:
|
||||
data = read_yaml(i, game="ARK")
|
||||
data = read_yaml(i, g="ark")
|
||||
dict_mapname[data['RCONPort']] = data['map']
|
||||
dict_adminpwd[data['RCONPort']] = data['ServerAdminPassword']
|
||||
if m == "all":
|
||||
@ -896,7 +908,7 @@ def zero(x=""):
|
||||
if not os.path.exists(dir_config + "config"):
|
||||
dir_server = path_server()
|
||||
else:
|
||||
data = read_yaml(game="path_server")
|
||||
data = read_yaml(g="path_server")
|
||||
if data['path_server'] == "":
|
||||
path_server()
|
||||
else:
|
||||
|
Loading…
Reference in New Issue
Block a user