#!/usr/bin/python3 """Re-runs a docker container using the same arguments as before. Given the name of a container, the previous arguments are determined and reconstructed by looking at the `docker inspect` output. Each function named `handle_*` handles one configuration option, reading the relevant information from the inspect output and adding the relevant command line flags to the config. """ import argparse import inspect import json import subprocess import sys class Container(object): """Encapsulates information about a container.""" def __init__(self, name, container_info, image_info): """Creates a new Container. Args: name (str): The name of the container. container_info (dict): Dictionary describing the container state. image_info (dict): Dictionary describing the image state. """ self.args = ['--name=%s' % name] """The arguments passed to docker to create the container.""" self.image = '' """The image that the container uses.""" self.cmd = [] """The command executed within the container.""" self.info = container_info """The container information as returned by `docker inspect`""" self.image_info = image_info """The image information as returned by `docker inspect`""" def command_line(self): """Gets the full command-line used to run this container.""" return ['docker', 'run'] + sorted(self.args) + [self.image] + self.cmd def add_args_from_list(self, template, selector): """Adds an argument for each item in a list. Args: template (str): Template to use for the argument. Use %s for value. selector (func): Function to extract the list from our info. """ target = selector(self.info) if target: self.args.extend([template % entry for entry in target]) def docker_inspect(target, what): """Uses `docker inspect` to get details about the given container or image. Args: target (str): The name of the container or image to inspect. what (str): The type of object to inspect ('container' or 'image'). Returns: dict: Detailed information about the target. Raises: CalledProcessError: An error occurred talking to Docker. """ output = subprocess.check_output(['docker', 'inspect', '--type=%s' % what, target]) return json.loads(output.decode('utf-8'))[0] def handle_binds(container, config): """Copies the volume bind (--volume/-v) arguments.""" if container['HostConfig']['Binds']: config['args'].extend(['--volume=%s' % bind for bind in container['HostConfig']['Binds']]) def handle_image(container, config): """Copies the image argument.""" config['image'] = container['Config']['Image'] def handle_name(container, config): """Copies the name (--name) argument.""" # Trim the leading / off the name. They're equivalent from docker's point # of view, but having the plain name looks nicer from a human point of view. config['args'].append('--name=%s' % container['Name'][1:]) def handle_network_mode(container, config): """Copies the network mode (--net) argument.""" network = container['HostConfig']['NetworkMode'] if network != 'default': config['args'].append('--net=%s' % network) def handle_ports(container, config): """Copies the port publication (-p) arguments.""" ports = container['HostConfig']['PortBindings'] if ports: for port, bindings in ports.items(): for binding in bindings: if binding['HostIp']: config['args'].append('-p=%s:%s:%s' % (binding['HostIp'], binding['HostPort'], port)) elif binding['HostPort']: config['args'].append('-p=%s:%s' % (binding['HostPort'], port)) else: config['args'].append('-p=%s' % port) def handle_restart(container, config): """Copies the restart policy (--restart) argument.""" policy = container['HostConfig']['RestartPolicy'] if policy and policy['Name'] != 'no': arg = '--restart=%s' % policy['Name'] if policy['MaximumRetryCount'] > 0: arg += ':%s' % policy['MaximumRetryCount'] config['args'].append(arg) def handle_volumes_from(container, config): """Copies the volumes from (--volumes-from) argument.""" if container['HostConfig']['VolumesFrom']: config['args'].extend(['--volumes-from=%s' % cont for cont in container['HostConfig']['VolumesFrom']]) def functions(): """Lists all functions defined in this module. Returns: list of (str,function): List of (name, function) pairs for each function defined in this module. """ return [m for m in inspect.getmembers(sys.modules[__name__]) if inspect.isfunction(m[1])] def handlers(): """Lists all handlers defined in this module. Returns: list of function: All handlers (handle_* funcs) defined in this module. """ return [func for (name, func) in functions() if name.startswith('handle_')] def main(): """Script entry point.""" parser = argparse.ArgumentParser(description='Reruns docker containers ' \ 'with different parameters.') parser.add_argument('container', type=str, help='The container to rerun') parser.add_argument('-d', '--dry-run', action='store_true', help='Don\'t actually re-run the container, just ' \ 'print what would happen.') args = parser.parse_args() container = docker_inspect(args.container, 'container') docker_config = {'args': ['-d'], 'image': ''} for handler in handlers(): handler(container, docker_config) docker_config['args'].sort() commands = [ ['docker', 'stop', args.container], ['docker', 'rm', args.container], ['docker', 'run'] + docker_config['args'] + [docker_config['image']], ] if args.dry_run: print('Performing dry run for container %s. The following would be ' \ 'executed:' % args.container) for command in commands: print(' '.join(command)) else: print('Re-running container %s...' % args.container) for command in commands: subprocess.check_call(command) if __name__ == "__main__": main()