main_manager.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. @staticmethod
  40. def config_cache(name: str) -> Config:
  41. return Config(name)
  42. def add_script_file(self, file_name: str):
  43. # 当你添加了新的脚本文件后,需要添加缓存的列表
  44. if file_name in self._all_script_files:
  45. logger.warning(f'[{file_name}] script file already exists')
  46. return
  47. self._all_script_files = self.all_script_files()
  48. self.script_process[file_name] = ScriptProcess(file_name)
  49. def start_push_data_thread(self):
  50. try:
  51. asyncio.run(self.push_data_handle())
  52. except SystemExit as e:
  53. logger.info('Kill the main process')
  54. # sys.exit(0)
  55. try:
  56. os.kill(os.getpid(), signal.SIGILL)
  57. print("Process killed successfully.")
  58. except OSError:
  59. print("Failed to kill the process.")
  60. except Exception as e:
  61. logger.exception(e)
  62. sys.exit(0)
  63. async def push_data_handle(self):
  64. tasks: dict[str, Task] = {}
  65. from asyncio import sleep
  66. while 1:
  67. await sleep(3)
  68. if MainManager.signal_kill_server: # 结束所有的进程
  69. logger.info('Kill all server')
  70. for script_p in self.script_process.values():
  71. await script_p.stop()
  72. logger.info('Kill push data thread')
  73. sys.exit(0)
  74. # logger.info(asyncio.all_tasks())
  75. for name, script_p in self.script_process.items():
  76. # 遍历所有的
  77. # 如果 这个进程未激活 跳过
  78. # 如果 已经存在了 对应的协程 跳过
  79. # 如果这个进程异常/运行中 那这个协程也应该存在
  80. # logger.info(f'检测脚本的process: {name}')
  81. if script_p.state == ScriptState.INACTIVE:
  82. continue
  83. coroutine_state_name = f'coroutine_state_{name}'
  84. if coroutine_state_name not in tasks:
  85. tasks[coroutine_state_name] = asyncio.create_task(script_p.coroutine_broadcast_state(),
  86. name=coroutine_state_name)
  87. coroutine_log_name = f'coroutine_log_{name}'
  88. if coroutine_log_name not in tasks:
  89. tasks[coroutine_log_name] = asyncio.create_task(script_p.coroutine_broadcast_log(),
  90. name=coroutine_log_name)
  91. async def restart_processes(self, script_instances: list[str]):
  92. for instance in script_instances:
  93. logger.info(f'Restart script {instance}')
  94. if instance not in self.script_process:
  95. try:
  96. self.script_process[instance] = ScriptProcess(instance)
  97. except FileNotFoundError:
  98. logger.error(f'{instance} file not found')
  99. continue
  100. await self.script_process[instance].start()
  101. mm = MainManager()