Skip to content

Commit 9c878a2

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 9c878a2

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

docker/models/containers.py

+18-1
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'):

0 commit comments

Comments
 (0)