#!/usr/bin/env python3
"""重启RPC服务，解决端口占用问题"""

import psutil
import time
import subprocess
import sys

print("🔍 查找占用8008端口的进程...")
found = False
for conn in psutil.net_connections():
    try:
        if conn.laddr.port == 8008 and conn.status == psutil.CONN_LISTEN:
            pid = conn.pid
            print(f"✅ 找到占用端口8008的进程: PID {pid}")
            try:
                p = psutil.Process(pid)
                p.terminate()
                print(f"✅ 已终止进程 {pid}")
                found = True
            except Exception as e:
                print(f"❌ 终止进程 {pid} 失败: {e}")
    except Exception:
        pass

if not found:
    print("✅ 没有找到占用8008端口的进程")

time.sleep(3)

print("\n🚀 启动RPC服务...")
cmd = ["python", "/app/final_rpc_correct.py"]
proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print(f"✅ 启动进程: PID {proc.pid}")

time.sleep(3)

print("\n🔍 验证端口监听...")
started = False
for conn in psutil.net_connections():
    try:
        if conn.laddr.port == 8008 and conn.status == psutil.CONN_LISTEN:
            print(f"✅ 端口8008已经监听，PID {conn.pid}")
            started = True
    except Exception:
        pass

if started:
    print("\n🎉 RPC服务启动成功！")
    sys.exit(0)
else:
    print("\n❌ RPC服务启动失败！端口8008没有监听")
    sys.exit(1)
