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 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. class Container(object):
  15. """Encapsulates information about a container."""
  16. def __init__(self, container_info, image_info):
  17. """Creates a new Container.
  18. Args:
  19. name (str): The name of the container.
  20. container_info (dict): Dictionary describing the container state.
  21. image_info (dict): Dictionary describing the image state.
  22. """
  23. self.args = ['-d']
  24. """The arguments passed to docker to create the container."""
  25. self.image = ''
  26. """The image that the container uses."""
  27. self.cmd = []
  28. """The command executed within the container."""
  29. self.info = container_info
  30. """The container information as returned by `docker inspect`"""
  31. self.image_info = image_info
  32. """The image information as returned by `docker inspect`"""
  33. def command_line(self):
  34. """Gets the full command-line used to run this container."""
  35. return ['docker', 'run'] + sorted(self.args) + [self.image] + self.cmd
  36. def add_args_from_list(self, template, selector):
  37. """Adds an argument for each item in a list.
  38. Args:
  39. template (str): Template to use for the argument. Use %s for value.
  40. selector (func): Function to extract the list from our info.
  41. """
  42. target = selector(self.info)
  43. if target:
  44. self.args.extend([template % entry for entry in target])
  45. def if_image_diff(self, selector, fallback):
  46. """Gets a property if it's different from the image's config.
  47. Compares the value of a property in the container's information to the
  48. same property in the image information. If the value is different then
  49. the container's version is returned, otherwise the specified fallback
  50. is returned.
  51. This is useful where the container inherits config from the image,
  52. such as the command or the user to run as. We only want to include it
  53. in the arguments if it has been explicitly changed.
  54. Args:
  55. selector (func): Function to extract the property.
  56. fallback (object): Value to return if the properties are identical.
  57. """
  58. container = selector(self.info)
  59. image = selector(self.image_info)
  60. return fallback if container == image else container
  61. def docker_inspect(target, what):
  62. """Uses `docker inspect` to get details about the given container or image.
  63. Args:
  64. target (str): The name of the container or image to inspect.
  65. what (str): The type of object to inspect ('container' or 'image').
  66. Returns:
  67. dict: Detailed information about the target.
  68. Raises:
  69. CalledProcessError: An error occurred talking to Docker.
  70. """
  71. output = subprocess.check_output(['docker', 'inspect',
  72. '--type=%s' % what, target])
  73. return json.loads(output.decode('utf-8'))[0]
  74. def handle_binds(container):
  75. """Copies the volume bind (--volume/-v) arguments."""
  76. container.add_args_from_list('--volume=%s',
  77. lambda c: c['HostConfig']['Binds'])
  78. def handle_command(container):
  79. """Copies the command (trailing arguments)."""
  80. container.cmd = container.if_image_diff(lambda c: c['Config']['Cmd'], [])
  81. def handle_environment(container):
  82. """Copies the environment (-e/--env) arguments."""
  83. container_env = set(container.info['Config']['Env'] or [])
  84. image_env = set(container.image_info['Config']['Env'] or [])
  85. delta = container_env - image_env
  86. container.args.extend(['--env=%s' % env for env in delta])
  87. def handle_image(container):
  88. """Copies the image argument."""
  89. container.image = container.info['Config']['Image']
  90. def handle_labels(container):
  91. """Copies the label (-l/--label) arguments."""
  92. container_labels = set((container.info['Config']['Labels'] or {}).items())
  93. image_labels = set((container.image_info['Config']['Labels'] or {}).items())
  94. delta = container_labels - image_labels
  95. for key, value in delta:
  96. if value:
  97. container.args.append('--label=%s=%s' % (key, value))
  98. else:
  99. container.args.append('--label=%s' % key)
  100. def handle_name(container):
  101. """Copies the name (--name) argument."""
  102. # Trim the leading / off the name. They're equivalent from docker's point
  103. # of view, but having the plain name looks nicer from a human point of view.
  104. container.args.append('--name=%s' % container.info['Name'][1:])
  105. def handle_network_mode(container):
  106. """Copies the network mode (--net) argument."""
  107. network = container.info['HostConfig']['NetworkMode']
  108. if network != 'default':
  109. container.args.append('--net=%s' % network)
  110. def handle_ports(container):
  111. """Copies the port publication (-p) arguments."""
  112. ports = container.info['HostConfig']['PortBindings']
  113. if ports:
  114. for port, bindings in ports.items():
  115. # /tcp is the default - no need to include it
  116. port_name = port[:-4] if port.endswith('/tcp') else port
  117. for binding in bindings:
  118. if binding['HostIp']:
  119. container.args.append('-p=%s:%s:%s' % (binding['HostIp'],
  120. binding['HostPort'],
  121. port_name))
  122. elif binding['HostPort']:
  123. container.args.append('-p=%s:%s' % (binding['HostPort'],
  124. port_name))
  125. else:
  126. container.args.append('-p=%s' % port_name)
  127. def handle_restart(container):
  128. """Copies the restart policy (--restart) argument."""
  129. policy = container.info['HostConfig']['RestartPolicy']
  130. if policy and policy['Name'] != 'no':
  131. arg = '--restart=%s' % policy['Name']
  132. if policy['MaximumRetryCount'] > 0:
  133. arg += ':%s' % policy['MaximumRetryCount']
  134. container.args.append(arg)
  135. def handle_user(container):
  136. """Copies the user (--user/-u) argument."""
  137. user = container.if_image_diff(lambda c: c['Config']['User'], None)
  138. if user:
  139. container.args.append('--user=%s' % user)
  140. def handle_volumes_from(container):
  141. """Copies the volumes from (--volumes-from) argument."""
  142. container.add_args_from_list('--volumes-from=%s',
  143. lambda c: c['HostConfig']['VolumesFrom'])
  144. def functions():
  145. """Lists all functions defined in this module.
  146. Returns:
  147. list of (str,function): List of (name, function) pairs for each
  148. function defined in this module.
  149. """
  150. return [m for m
  151. in inspect.getmembers(sys.modules[__name__])
  152. if inspect.isfunction(m[1])]
  153. def handlers():
  154. """Lists all handlers defined in this module.
  155. Returns:
  156. list of function: All handlers (handle_* funcs) defined in this module.
  157. """
  158. return [func for (name, func) in functions() if name.startswith('handle_')]
  159. def main():
  160. """Script entry point."""
  161. parser = argparse.ArgumentParser(description='Reruns docker containers ' \
  162. 'with different parameters.')
  163. parser.add_argument('container', type=str, help='The container to rerun')
  164. parser.add_argument('-d', '--dry-run', action='store_true',
  165. help='Don\'t actually re-run the container, just ' \
  166. 'print what would happen.')
  167. args = parser.parse_args()
  168. container_info = docker_inspect(args.container, 'container')
  169. image_info = docker_inspect(container_info['Config']['Image'], 'image')
  170. container = Container(container_info, image_info)
  171. for handler in handlers():
  172. handler(container)
  173. commands = [
  174. ['docker', 'stop', args.container],
  175. ['docker', 'rm', args.container],
  176. container.command_line(),
  177. ]
  178. if args.dry_run:
  179. print('Performing dry run for container %s. The following would be ' \
  180. 'executed:' % args.container)
  181. for command in commands:
  182. print(' '.join(command))
  183. else:
  184. print('Re-running container %s...' % args.container)
  185. for command in commands:
  186. subprocess.check_call(command)
  187. if __name__ == "__main__":
  188. main()