I have a small app that uses the Azure Service Bus Queue to pass around messages.
I’d like the app to terminate gracefully on SIGTERM, meaning that it doesn’t fetch new messages from the queue and that it gets a chance to finish messages in flight.
This is my attempt so far:
async def signal_handler(cancel, task_status): task_status.started() with trio.open_signal_receiver(signal.SIGINT, signal.SIGTERM) as sigset_aiter: async for s in sigset_aiter: logger.debug("Cancelled!") cancel() async def queue(): servicebus_client = ServiceBusClient.from_connection_string( conn_str="connection_details", ) with servicebus_client: receiver = servicebus_client.get_queue_receiver( queue_name="name" ) with receiver: client = HTTPClient(connections=100).client() async with trio.open_nursery() as nursery: await nursery.start(signal_handler, nursery.cancel_scope.cancel) while True: received_msgs = receiver.receive_messages( max_message_count=10, max_wait_time=5, ) seen = set() for msg in received_msgs: event = json.loads(str(msg)) workitem_id = event["workItemId"] if workitem_id not in seen and _is_valid_event(event): seen.add(workitem_id) nursery.start_soon( process_workitem, client, event, msg, receiver.complete_message, ) else: receiver.complete_message(msg) await trio.sleep(10) async def process_workitem(client, event, message, complete_message): # do work
First of all, is this a good/correct solution?
If I do “CTRL-C” i get “Cancelled!” in the logs. But if I run this using for example using docker, I don’t get “Cancelled!” when running
docker stop (which as far as I can understand sends
SIGTERM and then waits 10 seconds before sending
If I do
pkill -SIGTERM I also get “Cancelled!”.