[docs]defget_start_method():try:current_process=psutil.Process()cmdline=current_process.cmdline()cmdline_str=' '.join(cmdline).lower()print("Debug - Current process command line: ",cmdline)# Look for 'xingen' in our own command lineif'mindroot'incmdline_str:# Check if we're under PM2 by environment or parent process treeif'PM2_HOME'inos.environorany('pm2'inp.name().lower()forpincurrent_process.parents()):return'pm2'return'mindroot'return'unknown'exceptExceptionase:print(f"Debug - Error in get_start_method: {str(e)}")return'unknown'
[docs]defspawn_restart():try:# Get the current command line that started this processcurrent_process=psutil.Process()original_cmd=current_process.cmdline()# Create a temporary script file instead of using -cwithtempfile.NamedTemporaryFile(mode='w',suffix='.py',delete=False)asf:f.write(f"""#!/usr/bin/env python3# Temporary restart script for xingenimport timeimport subprocessimport sysimport ostime.sleep(2.5) # Wait for old server to fully shutdowntry: cmd = {original_cmd!r} print("Restarting mindroot with command:", cmd) subprocess.run(cmd, check=True)except Exception as e: print(f"Error restarting mindroot: {{e}}") sys.exit(1)finally: # Clean up this temporary script try: os.unlink(__file__) except: pass""")script_path=f.name# Make the script executableos.chmod(script_path,0o755)# Start detached process that will survive parent's exitsubprocess.Popen([sys.executable,script_path],start_new_session=True,# Let's keep stdout/stderr for debuggingstdout=None,stderr=None)print(f"Debug - Spawned restart script: {script_path}")returnTrueexceptExceptionase:print(f"Debug - Error in spawn_restart: {str(e)}")returnFalse
[docs]asyncdefdelayed_exit():awaitasyncio.sleep(0.5)# Wait 500ms to allow response to be sentsys.exit(0)
[docs]@router.post("/restart")asyncdefrestart_server():try:method=get_start_method()ifmethod=='pm2':# PM2 will handle the restart automaticallymessage="Server stopping - PM2 will automatically restart it"elifmethod=='mindroot':# Spawn process to restart serverifspawn_restart():message="Server stopping - restart process initiated"else:return{"success":False,"message":"Failed to initiate restart process","method":method}else:return{"success":False,"message":"Unknown start method - please restart server manually","method":method}# Schedule the exit after response is sentasyncio.create_task(delayed_exit())return{"success":True,"message":message,"method":method}exceptExceptionase:return{"success":False,"message":f"Restart failed: {str(e)}","method":methodif'method'inlocals()else'unknown'}
[docs]@router.post("/stop")asyncdefstop_server():try:method=get_start_method()ifmethod=='pm2':message="Server stopping - PM2 will automatically restart it unless stopped through PM2"else:message="Server stopping - manual restart will be required"# Schedule the exit after response is sentasyncio.create_task(delayed_exit())return{"success":True,"message":message}exceptExceptionase:return{"success":False,"message":f"Stop failed: {str(e)}"}
[docs]@router.get("/ping")asyncdefping():"""Simple endpoint to check if server is running"""return{"status":"ok"}