main_manager.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # 主进程的管理
  4. # github https://github.com/runhey
  5. import asyncio
  6. from asyncio.tasks import Task
  7. from multiprocessing import Queue, Pipe
  8. from threading import Thread
  9. from module.logger import logger
  10. from module.config.config import Config
  11. from module.server.script_process import ScriptProcess, ScriptState
  12. from module.server.config_manager import ConfigManager
  13. class MainManager(ConfigManager):
  14. config_cache: Config = None # 缓存当前切换的配置
  15. script_process: dict[str: ScriptProcess] = None # 脚本进程
  16. push_data_thread: Thread = None # 数据推送线程
  17. def __init__(self) -> None:
  18. super().__init__()
  19. self.script_process: dict[str: ScriptProcess] = {} # 脚本进程
  20. self._all_script_files = self.all_script_files()
  21. for script_name in self._all_script_files:
  22. self.script_process[script_name] = ScriptProcess(script_name)
  23. self.push_data_thread = Thread(target=lambda : asyncio.run(self.push_data_handle()), daemon=True)
  24. self.push_data_thread.start()
  25. def ensure_config_cache(self, config_name):
  26. if self.config_cache is None:
  27. if config_name not in self._all_script_files:
  28. logger.warning(f'[{config_name}] script file does not exist')
  29. return None
  30. self.config_cache = Config(config_name)
  31. elif self.config_cache.config_name != config_name:
  32. self.config_cache = Config(config_name)
  33. return self.config_cache
  34. def add_script_file(self, file_name: str):
  35. # 当你添加了新的脚本文件后,需要添加缓存的列表
  36. if file_name in self._all_script_files:
  37. logger.warning(f'[{file_name}] script file already exists')
  38. return
  39. self._all_script_files = self.all_script_files()
  40. self.script_process[file_name] = ScriptProcess(file_name)
  41. async def push_data_handle(self):
  42. tasks : dict[str, Task] = {}
  43. from asyncio import sleep
  44. while 1:
  45. await sleep(3)
  46. # logger.info(asyncio.all_tasks())
  47. for name, script_p in self.script_process.items():
  48. # 遍历所有的
  49. # 如果 这个进程未激活 跳过
  50. # 如果 已经存在了 对应的协程 跳过
  51. # 如果这个进程异常/运行中 那这个协程也应该存在
  52. # logger.info(f'检测脚本的process: {name}')
  53. if script_p.state == ScriptState.INACTIVE:
  54. continue
  55. coroutine_state_name = f'coroutine_state_{name}'
  56. if coroutine_state_name not in tasks:
  57. tasks[coroutine_state_name] = asyncio.create_task(script_p.coroutine_broadcast_state(),
  58. name=coroutine_state_name)
  59. coroutine_log_name = f'coroutine_log_{name}'
  60. if coroutine_log_name not in tasks:
  61. tasks[coroutine_log_name] = asyncio.create_task(script_p.coroutine_broadcast_log(),
  62. name=coroutine_log_name)