#!/usr/bin/env python3 """fix_gateway.py — 网关健康检查+自愈脚本。 检查 gateway_zhiwei (position-analyst profile) 是否存活,端口8643是否开放。 如果挂了则重启。 执行器调用方式: python3 fix_gateway.py """ import sys, os, json, subprocess, socket GATEWAY_PORT = 8643 GATEWAY_PROFILE = "position-analyst" HERMES_BIN = "/home/hmo/hermes-agent/.venv/bin/python" GATEWAY_WD = "/home/hmo/hermes-agent" def tcp_check(host="127.0.0.1", port=8643, timeout=2): """TCP端口检查""" try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(timeout) result = s.connect_ex((host, port)) s.close() return result == 0 except Exception: return False def check_gateway_process(): """检查对应profile的网关进程""" import subprocess r = subprocess.run( ["pgrep", "-f", f"position-analyst.*gateway.*--replace"], capture_output=True, text=True, timeout=5 ) pids = [p.strip() for p in r.stdout.strip().split("\n") if p.strip()] return pids def restart_gateway(): """重启网关""" pids = check_gateway_process() if pids: for pid in pids: try: os.kill(int(pid), 15) # SIGTERM except: pass import time time.sleep(2) # 启动新网关(后台) subprocess.Popen( [HERMES_BIN, "-m", "hermes_cli.main", "-p", GATEWAY_PROFILE, "gateway", "run", "--replace"], cwd=GATEWAY_WD, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True ) return True def main(): component = sys.argv[1] if len(sys.argv) > 1 else "gateway_zhiwei" # 1. TCP端口检查 port_ok = tcp_check(port=GATEWAY_PORT) # 2. 进程检查 pids = check_gateway_process() proc_ok = len(pids) > 0 if port_ok and proc_ok: print(f"[OK] {component}: TCP端口{GATEWAY_PORT}开放, 进程={','.join(pids)}") return 0 # 异常情况 print(f"[DOWN] {component}: TCP端口={port_ok}, 进程={proc_ok} pids={pids}") print(f"[FIX] 正在重启网关...") if restart_gateway(): import time time.sleep(5) port_ok = tcp_check(port=GATEWAY_PORT) pids = check_gateway_process() if port_ok and pids: print(f"[OK] {component}: 重启成功 端口={port_ok} pids={pids}") return 0 else: print(f"[FAIL] {component}: 重启后仍未恢复 port={port_ok} pids={pids}") return 1 return 1 if __name__ == "__main__": sys.exit(main())