refactor(lifecycle): add graceful support and remove signal handling

This commit is contained in:
InfinityPacer
2024-10-18 00:35:54 +08:00
parent c02c19d719
commit 62ac03fb29
3 changed files with 11 additions and 23 deletions

View File

@@ -14,18 +14,24 @@ async def lifespan(app: FastAPI):
定义应用的生命周期事件
"""
print("Starting up...")
# 启动模块
start_modules(app)
# 初始化路由
init_routers(app)
# 初始化插件
plugin_init_task = asyncio.create_task(init_plugins_async())
try:
# 在此处 yield表示应用已经启动控制权交回 FastAPI 主事件循环
yield
finally:
print("Shutting down...")
try:
# 取消插件初始化
plugin_init_task.cancel()
await plugin_init_task
except asyncio.CancelledError:
print("Plugin installation task cancelled.")
except Exception as e:
print(f"Error during plugin installation shutdown: {e}")
# 清理模块
shutdown_modules(app)

View File

@@ -1,10 +1,8 @@
import signal
import sys
from types import FrameType
from fastapi import FastAPI
from app.core.config import settings, global_vars
from app.core.config import global_vars, settings
from app.core.module import ModuleManager
from app.utils.system import SystemUtils
@@ -89,27 +87,12 @@ def check_auth():
)
def singal_handle():
"""
监听停止信号
"""
def stop_event(signum: int, _: FrameType):
"""
SIGTERM信号处理
"""
print(f"接收到停止信号:{signum},正在停止系统...")
global_vars.stop_system()
# 设置信号处理程序
signal.signal(signal.SIGTERM, stop_event)
signal.signal(signal.SIGINT, stop_event)
def shutdown_modules(_: FastAPI):
"""
服务关闭
"""
# 停止信号
global_vars.stop_system()
# 停止模块
ModuleManager().stop()
# 停止插件
@@ -159,5 +142,3 @@ def start_modules(_: FastAPI):
start_frontend()
# 检查认证状态
check_auth()
# 监听停止信号
singal_handle()