|
|
@@ -2,6 +2,8 @@
|
|
|
# @author runhey
|
|
|
# 脚本进程
|
|
|
# github https://github.com/runhey
|
|
|
+import sys, os
|
|
|
+import signal
|
|
|
import multiprocessing
|
|
|
from asyncio import QueueEmpty, CancelledError, sleep
|
|
|
from enum import Enum
|
|
|
@@ -10,12 +12,14 @@ from module.logger import logger
|
|
|
|
|
|
from module.server.script_websocket import ScriptWSManager
|
|
|
|
|
|
+
|
|
|
class ScriptState(int, Enum):
|
|
|
INACTIVE = 0
|
|
|
RUNNING = 1
|
|
|
WARNING = 2
|
|
|
UPDATING = 3
|
|
|
|
|
|
+
|
|
|
class ScriptProcess(ScriptWSManager):
|
|
|
|
|
|
def __init__(self, config_name: str) -> None:
|
|
|
@@ -26,9 +30,6 @@ class ScriptProcess(ScriptWSManager):
|
|
|
self.state: ScriptState = ScriptState.INACTIVE
|
|
|
self._process = None
|
|
|
|
|
|
-
|
|
|
-
|
|
|
-
|
|
|
async def start(self):
|
|
|
self.state = ScriptState.RUNNING
|
|
|
await self.broadcast_state({"state": self.state})
|
|
|
@@ -40,10 +41,10 @@ class ScriptProcess(ScriptWSManager):
|
|
|
self._process = multiprocessing.Process(target=func,
|
|
|
args=(self.config_name, self.state_queue, self.log_pipe_in,),
|
|
|
name=self.config_name,
|
|
|
- daemon=True)
|
|
|
+ daemon=True
|
|
|
+ )
|
|
|
self._process.start()
|
|
|
|
|
|
-
|
|
|
async def stop(self):
|
|
|
self.state = ScriptState.INACTIVE
|
|
|
await self.broadcast_state({"state": self.state})
|
|
|
@@ -54,6 +55,10 @@ class ScriptProcess(ScriptWSManager):
|
|
|
logger.warning(f'Script {self.config_name} is not running')
|
|
|
return
|
|
|
self._process.terminate()
|
|
|
+ self._process.join(timeout=0.7)
|
|
|
+ if self._process.is_alive():
|
|
|
+ logger.error(f'Script {self.config_name} subprocess terminate failed')
|
|
|
+ self._process.kill()
|
|
|
self._process = None
|
|
|
|
|
|
async def coroutine_broadcast_state(self):
|
|
|
@@ -114,6 +119,14 @@ class ScriptProcess(ScriptWSManager):
|
|
|
|
|
|
|
|
|
def func(config: str, state_queue: multiprocessing.Queue, log_pipe_in) -> None:
|
|
|
+ def signal_handler(signum, frame):
|
|
|
+ logger.info(f'Script {config} received signal {signum}, exiting gracefully')
|
|
|
+ log_pipe_in.close()
|
|
|
+ state_queue.close()
|
|
|
+ sys.exit(0)
|
|
|
+
|
|
|
+ signal.signal(signal.SIGTERM, signal_handler)
|
|
|
+ signal.signal(signal.SIGINT, signal_handler)
|
|
|
|
|
|
def start_log() -> None:
|
|
|
try:
|