-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrestart_service_on_changes.py
76 lines (53 loc) · 2.17 KB
/
restart_service_on_changes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import os
import time
import subprocess
import atexit
import signal
import sys
from datetime import datetime
from loguru import logger
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
logger.remove(0) # To not show the logs in the console
logger.add(f"logs/logs_{timestamp}.log", rotation="23:59", compression="zip")
process = None # Global variable to track the subprocess
def start_script():
"""Start the target Python script as a subprocess."""
return subprocess.Popen(["python3", "chat.py"])
def get_modification_time(path):
"""Get the last modification time of a file or directory."""
try:
return os.path.getmtime(path)
except FileNotFoundError:
return None
def restart_script(process):
"""Restart the target script by terminating the previous subprocess and starting a new one."""
if process is not None:
process.terminate()
return start_script()
def cleanup_and_exit():
"""Cleanup function to ensure subprocess termination on script exit."""
global process
if process is not None:
process.terminate()
def handle_sigterm(signum, frame):
"""Signal handler for handling SIGTERM signal."""
cleanup_and_exit()
sys.exit(0)
if __name__ == "__main__":
directory_path = "/chat_llm/input_docs"
logger.info(f"The document directory path: {directory_path}")
last_modification_time = get_modification_time(directory_path)
logger.info(f"The last modification time in the directory is: {last_modification_time}")
process = start_script()
atexit.register(cleanup_and_exit) # Register the cleanup function
signal.signal(signal.SIGTERM, handle_sigterm) # Handle SIGTERM signal
try:
while True:
current_modification_time = get_modification_time(directory_path)
if current_modification_time != last_modification_time:
logger.info(f"Changes detected in '{directory_path}'. Restarting script...")
process = restart_script(process)
last_modification_time = current_modification_time
time.sleep(20) # Check the changes in the directory every 20 seconds
except KeyboardInterrupt:
pass