Skip to content

Commit 4ced198

Browse files
fix(core): Avoid hanging upon bad docker host connection (#742)
- 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]>
1 parent 932ee30 commit 4ced198

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

core/testcontainers/core/container.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from testcontainers.core.config import ConnectionMode
1313
from testcontainers.core.config import testcontainers_config as c
1414
from testcontainers.core.docker_client import DockerClient
15-
from testcontainers.core.exceptions import ContainerStartException
15+
from testcontainers.core.exceptions import ContainerConnectException, ContainerStartException
1616
from testcontainers.core.labels import LABEL_SESSION_ID, SESSION_ID
1717
from testcontainers.core.network import Network
1818
from testcontainers.core.utils import is_arm, setup_logger
@@ -228,15 +228,21 @@ def _create_instance(cls) -> "Reaper":
228228
.with_env("RYUK_RECONNECTION_TIMEOUT", c.ryuk_reconnection_timeout)
229229
.start()
230230
)
231-
wait_for_logs(Reaper._container, r".* Started!")
231+
wait_for_logs(Reaper._container, r".* Started!", timeout=20, raise_on_exit=True)
232232

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

236+
if not container_host or not container_port:
237+
raise ContainerConnectException(
238+
f"Could not obtain network details for {Reaper._container._container.id}. Host: {container_host} Port: {container_port}"
239+
)
240+
236241
last_connection_exception: Optional[Exception] = None
237242
for _ in range(50):
238243
try:
239244
Reaper._socket = socket()
245+
Reaper._socket.settimeout(1)
240246
Reaper._socket.connect((container_host, container_port))
241247
last_connection_exception = None
242248
break

core/testcontainers/core/exceptions.py

+4
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ class ContainerStartException(RuntimeError):
1616
pass
1717

1818

19+
class ContainerConnectException(RuntimeError):
20+
pass
21+
22+
1923
class ContainerIsNotRunning(RuntimeError):
2024
pass
2125

0 commit comments

Comments
 (0)