Skip to content

Commit

Permalink
fix(core): Avoid hanging upon bad docker host connection (#742)
Browse files Browse the repository at this point in the history
- Shorten the socket connection timeout
- Add a timeout on waiting for logs
- Add check for host and port values
- The previous implementation _technically_ would have timed out, but
the default socket
timeout * 50 iterations is a very long time to wait.

Resolves #741

---------

Co-authored-by: David Ankin <[email protected]>
  • Loading branch information
mmwinther and alexanderankin authored Nov 25, 2024
1 parent 932ee30 commit 4ced198
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
10 changes: 8 additions & 2 deletions core/testcontainers/core/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from testcontainers.core.config import ConnectionMode
from testcontainers.core.config import testcontainers_config as c
from testcontainers.core.docker_client import DockerClient
from testcontainers.core.exceptions import ContainerStartException
from testcontainers.core.exceptions import ContainerConnectException, ContainerStartException
from testcontainers.core.labels import LABEL_SESSION_ID, SESSION_ID
from testcontainers.core.network import Network
from testcontainers.core.utils import is_arm, setup_logger
Expand Down Expand Up @@ -228,15 +228,21 @@ def _create_instance(cls) -> "Reaper":
.with_env("RYUK_RECONNECTION_TIMEOUT", c.ryuk_reconnection_timeout)
.start()
)
wait_for_logs(Reaper._container, r".* Started!")
wait_for_logs(Reaper._container, r".* Started!", timeout=20, raise_on_exit=True)

container_host = Reaper._container.get_container_host_ip()
container_port = int(Reaper._container.get_exposed_port(8080))

if not container_host or not container_port:
raise ContainerConnectException(
f"Could not obtain network details for {Reaper._container._container.id}. Host: {container_host} Port: {container_port}"
)

last_connection_exception: Optional[Exception] = None
for _ in range(50):
try:
Reaper._socket = socket()
Reaper._socket.settimeout(1)
Reaper._socket.connect((container_host, container_port))
last_connection_exception = None
break
Expand Down
4 changes: 4 additions & 0 deletions core/testcontainers/core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ class ContainerStartException(RuntimeError):
pass


class ContainerConnectException(RuntimeError):
pass


class ContainerIsNotRunning(RuntimeError):
pass

Expand Down

0 comments on commit 4ced198

Please sign in to comment.