-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstart_server.py
More file actions
649 lines (597 loc) · 28.8 KB
/
start_server.py
File metadata and controls
649 lines (597 loc) · 28.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
import os, sys, time, shutil, zipfile, base64, json, subprocess, threading, urllib.request, tkinter as tk, re, socket
from tkinter import ttk, scrolledtext, IntVar, StringVar
from datetime import datetime
def get_dedicated_name():
if not os.path.isfile(SERVER_ID_FILE): return ""
with open(SERVER_ID_FILE, "r") as f:
for line in f:
if line.strip().startswith("DedicatedServerName"):
return line.split("=",1)[1].strip()
return ""
def get_public_ip():
try:
with urllib.request.urlopen("https://icanhazip.com", timeout=5) as response:
return response.read().decode().strip()
except: return None
def get_setting_value(file_path, keyword):
if not os.path.isfile(file_path): return None
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
option_line, in_section = None, False
for line in lines:
line = line.strip()
if line == "[/Script/Pal.PalGameWorldSettings]": in_section = True
elif in_section and line.startswith("OptionSettings="):
option_line = line[len("OptionSettings="):].strip(); break
if not option_line: return None
if option_line.startswith("(") and option_line.endswith(")"): option_line = option_line[1:-1]
import re
parts = re.findall(r'(?:[^,"\'\s]+|"[^"]*"|\'[^\']*\')+', option_line)
for part in parts:
if "=" not in part: continue
k, v = part.split("=", 1)
if k.strip() == keyword: return v.strip().strip('"')
return None
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
STEAMCMD_DIR = os.path.join(SCRIPT_DIR, "steamcmd")
STEAMCMD_EXE = os.path.join(STEAMCMD_DIR, "steamcmd.exe")
STEAMCMD_ZIP = os.path.join(SCRIPT_DIR, "steamcmd.zip")
STEAMCMD_URL = "https://steamcdn-a.akamaihd.net/client/installer/steamcmd.zip"
INSTALL_DIR = os.path.join(SCRIPT_DIR, "server")
TARGET_DIR = os.path.join(INSTALL_DIR, "Pal", "Binaries", "Win64")
TARGET_EXE = os.path.join(TARGET_DIR, "PalServer-Win64-Shipping-Cmd.exe")
SERVER_ID_FILE = os.path.join(INSTALL_DIR, "Pal", "Saved", "Config", "WindowsServer", "GameUserSettings.ini")
SERVER_SETTINGS_FILE = os.path.join(INSTALL_DIR, "Pal", "Saved", "Config", "WindowsServer", "PalWorldSettings.ini")
BACKUP_PATH = os.path.join(INSTALL_DIR, "Pal", "Saved")
BACKUP_DIR = os.path.join(SCRIPT_DIR, "backups")
game_app_id = "2394010"
RESTART_INTERVAL_HOURS = 24
MAX_SAVE_AGE_MINUTES = 10
paldefender_enabled = 1
start_thread = None
is_starting = False
manual_stop = False
public_lobby_flag = True
start_time = time.time()
last_restart_time = time.time()
last_checked_minute = None
server_restapi_port = get_setting_value(SERVER_SETTINGS_FILE, "RESTAPIPort")
admin_password = get_setting_value(SERVER_SETTINGS_FILE, "AdminPassword")
SERVER_PORT = get_setting_value(SERVER_SETTINGS_FILE, "PublicPort")
server_query_port = "27015"
server_address = "127.0.0.1"
username = "admin"
def get_free_query_port(start_port):
port=int(start_port)
while True:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
try:
s.bind(("0.0.0.0",port))
return str(port)
except:
port+=1
def base64_auth_info(): return base64.b64encode(f"{username}:{admin_password}".encode('ascii')).decode('ascii')
def retrieve_info(url):
try:
req = urllib.request.Request(url)
req.add_header('Accept', 'application/json')
req.add_header('Authorization', f'Basic {base64_auth_info()}')
req.add_header('User-Agent', 'Mozilla/5.0 (PylarBot)')
with urllib.request.urlopen(req, timeout=5) as response:
if response.status == 200:
data = json.loads(response.read().decode())
return data
except Exception as e:
pass
return None
def get_metrics_info():
url = f"http://{server_address}:{server_restapi_port}/v1/api/metrics"
data = retrieve_info(url)
return {"players": str(data.get("currentplayernum", 0)), "fps": str(data.get("serverfps", "N/A"))} if data else None
def get_server_version_from_api():
url = f"http://{server_address}:{server_restapi_port}/v1/api/info"
data = retrieve_info(url)
if data and "version" in data: return ".".join(data["version"].split(".")[:3])
return "Offline"
def apply_dark_theme(window):
font_style = ("Arial", 10)
style = ttk.Style(window)
style.theme_use('clam')
style.configure("Dark.TButton", background="#555555", foreground="white", font=font_style, padding=6)
style.map("Dark.TButton", background=[("active", "#666666"), ("!disabled", "#555555")])
style.configure("TFrame", background="#2f2f2f")
style.configure("TLabel", background="#2f2f2f", foreground="white")
style.configure("Treeview", background="#333333", foreground="white", fieldbackground="#333333", borderwidth=0)
style.configure("Treeview.Heading", background="#444444", foreground="white", font=("Arial", 10, "bold"))
style.configure("TEntry", fieldbackground="#444444", foreground="white")
window.configure(bg="#2f2f2f")
def update_status(msg): status_var.set(msg)
def update_upt(msg): uptime_var.set(msg)
def update_mem(msg): mem_var.set(msg)
def update_save(msg): save_var.set(msg)
def update_version(msg): version_var.set(msg)
def log(msg):
now = datetime.now().strftime("[%I:%M:%S%p]").lstrip("0")
message = f"{now} {msg}"
log_box.config(state=tk.NORMAL)
log_box.insert(tk.END, message + "\n")
log_box.see(tk.END)
log_box.config(state=tk.DISABLED)
def download_and_extract_steamcmd():
if os.path.exists(STEAMCMD_EXE): return
log("SteamCMD not found. Downloading...")
try:
urllib.request.urlretrieve(STEAMCMD_URL, STEAMCMD_ZIP)
with zipfile.ZipFile(STEAMCMD_ZIP, 'r') as zip_ref: zip_ref.extractall(STEAMCMD_DIR)
os.remove(STEAMCMD_ZIP)
log("SteamCMD installed.")
except Exception as e: log(f"Failed to download SteamCMD: {e}")
steamcmd_initialize()
def steamcmd_initialize():
init_log = os.path.join(STEAMCMD_DIR, "init.log")
cmd = [STEAMCMD_EXE, "+login", "anonymous", "+quit"]
log("SteamCMD initialization started...")
with open(init_log, "w", encoding="utf-8") as out:
subprocess.run(cmd, text=True, stdout=out, stderr=out)
log("SteamCMD initialization finished.")
def get_latest_paldefender_version():
url = "https://github.com/Ultimeit/PalDefender/releases/latest"
try:
req = urllib.request.Request(url, method="HEAD")
with urllib.request.urlopen(req) as response:
return response.geturl().split("/")[-1]
except:
return None
def get_paldefender_asset_url(version):
if not version:
return None
possible_names = ["PalDefender.zip", "PalDefender_Windows.zip"]
base = f"https://github.com/Ultimeit/PalDefender/releases/download/{version}/"
for name in possible_names:
try:
url = base + name
req = urllib.request.Request(url, method="HEAD")
with urllib.request.urlopen(req):
return url
except:
continue
return None
def check_and_install_paldefender():
if not paldefender_enabled:
removed_any = False
for filename in ["PalDefender.dll", "version.dll"]:
path = os.path.join(TARGET_DIR, filename)
if os.path.exists(path):
removed_any = True
try: os.remove(path)
except: pass
if removed_any: log("PalDefender is disabled. Removing files...")
else: log("PalDefender is disabled.")
return
log("Checking PalDefender...")
version = get_latest_paldefender_version()
if not version:
log("Failed to fetch PalDefender version.")
return
url = get_paldefender_asset_url(version)
if not url:
log("No Windows asset found.")
return
paldefender_zip = os.path.join(INSTALL_DIR, "PalDefender_Windows.zip")
try:
log(f"Downloading PalDefender {version}...")
with urllib.request.urlopen(url) as response, open(paldefender_zip, 'wb') as out_file: shutil.copyfileobj(response, out_file)
log("Extracting PalDefender...")
with zipfile.ZipFile(paldefender_zip, 'r') as zip_ref: zip_ref.extractall(TARGET_DIR)
os.remove(paldefender_zip)
log("PalDefender installed.")
except Exception as e:
log(f"Error installing PalDefender: {e}")
def update_settings_from_ui():
global paldefender_enabled, RESTART_INTERVAL_HOURS, SERVER_PORT
paldefender_enabled = bool(paldefender_enabled_var.get())
try:
RESTART_INTERVAL_HOURS = int(restart_hours_var.get())
except:
RESTART_INTERVAL_HOURS = 24
SERVER_PORT = get_setting_value(SERVER_SETTINGS_FILE, "PublicPort")
def extract_buildid_from_file(file_path):
with open(file_path, "r", encoding="utf-8") as file:
for line in file:
if '"buildid"' in line:
return line.split('"')[3]
return None
def check_update():
global last_checked_minute
current_minute = time.localtime().tm_min
if last_checked_minute == current_minute: return
log("Now checking for update...")
last_checked_minute = current_minute
appinfo_dir = os.path.join(INSTALL_DIR, "steamapps")
os.makedirs(appinfo_dir, exist_ok=True)
buildid_output_file = os.path.join(INSTALL_DIR, "buildid_output.log")
appinfo_file = os.path.join(appinfo_dir, f"appmanifest_{game_app_id}.acf")
steamcmd_cmd = [
STEAMCMD_EXE, "+login", "anonymous", "+app_info_update", str(game_app_id),
"+app_info_print", str(game_app_id), "+logoff", "+quit"
]
with open(buildid_output_file, "w", encoding="utf-8") as out:
try: subprocess.run(steamcmd_cmd, text=True, stdout=out, stderr=out, check=True)
except subprocess.CalledProcessError: return
buildid = extract_buildid_from_file(buildid_output_file)
old_buildid = extract_buildid_from_file(appinfo_file) if os.path.exists(appinfo_file) else None
log(f"[BuildID] Current: {old_buildid} | New: {buildid}")
if old_buildid != buildid:
log("Server update detected, starting update...")
if os.path.exists(TARGET_EXE): kill_process(TARGET_EXE)
timestamp = datetime.now().strftime("%Y%m%d_%H%M")
update_dir = os.path.join(SCRIPT_DIR, "server_updates", f"Build_{buildid}_{timestamp}")
os.makedirs(update_dir, exist_ok=True)
cmd = [
STEAMCMD_EXE, "+login", "anonymous",
"+force_install_dir", update_dir,
"+app_update", game_app_id, "+quit"
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
log(f"Update downloaded to {update_dir}")
for item in os.listdir(update_dir):
s = os.path.join(update_dir, item)
d = os.path.join(INSTALL_DIR, item)
if os.path.isdir(s):
shutil.copytree(s, d, dirs_exist_ok=True, ignore=shutil.ignore_patterns('Engine.ini', 'PalWorldSettings.ini'))
else:
shutil.copy2(s, d)
log("Update files copied to main install directory.")
else:
log("No update detected.")
if os.path.exists(buildid_output_file): os.remove(buildid_output_file)
def perform_backup():
datestamp = datetime.now().strftime('%Y-%m-%d')
hourstamp = datetime.now().strftime('%H')
daily_folder = os.path.join(BACKUP_DIR, f"Backup_{datestamp}")
os.makedirs(daily_folder, exist_ok=True)
backup_file = os.path.join(daily_folder, f"Backup_{hourstamp}.zip")
if not os.path.exists(backup_file):
log("Starting backup...")
try:
with zipfile.ZipFile(backup_file, 'w', zipfile.ZIP_DEFLATED) as backup_zip:
for foldername, subfolders, filenames in os.walk(BACKUP_PATH):
for filename in filenames:
filepath = os.path.join(foldername, filename)
arcname = os.path.join(os.path.basename(BACKUP_PATH), os.path.relpath(filepath, BACKUP_PATH))
backup_zip.write(filepath, arcname)
log(f"Backup completed: Backup_{datestamp}/Backup_{hourstamp}.zip")
except Exception as e:
log(f"Backup failed: {e}")
def start_server():
global start_thread, is_starting
update_settings_from_ui()
if start_thread and start_thread.is_alive():
log("Start server is already in progress...")
return
is_starting = True
btn_start.config(state=tk.DISABLED)
btn_stop.config(state=tk.NORMAL)
start_thread = threading.Thread(target=_start_server, daemon=True)
start_thread.start()
def _start_server():
global manual_stop,server_query_port
manual_stop=False
if os.path.exists(TARGET_EXE): kill_process(TARGET_EXE)
download_and_extract_steamcmd()
check_update()
check_and_install_paldefender()
server_query_port=get_free_query_port(server_query_port)
log(f"Using QueryPort {server_query_port}")
log("Starting server, please wait...")
cmd=[TARGET_EXE,"-useperfthreads","-UseMultithreadForDS",f"-port={SERVER_PORT}",f"-QueryPort={server_query_port}"]
if public_lobby_flag: cmd.append("-publiclobby")
subprocess.Popen(cmd,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
def stop_server():
global manual_stop, is_starting
manual_stop = True
is_starting = False
btn_stop.config(state=tk.DISABLED)
btn_start.config(state=tk.DISABLED)
if os.path.exists(TARGET_EXE): kill_process(TARGET_EXE)
log("Stopping server...")
def trim_ram_usage(exe_path):
exe_name = os.path.basename(exe_path)
exe_dir = os.path.dirname(os.path.abspath(exe_path)).lower()
ps_script = f"""
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class Win32 {{
[DllImport("psapi.dll")]
public static extern bool EmptyWorkingSet(IntPtr hProcess);
}}
"@
function Format-Size([double]$sizeMB) {{
if ($sizeMB -ge 1024) {{
return '{{0:N2}} GB' -f ($sizeMB / 1024)
}} else {{
return '{{0:N2}} MB' -f $sizeMB
}}
}}
$output = @()
$processes = Get-Process -Name '{os.path.splitext(exe_name)[0]}' -ErrorAction SilentlyContinue
$found = $false
foreach ($proc in $processes) {{
try {{
$path = ($proc.Path) -replace '\\\\', '/'
if ($path -and $path.ToLower().StartsWith("{exe_dir.replace("\\", "/")}")) {{
$found = $true
$beforeMB = $proc.WorkingSet64 / 1MB
[Win32]::EmptyWorkingSet($proc.Handle) | Out-Null
Start-Sleep -Seconds 1
$proc.Refresh()
$afterMB = $proc.WorkingSet64 / 1MB
$beforeFormatted = Format-Size $beforeMB
$afterFormatted = Format-Size $afterMB
$output += "Trimmed RAM for PID $($proc.Id): $beforeFormatted -> $afterFormatted"
}}
}} catch {{
$output += "Error processing PID $($proc.Id): $($_.Exception.Message)"
}}
}}
if (-not $found) {{
$output += "No matching process in specified directory found."
}}
$output -join "`n"
"""
completed = subprocess.run(["powershell", "-Command", ps_script], capture_output=True, text=True)
out = completed.stdout.strip()
log(out if out else "No output from PowerShell script.")
def send_server_announcement(message):
url = f"http://{server_address}:{server_restapi_port}/v1/api/announce"
data = json.dumps({"message": message}).encode("utf-8")
req = urllib.request.Request(url, data=data, method="POST")
req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', f'Basic {base64_auth_info()}')
try:
with urllib.request.urlopen(req, timeout=5) as response:
if response.status == 200: log(f"Announcement sent: {message}")
except:
log(f"Failed to send announcement: {message}")
def monitor_server():
global last_restart_time, start_time, save_stale_stacks, manual_stop, paldefender_installed_once
was_running = False
last_crash_check_time = 0
last_checked_time = 0
paldefender_installed_once = False
booted_message_printed = False
boot_start_time = None
warning_minutes_sent = set()
hour_warnings_sent = set()
while True:
running = is_process_running(TARGET_EXE)
root.after(0, set_controls_state, running)
DEDICATED_NAME = get_dedicated_name()
SAVE_FILE = os.path.join(INSTALL_DIR, "Pal", "Saved", "SaveGames", "0", DEDICATED_NAME, "Level.sav")
if running:
if not was_running:
start_time = last_restart_time = time.time()
boot_start_time = time.time()
warning_minutes_sent.clear()
hour_warnings_sent.clear()
was_running = True
mem = get_memory_usage(TARGET_EXE)
ver = get_server_version_from_api()
if ver == "Offline":
update_status("Online"); update_version(ver)
players_var.set("0"); fps_var.set("N/A")
update_upt("0h 0m 0s"); update_mem(mem); update_save("N/A"); update_restart_timer()
last_restart_time = time.time()
time.sleep(1)
continue
if not booted_message_printed:
boot_time = time.time() - boot_start_time if boot_start_time else 0
boot_time_str = f"{int(boot_time)}s" if boot_time < 60 else f"{int(boot_time//60)}m {int(boot_time%60)}s"
log(f"Server is fully booted up, enjoy! Boot time: {boot_time_str}")
booted_message_printed = True
runtime = format_runtime(time.time() - start_time)
last_save = time_since_modified(SAVE_FILE) if os.path.exists(SAVE_FILE) else None
metrics = get_metrics_info()
players_var.set(metrics["players"] if metrics else "0")
fps_var.set(metrics["fps"] if metrics else "N/A")
update_upt(runtime); update_mem(mem); update_save(last_save); update_version(ver); update_status("Online"); update_restart_timer()
time_to_restart = RESTART_INTERVAL_HOURS*3600 - (time.time() - last_restart_time)
hours_left = int(time_to_restart // 3600)
minutes_left = int((time_to_restart % 3600) // 60)
if hours_left > 0 and hours_left not in hour_warnings_sent:
send_server_announcement(f"Server will restart in {hours_left} hour{'s' if hours_left>1 else ''}!")
hour_warnings_sent.add(hours_left)
for m in range(5,0,-1):
if 0 < time_to_restart <= m*60 and m not in warning_minutes_sent:
send_server_announcement(f"Server will restart in {m} minute{'s' if m>1 else ''}! Please save your progress.")
warning_minutes_sent.add(m)
if 0 < time_to_restart <= 60 and "final" not in warning_minutes_sent:
send_server_announcement("Server restarting now!")
warning_minutes_sent.add("final")
if time.time() - last_checked_time >= 60:
check_update(); perform_backup(); trim_ram_usage(TARGET_EXE)
last_checked_time = time.time()
if os.path.isfile(SAVE_FILE):
last_mod_time = os.path.getmtime(SAVE_FILE)
age_minutes = (time.time() - last_mod_time) / 60
if age_minutes >= MAX_SAVE_AGE_MINUTES:
save_stale_stacks += 1
log(f"Save file stale for {age_minutes:.1f} mins, stack {save_stale_stacks}/5")
if save_stale_stacks >= 5:
log("Save stale limit reached, rebooting server!")
stop_server(); time.sleep(2); _start_server()
last_restart_time = start_time = time.time()
save_stale_stacks = 0
warning_minutes_sent.clear()
hour_warnings_sent.clear()
else:
save_stale_stacks = 0
if time.time() - last_restart_time >= RESTART_INTERVAL_HOURS * 3600:
log("Scheduled restart.")
stop_server(); time.sleep(2); _start_server()
last_restart_time = start_time = time.time()
warning_minutes_sent.clear()
hour_warnings_sent.clear()
else:
update_status("Offline"); update_upt("0h 0m 0s"); update_mem("N/A"); update_save("N/A"); update_version("Offline")
players_var.set("0"); fps_var.set("N/A"); update_restart_timer()
save_stale_stacks = 0
booted_message_printed = False
boot_start_time = None
warning_minutes_sent.clear()
hour_warnings_sent.clear()
if was_running:
if manual_stop:
log("Server stopped manually.")
manual_stop = False
root.after(0, lambda: (btn_start.config(state=tk.NORMAL), btn_stop.config(state=tk.DISABLED)))
else:
log("Server crashed! Restarting instantly...")
time.sleep(2)
_start_server()
last_restart_time = start_time = time.time()
was_running = False
time.sleep(1)
def update_restart_timer():
if not is_process_running(TARGET_EXE) or get_server_version_from_api() == "Offline":
restart_in_var.set(f"{RESTART_INTERVAL_HOURS}h 0m 0s")
global last_restart_time
last_restart_time = time.time()
return
remaining = max(0, int(last_restart_time + RESTART_INTERVAL_HOURS*3600 - time.time()))
h, rem = divmod(remaining, 3600)
m, s = divmod(rem, 60)
restart_in_var.set(f"{h}h {m}m {s}s")
def get_process_id(executable_name, target_path):
try:
ps_cmd = f"Get-Process -Name '{os.path.splitext(executable_name)[0]}' | Select-Object Id,Path"
result = subprocess.run(["powershell", "-Command", ps_cmd], capture_output=True, text=True)
lines = [l.strip() for l in result.stdout.splitlines() if l.strip() and not l.startswith("Id") and not l.startswith("--")]
for line in lines:
parts = line.split(maxsplit=1)
if len(parts) == 2:
pid, exe_path = parts[0], parts[1]
if os.path.normcase(target_path) in os.path.normcase(exe_path):
return pid
return None
except Exception as e:
print(f"DEBUG: Error -> {e}")
return None
def is_process_running(path):
exe_name = os.path.basename(path)
script_dir = os.path.dirname(os.path.abspath(__file__))
return bool(get_process_id(exe_name, script_dir))
def kill_process(path):
exe_name = os.path.basename(path)
script_dir = os.path.dirname(os.path.abspath(__file__))
pid = get_process_id(exe_name, script_dir)
if pid:
subprocess.run(["taskkill", "/F", "/PID", pid], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def get_memory_usage(exe_path):
exe_name = os.path.basename(exe_path)
exe_dir = os.path.dirname(os.path.abspath(exe_path)).lower()
try:
ps_script = f"""
$processes = Get-Process -Name '{os.path.splitext(exe_name)[0]}' -ErrorAction SilentlyContinue
foreach ($proc in $processes) {{
try {{
$path = (Get-Process -Id $proc.Id | Select-Object -ExpandProperty Path) -replace '\\\\','/'
if ($path -and $path.ToLower().StartsWith("{exe_dir.replace("\\","/")}")) {{
$memMB = [math]::Round($proc.WorkingSet64 / 1MB, 2)
if ($memMB -ge 1024) {{
$memGB = [math]::Round($memMB / 1024, 2)
Write-Output "$memGB GB"
}} else {{
Write-Output "$memMB MB"
}}
break
}}
}} catch {{}}
}}
"""
completed = subprocess.run(["powershell", "-Command", ps_script], capture_output=True, text=True)
return completed.stdout.strip() if completed.stdout.strip() else "N/A"
except:
return "N/A"
def time_since_modified(filepath):
if not os.path.isfile(filepath): return "N/A"
diff = int(time.time() - os.path.getmtime(filepath)); mins = diff // 60
return f"{mins}m ago" if mins < 60 else f"{mins//60}h ago"
def format_runtime(seconds):
mins, sec = divmod(int(seconds), 60); hours, mins = divmod(mins, 60)
return f"{hours}h {mins}m {sec}s"
root = tk.Tk()
paldefender_enabled_var, restart_hours_var = IntVar(value=paldefender_enabled), StringVar(value=str(RESTART_INTERVAL_HOURS))
status_var, uptime_var, mem_var, save_var, restart_in_var, version_var, players_var, fps_var = (StringVar(value=v) for v in ["Idle","0h 0m 0s","N/A","N/A","","Offline","0","N/A"])
try: root.iconbitmap("pal.ico")
except: pass
root.title("Palworld Server Manager")
root.geometry("950x400")
apply_dark_theme(root)
main_frame = ttk.Frame(root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
left_frame = ttk.Frame(main_frame)
left_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 15))
btn_frame = ttk.Frame(left_frame)
btn_frame.pack(anchor="w", pady=(0, 10))
btn_start = ttk.Button(btn_frame, text="Start Server", command=start_server, style="Dark.TButton")
btn_start.pack(fill=tk.X, pady=3)
btn_stop = ttk.Button(btn_frame, text="Stop Server", command=stop_server, style="Dark.TButton")
btn_stop.pack(fill=tk.X, pady=3)
toggle_frame = ttk.Frame(left_frame)
toggle_frame.pack(anchor="w", pady=(10, 10))
paldefender_toggle_btn = tk.Button(toggle_frame, text=("☑ Enable PalDefender" if paldefender_enabled else "☐ Enable PalDefender"),
command=lambda: toggle_option("paldefender"), relief="flat", fg="white", bg="#2f2f2f",
activebackground="black", activeforeground="white")
paldefender_toggle_btn.pack(anchor="w", pady=3)
public_toggle_btn = tk.Button(toggle_frame, text=("☑ Public Lobby" if public_lobby_flag else "☐ Public Lobby"),
command=lambda: toggle_option("public"), relief="flat", fg="white", bg="#2f2f2f",
activebackground="black", activeforeground="white")
public_toggle_btn.pack(anchor="w", pady=3)
config_frame = ttk.Frame(left_frame)
config_frame.pack(anchor="w", pady=(10, 10))
ttk.Label(config_frame, text="Restart Interval (hrs):", style="TLabel").grid(row=0, column=0, sticky='e', padx=5)
restart_entry = ttk.Entry(config_frame, width=5, textvariable=restart_hours_var)
restart_entry.grid(row=0, column=1, padx=5)
right_frame = ttk.Frame(main_frame)
right_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
stats_frame = ttk.Frame(right_frame)
stats_frame.pack(anchor="n", pady=(0, 10))
labels = [("Status:", status_var), ("Version:", version_var), ("FPS:", fps_var), ("Mem:", mem_var),
("Uptime:", uptime_var), ("Restart:", restart_in_var), ("Last:", save_var), ("Players:", players_var)]
for i, (label, var) in enumerate(labels):
ttk.Label(stats_frame, text=label, style="TLabel").grid(row=i//4, column=(i%4)*2, sticky='e', padx=5, pady=2)
ttk.Label(stats_frame, textvariable=var, style="TLabel").grid(row=i//4, column=(i%4)*2+1, sticky='w', padx=5, pady=2)
log_frame = ttk.Frame(right_frame)
log_frame.pack(fill=tk.BOTH, expand=True, pady=(10, 0))
log_box = scrolledtext.ScrolledText(log_frame, wrap=tk.WORD, width=100, height=12, bg="#333333", fg="white",
font=("Arial", 10), state=tk.DISABLED)
log_box.pack(fill=tk.BOTH, expand=True)
def set_controls_state(running):
global is_starting
state = tk.DISABLED if running or is_starting else tk.NORMAL
btn_start.config(state=tk.DISABLED if running or is_starting else tk.NORMAL)
btn_stop.config(state=tk.NORMAL if running or is_starting else tk.DISABLED)
for btn in (paldefender_toggle_btn, public_toggle_btn):
btn.config(state=state)
if state == tk.DISABLED:
btn.config(fg="#555555", bg="#2f2f2f", activeforeground="#555555", activebackground="#2f2f2f")
else:
btn.config(fg="white", bg="#2f2f2f", activeforeground="white", activebackground="black")
restart_entry.config(state=state)
def toggle_option(option):
global paldefender_enabled, public_lobby_flag
if option == "paldefender":
paldefender_enabled = not paldefender_enabled
paldefender_enabled_var.set(int(paldefender_enabled))
paldefender_toggle_btn.config(text=("☑ Enable PalDefender" if paldefender_enabled else "☐ Enable PalDefender"))
elif option == "public":
public_lobby_flag = not public_lobby_flag
public_toggle_btn.config(text=("☑ Public Lobby" if public_lobby_flag else "☐ Public Lobby"))
def on_closing():
stop_server()
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
threading.Thread(target=monitor_server, daemon=True).start()
root.mainloop()