"""Stop the running SteamBase server and start it again. Usage: python tools/restart_server.py python tools/restart_server.py --port 9000 """ import os import socket import subprocess import sys import time for stream in (sys.stdout, sys.stderr): try: stream.reconfigure(encoding="utf-8") except Exception: pass APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PID_FILE = os.path.join(APP_DIR, "data", "server.pid") SERVER = os.path.join(APP_DIR, "web", "server.py") def pid_from_file(): try: with open(PID_FILE, encoding="ascii") as handle: return int(handle.read().strip()) except (OSError, ValueError): return None def kill_pid(pid): if not pid or pid <= 0: return script = ( f"$proc = Get-CimInstance Win32_Process -Filter 'ProcessId={pid}' " "-ErrorAction SilentlyContinue; " "if ($proc -and $proc.CommandLine -like '*server.py*') { " "Stop-Process -Id $proc.ProcessId -Force -ErrorAction SilentlyContinue }" ) try: subprocess.run( ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15) except Exception: pass def port_busy(port, host="127.0.0.1"): sock = socket.socket() sock.settimeout(0.2) try: sock.connect((host, port)) return True except OSError: return False finally: sock.close() def kill_port(port): script = ( f"Get-NetTCPConnection -LocalPort {port} -State Listen -ErrorAction SilentlyContinue " "| Select-Object -ExpandProperty OwningProcess -Unique " "| ForEach-Object { " "$proc = Get-CimInstance Win32_Process -Filter \"ProcessId=$_\" " "-ErrorAction SilentlyContinue; " "if ($proc -and $proc.CommandLine -like '*server.py*') { " "Stop-Process -Id $_ -Force -ErrorAction SilentlyContinue } }" ) try: subprocess.run( ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", script], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20) except Exception: pass def free_port(start): port = start while port_busy(port) and port < start + 50: port += 1 return port def main(): args = [arg for arg in sys.argv[1:] if arg != "--no-open"] no_open = "--no-open" in sys.argv[1:] port = 8765 if "--port" in args: try: port = int(args[args.index("--port") + 1]) except (IndexError, ValueError): raise SystemExit("invalid --port") elif args: try: port = int(args[0]) except ValueError: raise SystemExit(f"unknown argument: {args[0]}") pid = pid_from_file() if pid: kill_pid(pid) try: os.remove(PID_FILE) except OSError: pass kill_port(port) for _ in range(25): if not port_busy(port): break time.sleep(0.2) final_port = free_port(port) if final_port != port: print(f"Port {port} is busy; starting on {final_port}.") cmd = [sys.executable, SERVER, "--port", str(final_port)] if not no_open: cmd.append("--open") return subprocess.call(cmd, cwd=APP_DIR) if __name__ == "__main__": raise SystemExit(main())