Răsfoiți Sursa

feat: Kill server

ryland 3 ani în urmă
părinte
comite
d3abdeeeee
2 a modificat fișierele cu 38 adăugiri și 5 ștergeri
  1. 10 2
      module/server/home_router.py
  2. 28 3
      module/server/main_manager.py

+ 10 - 2
module/server/home_router.py

@@ -4,21 +4,25 @@
 from fastapi import APIRouter
 from fastapi import APIRouter
 
 
 from module.logger import logger
 from module.logger import logger
-
+from module.server.main_manager import MainManager
 
 
 home_app = APIRouter(
 home_app = APIRouter(
     prefix="/home",
     prefix="/home",
     tags=["home"],
     tags=["home"],
 )
 )
 
 
+
 @home_app.get('/test')
 @home_app.get('/test')
 async def home_test():
 async def home_test():
-    return {'message':'test'}
+    return {'message': 'test'}
+
+
 #  gcc -Wall -pedantic -shared -fPIC -o group_work.so group_work.c -lwiringPi
 #  gcc -Wall -pedantic -shared -fPIC -o group_work.so group_work.c -lwiringPi
 @home_app.get('/home_menu')
 @home_app.get('/home_menu')
 async def home_menu():
 async def home_menu():
     return {'Home': [], 'Updater': [], 'Tool': []}
     return {'Home': [], 'Updater': [], 'Tool': []}
 
 
+
 @home_app.post('/notify_test')
 @home_app.post('/notify_test')
 async def notify_test(setting: str, title: str, content: str):
 async def notify_test(setting: str, title: str, content: str):
     from module.notify.notify import Notifier
     from module.notify.notify import Notifier
@@ -35,3 +39,7 @@ async def notify_test(setting: str, title: str, content: str):
         return str(e)
         return str(e)
 
 
 
 
+@home_app.get('/kill_server')
+async def kill_server():
+    MainManager.signal_kill_server = True
+    return 'success'

+ 28 - 3
module/server/main_manager.py

@@ -3,6 +3,9 @@
 # 主进程的管理
 # 主进程的管理
 # github https://github.com/runhey
 # github https://github.com/runhey
 import asyncio
 import asyncio
+import sys
+import os
+import signal
 from asyncio.tasks import Task
 from asyncio.tasks import Task
 from multiprocessing import Queue, Pipe
 from multiprocessing import Queue, Pipe
 from threading import Thread
 from threading import Thread
@@ -17,6 +20,7 @@ class MainManager(ConfigManager):
     config_cache: Config = None  # 缓存当前切换的配置
     config_cache: Config = None  # 缓存当前切换的配置
     script_process: dict[str: ScriptProcess] = None  # 脚本进程
     script_process: dict[str: ScriptProcess] = None  # 脚本进程
     push_data_thread: Thread = None  # 数据推送线程
     push_data_thread: Thread = None  # 数据推送线程
+    signal_kill_server: bool = False
 
 
     def __init__(self) -> None:
     def __init__(self) -> None:
         super().__init__()
         super().__init__()
@@ -24,7 +28,7 @@ class MainManager(ConfigManager):
         self._all_script_files = self.all_script_files()
         self._all_script_files = self.all_script_files()
         for script_name in self._all_script_files:
         for script_name in self._all_script_files:
             self.script_process[script_name] = ScriptProcess(script_name)
             self.script_process[script_name] = ScriptProcess(script_name)
-        self.push_data_thread = Thread(target=lambda : asyncio.run(self.push_data_handle()), daemon=True)
+        self.push_data_thread = Thread(target=self.start_push_data_thread, daemon=True)
         self.push_data_thread.start()
         self.push_data_thread.start()
 
 
     def ensure_config_cache(self, config_name):
     def ensure_config_cache(self, config_name):
@@ -45,11 +49,33 @@ class MainManager(ConfigManager):
         self._all_script_files = self.all_script_files()
         self._all_script_files = self.all_script_files()
         self.script_process[file_name] = ScriptProcess(file_name)
         self.script_process[file_name] = ScriptProcess(file_name)
 
 
+    def start_push_data_thread(self):
+        try:
+            asyncio.run(self.push_data_handle())
+        except SystemExit as e:
+            logger.info('Kill the main process')
+            # sys.exit(0)
+            try:
+                os.kill(os.getpid(), signal.SIGILL)
+                print("Process killed successfully.")
+            except OSError:
+                print("Failed to kill the process.")
+
+        except Exception as e:
+            logger.exception(e)
+            sys.exit(0)
+
     async def push_data_handle(self):
     async def push_data_handle(self):
-        tasks : dict[str, Task] = {}
+        tasks: dict[str, Task] = {}
         from asyncio import sleep
         from asyncio import sleep
         while 1:
         while 1:
             await sleep(3)
             await sleep(3)
+            if MainManager.signal_kill_server:  # 结束所有的进程
+                logger.info('Kill all server')
+                for script_p in self.script_process.values():
+                    await script_p.stop()
+                logger.info('Kill push data thread')
+                sys.exit(0)
             # logger.info(asyncio.all_tasks())
             # logger.info(asyncio.all_tasks())
             for name, script_p in self.script_process.items():
             for name, script_p in self.script_process.items():
                 # 遍历所有的
                 # 遍历所有的
@@ -67,4 +93,3 @@ class MainManager(ConfigManager):
                 if coroutine_log_name not in tasks:
                 if coroutine_log_name not in tasks:
                     tasks[coroutine_log_name] = asyncio.create_task(script_p.coroutine_broadcast_log(),
                     tasks[coroutine_log_name] = asyncio.create_task(script_p.coroutine_broadcast_log(),
                                                                     name=coroutine_log_name)
                                                                     name=coroutine_log_name)
-