Skip to content

Commit

Permalink
fix DinD host detection when using local socket
Browse files Browse the repository at this point in the history
When using IPC socket (unix/npipe) to communicate with local docker
server docker-py implementation rewrites the base url to HTTP, see
https://github.com/docker/docker-py/blob/e901eac7a8c5f29c7720eafb9f58c8356cca2324/docker/api/client.py#L143-L168

We cannot rely on URL scheme in order to detect such connections.
Instead, we detect connection adapters added by docker-py api client:

- UnixHTTPAdapter
  https://github.com/docker/docker-py/blob/e901eac7a8c5f29c7720eafb9f58c8356cca2324/docker/transport/unixconn.py

- NpipeHTTPAdapter
  https://github.com/docker/docker-py/blob/e901eac7a8c5f29c7720eafb9f58c8356cca2324/docker/transport/npipeconn.py

As NpipeHTTPAdapter type may not be available outside of Windows we rely on
adapter-specific attributes.
  • Loading branch information
ikravets committed Jan 1, 2023
1 parent 31af452 commit afa057e
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions testcontainers/core/docker_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import urllib
import docker
from docker.models.containers import Container
from docker.transport import UnixHTTPAdapter
from testcontainers.core.utils import inside_container
from testcontainers.core.utils import default_gateway_ip

Expand Down Expand Up @@ -72,11 +73,14 @@ def host(self):

except ValueError:
return None
adapter = self.client.api.get_adapter(self.client.api.base_url)
is_ipc = isinstance(adapter, UnixHTTPAdapter)
is_ipc |= hasattr(adapter, "socket_path") or hasattr(adapter, "npipe_path")
is_ipc |= 'unix' in url.scheme or 'npipe' in url.scheme
if is_ipc and inside_container():
ip_address = default_gateway_ip()
if ip_address:
return ip_address
if 'http' in url.scheme or 'tcp' in url.scheme:
return url.hostname
if 'unix' in url.scheme or 'npipe' in url.scheme:
if inside_container():
ip_address = default_gateway_ip()
if ip_address:
return ip_address
return "localhost"

0 comments on commit afa057e

Please sign in to comment.