Skip to content

Fix UnixHTTPConnection.connect leaking the socket on failure - #3466

Open
tony1233200 wants to merge 1 commit into
docker:mainfrom
tony1233200:fix/3464-unix-socket-leak
Open

tony1233200 wants to merge 1 commit into
docker:mainfrom
tony1233200:fix/3464-unix-socket-leak

Conversation

@tony1233200

Copy link
Copy Markdown

Fix UnixHTTPConnection.connect leaking the socket on failure

Fixes #3464

Root cause

UnixHTTPConnection.connect() in docker/transport/unixconn.py created the
AF_UNIX socket and then called sock.connect(self.unix_socket) without
closing it on failure. When the daemon socket cannot be reached (Docker not
running, wrong path), the exception propagated while the socket stayed open
until the garbage collector ran, which then emitted
ResourceWarning: unclosed <socket.socket ...>.

Fix

Wrap the settimeout/connect calls in try/except, close the socket on
any failure, then re-raise. self.sock is only assigned after a successful
connect, so a failed connection no longer leaves a half-open socket behind.

Reproduction

import gc, warnings
import docker
warnings.simplefilter("always", ResourceWarning)
try:
    docker.DockerClient(base_url="unix:///nonexistent/docker.sock")
except docker.errors.DockerException as exc:
    print("DockerException:", exc)
gc.collect()
  • Before: ResourceWarning: unclosed <socket.socket fd=3, family=1, type=1, proto=0> at gc.collect().
  • After: no leaked-socket warning; the DockerException is unchanged.

Tests

New regression tests in tests/unit/transport/test_unixconn.py:

  • test_connect_closes_socket_on_failure — fails on unfixed code (leaked
    ResourceWarning recorded), passes with the fix; also asserts conn.sock
    stays None.
  • test_connect_sets_sock_on_success — connects against a real local unix
    socket server; passes before and after.

Results: pytest tests/unit/transport/test_unixconn.py — 2 passed
(with -W error::ResourceWarning).

Full unit suite: pytest tests/unit — 607 passed, 10 skipped, 8 xfailed,
1 xpassed, 8 failed. The 8 failures are all pre-existing
TCPSocketStreamTest cases in tests/unit/api_test.py failing with
ProxyError against the sandbox egress proxy; they fail identically on
unfixed code.

Lint: ruff check docker tests (the CI lint command) is clean.


AI disclosure: this change was developed with AI assistance (Claude) and verified by running the reproduction and tests above.

Fixes docker#3464

connect() created the AF_UNIX socket and then raised from sock.connect() without closing it, leaving the socket open until the garbage collector ran (ResourceWarning: unclosed socket). Close the socket on any failure before re-raising.
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.

UnixHTTPConnection.connect leaves its socket open when the connect fails (ResourceWarning)

2 participants