Fix env save-and-restart by deferring PM2 restart until after HTTP response.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -335,7 +335,11 @@
|
||||
}
|
||||
|
||||
async function restartInstance() {
|
||||
await fetchJson("/api/admin/restart", { method: "POST" });
|
||||
try {
|
||||
await fetchJson("/api/admin/restart", { method: "POST" });
|
||||
} catch (_) {
|
||||
// 重启会中断当前 HTTP 连接;只要后续 health 恢复即视为成功.
|
||||
}
|
||||
const deadline = Date.now() + 90000;
|
||||
while (Date.now() < deadline) {
|
||||
await new Promise((r) => setTimeout(r, 2000));
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Any
|
||||
@@ -23,10 +24,34 @@ def resolve_pm2_app_name(exchange_key: str) -> str:
|
||||
return default_pm2_app_name(exchange_key)
|
||||
|
||||
|
||||
def restart_instance_pm2(exchange_key: str) -> dict[str, Any]:
|
||||
def schedule_pm2_restart(app_name: str, *, delay_seconds: float = 1.0) -> dict[str, Any]:
|
||||
"""延迟触发 PM2 重启,便于 HTTP 响应先返回(避免重启当前进程导致请求中断)."""
|
||||
if not sys.platform.startswith("linux"):
|
||||
return {"ok": False, "msg": "仅 Linux 服务器支持 PM2 重启", "app": app_name}
|
||||
if not (app_name or "").strip():
|
||||
return {"ok": False, "msg": "未指定 PM2 应用名", "app": app_name}
|
||||
app_name = app_name.strip()
|
||||
try:
|
||||
cmd = f"sleep {delay_seconds} && exec pm2 restart {shlex.quote(app_name)} --update-env"
|
||||
subprocess.Popen(
|
||||
["bash", "-c", cmd],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
)
|
||||
return {"ok": True, "app": app_name, "msg": "重启已触发", "deferred": True}
|
||||
except FileNotFoundError:
|
||||
return {"ok": False, "msg": "未找到 bash 或 pm2 命令", "app": app_name}
|
||||
except Exception as e:
|
||||
return {"ok": False, "msg": str(e), "app": app_name}
|
||||
|
||||
|
||||
def restart_instance_pm2(exchange_key: str, *, defer: bool = False) -> 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)
|
||||
if defer:
|
||||
return schedule_pm2_restart(app_name)
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["pm2", "restart", app_name, "--update-env"],
|
||||
|
||||
@@ -140,7 +140,7 @@ def register_instance_settings_routes(
|
||||
@app.route("/api/admin/restart", methods=["POST"])
|
||||
@api_auth
|
||||
def api_admin_restart():
|
||||
result = restart_instance_pm2(exchange_key)
|
||||
result = restart_instance_pm2(exchange_key, defer=True)
|
||||
code = 200 if result.get("ok") else 500
|
||||
return jsonify({"ok": bool(result.get("ok")), **result}), code
|
||||
|
||||
|
||||
Reference in New Issue
Block a user