#!/usr/bin/env python3 """gateway_health.py — 知微网关/XMPP Bot 自愈脚本""" import subprocess, sys, time, os, json, urllib.request, socket GATEWAY_URL = "http://127.0.0.1:8643/health" BOT_PORT = 5805 BOT_SCRIPT = "/home/hmo/xmpp_zhiwei_bot.py" def check_port(port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(3) try: r = s.connect_ex(('127.0.0.1', port)) return r == 0 finally: s.close() def fix(what): if what == "gateway": r = subprocess.run(["python3", "-m", "hermes_cli.main", "-p", "position-analyst", "gateway", "run", "--replace"], cwd="/home/hmo/hermes-agent", timeout=60, capture_output=True, text=True) time.sleep(5) return check_port(8643) and r.returncode == 0 elif what == "xmpp_bot": # Kill existing if any subprocess.run(["pkill", "-f", "xmpp_zhiwei_bot.py"], timeout=5) time.sleep(2) subprocess.run(["python3", BOT_SCRIPT], timeout=30) time.sleep(5) return check_port(BOT_PORT) return False if __name__ == "__main__": target = sys.argv[1] if len(sys.argv) > 1 else "all" ok = True if target in ("all", "gateway"): if not check_port(8643): print("[HEALTH] gateway 8643 CLOSED → 修复中") if fix("gateway"): print("[HEALTH] gateway 修复成功") else: print("[HEALTH] ❌ gateway 修复失败", file=sys.stderr) ok = False else: print("[HEALTH] gateway 8643 正常") if target in ("all", "xmpp_bot"): if not check_port(BOT_PORT): print(f"[HEALTH] xmpp_bot {BOT_PORT} CLOSED → 修复中") if fix("xmpp_bot"): print("[HEALTH] xmpp_bot 修复成功") else: print("[HEALTH] ❌ xmpp_bot 修复失败", file=sys.stderr) ok = False else: print(f"[HEALTH] xmpp_bot {BOT_PORT} 正常") sys.exit(0 if ok else 1)