Utility to re-run a docker container with slightly different arguments
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

docker-rerun 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. #!/usr/bin/python3
  2. """Re-runs a docker container using the same arguments as before.
  3. Given the name of a container, the previous arguments are determined
  4. and reconstructed by looking at the `docker inspect` output.
  5. Each function named `handle_*` handles one configuration option,
  6. reading the relevant information from the inspect output and adding
  7. the relevant command line flags to the config.
  8. """
  9. import argparse
  10. import inspect
  11. import json
  12. import subprocess
  13. import sys
  14. def inspect_container(container):
  15. """Uses `docker inspect` to get details about the given container.
  16. Args:
  17. container (str): The name of the container to inspect.
  18. Returns:
  19. dict: Detailed information about the container.
  20. Raises:
  21. CalledProcessError: An error occurred talking to Docker.
  22. """
  23. output = subprocess.check_output(['docker', 'inspect',
  24. '--type=container', container])
  25. return json.loads(output.decode('utf-8'))[0]
  26. def handle_binds(container, config):
  27. """Copies the volume bind (--volume/-v) arguments."""
  28. if container['HostConfig']['Binds']:
  29. config['args'].extend(['--volume=%s' % bind
  30. for bind in container['HostConfig']['Binds']])
  31. def handle_image(container, config):
  32. """Copies the image argument."""
  33. config['image'] = container['Config']['Image']
  34. def handle_name(container, config):
  35. """Copies the name (--name) argument."""
  36. # Trim the leading / off the name. They're equivalent from docker's point
  37. # of view, but having the plain name looks nicer from a human point of view.
  38. config['args'].append('--name=%s' % container['Name'][1:])
  39. def handle_network_mode(container, config):
  40. """Copies the network mode (--net) argument."""
  41. network = container['HostConfig']['NetworkMode']
  42. if network != 'default':
  43. config['args'].append('--net=%s' % network)
  44. def handle_ports(container, config):
  45. """Copies the port publication (-p) arguments."""
  46. ports = container['HostConfig']['PortBindings']
  47. if ports:
  48. for port, bindings in ports.items():
  49. for binding in bindings:
  50. if binding['HostIp']:
  51. config['args'].append('-p=%s:%s:%s' % (binding['HostIp'],
  52. binding['HostPort'],
  53. port))
  54. elif binding['HostPort']:
  55. config['args'].append('-p=%s:%s' % (binding['HostPort'],
  56. port))
  57. else:
  58. config['args'].append('-p=%s' % port)
  59. def handle_restart(container, config):
  60. """Copies the restart policy (--restart) argument."""
  61. policy = container['HostConfig']['RestartPolicy']
  62. if policy and policy['Name'] != 'no':
  63. arg = '--restart=%s' % policy['Name']
  64. if policy['MaximumRetryCount'] > 0:
  65. arg += ':%s' % policy['MaximumRetryCount']
  66. config['args'].append(arg)
  67. def handle_volumes_from(container, config):
  68. """Copies the volumes from (--volumes-from) argument."""
  69. if container['HostConfig']['VolumesFrom']:
  70. config['args'].extend(['--volumes-from=%s' % cont for
  71. cont in container['HostConfig']['VolumesFrom']])
  72. def functions():
  73. """Lists all functions defined in this module.
  74. Returns:
  75. list of (str,function): List of (name, function) pairs for each
  76. function defined in this module.
  77. """
  78. return [m for m
  79. in inspect.getmembers(sys.modules[__name__])
  80. if inspect.isfunction(m[1])]
  81. def handlers():
  82. """Lists all handlers defined in this module.
  83. Returns:
  84. list of function: All handlers (handle_* funcs) defined in this module.
  85. """
  86. return [func for (name, func) in functions() if name.startswith('handle_')]
  87. def main():
  88. """Script entry point."""
  89. parser = argparse.ArgumentParser(description='Reruns docker containers ' \
  90. 'with different parameters.')
  91. parser.add_argument('container', type=str, help='The container to rerun')
  92. parser.add_argument('-d', '--dry-run', action='store_true',
  93. help='Don\'t actually re-run the container, just ' \
  94. 'print what would happen.')
  95. args = parser.parse_args()
  96. container = inspect_container(args.container)
  97. docker_config = {'args': ['-d'], 'image': ''}
  98. for handler in handlers():
  99. handler(container, docker_config)
  100. docker_config['args'].sort()
  101. commands = [
  102. ['docker', 'stop', args.container],
  103. ['docker', 'rm', args.container],
  104. ['docker', 'run'] + docker_config['args'] + [docker_config['image']],
  105. ]
  106. if args.dry_run:
  107. print('Performing dry run for container %s. The following would be ' \
  108. 'executed:' % args.container)
  109. for command in commands:
  110. print(' '.join(command))
  111. else:
  112. print('Re-running container %s...' % args.container)
  113. for command in commands:
  114. subprocess.check_call(command)
  115. if __name__ == "__main__":
  116. main()