Skip to content

Commit

Permalink
Merge pull request #920 from RockChinQ/feat/lifetime-controlling
Browse files Browse the repository at this point in the history
Feat: 生命周期和热重载
  • Loading branch information
RockChinQ authored Nov 16, 2024
2 parents 16153dc + 318b6e6 commit c031ab2
Show file tree
Hide file tree
Showing 29 changed files with 449 additions and 369 deletions.
15 changes: 8 additions & 7 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
# QChatGPT/main.py

asciiart = r"""
___ ___ _ _ ___ ___ _____
/ _ \ / __| |_ __ _| |_ / __| _ \_ _|
| (_) | (__| ' \/ _` | _| (_ | _/ | |
\__\_\\___|_||_\__,_|\__|\___|_| |_|
⭐️开源地址: https://github.com/RockChinQ/QChatGPT
📖文档地址: https://q.rkcn.top
_ ___ _
| | __ _ _ _ __ _| _ ) ___| |_
| |__/ _` | ' \/ _` | _ \/ _ \ _|
|____\__,_|_||_\__, |___/\___/\__|
|___/
⭐️开源地址: https://github.com/RockChinQ/LangBot
📖文档地址: https://docs.langbot.app
"""


Expand Down
4 changes: 2 additions & 2 deletions pkg/api/http/controller/groups/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class PluginsRouterGroup(group.RouterGroup):
async def initialize(self) -> None:
@self.route('', methods=['GET'])
async def _() -> str:
plugins = self.ap.plugin_mgr.plugins
plugins = self.ap.plugin_mgr.plugins()

plugins_data = [plugin.model_dump() for plugin in plugins]

Expand All @@ -27,7 +27,7 @@ async def _() -> str:
async def _(author: str, plugin_name: str) -> str:
data = await quart.request.json
target_enabled = data.get('target_enabled')
await self.ap.plugin_mgr.update_plugin_status(plugin_name, target_enabled)
await self.ap.plugin_mgr.update_plugin_switch(plugin_name, target_enabled)
return self.success()

@self.route('/<author>/<plugin_name>/update', methods=['POST'])
Expand Down
22 changes: 22 additions & 0 deletions pkg/api/http/controller/groups/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,25 @@ async def _(task_id: str) -> str:
return self.http_status(404, 404, "Task not found")

return self.success(data=task.to_dict())

@self.route('/reload', methods=['POST'])
async def _() -> str:
json_data = await quart.request.json

scope = json_data.get("scope")

await self.ap.reload(
scope=scope
)
return self.success()

@self.route('/_debug/exec', methods=['POST'])
async def _() -> str:
if not constants.debug_mode:
return self.http_status(403, 403, "Forbidden")

py_code = await quart.request.data

ap = self.ap

return self.success(data=exec(py_code, {"ap": ap}))
15 changes: 13 additions & 2 deletions pkg/api/http/controller/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import quart
import quart_cors

from ....core import app
from ....core import app, entities as core_entities
from .groups import logs, system, settings, plugins, stats
from . import group

Expand All @@ -32,15 +32,26 @@ async def shutdown_trigger_placeholder():
while True:
await asyncio.sleep(1)

async def exception_handler(*args, **kwargs):
try:
await self.quart_app.run_task(
*args, **kwargs
)
except Exception as e:
self.ap.logger.error(f"启动 HTTP 服务失败: {e}")

self.ap.task_mgr.create_task(
self.quart_app.run_task(
exception_handler(
host=self.ap.system_cfg.data["http-api"]["host"],
port=self.ap.system_cfg.data["http-api"]["port"],
shutdown_trigger=shutdown_trigger_placeholder,
),
name="http-api-quart",
scopes=[core_entities.LifecycleControlScope.APPLICATION],
)

# await asyncio.sleep(5)

async def register_routes(self) -> None:

@self.quart_app.route("/healthz")
Expand Down
6 changes: 2 additions & 4 deletions pkg/audit/center/apigroup.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import aiohttp
import requests

from ...core import app
from ...core import app, entities as core_entities


class APIGroup(metaclass=abc.ABCMeta):
Expand Down Expand Up @@ -65,14 +65,12 @@ async def do(
**kwargs,
) -> asyncio.Task:
"""执行请求"""
# task = asyncio.create_task(self._do(method, path, data, params, headers, **kwargs))

# self.ap.asyncio_tasks.append(task)

return self.ap.task_mgr.create_task(
self._do(method, path, data, params, headers, **kwargs),
kind="telemetry-operation",
name=f"{method} {path}",
scopes=[core_entities.LifecycleControlScope.APPLICATION],
).task

def gen_rid(self):
Expand Down
11 changes: 7 additions & 4 deletions pkg/command/operators/func.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,26 @@
from typing import AsyncGenerator

from .. import operator, entities, cmdmgr
from ...plugin import context as plugin_context


@operator.operator_class(name="func", help="查看所有已注册的内容函数", usage='!func')
class FuncOperator(operator.CommandOperator):
async def execute(
self, context: entities.ExecuteContext
) -> AsyncGenerator[entities.CommandReturn, None]:
reply_str = "当前已加载的内容函数: \n\n"
reply_str = "当前已启用的内容函数: \n\n"

index = 1

all_functions = await self.ap.tool_mgr.get_all_functions()
all_functions = await self.ap.tool_mgr.get_all_functions(
plugin_enabled=True,
plugin_status=plugin_context.RuntimeContainerStatus.INITIALIZED,
)

for func in all_functions:
reply_str += "{}. {}{}:\n{}\n\n".format(
reply_str += "{}. {}:\n{}\n\n".format(
index,
("(已禁用) " if not func.enable else ""),
func.name,
func.description,
)
Expand Down
8 changes: 4 additions & 4 deletions pkg/command/operators/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ async def execute(
context: entities.ExecuteContext
) -> typing.AsyncGenerator[entities.CommandReturn, None]:

plugin_list = self.ap.plugin_mgr.plugins
plugin_list = self.ap.plugin_mgr.plugins()
reply_str = "所有插件({}):\n".format(len(plugin_list))
idx = 0
for plugin in plugin_list:
Expand Down Expand Up @@ -110,7 +110,7 @@ async def execute(
try:
plugins = [
p.plugin_name
for p in self.ap.plugin_mgr.plugins
for p in self.ap.plugin_mgr.plugins()
]

if plugins:
Expand Down Expand Up @@ -182,7 +182,7 @@ async def execute(
plugin_name = context.crt_params[0]

try:
if await self.ap.plugin_mgr.update_plugin_status(plugin_name, True):
if await self.ap.plugin_mgr.update_plugin_switch(plugin_name, True):
yield entities.CommandReturn(text="已启用插件: {}".format(plugin_name))
else:
yield entities.CommandReturn(error=errors.CommandError("插件状态修改失败: 未找到插件 {}".format(plugin_name)))
Expand Down Expand Up @@ -210,7 +210,7 @@ async def execute(
plugin_name = context.crt_params[0]

try:
if await self.ap.plugin_mgr.update_plugin_status(plugin_name, False):
if await self.ap.plugin_mgr.update_plugin_switch(plugin_name, False):
yield entities.CommandReturn(text="已禁用插件: {}".format(plugin_name))
else:
yield entities.CommandReturn(error=errors.CommandError("插件状态修改失败: 未找到插件 {}".format(plugin_name)))
Expand Down
79 changes: 71 additions & 8 deletions pkg/core/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import asyncio
import threading
import traceback
import enum
import sys

from ..platform import manager as im_mgr
from ..provider.session import sessionmgr as llm_session_mgr
Expand All @@ -21,8 +23,9 @@
from ..utils import version as version_mgr, proxy as proxy_mgr, announce as announce_mgr
from ..persistence import mgr as persistencemgr
from ..api.http.controller import main as http_controller
from ..utils import logcache
from ..utils import logcache, ip
from . import taskmgr
from . import entities as core_entities


class Application:
Expand Down Expand Up @@ -104,24 +107,84 @@ async def initialize(self):
pass

async def run(self):
await self.plugin_mgr.initialize_plugins()

try:

await self.plugin_mgr.initialize_plugins()
# 后续可能会允许动态重启其他任务
# 故为了防止程序在非 Ctrl-C 情况下退出,这里创建一个不会结束的协程
async def never_ending():
while True:
await asyncio.sleep(1)

self.task_mgr.create_task(self.platform_mgr.run(), name="platform-manager")
self.task_mgr.create_task(self.ctrl.run(), name="query-controller")
self.task_mgr.create_task(self.http_ctrl.run(), name="http-api-controller")
self.task_mgr.create_task(never_ending(), name="never-ending-task")
self.task_mgr.create_task(self.platform_mgr.run(), name="platform-manager", scopes=[core_entities.LifecycleControlScope.APPLICATION, core_entities.LifecycleControlScope.PLATFORM])
self.task_mgr.create_task(self.ctrl.run(), name="query-controller", scopes=[core_entities.LifecycleControlScope.APPLICATION])
self.task_mgr.create_task(self.http_ctrl.run(), name="http-api-controller", scopes=[core_entities.LifecycleControlScope.APPLICATION])
self.task_mgr.create_task(never_ending(), name="never-ending-task", scopes=[core_entities.LifecycleControlScope.APPLICATION])

await self.print_web_access_info()
await self.task_mgr.wait_all()
except asyncio.CancelledError:
pass
except Exception as e:
self.logger.error(f"应用运行致命异常: {e}")
self.logger.debug(f"Traceback: {traceback.format_exc()}")

async def print_web_access_info(self):
"""打印访问 webui 的提示"""
import socket

host_ip = socket.gethostbyname(socket.gethostname())

public_ip = await ip.get_myip()

port = self.system_cfg.data['http-api']['port']

tips = f"""
=======================================
✨ 您可通过以下方式访问管理面板
🏠 本地地址:http://{host_ip}:{port}/
🌐 公网地址:http://{public_ip}:{port}/
📌 如果您在容器中运行此程序,请确保容器的 {port} 端口已对外暴露
🔗 若要使用公网地址访问,请阅读以下须知
1. 公网地址仅供参考,请以您的主机公网 IP 为准;
2. 要使用公网地址访问,请确保您的主机具有公网 IP,并且系统防火墙已放行 {port} 端口;
🤯 WebUI 仍处于 Beta 测试阶段,如有问题或建议请反馈到 https://github.com/RockChinQ/LangBot/issues
=======================================
""".strip()
for line in tips.split("\n"):
self.logger.info(line)

async def reload(
self,
scope: core_entities.LifecycleControlScope,
):
match scope:
case core_entities.LifecycleControlScope.PLATFORM.value:
self.logger.info("执行热重载 scope="+scope)
await self.platform_mgr.shutdown()

self.platform_mgr = im_mgr.PlatformManager(self)

await self.platform_mgr.initialize()

self.task_mgr.create_task(self.platform_mgr.run(), name="platform-manager", scopes=[core_entities.LifecycleControlScope.APPLICATION, core_entities.LifecycleControlScope.PLATFORM])
case core_entities.LifecycleControlScope.PLUGIN.value:
self.logger.info("执行热重载 scope="+scope)
await self.plugin_mgr.destroy_plugins()

# 删除 sys.module 中所有的 plugins/* 下的模块
for mod in list(sys.modules.keys()):
if mod.startswith("plugins."):
del sys.modules[mod]

self.plugin_mgr = plugin_mgr.PluginManager(self)
await self.plugin_mgr.initialize()

await self.plugin_mgr.initialize_plugins()

await self.plugin_mgr.load_plugins()
await self.plugin_mgr.initialize_plugins()
case _:
pass
4 changes: 4 additions & 0 deletions pkg/core/boot.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,17 @@ async def main(loop: asyncio.AbstractEventLoop):
# 挂系统信号处理
import signal

ap: app.Application

def signal_handler(sig, frame):
print("[Signal] 程序退出.")
# ap.shutdown()
os._exit(0)

signal.signal(signal.SIGINT, signal_handler)

app_inst = await make_app(loop)
ap = app_inst
await app_inst.run()
except Exception as e:
traceback.print_exc()
2 changes: 1 addition & 1 deletion pkg/core/bootutils/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"anthropic": "anthropic",
"colorlog": "colorlog",
"aiocqhttp": "aiocqhttp",
"botpy": "qq-botpy",
"botpy": "qq-botpy-rc",
"PIL": "pillow",
"nakuru": "nakuru-project-idk",
"tiktoken": "tiktoken",
Expand Down
8 changes: 8 additions & 0 deletions pkg/core/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@
from ..platform.types import entities as platform_entities



class LifecycleControlScope(enum.Enum):

APPLICATION = "application"
PLATFORM = "platform"
PLUGIN = "plugin"


class LauncherTypes(enum.Enum):
"""一个请求的发起者类型"""

Expand Down
Loading

0 comments on commit c031ab2

Please sign in to comment.