fix process handling

main
Alex 6 months ago
parent c217d44fef
commit 97e8c6c4c6

@ -1,15 +1,15 @@
import subprocess
import os
import logging
from flask import Flask, request, jsonify
import subprocess
import psutil
import keyboard # For capturing keyboard events
import signal
import time
import psutil
logging.basicConfig(filename='osiris_listener_playground.log', level=logging.DEBUG, format='%(asctime)s %(message)s')
from datetime import datetime
#logging.basicConfig(filename='osiris_listener_playground.log', level=logging.DEBUG, format='%(asctime)s %(message)s')
"""_
def read_pid_file(pid_file):
"""Read the PID from the specified PID file."""
""Read the PID from the specified PID file.""
try:
with open(pid_file, 'r') as file:
pid = int(file.read().strip())
@ -18,7 +18,7 @@ def read_pid_file(pid_file):
return None
def is_java_process_running(pid):
"""Check if a Java process with the given PID is running."""
""Check if a Java process with the given PID is running.""
try:
proc = psutil.Process(pid)
if 'java' in proc.name().lower():
@ -31,7 +31,14 @@ SCRIPTS = {
"start_gameservers_minecraft": [
# Vanilla (Port 25565)
{"name": "Minecraft Vanilla 1.21", "path": "C:/Users/4lexK/Desktop/GameServers/Minecraft/Vanilla_1-21/start_server.py", "params": ["--java_path", "C:/Program Files/Java/jdk-22/bin", "minecraft_server.1.21"]},
# The 1.12.2 Pack (SanderPack) (Port 25566)
{"name": "Minecraft The 1.12.2 Pack (SanderPack)", "path": "C:/Users/4lexK/Desktop/GameServers/Minecraft/1-12-2-Pack/start_server.py", "params": ["--java_path", "C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin", 'forge-1.12.2-14.23.5.2860']},
# GT New Horizon (SanderHorizon) (Port 25567)
{"name": "Minecraft GT New Horizon 2.6.0 (SanderHorizon)", "path": "C:/Users/4lexK/Desktop/GameServers/Minecraft/gt_new_horizons_2.6.0/start_server.py", "params": ["--java_path", "C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin'", 'forge-1.7.10-10.13.4.1614-1.7.10-universal']},
# rlcraft (SanderHardcore) (Port 25568)
{"name": "Minecraft rlcraft 2.9.3 (SanderHardcore)", "path": "C:/Users/4lexK/Desktop/GameServers/Minecraft/rlcraft/start_server.py", "params": ["--java_path", "C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin'", 'forge-1.12.2-14.23.5.2860']},
# Add more scripts and their parameters as needed
]
}
logging.info("Received request to start minecraft servers.")
@ -74,11 +81,133 @@ for script_info in SCRIPTS['start_gameservers_minecraft']:
"error": str(e)
})
logging.info(f"{results =}")
"""
# ""
current_pid = 8196
try:
subprocess.run(['taskkill', '/F', '/PID', str(current_pid)], check=True)
print(f"Process with PID {current_pid} has been terminated.")
except subprocess.CalledProcessError as e:
print(f"Failed to terminate process with PID {current_pid}. Error: {e}")
"""
#""
"""
# Define your list of Java server directories and commands
java_servers = [
{
'server_name': 'Vanilla 1.21',
'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/Vanilla_1-21/',
'command': ['C:/Program Files/Java/jdk-22/bin/java.exe', '-Xmx1024M', '-Xms1024M', '-jar', 'minecraft_server.1.21.jar', '--nogui', '--bonusChest'],
'wait_time': 30
},
{
'server_name': 'GT New Horizons 2.6.0',
'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/gt_new_horizons_2.6.0/',
'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx12G', '-Xms4G', '-XX:+UseStringDeduplication', '-XX:+UseCompressedOops', '-XX:+UseCodeCacheFlushing', '-Dfml.readTimeout=180', '-jar', 'forge-1.7.10-10.13.4.1614-1.7.10-universal.jar', '--nogui', '--bonusChest'],
'wait_time': 300
}
]
def is_java_process(pid):
try:
p = psutil.Process(pid)
return 'java' in p.name().lower()
except psutil.NoSuchProcess:
return False
def start_servers():
for server in java_servers:
os.chdir(server['directory'])
pid_file = os.path.join(server['directory'], 'server.pid')
log_file = os.path.join(server['directory'], 'logs', f'server_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
wait_time = server['wait_time']
# Create logs directory if it doesn't exist
os.makedirs(os.path.dirname(log_file), exist_ok=True)
if os.path.exists(pid_file):
with open(pid_file, 'r') as file:
pid = int(file.read().strip())
if psutil.pid_exists(pid) and is_java_process(pid):
print(f"Server in {server['directory']} is already running.")
continue
else:
os.remove(pid_file)
print(f"Starting server in {server['directory']}")
with open(log_file, 'w') as log:
process = subprocess.Popen(
server['command'],
cwd=server['directory'],
stdout=log,
stderr=log,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 'nt' else 0
)
time.sleep(wait_time)
with open(pid_file, 'w') as file:
file.write(str(process.pid))
print(f"Server in {server['directory']} with PID {process.pid} started successfully.")
def check_status():
for server in java_servers:
pid_file = os.path.join(server['directory'], 'server.pid')
if os.path.exists(pid_file):
with open(pid_file, 'r') as file:
pid = int(file.read().strip())
if psutil.pid_exists(pid) and is_java_process(pid):
print(f"Server in {server['directory']} is running with PID {pid}.")
else:
print(f"Server in {server['directory']} is not running.")
else:
print(f"No PID file found for server in {server['directory']}.")
def stop_servers():
for server in java_servers:
pid_file = os.path.join(server['directory'], 'server.pid')
wait_time = server['wait_time']
flag_delete_pid = False
if os.path.exists(pid_file):
with open(pid_file, 'r') as file:
pid = int(file.read().strip())
if psutil.pid_exists(pid) and is_java_process(pid):
p = psutil.Process(pid)
if os.name == 'nt':
p.terminate() # Use terminate for Windows
else:
p.send_signal(signal.SIGTERM)
try:
p.wait(timeout=wait_time)
if not psutil.pid_exists(pid):
flag_delete_pid = True
print(f"Stopped server in {server['directory']} with PID {pid}.")
else:
print(f"Failed to stop server in {server['directory']} with PID {pid}.")
except psutil.TimeoutExpired:
print(f"Timeout while stopping server in {server['directory']} with PID {pid}.")
else:
flag_delete_pid = True
print(f"Removed stale PID file for server in {server['directory']}.")
if flag_delete_pid:
os.remove(pid_file)
print(f"PID File Deleted")
flag_delete_pid = False
else:
print(f"No PID File for Server {server['server_name']}")
def main():
print("Press 'S' to start servers, 'D' to check status, 'F' to stop servers, and 'X' to exit.")
while True:
if keyboard.is_pressed('x'):
print("Exiting program.")
break
elif keyboard.is_pressed('s'):
start_servers()
elif keyboard.is_pressed('d'):
check_status()
elif keyboard.is_pressed('f'):
stop_servers()
time.sleep(0.1) # Small sleep to prevent high CPU usages
if __name__ == "__main__":
main()
Loading…
Cancel
Save