|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +""" |
| 4 | + docker-wait-any |
| 5 | +
|
| 6 | + This script takes one or more Docker container names as arguments, |
| 7 | + and it will block indefinitely while all of the specified containers |
| 8 | + are running. If any of the specified containers stop, the script will |
| 9 | + exit. |
| 10 | +
|
| 11 | + This script was created because the 'docker wait' command is lacking |
| 12 | + this functionality. It will block until ALL specified containers have |
| 13 | + stopped running. Here, we spawn multiple threads and wait on one |
| 14 | + container per thread. If any of the threads exit, the entire |
| 15 | + application will exit. |
| 16 | +
|
| 17 | + NOTE: This script is written against docker-py version 1.6.0. Newer |
| 18 | + versions of docker-py have a different API. |
| 19 | +""" |
| 20 | + |
| 21 | +import sys |
| 22 | +import threading |
| 23 | +from docker import Client |
| 24 | + |
| 25 | +# Instantiate a global event to share among our threads |
| 26 | +g_thread_exit_event = threading.Event() |
| 27 | + |
| 28 | + |
| 29 | +def usage(): |
| 30 | + print("Usage: {} <container_name> [<container_name> ...]".format(sys.argv[0])) |
| 31 | + sys.exit(1) |
| 32 | + |
| 33 | + |
| 34 | +def wait_for_container(docker_client, container_name): |
| 35 | + docker_client.wait(container_name) |
| 36 | + |
| 37 | + print("No longer waiting on container '{}'".format(container_name)) |
| 38 | + |
| 39 | + # Signal the main thread to exit |
| 40 | + g_thread_exit_event.set() |
| 41 | + |
| 42 | + |
| 43 | +def main(): |
| 44 | + thread_list = [] |
| 45 | + |
| 46 | + docker_client = Client(base_url='unix://var/run/docker.sock') |
| 47 | + |
| 48 | + # Ensure we were passed at least one argument |
| 49 | + if len(sys.argv) < 2: |
| 50 | + usage() |
| 51 | + |
| 52 | + container_names = sys.argv[1:] |
| 53 | + |
| 54 | + for container_name in container_names: |
| 55 | + t = threading.Thread(target=wait_for_container, args=[docker_client, container_name]) |
| 56 | + t.daemon = True |
| 57 | + t.start() |
| 58 | + thread_list.append(t) |
| 59 | + |
| 60 | + # Wait until we receive an event signifying one of the containers has stopped |
| 61 | + g_thread_exit_event.wait() |
| 62 | + sys.exit(0) |
| 63 | + |
| 64 | +if __name__ == '__main__': |
| 65 | + main() |
0 commit comments