From 5e4e7900f77047e5c312ae2c03dcd5e3e19fe644 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Colomb?= Date: Wed, 24 Apr 2024 12:46:19 +0200 Subject: [PATCH 1/2] Gracefully handle errors when binding SocketCAN fails. The parent class BusABC expects to be shutdown properly, checked via its self._is_shutdown flag during object deletion. But that flag is only set when the base class shutdown() is called, which doesn't happen if instantiation of the concrete class failed in can.Bus(). So there is no way to avoid the warning message "SocketcanBus was not properly shut down" if the constructor raised an exception. This change addresses that issue for the SocketCAN interface, by catching an OSError exception in bind_socket(), logging it, and calling self.shutdown(). --- can/interfaces/socketcan/socketcan.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/can/interfaces/socketcan/socketcan.py b/can/interfaces/socketcan/socketcan.py index cdf4afac6..c9ca732d4 100644 --- a/can/interfaces/socketcan/socketcan.py +++ b/can/interfaces/socketcan/socketcan.py @@ -705,14 +705,20 @@ def __init__( # so this is always supported by the kernel self.socket.setsockopt(socket.SOL_SOCKET, constants.SO_TIMESTAMPNS, 1) - bind_socket(self.socket, channel) - kwargs.update( - { - "receive_own_messages": receive_own_messages, - "fd": fd, - "local_loopback": local_loopback, - } - ) + try: + bind_socket(self.socket, channel) + kwargs.update( + { + "receive_own_messages": receive_own_messages, + "fd": fd, + "local_loopback": local_loopback, + } + ) + except OSError as error: + log.error("Could not access SocketCAN device %s (%s)", channel, error) + # Clean up so the parent class doesn't complain about not being shut down properly + self.shutdown() + raise super().__init__( channel=channel, can_filters=can_filters, From 813c39bfc1bc7a05eada67eb47249659cd4ee5c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Colomb?= Date: Tue, 30 Apr 2024 15:42:23 +0200 Subject: [PATCH 2/2] Remove shutdown call and obsolete comment. --- can/interfaces/socketcan/socketcan.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/can/interfaces/socketcan/socketcan.py b/can/interfaces/socketcan/socketcan.py index c9ca732d4..c4c92dce8 100644 --- a/can/interfaces/socketcan/socketcan.py +++ b/can/interfaces/socketcan/socketcan.py @@ -716,8 +716,6 @@ def __init__( ) except OSError as error: log.error("Could not access SocketCAN device %s (%s)", channel, error) - # Clean up so the parent class doesn't complain about not being shut down properly - self.shutdown() raise super().__init__( channel=channel,