-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
56 lines (47 loc) · 1.82 KB
/
main.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
import asyncio
import os
os.environ.setdefault("MQ_FILE_PATH", os.path.join(os.getcwd(), "mq_files/windows"))
import signal
import anyio
from src.bindings.bindings import Bindings
from src.common.log import get_logger
config_path = os.environ.get("CONFIG_PATH", "config.yaml")
logger = get_logger("main")
shutdown_event = asyncio.Event()
def handle_signal(sig, frame):
"""Handle termination signals from Kubernetes"""
logger.info(f"Received signal {sig}. Starting graceful shutdown...")
# Set the shutdown event - this will trigger the main loop to exit
asyncio.get_event_loop().call_soon_threadsafe(shutdown_event.set)
async def main():
bindings: Bindings | None = None
try:
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, handle_signal)
logger.info("Starting KubeMQ - IBM MQ bindings")
bindings = Bindings(config_path)
bindings.init()
await bindings.start()
# Wait for shutdown signal instead of infinite loop
await shutdown_event.wait()
except Exception as e:
logger.exception(f"Fialed to start Kubemq - IBM MQ bindings: {str(e)}")
finally:
logger.info("Stopping Kubemq - IBM MQ bindings")
if bindings:
await bindings.stop()
remaining_tasks = asyncio.all_tasks() - {asyncio.current_task()}
if remaining_tasks:
logger.info(f"Cancelling {len(remaining_tasks)} remaining tasks...")
for task in remaining_tasks:
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
logger.info("Kubemq - IBM MQ bindings stopped")
if __name__ == "__main__":
try:
anyio.run(main)
except KeyboardInterrupt:
logger.info("KeyboardInterrupt received")