main_manager.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # 主进程的管理
  4. # github https://github.com/runhey
  5. import asyncio
  6. import sys
  7. import os
  8. import signal
  9. from asyncio.tasks import Task
  10. from threading import Thread
  11. from module.logger import logger
  12. from module.config.config import Config
  13. from module.server.script_process import ScriptProcess, ScriptState
  14. from module.server.config_manager import ConfigManager
  15. class MainManager(ConfigManager):
  16. # config_cache: Config = None # 缓存当前切换的配置
  17. script_process: dict[str: ScriptProcess] = None # 脚本进程
  18. push_data_thread: Thread = None # 数据推送线程
  19. signal_kill_server: bool = False
  20. def __init__(self) -> None:
  21. super().__init__()
  22. self.script_process: dict[str: ScriptProcess] = {} # 脚本进程
  23. self._all_script_files = self.all_script_files()
  24. for script_name in self._all_script_files:
  25. self.script_process[script_name] = ScriptProcess(script_name)
  26. self.push_data_thread = Thread(target=self.start_push_data_thread, daemon=True)
  27. self.push_data_thread.start()
  28. # def ensure_config_cache(self, config_name: str, reload: bool = False):
  29. # if self.config_cache is None:
  30. # if config_name not in self._all_script_files:
  31. # logger.warning(f'[{config_name}] script file does not exist')
  32. # return None
  33. # self.config_cache = Config(config_name)
  34. # elif self.config_cache.config_name != config_name:
  35. # self.config_cache = Config(config_name)
  36. # if reload:
  37. # self.config_cache = Config(config_name)
  38. # return self.config_cache
  39. def add_script_file(self, file_name: str):
  40. # 当你添加了新的脚本文件后,需要添加缓存的列表
  41. if file_name in self._all_script_files:
  42. logger.warning(f'[{file_name}] script file already exists')
  43. return
  44. self._all_script_files = self.all_script_files()
  45. self.script_process[file_name] = ScriptProcess(file_name)
  46. def start_push_data_thread(self):
  47. try:
  48. asyncio.run(self.push_data_handle())
  49. except SystemExit as e:
  50. logger.info('Kill the main process')
  51. # sys.exit(0)
  52. try:
  53. os.kill(os.getpid(), signal.SIGILL)
  54. print("Process killed successfully.")
  55. except OSError:
  56. print("Failed to kill the process.")
  57. except Exception as e:
  58. logger.exception(e)
  59. sys.exit(0)
  60. async def push_data_handle(self):
  61. tasks: dict[str, Task] = {}
  62. from asyncio import sleep
  63. while 1:
  64. await sleep(3)
  65. if MainManager.signal_kill_server: # 结束所有的进程
  66. logger.info('Kill all server')
  67. for script_p in self.script_process.values():
  68. await script_p.stop()
  69. logger.info('Kill push data thread')
  70. sys.exit(0)
  71. # logger.info(asyncio.all_tasks())
  72. for name, script_p in self.script_process.items():
  73. # 遍历所有的
  74. # 如果 这个进程未激活 跳过
  75. # 如果 已经存在了 对应的协程 跳过
  76. # 如果这个进程异常/运行中 那这个协程也应该存在
  77. # logger.info(f'检测脚本的process: {name}')
  78. if script_p.state == ScriptState.INACTIVE:
  79. continue
  80. coroutine_state_name = f'coroutine_state_{name}'
  81. if coroutine_state_name not in tasks:
  82. tasks[coroutine_state_name] = asyncio.create_task(script_p.coroutine_broadcast_state(),
  83. name=coroutine_state_name)
  84. coroutine_log_name = f'coroutine_log_{name}'
  85. if coroutine_log_name not in tasks:
  86. tasks[coroutine_log_name] = asyncio.create_task(script_p.coroutine_broadcast_log(),
  87. name=coroutine_log_name)
  88. @staticmethod
  89. def config_cache(name: str) -> Config:
  90. return Config(name)