From bd266cdce2424a4016a11e240de174ce75352c64 Mon Sep 17 00:00:00 2001 From: Eric Callahan Date: Thu, 26 Jun 2025 07:52:08 -0400 Subject: [PATCH] eventloop: store reference to all background tasks Newer versions of Python can potentially destroy tasks before they are complete due to garbage collection. To prevent this a reference to all created tasks are kept in a set and removed when the task is done. Signed-off-by: Eric Callahan --- moonraker/components/mqtt.py | 29 +++++++++++++-------------- moonraker/components/shell_command.py | 9 ++++++--- moonraker/eventloop.py | 13 +++++++++--- moonraker/utils/cansocket.py | 9 ++++----- 4 files changed, 34 insertions(+), 26 deletions(-) diff --git a/moonraker/components/mqtt.py b/moonraker/components/mqtt.py index 06164d9..498769c 100644 --- a/moonraker/components/mqtt.py +++ b/moonraker/components/mqtt.py @@ -77,10 +77,10 @@ class ExtPahoClient(paho_mqtt.Client): "to_process": 0, "pos": 0 } - with self._out_packet_mutex: + with self._out_packet_mutex: # type: ignore self._out_packet = deque() # type: ignore - with self._current_out_packet_mutex: + with self._current_out_packet_mutex: # type: ignore self._current_out_packet = None else: self._in_packet = { @@ -118,7 +118,7 @@ class ExtPahoClient(paho_mqtt.Client): try: # Try with server_hostname, even it's not supported in # certain scenarios - sock = self._ssl_context.wrap_socket( + sock = self._ssl_context.wrap_socket( # type: ignore sock, server_hostname=self._host, do_handshake_on_connect=False, @@ -129,7 +129,7 @@ class ExtPahoClient(paho_mqtt.Client): except ValueError: # Python version requires SNI in order to handle # server_hostname, but SNI is not available - sock = self._ssl_context.wrap_socket( + sock = self._ssl_context.wrap_socket( # type: ignore sock, do_handshake_on_connect=False, ) @@ -137,7 +137,7 @@ class ExtPahoClient(paho_mqtt.Client): # If SSL context has already checked hostname, then don't need # to do it again if (hasattr(self._ssl_context, 'check_hostname') and - self._ssl_context.check_hostname): + self._ssl_context.check_hostname): # type: ignore verify_host = False assert isinstance(sock, ssl.SSLSocket) @@ -152,7 +152,7 @@ class ExtPahoClient(paho_mqtt.Client): sock = paho_mqtt.WebsocketWrapper( sock, self._host, self._port, self._ssl, self._websocket_path, self._websocket_extra_headers - ) + ) # type: ignore self._sock = sock assert self._sock is not None @@ -175,7 +175,7 @@ class ExtPahoClient(paho_mqtt.Client): } self._ping_t = 0.0 # type: ignore - self._state = paho_mqtt._ConnectionState.MQTT_CS_CONNECTING + self._state = paho_mqtt._ConnectionState.MQTT_CS_CONNECTING # type: ignore self._sock_close() @@ -199,7 +199,7 @@ class ExtPahoClient(paho_mqtt.Client): self._messages_reconnect_reset() with self._callback_mutex: - on_pre_connect = self.on_pre_connect + on_pre_connect = self.on_pre_connect # type: ignore if on_pre_connect: try: @@ -212,11 +212,11 @@ class ExtPahoClient(paho_mqtt.Client): if not self.suppress_exceptions: raise - self._sock = sock or self._create_socket() + self._sock = sock or self._create_socket() # type: ignore self._sock.setblocking(False) # type: ignore[attr-defined] self._registered_write = False - self._call_socket_open(self._sock) + self._call_socket_open(self._sock) # type: ignore return self._send_connect(self._keepalive) @@ -352,12 +352,12 @@ class MQTTClient(APITransport): "between 0 and 2") self.publish_split_status = \ config.getboolean("publish_split_status", False) - client_id: Optional[str] = config.get("client_id", None) + client_id: str = config.get("client_id", "") if PAHO_MQTT_VERSION < (2, 0): self.client = ExtPahoClient(client_id, protocol=self.protocol) else: self.client = ExtPahoClient( - paho_mqtt.CallbackAPIVersion.VERSION1, client_id, + paho_mqtt.CallbackAPIVersion.VERSION1, client_id, # type: ignore protocol=self.protocol ) self.client.on_connect = self._on_connect @@ -530,7 +530,7 @@ class MQTTClient(APITransport): logging.info("MQTT Server Disconnected, reason: " f"{paho_mqtt.error_string(reason_code)}") if self.connect_task is None: - self.connect_task = asyncio.create_task(self._do_reconnect()) + self.connect_task = self.eventloop.create_task(self._do_reconnect()) self.server.send_event("mqtt:disconnected") self.connect_evt.clear() @@ -587,8 +587,7 @@ class MQTTClient(APITransport): logging.exception("MQTT Connection Error") last_err = e continue - self.client.socket().setsockopt( - socket.SOL_SOCKET, socket.SO_SNDBUF, 2048) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048) break self.connect_task = None diff --git a/moonraker/components/shell_command.py b/moonraker/components/shell_command.py index 959ae74..739fff8 100644 --- a/moonraker/components/shell_command.py +++ b/moonraker/components/shell_command.py @@ -97,7 +97,7 @@ class ShellCommandProtocol(asyncio.subprocess.SubprocessStreamProtocol): if cb is not None: if isinstance(data, str): data = data.encode() - lines = data.split(b'\n') + lines = cast(bytes, data).split(b'\n') lines[0] = self.pending_data[data_idx] + lines[0] self.pending_data[data_idx] = lines.pop() for line in lines: @@ -238,6 +238,7 @@ class ShellCommand: self.factory.add_running_command(self) attempts = max(1, attempts) stdin: Optional[bytes] = None + stdout = stderr = b"" if proc_input is not None: stdin = proc_input.encode() while attempts > 0: @@ -345,6 +346,7 @@ class ShellCommand: class ShellCommandFactory: error = ShellCommandError def __init__(self, config: ConfigHelper) -> None: + self.eventloop = config.get_server().get_event_loop() self.running_commands: Set[ShellCommand] = set() def add_running_command(self, cmd: ShellCommand) -> None: @@ -393,6 +395,7 @@ class ShellCommandFactory: self, cmd, callback, std_err_callback, env, log_stderr, cwd ) attempts = max(1, attempts) + async def _wrapper() -> None: for _ in range(attempts): if await scmd.run( @@ -403,7 +406,7 @@ class ShellCommandFactory: else: ret_code = scmd.get_return_code() raise ShellCommandError(f"Error running command {cmd}", ret_code) - return asyncio.create_task(_wrapper()) + return self.eventloop.create_task(_wrapper()) def exec_cmd( self, @@ -427,7 +430,7 @@ class ShellCommandFactory: timeout, attempts, log_complete, sig_idx, proc_input, success_codes ) - return asyncio.create_task(coro) + return self.eventloop.create_task(coro) async def close(self) -> None: for cmd in self.running_commands: diff --git a/moonraker/eventloop.py b/moonraker/eventloop.py index e2c2c16..5943ccd 100644 --- a/moonraker/eventloop.py +++ b/moonraker/eventloop.py @@ -20,7 +20,8 @@ from typing import ( Optional, Tuple, TypeVar, - Union + Union, + Set ) _uvl_var = os.getenv("MOONRAKER_ENABLE_UVLOOP", "y").lower() @@ -49,6 +50,7 @@ class EventLoop: def reset(self) -> None: self.aioloop = asyncio.get_running_loop() + self.bg_tasks: Set[asyncio.Task] = set() self.add_signal_handler = self.aioloop.add_signal_handler self.remove_signal_handler = self.aioloop.remove_signal_handler self.add_reader = self.aioloop.add_reader @@ -57,11 +59,16 @@ class EventLoop: self.remove_writer = self.aioloop.remove_writer self.get_loop_time = self.aioloop.time self.create_future = self.aioloop.create_future - self.create_task = self.aioloop.create_task self.call_at = self.aioloop.call_at self.set_debug = self.aioloop.set_debug self.is_running = self.aioloop.is_running + def create_task(self, coro: asyncio._CoroutineLike[_T]) -> asyncio.Task[_T]: + tsk = self.aioloop.create_task(coro) + self.bg_tasks.add(tsk) + tsk.add_done_callback(self.bg_tasks.discard) + return tsk + def _create_new_loop(self) -> asyncio.AbstractEventLoop: for _ in range(5): # Sometimes the new loop does not properly instantiate. @@ -91,7 +98,7 @@ class EventLoop: raise except Exception: logging.exception("Error Running Callback") - self.aioloop.create_task(_wrapper()) + self.create_task(_wrapper()) def delay_callback(self, delay: float, diff --git a/moonraker/utils/cansocket.py b/moonraker/utils/cansocket.py index ac22033..70e5231 100644 --- a/moonraker/utils/cansocket.py +++ b/moonraker/utils/cansocket.py @@ -70,7 +70,7 @@ class CanSocket: self.input_buffer = b"" self.output_packets: List[bytes] = [] self.input_busy = False - self.output_busy = False + self.send_task: asyncio.Task | None = None self.closed = True try: self.cansock.bind((interface,)) @@ -139,10 +139,9 @@ class CanSocket: packet = struct.pack( CAN_FMT, can_id, length, pkt_data) self.output_packets.append(packet) - if self.output_busy: + if self.send_task is not None: return - self.output_busy = True - asyncio.create_task(self._do_can_send()) + self.send_task = asyncio.create_task(self._do_can_send()) async def _do_can_send(self): while self.output_packets: @@ -153,7 +152,7 @@ class CanSocket: logging.info("Socket Write Error, closing") self.close() break - self.output_busy = False + self.send_task = None def close(self): if self.closed: