fix(recommendations): 优化推荐服务进程检查逻辑

更新 `_recommendations_process_running` 函数,增强对推荐服务进程的检查能力,支持 pgrep 和 ps 方式,确保在不同环境下均能准确获取进程状态。此改动提升了系统的稳定性与兼容性,确保推荐服务的有效管理。
This commit is contained in:
薇薇安 2026-02-23 19:18:09 +08:00
parent 5f256daf27
commit 4479c4f02d

View File

@ -1355,18 +1355,35 @@ async def backend_stop(_admin: Dict[str, Any] = Depends(require_system_admin)) -
def _recommendations_process_running() -> Tuple[bool, Optional[int]]:
"""检查推荐服务进程是否运行,返回 (running, pid)"""
"""检查推荐服务进程是否运行,返回 (running, pid)。兼容 pgrep/ps 及 supervisor 等启动方式。"""
# 1. 优先 pgrepLinux/macOS 常见)
for pattern in ["trading_system.recommendations_main", "recommendations_main"]:
try:
result = subprocess.run(
["pgrep", "-f", pattern],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0 and result.stdout.strip():
pids = [x for x in result.stdout.strip().split() if x.isdigit()]
if pids:
return True, int(pids[0])
except (FileNotFoundError, subprocess.TimeoutExpired, ValueError):
break
# 2. 回退ps + greppgrep 不可用或匹配失败时)
try:
result = subprocess.run(
["pgrep", "-f", "trading_system.recommendations_main"],
["sh", "-c", "ps aux 2>/dev/null | grep -E 'recommendations_main|trading_system.recommendations' | grep -v grep | head -1"],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0 and result.stdout.strip():
pids = result.stdout.strip().split()
pid = int(pids[0]) if pids else None
return True, pid
parts = result.stdout.strip().split()
if len(parts) >= 2 and parts[1].isdigit():
return True, int(parts[1])
except (FileNotFoundError, subprocess.TimeoutExpired, ValueError):
pass
return False, None