From f36d41550cc94c11e90380c7e731e79f502efc6b Mon Sep 17 00:00:00 2001 From: jingrow Date: Sun, 2 Nov 2025 13:32:41 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=8E=AF=E5=A2=83=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E9=87=8D=E5=90=AF=E6=97=A0=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/jingrow/jingrow/api/system.py | 50 +++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 14 deletions(-) diff --git a/apps/jingrow/jingrow/api/system.py b/apps/jingrow/jingrow/api/system.py index 09443e8..52dc96c 100644 --- a/apps/jingrow/jingrow/api/system.py +++ b/apps/jingrow/jingrow/api/system.py @@ -282,26 +282,49 @@ async def restart_environment(request: Request): import asyncio import os import signal + from pathlib import Path async def delayed_restart(): # 等待一小段时间,确保响应已经返回 await asyncio.sleep(2) logger.info("开始执行环境重启...") - # 获取当前进程ID - current_pid = os.getpid() + # 获取当前配置 + settings = get_settings() + is_production = str(getattr(settings, "environment", "development")).lower() == "production" + reload_enabled = (not is_production) and bool(getattr(settings, "backend_reload", True)) - # 如果是开发模式,可以通过设置重启标志或发送信号 - # 这里使用发送SIGTERM信号来触发重启(如果使用reload模式) - try: - # 发送SIGTERM信号给当前进程 - # 如果使用uvicorn的reload模式,这会触发重启 - os.kill(current_pid, signal.SIGTERM) - except Exception as e: - logger.error(f"发送重启信号失败: {str(e)}") - # 如果发送信号失败,尝试其他方法 - # 可以通过修改配置文件或环境变量来触发重启 - logger.warning("无法通过信号重启,请手动重启服务") + if reload_enabled: + # 开发模式:通过修改被监控的 Python 文件时间戳来触发 uvicorn reload + try: + # 获取当前文件路径(system.py 在 reload_dir 中) + current_file = Path(__file__) + + # 修改文件时间戳来触发 uvicorn 的文件变化检测 + # 这会触发 uvicorn 的自动重启 + current_time = os.path.getmtime(current_file) + # touch 文件:更新访问和修改时间 + os.utime(current_file, (current_time + 1, current_time + 1)) + + logger.info(f"已通过修改文件时间戳触发 uvicorn reload,系统将在稍后自动重启") + except Exception as e: + logger.error(f"通过文件时间戳触发重启失败: {str(e)}") + # 回退到信号方式 + try: + current_pid = os.getpid() + os.kill(current_pid, signal.SIGTERM) + logger.info("已发送重启信号") + except Exception as sig_error: + logger.error(f"发送重启信号也失败: {str(sig_error)}") + else: + # 生产模式:发送信号 + try: + current_pid = os.getpid() + os.kill(current_pid, signal.SIGTERM) + logger.info("生产模式:已发送重启信号") + except Exception as e: + logger.error(f"发送重启信号失败: {str(e)}") + logger.warning("无法通过信号重启,请手动重启服务") # 启动后台任务 asyncio.create_task(delayed_restart()) @@ -316,4 +339,3 @@ async def restart_environment(request: Request): except Exception as e: logger.error(f"重启环境失败: {str(e)}") raise HTTPException(status_code=500, detail=f"重启环境失败: {str(e)}") -