⚡ 添加liteyuki.channel.Channel通道,可安全跨进程通信
This commit is contained in:
@ -1,20 +1,25 @@
|
||||
import asyncio
|
||||
import multiprocessing
|
||||
import time
|
||||
from typing import Any, Coroutine, Optional
|
||||
|
||||
import nonebot
|
||||
|
||||
import liteyuki
|
||||
from liteyuki.plugin.load import load_plugin, load_plugins
|
||||
from liteyuki.utils import run_coroutine
|
||||
from liteyuki.log import logger, init_log
|
||||
|
||||
from src.utils import (
|
||||
adapter_manager,
|
||||
driver_manager,
|
||||
)
|
||||
from src.utils.base.log import logger
|
||||
|
||||
from liteyuki.bot.lifespan import (
|
||||
Lifespan,
|
||||
LIFESPAN_FUNC,
|
||||
)
|
||||
|
||||
from liteyuki.core.spawn_process import nb_run, ProcessingManager
|
||||
|
||||
__all__ = [
|
||||
@ -22,21 +27,18 @@ __all__ = [
|
||||
"get_bot"
|
||||
]
|
||||
|
||||
_MAIN_PROCESS = multiprocessing.current_process().name == "MainProcess"
|
||||
"""是否为主进程"""
|
||||
IS_MAIN_PROCESS = multiprocessing.current_process().name == "MainProcess"
|
||||
|
||||
|
||||
class LiteyukiBot:
|
||||
def __init__(self, *args, **kwargs):
|
||||
|
||||
global _BOT_INSTANCE
|
||||
_BOT_INSTANCE = self # 引用
|
||||
self.running = False
|
||||
self.config: dict[str, Any] = kwargs
|
||||
self.lifespan: Lifespan = Lifespan()
|
||||
self.init(**self.config) # 初始化
|
||||
|
||||
if not _MAIN_PROCESS:
|
||||
pass
|
||||
if not IS_MAIN_PROCESS:
|
||||
self.config: dict[str, Any] = kwargs
|
||||
self.lifespan: Lifespan = Lifespan()
|
||||
self.init(**self.config) # 初始化
|
||||
else:
|
||||
print("\033[34m" + r"""
|
||||
__ ______ ________ ________ __ __ __ __ __ __ ______
|
||||
@ -51,96 +53,57 @@ $$$$$$$$/ $$$$$$/ $$/ $$$$$$$$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/
|
||||
""" + "\033[0m")
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
if _MAIN_PROCESS:
|
||||
load_plugins("liteyuki/plugins")
|
||||
asyncio.run(self.lifespan.before_start())
|
||||
if IS_MAIN_PROCESS:
|
||||
self._run_nb_in_spawn_process(*args, **kwargs)
|
||||
else:
|
||||
# 子进程启动
|
||||
|
||||
load_plugins("liteyuki/plugins") # 加载轻雪插件
|
||||
driver_manager.init(config=self.config)
|
||||
adapter_manager.init(self.config)
|
||||
adapter_manager.register()
|
||||
nonebot.load_plugin("src.liteyuki_main")
|
||||
run_coroutine(self.lifespan.after_start()) # 启动前
|
||||
|
||||
def _run_nb_in_spawn_process(self, *args, **kwargs):
|
||||
"""
|
||||
在新的进程中运行nonebot.run方法
|
||||
在新的进程中运行nonebot.run方法,该函数在主进程中被调用
|
||||
Args:
|
||||
*args:
|
||||
**kwargs:
|
||||
|
||||
Returns:
|
||||
"""
|
||||
|
||||
timeout_limit: int = 20
|
||||
should_exit = False
|
||||
|
||||
while not should_exit:
|
||||
ctx = multiprocessing.get_context("spawn")
|
||||
event = ctx.Event()
|
||||
ProcessingManager.event = event
|
||||
process = ctx.Process(
|
||||
target=nb_run,
|
||||
args=(event,) + args,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
process.start() # 启动进程
|
||||
|
||||
asyncio.run(self.lifespan.after_start())
|
||||
if IS_MAIN_PROCESS:
|
||||
timeout_limit: int = 20
|
||||
should_exit = False
|
||||
|
||||
while not should_exit:
|
||||
if ProcessingManager.event.wait(1):
|
||||
logger.info("Receive reboot event")
|
||||
process.terminate()
|
||||
process.join(timeout_limit)
|
||||
if process.is_alive():
|
||||
logger.warning(
|
||||
f"Process {process.pid} is still alive after {timeout_limit} seconds, force kill it."
|
||||
)
|
||||
process.kill()
|
||||
break
|
||||
elif process.is_alive():
|
||||
continue
|
||||
else:
|
||||
should_exit = True
|
||||
ctx = multiprocessing.get_context("spawn")
|
||||
event = ctx.Event()
|
||||
ProcessingManager.event = event
|
||||
process = ctx.Process(
|
||||
target=nb_run,
|
||||
args=(event,) + args,
|
||||
kwargs=kwargs,
|
||||
)
|
||||
process.start() # 启动进程
|
||||
|
||||
@staticmethod
|
||||
def _run_coroutine(*coro: Coroutine):
|
||||
"""
|
||||
运行协程
|
||||
Args:
|
||||
coro:
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
# 检测是否有现有的事件循环
|
||||
new_loop = False
|
||||
try:
|
||||
loop = asyncio.get_event_loop()
|
||||
except RuntimeError:
|
||||
new_loop = True
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
if new_loop:
|
||||
for c in coro:
|
||||
loop.run_until_complete(c)
|
||||
loop.close()
|
||||
|
||||
else:
|
||||
for c in coro:
|
||||
loop.create_task(c)
|
||||
|
||||
@property
|
||||
def status(self) -> int:
|
||||
"""
|
||||
获取轻雪状态
|
||||
Returns:
|
||||
int: 0:未启动 1:运行中
|
||||
"""
|
||||
return 1 if self.running else 0
|
||||
while not should_exit:
|
||||
if ProcessingManager.event.wait(1):
|
||||
logger.info("Receive reboot event")
|
||||
process.terminate()
|
||||
process.join(timeout_limit)
|
||||
if process.is_alive():
|
||||
logger.warning(
|
||||
f"Process {process.pid} is still alive after {timeout_limit} seconds, force kill it."
|
||||
)
|
||||
process.kill()
|
||||
break
|
||||
elif process.is_alive():
|
||||
liteyuki.chan.send("轻雪进程正常运行", "sub")
|
||||
continue
|
||||
else:
|
||||
should_exit = True
|
||||
|
||||
def restart(self):
|
||||
"""
|
||||
@ -149,14 +112,12 @@ $$$$$$$$/ $$$$$$/ $$/ $$$$$$$$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/
|
||||
|
||||
"""
|
||||
logger.info("Stopping LiteyukiBot...")
|
||||
|
||||
logger.debug("Running before_restart functions...")
|
||||
self._run_coroutine(self.lifespan.before_restart())
|
||||
run_coroutine(self.lifespan.before_restart())
|
||||
logger.debug("Running before_shutdown functions...")
|
||||
self._run_coroutine(self.lifespan.before_shutdown())
|
||||
run_coroutine(self.lifespan.before_shutdown())
|
||||
|
||||
ProcessingManager.restart()
|
||||
self.running = False
|
||||
|
||||
def init(self, *args, **kwargs):
|
||||
"""
|
||||
@ -166,13 +127,12 @@ $$$$$$$$/ $$$$$$/ $$/ $$$$$$$$/ $$/ $$$$$$/ $$/ $$/ $$$$$$/
|
||||
"""
|
||||
self.init_config()
|
||||
self.init_logger()
|
||||
if not _MAIN_PROCESS:
|
||||
if not IS_MAIN_PROCESS:
|
||||
nonebot.init(**kwargs)
|
||||
asyncio.run(self.lifespan.after_nonebot_init())
|
||||
|
||||
def init_logger(self):
|
||||
from src.utils.base.log import init_log
|
||||
init_log()
|
||||
init_log(config=self.config)
|
||||
|
||||
def init_config(self):
|
||||
pass
|
||||
|
Reference in New Issue
Block a user