Skip to content

Commit d1d4986

Browse files
committed
fix: handle SIGTERM and SIGINT gracefully for clean shutdown
Use asyncio signal handlers for both SIGTERM (systemd stop) and SIGINT (Ctrl+C), logging the signal name and cancelling all tasks to go through the normal cleanup path instead of exiting with code 143.
1 parent 259da26 commit d1d4986

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

irc_bot.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import contextlib
33
import datetime
44
import logging
5+
import signal
56
import socket
67
import traceback
78

@@ -151,7 +152,21 @@ def write_starting_date():
151152
f.write("Started at: " + str(datetime.datetime.today()))
152153

153154

155+
_shutdown_logger = logging.getLogger("IRCMainLoop")
156+
157+
158+
def _handle_signal(sig, loop):
159+
_shutdown_logger.info("Received %s, shutting down...", sig.name)
160+
for task in asyncio.all_tasks(loop):
161+
if task is not asyncio.current_task():
162+
task.cancel()
163+
164+
154165
async def async_main():
166+
loop = asyncio.get_running_loop()
167+
for sig in (signal.SIGTERM, signal.SIGINT):
168+
loop.add_signal_handler(sig, _handle_signal, sig, loop)
169+
155170
write_starting_date()
156171

157172
config_obj = Configuration()
@@ -204,5 +219,4 @@ async def async_main():
204219

205220

206221
if __name__ == "__main__":
207-
with contextlib.suppress(KeyboardInterrupt):
208-
asyncio.run(async_main())
222+
asyncio.run(async_main())

0 commit comments

Comments
 (0)