-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_manager.py
More file actions
88 lines (73 loc) · 2.72 KB
/
process_manager.py
File metadata and controls
88 lines (73 loc) · 2.72 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
import subprocess
import os
import time
import signal
import sys
from multiprocessing import Process
from monitoring.health_check import start_health_server
# Global flag for graceful shutdown
shutdown_flag = False
def signal_handler(signum, frame):
"""Handle shutdown signals"""
global shutdown_flag
print(f"Received signal {signum}. Initiating graceful shutdown...")
shutdown_flag = True
def start_process(command):
"""Starts a process and keeps it alive"""
global shutdown_flag
restart_count = 0
while not shutdown_flag:
try:
print(f"Starting command: {command} (attempt {restart_count + 1})")
process = subprocess.Popen(command, shell=True)
process.wait()
if shutdown_flag:
break
restart_count += 1
print(f"Process '{command}' exited. Restart count: {restart_count}")
# Add delay between restarts to prevent rapid cycling
if restart_count > 5:
print(f"Too many restarts for '{command}'. Waiting 30 seconds...")
time.sleep(30)
else:
time.sleep(5)
except KeyboardInterrupt:
print(f"KeyboardInterrupt received for command: {command}")
break
except Exception as e:
print(f"Unexpected error for command '{command}': {e}")
time.sleep(10)
def run():
"""Main process manager"""
# Set up signal handlers
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
processes = [
Process(target=start_process, args=("rq worker warmup",)),
Process(target=start_process, args=("rq worker warmup_reply",)),
Process(target=start_process, args=("rq worker warmup_read",)),
Process(target=start_health_server)
]
try:
for p in processes:
p.start()
print(f"Started process: {p.name}")
# Wait for processes with proper cleanup
while any(p.is_alive() for p in processes):
time.sleep(1)
if shutdown_flag:
break
except KeyboardInterrupt:
print("Main process interrupted. Shutting down...")
finally:
# Clean shutdown
print("Terminating all processes...")
for p in processes:
if p.is_alive():
p.terminate()
p.join(timeout=5)
if p.is_alive():
print(f"Force killing process: {p.name}")
p.kill()
if __name__ == "__main__":
run()