修复环境配置重启无效
This commit is contained in:
parent
bd214cc117
commit
f36d41550c
@ -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)}")
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user