Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup socket on connection error/timeout #346

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

kurt-cb
Copy link

@kurt-cb kurt-cb commented Jun 16, 2022

When constructing a connection to a server, and the server is not responsive, the socket is not closed in a timely fashion and can cause a secondary exception when cleaning up in the exception handler due to the resource leak. This is

ConnectionError: ("Error connecting to host '%s:%s' - %s - retry %s/%s", 'kg-meter2', 22, 'timed out', 3, 3)
E
E During handling of the above exception, another exception occurred:
E
E Traceback (most recent call last):
E File "/home/kgodwin/.local/lib/python3.8/site-packages/_pytest/unraisableexception.py", line 43, in _hook
E self.unraisable = unraisable
E ResourceWarning: unclosed <socket object, fd=23, family=2, type=1, proto=0>

@@ -302,8 +302,12 @@ def _connect_socket(self, family, _type, proto, sock_addr, host, port, retries):
try:
self.sock.connect(sock_addr)
except ConnectionRefusedError:
self.sock.shutdown(socket.SHUT_RDWR)
Copy link
Member

@pkittenis pkittenis Aug 5, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
self.sock.shutdown(socket.SHUT_RDWR)
if not self.sock.closed:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()

Otherwise will get test failures for already closed sockets - see test failures. Might also want to split the above block to an internal function, since same thing is needed below.

raise
except sock_error as ex:
self.sock.shutdown(socket.SHUT_RDWR)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also needs a check that self.sock is not already closed - as above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants