Files
crypto_monitor/lib/instance/instance_pm2_lib.py
T
dekun ef4b2f17ca Add instance nav prefs, env config UI, and PM2 restart.
P1-P4: configurable nav/section visibility in system settings, full .env editor with restart badges, password change, runtime hot overrides, and single-instance pm2 restart. Works in hub embed iframe.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-08 20:07:06 +08:00

50 lines
1.5 KiB
Python

"""PM2 重启当前实例(仅 Linux 部署环境)。"""
from __future__ import annotations
import os
import subprocess
import sys
from typing import Any
def default_pm2_app_name(exchange_key: str) -> str:
mapping = {
"okx": "crypto_okx",
"binance": "crypto_binance",
"gate": "crypto_gate",
}
return mapping.get((exchange_key or "").strip().lower(), "crypto_okx")
def resolve_pm2_app_name(exchange_key: str) -> str:
explicit = (os.getenv("PM2_APP_NAME") or "").strip()
if explicit:
return explicit
return default_pm2_app_name(exchange_key)
def restart_instance_pm2(exchange_key: str) -> dict[str, Any]:
if not sys.platform.startswith("linux"):
return {"ok": False, "msg": "仅 Linux 服务器支持 PM2 重启", "app": None}
app_name = resolve_pm2_app_name(exchange_key)
try:
proc = subprocess.run(
["pm2", "restart", app_name, "--update-env"],
capture_output=True,
text=True,
timeout=120,
)
ok = proc.returncode == 0
return {
"ok": ok,
"app": app_name,
"msg": (proc.stdout or proc.stderr or "").strip()[:500],
"returncode": proc.returncode,
}
except FileNotFoundError:
return {"ok": False, "msg": "未找到 pm2 命令", "app": app_name}
except subprocess.TimeoutExpired:
return {"ok": False, "msg": "pm2 restart 超时", "app": app_name}
except Exception as e:
return {"ok": False, "msg": str(e), "app": app_name}