import socket
import subprocess
import time
from datetime import datetime

def get_time():
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')


def check_port(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        result = sock.connect_ex((host, port))
        sock.close()
        return result
    except Exception as e:
        print(f"[{get_time()}] 端口检测异常: {str(e)}")
        return False



def restart_service():
    try:
        subprocess.run("bash /root/docker/milvus/standalone_embed.sh restart", shell=True)
        # 正确示例
     #   subprocess.run(["bash", "standalone_embed.sh", "restart"])
        print(f"[{get_time()}] milvus服务重启成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"[{get_time()}] 服务重启失败: {str(e)}")
        return False


def restart_zzbservice():
    try:
        subprocess.run("cd /root/pdf_parser/zzb_data_prod", shell=True)
        subprocess.run("nohup python3 app.py > app.log 2>&1 &", shell=True)
        print("zzb服务重启成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"[{get_time()}] zzb服务重启失败: {str(e)}")

if __name__ == '__main__':
    print(f"[{get_time()}] 启动Milvus监控服务")
    port_ok = check_port("127.0.0.1", 19530)
    if  port_ok not in [0,True]:
        print("检测到Milvus服务异常，尝试重启...")
        restart_service()

    print(f"[{get_time()}] 启动zzb监控服务")
    port_ok = check_port("127.0.0.1", 8000)

    if  port_ok not in [0,True]:
        print("检测到zzb服务异常，尝试重启...")
        restart_zzbservice()
            
     
