Skip to content

Commit 6fc2b9a

Browse files
author
hugues de keyzer
committed
fix waiting for auto_remove container
use the same logic as the cli to wait for the exit of a container when running one: ensure that a container run with auto_remove set to True has been removed when the function returns. this prevents a race condition when trying to run another container with the same name directly afterwards. signed-off-by: hugues de keyzer <[email protected]>
1 parent db7f8b8 commit 6fc2b9a

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

docker/models/containers.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -894,7 +894,24 @@ def run(self, image, command=None, stdout=True, stderr=False,
894894
stdout=stdout, stderr=stderr, stream=True, follow=True
895895
)
896896

897-
exit_status = container.wait()['StatusCode']
897+
if kwargs.get('auto_remove'):
898+
wait_condition = 'removed'
899+
else:
900+
# the wait condition should theoretically be 'next-exit' (as is
901+
# used by the cli), but it may have exited already if its run time
902+
# was very short, which would cause the wait to hang.
903+
# 'not-running' works in both cases.
904+
wait_condition = 'not-running'
905+
try:
906+
exit_status = container.wait(condition=wait_condition)['StatusCode']
907+
except NotFound:
908+
if wait_condition == 'removed':
909+
# it has been already removed, which is why it was not found,
910+
# so everything fine here. unfortunately, there is no way to
911+
# have its real exit status, so assume success.
912+
exit_status = 0
913+
else:
914+
raise
898915
if exit_status != 0:
899916
out = None
900917
if not kwargs.get('auto_remove'):

tests/unit/models_containers_test.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@ def test_run(self):
2727
)
2828
client.api.inspect_container.assert_called_with(FAKE_CONTAINER_ID)
2929
client.api.start.assert_called_with(FAKE_CONTAINER_ID)
30-
client.api.wait.assert_called_with(FAKE_CONTAINER_ID)
30+
client.api.wait.assert_called_with(
31+
FAKE_CONTAINER_ID, condition='not-running'
32+
)
3133
client.api.logs.assert_called_with(
3234
FAKE_CONTAINER_ID, stderr=False, stdout=True, stream=True,
3335
follow=True

0 commit comments

Comments
 (0)