From 1bce504ff49ca1d7a0996869d56db4273fa54948 Mon Sep 17 00:00:00 2001 From: Alex Kavanagh Date: Tue, 23 Jan 2024 18:52:38 +0000 Subject: [PATCH] Add a try: except: around loop.add_signal_handler() For py 3.8, 3.9 and 3.10, the set_wakeup_fd() call fails on a background thread, due to [1], which has been fixed in py3.11. This patch simply catches the error if the python version can't do the adding of a signal handler so that the existing/previous behaviour continues. [1] https://github.com/python/cpython/issues/87173 Closes-Bug: #1010 --- juju/client/connection.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/juju/client/connection.py b/juju/client/connection.py index 3d680175d..520625374 100644 --- a/juju/client/connection.py +++ b/juju/client/connection.py @@ -425,9 +425,14 @@ def _exit_tasks(): for task in jasyncio.all_tasks(): task.cancel() - loop = jasyncio.get_running_loop() - for sig in (signal.SIGINT, signal.SIGTERM): - loop.add_signal_handler(sig, _exit_tasks) + try: + loop = jasyncio.get_running_loop() + for sig in (signal.SIGINT, signal.SIGTERM): + loop.add_signal_handler(sig, _exit_tasks) + except (ValueError, OSError, RuntimeError) as e: + # add_signal_handler doesn't work in a thread + if 'main thread' not in str(e): + raise return (await websockets.connect( url, @@ -474,9 +479,14 @@ async def close(self, to_reconnect=False): self.proxy.close() # Remove signal handlers - loop = jasyncio.get_running_loop() - for sig in (signal.SIGINT, signal.SIGTERM): - loop.remove_signal_handler(sig) + try: + loop = jasyncio.get_running_loop() + for sig in (signal.SIGINT, signal.SIGTERM): + loop.remove_signal_handler(sig) + except (ValueError, OSError, RuntimeError) as e: + # add_signal_handler doesn't work in a thread + if 'main thread' not in str(e): + raise async def _recv(self, request_id): if not self.is_open: