text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Updates instances from a container configuration. Typically this means restarting or recreating containers based <END_TASK> <USER_TASK:> Description: def update(self, container, instances=None, map_name=None, **kwargs): """ Updates instances from a container configuration. Typically this means restarting or recreating containers based on detected changes in the configuration or environment. Note that not all policy classes necessarily implement this method. :param container: Container name. :type container: unicode | str :param instances: Instance names to remove. If not specified, will remove all instances as specified in the configuration (or just one default instance). :type instances: collections.Iterable[unicode | str | NoneType] :param map_name: Container map name. Optional - if not provided the default map is used. :type map_name: unicode | str :param kwargs: Additional kwargs. Only options controlling policy behavior are considered. :return: Return values of actions. :rtype: list[dockermap.map.runner.ActionOutput] """
return self.run_actions('update', container, instances=instances, map_name=map_name, **kwargs)
<SYSTEM_TASK:> Generic function for running container actions based on a policy. <END_TASK> <USER_TASK:> Description: def call(self, action_name, container, instances=None, map_name=None, **kwargs): """ Generic function for running container actions based on a policy. :param action_name: Action name. :type action_name: unicode | str :param container: Container name. :type container: unicode | str :param instances: Instance names to remove. If not specified, runs on all instances as specified in the configuration (or just one default instance). :type instances: collections.Iterable[unicode | str | NoneType] :param map_name: Container map name. Optional - if not provided the default map is used. :type map_name: unicode | str :param kwargs: Additional kwargs for the policy method. :return: Return values of actions. :rtype: list[dockermap.map.runner.ActionOutput] """
return self.run_actions(action_name, container, instances=instances, map_name=map_name, **kwargs)
<SYSTEM_TASK:> Pulls images for container configurations along their dependency path. <END_TASK> <USER_TASK:> Description: def pull_images(self, container, instances=None, map_name=None, **kwargs): """ Pulls images for container configurations along their dependency path. :param container: Container configuration name. :type container: unicode | str :param map_name: Container map name. :type map_name: unicode | str :param instances: Not applicable for images. :type instances: unicode | str :param kwargs: Keyword arguments to the script runner function. :return: Return values of actions. :rtype: list[dockermap.map.runner.ActionOutput] """
return self.run_actions('pull_images', container, map_name=map_name, **kwargs)
<SYSTEM_TASK:> Lists the names of all persistent containers on the specified map or all maps. Attached containers are always <END_TASK> <USER_TASK:> Description: def list_persistent_containers(self, map_name=None): """ Lists the names of all persistent containers on the specified map or all maps. Attached containers are always considered persistent. :param map_name: Container map name. Optional, only returns persistent containers from the specified map. :type map_name: unicode | str :return: List of container names. :rtype: list[unicode | str] """
if map_name: maps = [self._maps[map_name].get_extended_map()] else: maps = [m.get_extended_map() for m in self._maps.values()] cname_func = self.policy_class.cname aname_func = self.policy_class.aname c_names = [] for c_map in maps: m_name = c_map.name attached, persistent = c_map.get_persistent_items() if c_map.use_attached_parent_name: c_names.extend([aname_func(m_name, ca, c_name) for c_name, ca in attached]) else: c_names.extend([aname_func(m_name, ca[1]) for ca in attached]) c_names.extend([cname_func(m_name, c_name, ci) for c_name, ci in persistent]) return c_names
<SYSTEM_TASK:> Decorator for simple REST endpoints. <END_TASK> <USER_TASK:> Description: def rest(f): """Decorator for simple REST endpoints. Functions must return one of these values: - a dict to jsonify - nothing for an empty 204 response - a tuple containing a status code and a dict to jsonify """
@wraps(f) def wrapper(*args, **kwargs): ret = f(*args, **kwargs) if ret is None: response = '', 204 elif isinstance(ret, current_app.response_class): response = ret elif isinstance(ret, tuple): # code, result_dict|msg_string if isinstance(ret[1], basestring): response = jsonify(msg=ret[1]) else: response = jsonify(**ret[1]) response.status_code = ret[0] else: response = jsonify(**ret) return response return wrapper
<SYSTEM_TASK:> Logs in to a Docker registry. <END_TASK> <USER_TASK:> Description: def login(self, action, registry, **kwargs): """ Logs in to a Docker registry. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param registry: Name of the registry server to login to. :type registry: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict """
log.info("Logging into registry %s.", registry) login_kwargs = {'registry': registry} auth_config = action.client_config.auth_configs.get(registry) if auth_config: log.debug("Registry auth config for %s found.", registry) login_kwargs.update(auth_config) insecure_registry = kwargs.get('insecure_registry') if insecure_registry is not None: login_kwargs['insecure_registry'] = insecure_registry else: raise KeyError("No login information found for registry.", registry) update_kwargs(login_kwargs, kwargs) res = action.client.login(**login_kwargs) if res: log.debug("User %(username)s logged into %(registry)s.", login_kwargs) self._login_registries.add(registry) return res
<SYSTEM_TASK:> Pulls an image for a container configuration <END_TASK> <USER_TASK:> Description: def pull(self, action, image_name, **kwargs): """ Pulls an image for a container configuration :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param image_name: Image name. :type image_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict """
config_id = action.config_id registry, __, image = config_id.config_name.rpartition('/') if registry and '.' in registry and registry not in self._login_registries: self.login(action, registry, insecure_registry=kwargs.get('insecure_registry')) log.info("Pulling image %s:%s.", config_id.config_name, config_id.instance_name) res = action.client.pull(repository=config_id.config_name, tag=config_id.instance_name, **kwargs) log.debug("Done pulling image %s:%s.", config_id.config_name, config_id.instance_name) self._policy.images[action.client_name].refresh_repo(config_id.config_name) log.debug("Refreshed image cache for repo %s.", config_id.config_name) return res
<SYSTEM_TASK:> Parses the output of the Docker CLI 'docker network ls' and returns it in the format similar to the Docker API. <END_TASK> <USER_TASK:> Description: def parse_networks_output(out): """ Parses the output of the Docker CLI 'docker network ls' and returns it in the format similar to the Docker API. :param out: CLI output. :type out: unicode | str :return: Parsed result. :rtype: list[dict] """
if not out: return [] line_iter = islice(out.splitlines(), 1, None) # Skip header return list(map(_network_info, line_iter))
<SYSTEM_TASK:> Parses the output of the Docker CLI 'docker volume ls' and returns it in the format similar to the Docker API. <END_TASK> <USER_TASK:> Description: def parse_volumes_output(out): """ Parses the output of the Docker CLI 'docker volume ls' and returns it in the format similar to the Docker API. :param out: CLI output. :type out: unicode | str :return: Parsed result. :rtype: list[dict] """
if not out: return [] line_iter = islice(out.splitlines(), 1, None) # Skip header return list(map(_volume_info, line_iter))
<SYSTEM_TASK:> Parses the output of the Docker CLI 'docker images'. Note this is currently incomplete and only returns the ids and <END_TASK> <USER_TASK:> Description: def parse_images_output(out): """ Parses the output of the Docker CLI 'docker images'. Note this is currently incomplete and only returns the ids and tags of images, as the Docker CLI heavily modifies the output for human readability. The parent image id is also not available on the CLI, so a full API compatibility is not possible. :param out: CLI output. :type out: unicode | str :return: Parsed result. :rtype: list[dict] """
line_iter = islice(out.splitlines(), 1, None) # Skip header split_lines = (line.split() for line in line_iter) return [ _summarize_tags(image_id, image_lines) for image_id, image_lines in groupby(sorted(split_lines, key=_get_image_id), key=_get_image_id) ]
<SYSTEM_TASK:> Fetches image and their ids from the client. <END_TASK> <USER_TASK:> Description: def refresh(self): """ Fetches image and their ids from the client. """
if not self._client: return current_images = self._client.images() self.clear() self._update(current_images) for image in current_images: tags = image.get('RepoTags') if tags: self.update({tag: image['Id'] for tag in tags})
<SYSTEM_TASK:> Fetches all current container names from the client, along with their id. <END_TASK> <USER_TASK:> Description: def refresh(self): """ Fetches all current container names from the client, along with their id. """
if not self._client: return current_containers = self._client.containers(all=True) self.clear() for container in current_containers: container_names = container.get('Names') if container_names: c_id = container['Id'] self.update((name[1:], c_id) for name in container_names)
<SYSTEM_TASK:> Fetches all current network names from the client, along with their id. <END_TASK> <USER_TASK:> Description: def refresh(self): """ Fetches all current network names from the client, along with their id. """
if not self._client: return current_networks = self._client.networks() self.clear() self.update((net['Name'], net['Id']) for net in current_networks)
<SYSTEM_TASK:> Fetches all current network names from the client. <END_TASK> <USER_TASK:> Description: def refresh(self): """ Fetches all current network names from the client. """
if not self._client: return current_volumes = self._client.volumes()['Volumes'] self.clear() if current_volumes: self.update(vol['Name'] for vol in current_volumes)
<SYSTEM_TASK:> Forces a refresh of a cached item. <END_TASK> <USER_TASK:> Description: def refresh(self, item): """ Forces a refresh of a cached item. :param item: Client name. :type item: unicode | str :return: Items in the cache. :rtype: DockerHostItemCache.item_class """
client = self._clients[item].get_client() self[item] = val = self.item_class(client) return val
<SYSTEM_TASK:> Generates a tuple of the full image name and tag, that should be used when creating a new container. <END_TASK> <USER_TASK:> Description: def get_image(self, image): """ Generates a tuple of the full image name and tag, that should be used when creating a new container. This implementation applies the following rules: * If the image name starts with ``/``, the following image name is returned. * If ``/`` is found anywhere else in the image name, it is assumed to be a repository-prefixed image and returned as it is. * Otherwise, if the given container map has a repository prefix set, this is prepended to the image name. * In any other case, the image name is not modified. Where there is a tag included in the ``image`` name, it is not modified. If it is not, the default tag from the container map, or ``latest`` is used. :param image: Image name. :type image: unicode | str :return: Image name, where applicable prefixed with a repository, and tag. :rtype: (unicode | str, unicode | str) """
name, __, tag = image.rpartition(':') if not name: name, tag = tag, name if '/' in name: if name[0] == '/': repo_name = name[1:] else: repo_name = name else: default_prefix = resolve_value(self.repository) if default_prefix: repo_name = '{0}/{1}'.format(default_prefix, name) else: repo_name = name if tag: return repo_name, tag default_tag = resolve_value(self.default_tag) return repo_name, default_tag or 'latest'
<SYSTEM_TASK:> Generates a configuration that includes all inherited values. <END_TASK> <USER_TASK:> Description: def get_extended(self, config): """ Generates a configuration that includes all inherited values. :param config: Container configuration. :type config: ContainerConfiguration :return: A merged (shallow) copy of all inherited configurations merged with the container configuration. :rtype: ContainerConfiguration """
if not config.extends or self._extended: return config extended_config = ContainerConfiguration() for ext_name in config.extends: ext_cfg_base = self._containers.get(ext_name) if not ext_cfg_base: raise KeyError(ext_name) ext_cfg = self.get_extended(ext_cfg_base) extended_config.merge_from_obj(ext_cfg) extended_config.merge_from_obj(config) return extended_config
<SYSTEM_TASK:> Creates a copy of this map which includes all non-abstract configurations in their extended form. <END_TASK> <USER_TASK:> Description: def get_extended_map(self): """ Creates a copy of this map which includes all non-abstract configurations in their extended form. :return: Copy of this map. :rtype: ContainerMap """
map_copy = self.__class__(self.name) map_copy.update_from_obj(self, copy=True, update_containers=False) for c_name, c_config in self: map_copy._containers[c_name] = self.get_extended(c_config) map_copy._extended = True return map_copy
<SYSTEM_TASK:> Creates all missing containers, networks, and volumes. <END_TASK> <USER_TASK:> Description: def get_state_actions(self, state, **kwargs): """ Creates all missing containers, networks, and volumes. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :rtype: list[dockermap.map.action.ItemAction] """
if state.base_state == State.ABSENT: if state.config_id.config_type == ItemType.IMAGE: return [ItemAction(state, ImageAction.PULL)] actions = [ItemAction(state, Action.CREATE, extra_data=kwargs)] if state.config_id.config_type == ItemType.CONTAINER: actions.append(ItemAction(state, ContainerUtilAction.CONNECT_ALL)) return actions
<SYSTEM_TASK:> Generally starts containers that are not running. Attached containers are skipped unless they are initial. <END_TASK> <USER_TASK:> Description: def get_state_actions(self, state, **kwargs): """ Generally starts containers that are not running. Attached containers are skipped unless they are initial. Attached containers are also prepared with permissions. Where applicable, exec commands are run in started instance containers. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :rtype: list[dockermap.map.action.ItemAction] """
config_type = state.config_id.config_type if (config_type == ItemType.VOLUME and state.base_state == State.PRESENT and state.state_flags & StateFlags.INITIAL): return [ ItemAction(state, Action.START), ItemAction(state, VolumeUtilAction.PREPARE), ] elif config_type == ItemType.CONTAINER and state.base_state == State.PRESENT: return [ ItemAction(state, Action.START, extra_data=kwargs), ItemAction(state, ContainerUtilAction.EXEC_ALL), ]
<SYSTEM_TASK:> Restarts instance containers. <END_TASK> <USER_TASK:> Description: def get_state_actions(self, state, **kwargs): """ Restarts instance containers. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :rtype: list[dockermap.map.action.ItemAction] """
if (state.config_id.config_type == ItemType.CONTAINER and state.base_state != State.ABSENT and not state.state_flags & StateFlags.INITIAL): actions = [ItemAction(state, DerivedAction.RESTART_CONTAINER, extra_data=kwargs)] if self.restart_exec_commands: actions.append(ItemAction(state, ContainerUtilAction.EXEC_ALL, extra_data=kwargs)) return actions
<SYSTEM_TASK:> Stops containers that are running. Does not check attached containers. Considers using the pre-configured <END_TASK> <USER_TASK:> Description: def get_state_actions(self, state, **kwargs): """ Stops containers that are running. Does not check attached containers. Considers using the pre-configured ``stop_signal``. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :rtype: list[dockermap.map.action.ItemAction] """
if (state.config_id.config_type == ItemType.CONTAINER and state.base_state != State.ABSENT and not state.state_flags & StateFlags.INITIAL): return [ItemAction(state, ContainerUtilAction.SIGNAL_STOP, extra_data=kwargs)]
<SYSTEM_TASK:> Removes containers that are stopped. Optionally skips persistent containers. Attached containers are skipped <END_TASK> <USER_TASK:> Description: def get_state_actions(self, state, **kwargs): """ Removes containers that are stopped. Optionally skips persistent containers. Attached containers are skipped by default from removal but can optionally be included. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :rtype: list[dockermap.map.action.ItemAction] """
config_type = state.config_id.config_type if config_type == ItemType.CONTAINER: extra_data = kwargs else: extra_data = None if state.base_state == State.PRESENT: if ((config_type == ItemType.VOLUME and self.remove_attached) or (config_type == ItemType.CONTAINER and self.remove_persistent or not state.state_flags & StateFlags.PERSISTENT)): return [ItemAction(state, Action.REMOVE, extra_data=extra_data)] elif config_type == ItemType.NETWORK: connected_containers = state.extra_data.get('containers') if connected_containers: actions = [ItemAction(state, NetworkUtilAction.DISCONNECT_ALL, {'containers': connected_containers})] else: actions = [] actions.append(ItemAction(state, Action.REMOVE, extra_data=kwargs)) return actions
<SYSTEM_TASK:> A combination of CreateActionGenerator and StartActionGenerator - creates and starts containers where <END_TASK> <USER_TASK:> Description: def get_state_actions(self, state, **kwargs): """ A combination of CreateActionGenerator and StartActionGenerator - creates and starts containers where appropriate. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :rtype: list[dockermap.map.action.ItemAction] """
config_type = state.config_id.config_type if config_type == ItemType.VOLUME: if state.base_state == State.ABSENT: return [ ItemAction(state, Action.CREATE), ItemAction(state, VolumeUtilAction.PREPARE), ] elif state.base_state == State.PRESENT and state.state_flags & StateFlags.INITIAL: return [ ItemAction(state, Action.START), ItemAction(state, VolumeUtilAction.PREPARE), ] elif config_type == ItemType.CONTAINER: if state.base_state == State.ABSENT: return [ ItemAction(state, DerivedAction.STARTUP_CONTAINER), ItemAction(state, ContainerUtilAction.EXEC_ALL), ] elif state.base_state == State.PRESENT: return [ ItemAction(state, Action.START), ItemAction(state, ContainerUtilAction.EXEC_ALL), ] else: if config_type == ItemType.NETWORK: return [ItemAction(state, Action.CREATE)] elif config_type == ItemType.IMAGE: return [ItemAction(state, ImageAction.PULL)]
<SYSTEM_TASK:> A combination of StopActionGenerator and RemoveActionGenerator - stops and removes containers where <END_TASK> <USER_TASK:> Description: def get_state_actions(self, state, **kwargs): """ A combination of StopActionGenerator and RemoveActionGenerator - stops and removes containers where appropriate. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :rtype: list[dockermap.map.action.ItemAction] """
config_type = state.config_id.config_type if config_type == ItemType.NETWORK: if state.base_state == State.PRESENT: connected_containers = state.extra_data.get('containers') if connected_containers: cc_names = [c.get('Name', c['Id']) for c in connected_containers] actions = [ItemAction(state, NetworkUtilAction.DISCONNECT_ALL, extra_data={'containers': cc_names})] else: actions = [] actions.append(ItemAction(state, Action.REMOVE, extra_data=kwargs)) return actions elif config_type == ItemType.VOLUME and self.remove_attached: return [ItemAction(state, Action.REMOVE)] elif config_type == ItemType.CONTAINER: if self.remove_persistent or not state.state_flags & StateFlags.PERSISTENT: if state.base_state == State.RUNNING or state.state_flags & StateFlags.RESTARTING: return [ItemAction(state, DerivedAction.SHUTDOWN_CONTAINER)] elif state.base_state == State.PRESENT: return [ItemAction(state, Action.REMOVE)] elif state.base_state == State.RUNNING or state.state_flags & StateFlags.RESTARTING: return [ItemAction(state, Action.REMOVE)]
<SYSTEM_TASK:> Sends kill signals to running containers. <END_TASK> <USER_TASK:> Description: def get_state_actions(self, state, **kwargs): """ Sends kill signals to running containers. :param state: Configuration state. :type state: dockermap.map.state.ConfigState :param kwargs: Additional keyword arguments. :return: Actions on the client, map, and configurations. :rtype: list[dockermap.map.action.ItemAction] """
if state.config_id.config_type == ItemType.CONTAINER and state.base_state == State.RUNNING: return [ItemAction(state, Action.KILL, extra_data=kwargs)]
<SYSTEM_TASK:> Return target paths where the package content should be installed <END_TASK> <USER_TASK:> Description: def get_distribution_paths(name): """Return target paths where the package content should be installed"""
pyver = 'python' + sys.version[:3] paths = { 'prefix' : '{prefix}', 'data' : '{prefix}/lib/{pyver}/site-packages', 'purelib': '{prefix}/lib/{pyver}/site-packages', 'platlib': '{prefix}/lib/{pyver}/site-packages', 'headers': '{prefix}/include/{pyver}/{name}', 'scripts': '{prefix}/bin', } # pip uses a similar path as an alternative to the system's (read-only) # include directory: if hasattr(sys, 'real_prefix'): # virtualenv paths['headers'] = os.path.abspath( os.path.join(sys.prefix, 'include', 'site', pyver, name)) # Replacing vars for key, val in paths.items(): paths[key] = val.format(prefix=PREFIX, name=name, pyver=pyver) return paths
<SYSTEM_TASK:> Decodes the JSON response, simply ignoring syntax errors. Therefore it should be used for filtering visible output <END_TASK> <USER_TASK:> Description: def parse_response(response): """ Decodes the JSON response, simply ignoring syntax errors. Therefore it should be used for filtering visible output only. :param response: Server response as a JSON string. :type response: unicode | str :return: Decoded object from the JSON string. Returns an empty dictionary if input was invalid. :rtype: dict """
if isinstance(response, six.binary_type): response = response.decode('utf-8') try: obj = json.loads(response) except ValueError: return {} return obj
<SYSTEM_TASK:> Login to a Docker registry server. <END_TASK> <USER_TASK:> Description: def login(self, username, password=None, email=None, registry=None, reauth=False, **kwargs): """ Login to a Docker registry server. :param username: User name for login. :type username: unicode | str :param password: Login password; may be ``None`` if blank. :type password: unicode | str :param email: Optional; email address for login. :type email: unicode | str :param registry: Optional registry URL to log in to. Uses the Docker index by default. :type registry: unicode | str :param reauth: Re-authenticate, even if the login has been successful before. :type reauth: bool :param kwargs: Additional kwargs to :meth:`docker.client.Client.login`. :return: ``True`` if the login has succeeded, or if it has not been necessary as it succeeded before. ``False`` otherwise. :rtype: bool """
response = super(DockerClientWrapper, self).login(username, password, email, registry, reauth=reauth, **kwargs) return response.get('Status') == 'Login Succeeded' or response.get('username') == username
<SYSTEM_TASK:> Pushes an image repository to the registry. <END_TASK> <USER_TASK:> Description: def push(self, repository, stream=False, raise_on_error=True, **kwargs): """ Pushes an image repository to the registry. :param repository: Name of the repository (can include a tag). :type repository: unicode | str :param stream: Use the stream output format with additional status information. :type stream: bool :param raise_on_error: Raises errors in the status output as a DockerStatusException. Otherwise only logs errors. :type raise_on_error: bool :param kwargs: Additional kwargs for :meth:`docker.client.Client.push`. :return: ``True`` if the image has been pushed successfully. :rtype: bool """
response = super(DockerClientWrapper, self).push(repository, stream=stream, **kwargs) if stream: result = self._docker_status_stream(response, raise_on_error) else: result = self._docker_status_stream(response.split('\r\n') if response else (), raise_on_error) return result and not result.get('error')
<SYSTEM_TASK:> Removes a container. For convenience optionally ignores API errors. <END_TASK> <USER_TASK:> Description: def remove_container(self, container, raise_on_error=True, raise_not_found=False, **kwargs): """ Removes a container. For convenience optionally ignores API errors. :param container: Container name or id. :type container: unicode | str :param raise_on_error: Errors on stop and removal may result from Docker volume problems, that may not affect further actions. Such errors are always logged, but do not raise an exception if this is set to ``True``. :type raise_on_error: bool :param raise_not_found: Whether to raise 404 errors, i.e. that the container to be removed was not found. Default is ``False``. :type raise_not_found: bool :param kwargs: Additional keyword args for :meth:`docker.client.Client.remove_container`. """
try: super(DockerClientWrapper, self).remove_container(container, **kwargs) except APIError as e: exc_info = sys.exc_info() if e.response.status_code == 404: if raise_not_found: six.reraise(*exc_info) else: self.push_log("Failed to remove container '%s': %s", logging.ERROR, container, e.explanation) if raise_on_error: six.reraise(*exc_info)
<SYSTEM_TASK:> Stops a container. For convenience optionally ignores API errors. <END_TASK> <USER_TASK:> Description: def stop(self, container, raise_on_error=True, **kwargs): """ Stops a container. For convenience optionally ignores API errors. :param container: Container name. :type container: unicode | str :param raise_on_error: Errors on stop and removal may result from Docker volume problems, that may not affect further actions. Such errors are always logged, but do not raise an exception if this is set to ``True``. :type raise_on_error: bool :param kwargs: Additional keyword args for :meth:`docker.client.Client.stop`. """
try: super(DockerClientWrapper, self).stop(container, **kwargs) except APIError as e: exc_info = sys.exc_info() self.push_log("Failed to stop container '%s': %s", logging.ERROR, container, e.explanation) if raise_on_error: six.reraise(*exc_info)
<SYSTEM_TASK:> Generates a function that checks whether the given image has any of the listed tags. <END_TASK> <USER_TASK:> Description: def tag_check_function(tags): """ Generates a function that checks whether the given image has any of the listed tags. :param tags: Tags to check for. :type tags: list[unicode | str] | set[unicode | str] :return: Function that returns ``True`` if any of the given tags apply to the image, ``False`` otherwise. :rtype: (unicode | str) -> bool """
suffixes = [':{0}'.format(t) for t in tags] def _check_image(image): repo_tags = image['RepoTags'] if not repo_tags: return False return any(r_tag.endswith(s) for s in suffixes for r_tag in repo_tags) return _check_image
<SYSTEM_TASK:> Adds extra tags to an image after de-duplicating tag names. <END_TASK> <USER_TASK:> Description: def add_extra_tags(self, image_id, main_tag, extra_tags, add_latest): """ Adds extra tags to an image after de-duplicating tag names. :param image_id: Id of the image. :type image_id: unicode | str :param main_tag: Repo / tag specification that has been used to build the image. If present, the tag will be removed from further arguments. :type main_tag: unicode | str :param extra_tags: Additional tags to add to the image. :type extra_tags: list | tuple | set | NoneType :param add_latest: Whether to add a ``latest`` tag to the image. :type add_latest: bool """
repo, __, i_tag = main_tag.rpartition(':') tag_set = set(extra_tags or ()) if add_latest: tag_set.add('latest') tag_set.discard(i_tag) added_tags = [] tag_kwargs = {} if str(self.api_version) < DEPRECATED_FORCE_TAG_VERSION: tag_kwargs['force'] = True if repo and tag_set: for t in tag_set: try: self.tag(image_id, repo, t, **tag_kwargs) except: exc_info = sys.exc_info() raise PartialResultsError(exc_info, added_tags) else: added_tags.append(t) return added_tags
<SYSTEM_TASK:> Writes logs. To be fully implemented by subclasses. <END_TASK> <USER_TASK:> Description: def push_log(self, info, level, *args, **kwargs): """ Writes logs. To be fully implemented by subclasses. :param info: Log message content. :type info: unicode | str :param level: Logging level. :type level: int :param args: Positional arguments to pass to logger. :param kwargs: Keyword arguments to pass to logger. """
log.log(level, info, *args, **kwargs)
<SYSTEM_TASK:> Finds all stopped containers and removes them; by default does not remove containers that have never been <END_TASK> <USER_TASK:> Description: def cleanup_containers(self, include_initial=False, exclude=None, raise_on_error=False, list_only=False): """ Finds all stopped containers and removes them; by default does not remove containers that have never been started. :param include_initial: Consider containers that have never been started. :type include_initial: bool :param exclude: Container names to exclude from the cleanup process. :type exclude: collections.Iterable[unicode | str] :param raise_on_error: Forward errors raised by the client and cancel the process. By default only logs errors. :type raise_on_error: bool :param list_only: When set to ``True``, only lists containers, but does not actually remove them. :type list_only: bool :return: List of removed containers. :rtype: list[unicode | str] """
exclude_names = set(exclude or ()) def _stopped_containers(): for container in self.containers(all=True): c_names = [name[1:] for name in container['Names'] or () if name.find('/', 2)] c_status = container['Status'] if (((include_initial and c_status == '') or c_status.startswith('Exited') or c_status == 'Dead') and exclude_names.isdisjoint(c_names)): c_id = container['Id'] c_name = primary_container_name(c_names, default=c_id, strip_trailing_slash=False) yield c_id, c_name stopped_containers = list(_stopped_containers()) if list_only: return stopped_containers removed_containers = [] for cid, cn in stopped_containers: try: self.remove_container(cn) except: exc_info = sys.exc_info() if raise_on_error: raise PartialResultsError(exc_info, removed_containers) else: removed_containers.append(cn) return removed_containers
<SYSTEM_TASK:> Finds all images that are neither used by any container nor another image, and removes them; by default does not <END_TASK> <USER_TASK:> Description: def cleanup_images(self, remove_old=False, keep_tags=None, force=False, raise_on_error=False, list_only=False): """ Finds all images that are neither used by any container nor another image, and removes them; by default does not remove repository images. :param remove_old: Also removes images that have repository names, but no `latest` tag. :type remove_old: bool :param keep_tags: List of tags to not remove. :type keep_tags: list[unicode | str] :param force: If an image is referenced by multiple repositories, Docker by default will not remove the image. Setting this to ``True`` forces the removal. :type force: bool :param raise_on_error: Forward errors raised by the client and cancel the process. By default only logs errors. :type raise_on_error: bool :param list_only: When set to ``True`` only lists images, but does not actually remove them. :type list_only: bool :return: List of removed image ids. :rtype: list[unicode | str] """
used_images = set(self.inspect_container(container['Id'])['Image'] for container in self.containers(all=True)) all_images = self.images(all=True) image_dependencies = [(image['Id'], image['ParentId']) for image in all_images if image['ParentId']] if remove_old: check_tags = {'latest'} if keep_tags: check_tags.update(keep_tags) tag_check = tag_check_function(check_tags) elif remove_old: tag_check = tag_check_function(['latest']) else: tag_check = is_repo_image keep_images = {image['Id'] for image in all_images if tag_check(image)} | used_images test_images = [image['Id'] for image in all_images if image['Id'] not in keep_images] resolver = ImageDependentsResolver(image_dependencies) unused_images = [image_id for image_id in test_images if keep_images.isdisjoint(resolver.get_dependencies(image_id))] if list_only: return unused_images removed_images = [] for iid in unused_images: try: self.remove_image(iid, force=force) except: exc_info = sys.exc_info() if raise_on_error: raise PartialResultsError(exc_info, removed_images) else: removed_images.append(iid) return removed_images
<SYSTEM_TASK:> Fetches names of all present containers from Docker. <END_TASK> <USER_TASK:> Description: def get_container_names(self): """ Fetches names of all present containers from Docker. :return: All container names. :rtype: set """
current_containers = self.containers(all=True) return set(c_name[1:] for c in current_containers for c_name in c['Names'])
<SYSTEM_TASK:> Returns the actual value for the given object, if it is a late-resolving object type. <END_TASK> <USER_TASK:> Description: def resolve_value(value, types=type_registry): """ Returns the actual value for the given object, if it is a late-resolving object type. If not, the value itself is simply returned. :param value: Lazy object, registered type in :attr:`type_registry`, or a simple value. In the latter case, the value is returned as-is. :type value: str | unicode | int | AbstractLazyObject | unknown :return: Resolved value. """
if value is None: return None elif isinstance(value, lazy_type): return value.get() elif types: resolve_func = types.get(expand_type_name(type(value))) if resolve_func: return resolve_func(value) return value
<SYSTEM_TASK:> Resolves all late-resolving types into their current values to a certain depth in a dictionary or list. <END_TASK> <USER_TASK:> Description: def resolve_deep(values, max_depth=5, types=None): """ Resolves all late-resolving types into their current values to a certain depth in a dictionary or list. :param values: Values to resolve of any type. :param max_depth: Maximum depth to recurse into nested lists, tuples and dictionaries. Below that depth values are returned as they are. :type max_depth: int :param: Dictionary of types and functions to resolve, that are not registered in ``type_registry``. :type: dict[unicode | str, function] :return: Resolved values. """
def _resolve_sub(v, level): l1 = level + 1 res_val = resolve_value(v, all_types) if l1 < max_depth: if isinstance(res_val, (list, tuple)): return [_resolve_sub(item, l1) for item in res_val] elif isinstance(res_val, dict): return {resolve_value(rk, all_types): _resolve_sub(rv, l1) for rk, rv in iteritems(res_val)} return res_val if types: all_types = type_registry.copy() all_types.update(types) else: all_types = type_registry return _resolve_sub(values, -1)
<SYSTEM_TASK:> Resolves and returns the object value. Re-uses an existing previous evaluation, if applicable. <END_TASK> <USER_TASK:> Description: def get(self): """ Resolves and returns the object value. Re-uses an existing previous evaluation, if applicable. :return: The result of evaluating the object. """
if not self._evaluated: self._val = self._func(*self._args, **self._kwargs) self._evaluated = True return self._val
<SYSTEM_TASK:> Utility function that merges multiple dependency paths, as far as they share dependencies. Paths are evaluated <END_TASK> <USER_TASK:> Description: def merge_dependency_paths(item_paths): """ Utility function that merges multiple dependency paths, as far as they share dependencies. Paths are evaluated and merged in the incoming order. Later paths that are independent, but share some dependencies, are shortened by these dependencies. Paths that are contained in another entirely are discarded. :param item_paths: List or tuple of items along with their dependency path. :type item_paths: collections.Iterable[(Any, list[Any])] :return: List of merged or independent paths. :rtype: list[(Any, list[Any])] """
merged_paths = [] for item, path in item_paths: sub_path_idx = [] path_set = set(path) for index, (merged_item, merged_path, merged_set) in enumerate(merged_paths): if item in merged_set: path = None break elif merged_item in path_set: sub_path_idx.append(index) elif merged_set & path_set: path = [p for p in path if p not in merged_set] path_set = set(path) if not path: break for spi in reversed(sub_path_idx): merged_paths.pop(spi) if path is not None: merged_paths.append((item, path, path_set)) return [(i[0], i[1]) for i in merged_paths]
<SYSTEM_TASK:> Updates this configuration object from a dictionary. <END_TASK> <USER_TASK:> Description: def update_from_dict(self, dct): """ Updates this configuration object from a dictionary. See :meth:`ConfigurationObject.update` for details. :param dct: Values to update the ConfigurationObject with. :type dct: dict """
if not dct: return all_props = self.__class__.CONFIG_PROPERTIES for key, value in six.iteritems(dct): attr_config = all_props.get(key) if attr_config: setattr(self, key, value) else: self.update_default_from_dict(key, value)
<SYSTEM_TASK:> Updates this configuration object from another. <END_TASK> <USER_TASK:> Description: def update_from_obj(self, obj, copy=False): """ Updates this configuration object from another. See :meth:`ConfigurationObject.update` for details. :param obj: Values to update the ConfigurationObject with. :type obj: ConfigurationObject :param copy: Copies lists and dictionaries. :type copy: bool """
obj.clean() obj_config = obj._config all_props = self.__class__.CONFIG_PROPERTIES if copy: for key, value in six.iteritems(obj_config): attr_config = all_props.get(key) if attr_config: attr_type = attr_config.attr_type if attr_type: if issubclass(attr_type, list): self._config[key] = value[:] elif attr_type is dict: self._config[key] = value.copy() else: self._config[key] = value self._modified.discard(key) else: filtered_dict = {key: value for key, value in six.iteritems(obj_config) if key in all_props} self._config.update(filtered_dict) self._modified.difference_update(filtered_dict.keys())
<SYSTEM_TASK:> Merges a dictionary into this configuration object. <END_TASK> <USER_TASK:> Description: def merge_from_dict(self, dct, lists_only=False): """ Merges a dictionary into this configuration object. See :meth:`ConfigurationObject.merge` for details. :param dct: Values to update the ConfigurationObject with. :type dct: dict :param lists_only: Ignore single-value attributes and update dictionary options. :type lists_only: bool """
if not dct: return self.clean() all_props = self.__class__.CONFIG_PROPERTIES for key, value in six.iteritems(dct): attr_config = all_props.get(key) if attr_config: attr_type, default, input_func, merge_func = attr_config[:4] if (merge_func is not False and value != default and (not lists_only or (attr_type and issubclass(attr_type, list)))): if input_func: value = input_func(value) self._merge_value(attr_type, merge_func, key, value) else: self.merge_default_from_dict(key, value, lists_only=lists_only)
<SYSTEM_TASK:> Merges a configuration object into this one. <END_TASK> <USER_TASK:> Description: def merge_from_obj(self, obj, lists_only=False): """ Merges a configuration object into this one. See :meth:`ConfigurationObject.merge` for details. :param obj: Values to update the ConfigurationObject with. :type obj: ConfigurationObject :param lists_only: Ignore single-value attributes and update dictionary options. :type lists_only: bool """
self.clean() obj.clean() obj_config = obj._config all_props = self.__class__.CONFIG_PROPERTIES for key, value in six.iteritems(obj_config): attr_config = all_props[key] attr_type, default, __, merge_func = attr_config[:4] if (merge_func is not False and value != default and (not lists_only or (attr_type and issubclass(attr_type, list)))): self._merge_value(attr_type, merge_func, key, value)
<SYSTEM_TASK:> Updates the configuration with the contents of the given configuration object or dictionary. <END_TASK> <USER_TASK:> Description: def update(self, values, copy_instance=False): """ Updates the configuration with the contents of the given configuration object or dictionary. In case of a dictionary, only valid attributes for this class are considered. Existing attributes are replaced with the new values. The object is not cleaned before or after, i.e. may accept invalid input. In case of an update by object, that object is cleaned before the update, so that updated values should be validated. However, already-stored values are not cleaned before or after. :param values: Dictionary or ConfigurationObject to update this configuration with. :type values: dict | ConfigurationObject :param copy_instance: Copies lists and dictionaries. Only has an effect if ``values`` is a ConfigurationObject. :type copy_instance: bool """
if isinstance(values, self.__class__): self.update_from_obj(values, copy=copy_instance) elif isinstance(values, dict): self.update_from_dict(values) else: raise ValueError("{0} or dictionary expected; found '{1}'.".format(self.__class__.__name__, type(values).__name__))
<SYSTEM_TASK:> Merges list-based attributes into one list including unique elements from both lists. When ``lists_only`` is <END_TASK> <USER_TASK:> Description: def merge(self, values, lists_only=False): """ Merges list-based attributes into one list including unique elements from both lists. When ``lists_only`` is set to ``False``, updates dictionaries and overwrites single-value attributes. The resulting configuration is 'clean', i.e. input values converted and validated. If the conversion is not possible, a ``ValueError`` is raised. :param values: Values to update the ConfigurationObject with. :type values: dict | ConfigurationObject :param lists_only: Ignore single-value attributes and update dictionary options. :type lists_only: bool """
if isinstance(values, self.__class__): self.merge_from_obj(values, lists_only=lists_only) elif isinstance(values, dict): self.merge_from_dict(values, lists_only=lists_only) else: raise ValueError("{0} or dictionary expected; found '{1}'.".format(self.__class__.__name__, type(values).__name__))
<SYSTEM_TASK:> Cleans the input values of this configuration object. <END_TASK> <USER_TASK:> Description: def clean(self): """ Cleans the input values of this configuration object. Fields that have gotten updated through properties are converted to configuration values that match the format needed by functions using them. For example, for list-like values it means that input of single strings is transformed into a single-entry list. If this conversion fails, a ``ValueError`` is raised. """
all_props = self.__class__.CONFIG_PROPERTIES for prop_name in self._modified: attr_config = all_props.get(prop_name) if attr_config and attr_config.input_func: self._config[prop_name] = attr_config.input_func(self._config[prop_name]) self._modified.clear()
<SYSTEM_TASK:> Returns a copy of the configuration dictionary. Changes in this should not reflect on the original <END_TASK> <USER_TASK:> Description: def as_dict(self): """ Returns a copy of the configuration dictionary. Changes in this should not reflect on the original object. :return: Configuration dictionary. :rtype: dict """
self.clean() d = OrderedDict() all_props = self.__class__.CONFIG_PROPERTIES for attr_name, attr_config in six.iteritems(all_props): value = self._config[attr_name] attr_type = attr_config.attr_type if attr_type: if value: if issubclass(attr_type, list): if issubclass(attr_type, NamedTupleList): d[attr_name] = [i._asdict() for i in value] else: d[attr_name] = value[:] elif attr_type is dict: d[attr_name] = dict(value) elif value is not NotSet: d[attr_name] = value return d
<SYSTEM_TASK:> Performs a dependency check on the given item. <END_TASK> <USER_TASK:> Description: def get_dependencies(self, item): """ Performs a dependency check on the given item. :param item: Node to start the dependency check with. :return: The result on merged dependencies down the hierarchy. """
def _get_sub_dependency(sub_item): e = self._deps.get(sub_item) if e is None: return self.get_default() if e.dependencies is NotInitialized: e.dependencies = self.merge_dependency(sub_item, _get_sub_dependency, e.parent) return e.dependencies return _get_sub_dependency(item)
<SYSTEM_TASK:> Returns the direct dependencies or dependents of a single item. Does not follow the entire dependency path. <END_TASK> <USER_TASK:> Description: def get(self, item): """ Returns the direct dependencies or dependents of a single item. Does not follow the entire dependency path. :param item: Node to return dependencies for. :return: Immediate dependencies or dependents. """
e = self._deps.get(item) if e is None: return self.get_default() return e.parent
<SYSTEM_TASK:> Merge dependencies of element with further dependencies. First parent dependencies are checked, and then <END_TASK> <USER_TASK:> Description: def merge_dependency(self, item, resolve_parent, parents): """ Merge dependencies of element with further dependencies. First parent dependencies are checked, and then immediate dependencies of the current element should be added to the list, but without duplicating any entries. :param item: Item. :param resolve_parent: Function to resolve parent dependencies. :type resolve_parent: function :type parents: collections.Iterable :return: List of recursively resolved dependencies of this container. :rtype: list :raise CircularDependency: If the current element depends on one found deeper in the hierarchy. """
dep = [] for parent_key in parents: if item == parent_key: raise CircularDependency(item, True) parent_dep = resolve_parent(parent_key) if item in parent_dep: raise CircularDependency(item) merge_list(dep, parent_dep) merge_list(dep, parents) return dep
<SYSTEM_TASK:> Updates the dependencies with the given items. Note that this does not reset all previously-evaluated and cached <END_TASK> <USER_TASK:> Description: def update(self, items): """ Updates the dependencies with the given items. Note that this does not reset all previously-evaluated and cached nodes. :param items: Iterable or dictionary in the format `(dependent_item, dependencies)`. :type items: collections.Iterable """
for item, parents in _iterate_dependencies(items): dep = self._deps[item] merge_list(dep.parent, parents)
<SYSTEM_TASK:> Stops a container, either using the default client stop method, or sending a custom signal and waiting <END_TASK> <USER_TASK:> Description: def signal_stop(self, action, c_name, **kwargs): """ Stops a container, either using the default client stop method, or sending a custom signal and waiting for the container to stop. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param c_name: Container name. :type c_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict """
client = action.client sig = action.config.stop_signal stop_kwargs = self.get_container_stop_kwargs(action, c_name, kwargs=kwargs) if not sig or sig == 'SIGTERM' or sig == signal.SIGTERM: try: client.stop(**stop_kwargs) except Timeout: log.warning("Container %s did not stop in time - sent SIGKILL.", c_name) try: client.wait(c_name, timeout=stop_kwargs.get('timeout', 10)) except Timeout: pass else: log.debug("Sending signal %s to the container %s and waiting for stop.", sig, c_name) client.kill(c_name, signal=sig) client.wait(c_name, timeout=stop_kwargs.get('timeout', 10))
<SYSTEM_TASK:> Converts, as far as possible, Go filepath.Match patterns into Python regular expression patterns. Blank lines are <END_TASK> <USER_TASK:> Description: def preprocess_matches(input_items): """ Converts, as far as possible, Go filepath.Match patterns into Python regular expression patterns. Blank lines are ignored. This is a generator of two-element-tuples, with the first item as the compiled regular expression. Items prefixed with an exclamation mark are considered negative exclusions, i.e. exemptions. These have the second tuple item set to ``True``, others to ``False``. :param input_items: Input patterns to convert. :return: Generator of converted patterns. :rtype: collections.Iterable[(__RegEx, bool)] """
for i in input_items: s = i.strip() if not s: continue if s[0] == '!': is_negative = True match_str = s[1:] if not match_str: continue else: is_negative = False match_str = s yield re.compile(fnmatch.translate(LITERAL_PATTERN.sub(r'[\g<1>]', match_str))), is_negative
<SYSTEM_TASK:> Generates exclusion patterns from a ``.dockerignore`` file located in the given path. Returns ``None`` if the <END_TASK> <USER_TASK:> Description: def get_exclusions(path): """ Generates exclusion patterns from a ``.dockerignore`` file located in the given path. Returns ``None`` if the file does not exist. :param path: Path to look up the ``.dockerignore`` in. :type path: unicode | str :return: List of patterns, that can be passed into :func:`get_filter_func`. :rtype: list[(__RegEx, bool)] """
if not os.path.isdir(path): return None dockerignore_file = os.path.join(path, '.dockerignore') if not os.path.isfile(dockerignore_file): return None with open(dockerignore_file, 'rb') as dif: return list(preprocess_matches(dif.readlines()))
<SYSTEM_TASK:> Add a file or directory to the context tarball. <END_TASK> <USER_TASK:> Description: def add(self, name, arcname=None, **kwargs): """ Add a file or directory to the context tarball. :param name: File or directory path. :type name: unicode | str :param args: Additional args for :meth:`tarfile.TarFile.add`. :param kwargs: Additional kwargs for :meth:`tarfile.TarFile.add`. """
if os.path.isdir(name): exclusions = get_exclusions(name) if exclusions: target_prefix = os.path.abspath(arcname or name) kwargs.setdefault('filter', get_filter_func(exclusions, target_prefix)) self.tarfile.add(name, arcname=arcname, **kwargs)
<SYSTEM_TASK:> Saves the entire Docker context tarball to a separate file. <END_TASK> <USER_TASK:> Description: def save(self, name): """ Saves the entire Docker context tarball to a separate file. :param name: File path to save the tarball into. :type name: unicode | str """
with open(name, 'wb+') as f: while True: buf = self._fileobj.read() if not buf: break f.write(buf)
<SYSTEM_TASK:> Generates volume paths for the ``volumes`` argument during container creation. <END_TASK> <USER_TASK:> Description: def get_volumes(container_map, config, default_volume_paths, include_named): """ Generates volume paths for the ``volumes`` argument during container creation. :param container_map: Container map. :type container_map: dockermap.map.config.main.ContainerMap :param config: Container configuration. :type config: dockermap.map.config.container.ContainerConfiguration :param default_volume_paths: Dictionary with volume aliases and their default paths. :type default_volume_paths: dict[unicode | str, unicode | str] :param include_named: Whether to include attached and their re-used volumes. This should be done if Docker supports named volumes; otherwise volumes are inherited from other containers via ``volumes_from``. :type include_named: bool :return: List of shared volume mount points. :rtype: list[unicode | str] """
def _bind_volume_path(vol): if isinstance(vol, HostVolume): return resolve_value(vol.path) v_path = resolve_value(default_volume_paths.get(vol.name)) if v_path: return v_path raise KeyError("No host-volume information found for alias {0}.".format(vol)) def _attached_volume_path(vol): if isinstance(vol, UsedVolume): return resolve_value(vol.path) v_path = resolve_value(default_volume_paths.get(vol.name)) if v_path: return v_path raise KeyError("No volume information found for alias {0}.".format(vol)) def _used_volume_path(vol): if isinstance(vol, UsedVolume): return resolve_value(vol.path) if container_map.use_attached_parent_name: return resolve_value(default_volume_paths.get(vol.name.partition('.')[2])) return resolve_value(default_volume_paths.get(vol.name)) volumes = list(map(resolve_value, config.shares)) volumes.extend(map(_bind_volume_path, config.binds)) if include_named: volumes.extend(map(_attached_volume_path, config.attaches)) volumes.extend(filter(None, map(_used_volume_path, config.uses))) return volumes
<SYSTEM_TASK:> Generates volume paths for the host config ``volumes_from`` argument during container creation. <END_TASK> <USER_TASK:> Description: def get_volumes_from(container_map, config_name, config, policy, include_volumes): """ Generates volume paths for the host config ``volumes_from`` argument during container creation. :param container_map: Container map. :type container_map: dockermap.map.config.main.ContainerMap :param config_name: Container configuration name. :type config_name: unicode | str :param config: Container configuration. :type config: dockermap.map.config.container.ContainerConfiguration :param policy: Base policy for generating names and determining volumes. :type policy: dockermap.map.policy.base.BasePolicy :param include_volumes: Whether to include attached and their re-used volumes. This should not be done if Docker supports named volumes, because these are included in ``volumes`` with their paths. :type include_volumes: bool :return: List of shared volume mount points. :rtype: list[unicode | str] """
aname = policy.aname cname = policy.cname map_name = container_map.name volume_names = set(policy.default_volume_paths[map_name].keys()) def container_name(u_name): uc_name, __, ui_name = u_name.partition('.') return cname(map_name, uc_name, ui_name) def volume_or_container_name(u_name): if u_name in volume_names: if container_map.use_attached_parent_name: v_parent_name, __, attached_name = u_name.partition('.') return aname(map_name, attached_name, v_parent_name) return aname(map_name, u_name) return container_name(u_name) def volume_str(name, readonly): if readonly: return '{0}:ro'.format(name) return name use_attached_parent_name = container_map.use_attached_parent_name if include_volumes: volumes_from = [volume_str(volume_or_container_name(u.name), u.readonly) for u in config.uses] a_parent_name = config_name if use_attached_parent_name else None volumes_from.extend([aname(map_name, attached.name, a_parent_name) for attached in config.attaches]) return volumes_from if use_attached_parent_name: return [volume_str(container_name(u.name), u.readonly) for u in config.uses if u.name.partition('.')[2] not in volume_names] return [volume_str(container_name(u.name), u.readonly) for u in config.uses if u.name not in volume_names]
<SYSTEM_TASK:> Generates the input dictionary contents for the ``port_bindings`` argument. <END_TASK> <USER_TASK:> Description: def get_port_bindings(container_config, client_config): """ Generates the input dictionary contents for the ``port_bindings`` argument. :param container_config: Container configuration. :type container_config: dockermap.map.config.container.ContainerConfiguration :param client_config: Client configuration. :type client_config: dockermap.map.config.client.ClientConfiguration :return: Dictionary of ports with mapped port, and if applicable, with bind address :rtype: dict[unicode | str, list[unicode | str | int | tuple]] """
port_bindings = {} if_ipv4 = client_config.interfaces if_ipv6 = client_config.interfaces_ipv6 for exposed_port, ex_port_bindings in itertools.groupby( sorted(container_config.exposes, key=_get_ex_port), _get_ex_port): bind_list = list(_get_port_bindings(ex_port_bindings, if_ipv4, if_ipv6)) if bind_list: port_bindings[exposed_port] = bind_list return port_bindings
<SYSTEM_TASK:> Generates the command lines for adjusting a volume's ownership and permission flags. Returns an empty list if there <END_TASK> <USER_TASK:> Description: def get_preparation_cmd(user, permissions, path): """ Generates the command lines for adjusting a volume's ownership and permission flags. Returns an empty list if there is nothing to adjust. :param user: User to set ownership for on the path via ``chown``. :type user: unicode | str | int | dockermap.functional.AbstractLazyObject :param permissions: Permission flags to set via ``chmod``. :type permissions: unicode | str | dockermap.functional.AbstractLazyObject :param path: Path to adjust permissions on. :type path: unicode | str :return: Iterator over resulting command strings. :rtype: collections.Iterable[unicode | str] """
r_user = resolve_value(user) r_permissions = resolve_value(permissions) if user: yield chown(r_user, path) if permissions: yield chmod(r_permissions, path)
<SYSTEM_TASK:> Returns the hash of the file of an internal url <END_TASK> <USER_TASK:> Description: def get_urlhash(self, url, fmt): """Returns the hash of the file of an internal url """
with self.open(os.path.basename(url)) as f: return {'url': fmt(url), 'sha256': filehash(f, 'sha256')}
<SYSTEM_TASK:> List all versions of a package <END_TASK> <USER_TASK:> Description: def package_releases(self, package, url_fmt=lambda u: u): """List all versions of a package Along with the version, the caller also receives the file list with all the available formats. """
return [{ 'name': package, 'version': version, 'urls': [self.get_urlhash(f, url_fmt) for f in files] } for version, files in self.storage.get(package, {}).items()]
<SYSTEM_TASK:> Fetches information about the container from the client. <END_TASK> <USER_TASK:> Description: def inspect(self): """ Fetches information about the container from the client. """
policy = self.policy config_id = self.config_id if self.config_id.config_type == ItemType.VOLUME: if self.container_map.use_attached_parent_name: container_name = policy.aname(config_id.map_name, config_id.instance_name, config_id.config_name) else: container_name = policy.aname(config_id.map_name, config_id.instance_name) else: container_name = policy.cname(config_id.map_name, config_id.config_name, config_id.instance_name) self.container_name = container_name if container_name in policy.container_names[self.client_name]: self.detail = self.client.inspect_container(container_name) else: self.detail = NOT_FOUND
<SYSTEM_TASK:> Fetches image information from the client. <END_TASK> <USER_TASK:> Description: def inspect(self): """ Fetches image information from the client. """
policy = self.policy image_name = format_image_tag((self.config_id.config_name, self.config_id.instance_name)) image_id = policy.images[self.client_name].get(image_name) if image_id: self.detail = {'Id': image_id} # Currently there is no need for actually inspecting the image. else: self.detail = NOT_FOUND
<SYSTEM_TASK:> Generates the actions on a single item, which can be either a dependency or a explicitly selected <END_TASK> <USER_TASK:> Description: def generate_config_states(self, config_id, config_flags=ConfigFlags.NONE): """ Generates the actions on a single item, which can be either a dependency or a explicitly selected container. :param config_id: Configuration id tuple. :type config_id: dockermap.map.input.MapConfigId :param config_flags: Optional configuration flags. :type config_flags: dockermap.map.policy.ConfigFlags :return: Generator for container state information. :rtype: collections.Iterable[dockermap.map.state.ContainerConfigStates] """
c_map = self._policy.container_maps[config_id.map_name] clients = c_map.clients or [self._policy.default_client_name] config_type = config_id.config_type for client_name in clients: if config_type == ItemType.CONTAINER: c_state = self.get_container_state(client_name, config_id, config_flags) elif config_type == ItemType.VOLUME: client_config = self._policy.clients[client_name] if client_config.features['volumes']: c_state = self.get_volume_state(client_name, config_id, config_flags) else: c_state = self.get_container_state(client_name, config_id, config_flags) elif config_type == ItemType.NETWORK: c_state = self.get_network_state(client_name, config_id, config_flags) elif config_type == ItemType.IMAGE: c_state = self.get_image_state(client_name, config_id, config_flags) else: raise ValueError("Invalid configuration type.", config_type) c_state.inspect() # Extract base state, state flags, and extra info. state_info = ConfigState(client_name, config_id, config_flags, *c_state.get_state()) log.debug("Configuration state information: %s", state_info) yield state_info
<SYSTEM_TASK:> Generates state information for the selected containers. <END_TASK> <USER_TASK:> Description: def get_states(self, config_ids): """ Generates state information for the selected containers. :param config_ids: List of MapConfigId tuples. :type config_ids: list[dockermap.map.input.MapConfigId] :return: Iterable of configuration states. :rtype: collections.Iterable[dockermap.map.state.ConfigState] """
return itertools.chain.from_iterable(self.generate_config_states(config_id) for config_id in config_ids)
<SYSTEM_TASK:> Generates keyword arguments for waiting for a container when preparing a volume. The container name may be <END_TASK> <USER_TASK:> Description: def get_attached_preparation_wait_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for waiting for a container when preparing a volume. The container name may be the container being prepared, or the id of the container calling preparation commands. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param container_name: Container name or id. Set ``None`` when included in kwargs for ``create_container``. :type container_name: unicode | str | NoneType :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict | NoneType :return: Resulting keyword arguments. :rtype: dict """
c_kwargs = dict(container=container_name) client_config = action.client_config c_kwargs = dict(container=container_name) wait_timeout = client_config.get('wait_timeout') if wait_timeout is not None: c_kwargs['timeout'] = wait_timeout update_kwargs(c_kwargs, kwargs) return c_kwargs
<SYSTEM_TASK:> Runs a temporary container for preparing an attached volume for a container configuration. <END_TASK> <USER_TASK:> Description: def _prepare_container(self, client, action, volume_container, volume_alias): """ Runs a temporary container for preparing an attached volume for a container configuration. :param client: Docker client. :type client: docker.Client :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param volume_container: Name of the container that shares the volume. :type volume_container: unicode | str :param volume_alias: Volume alias that is used for map references, for looking up paths. :type volume_alias: unicode | str """
apc_kwargs = self.get_attached_preparation_create_kwargs(action, volume_container, volume_alias) if not apc_kwargs: return a_wait_kwargs = self.get_attached_preparation_wait_kwargs(action, volume_container) client.wait(volume_container, **a_wait_kwargs) temp_container = client.create_container(**apc_kwargs) temp_id = temp_container['Id'] try: if action.client_config.features['host_config']: client.start(temp_id) else: aps_kwargs = self.get_attached_preparation_host_config_kwargs(action, temp_id, volume_container) client.start(**aps_kwargs) temp_wait_kwargs = self.get_attached_preparation_wait_kwargs(action, temp_id) client.wait(temp_id, **temp_wait_kwargs) finally: client.remove_container(temp_id)
<SYSTEM_TASK:> Prepares an attached volume for a container configuration. <END_TASK> <USER_TASK:> Description: def prepare_attached(self, action, a_name, **kwargs): """ Prepares an attached volume for a container configuration. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param a_name: The full name or id of the container sharing the volume. :type a_name: unicode | str """
client = action.client config_id = action.config_id policy = self._policy if action.container_map.use_attached_parent_name: v_alias = '{0.config_name}.{0.instance_name}'.format(config_id) else: v_alias = config_id.instance_name user = policy.volume_users[config_id.map_name][v_alias] permissions = policy.volume_permissions[config_id.map_name][v_alias] if not (self.prepare_local and hasattr(client, 'run_cmd')): return self._prepare_container(client, action, a_name, v_alias) if action.client_config.features['volumes']: volume_detail = client.inspect_volume(a_name) local_path = volume_detail['Mountpoint'] else: instance_detail = client.inspect_container(a_name) volumes = get_instance_volumes(instance_detail, False) path = resolve_value(policy.default_volume_paths[config_id.map_name][v_alias]) local_path = volumes.get(path) if not local_path: raise ValueError("Could not locate local path of volume alias '{0}' / " "path '{1}' in container {2}.".format(action.config_id.instance_name, path, a_name)) return [ client.run_cmd(cmd) for cmd in get_preparation_cmd(user, permissions, local_path) ]
<SYSTEM_TASK:> Resolves a volume alias of a container configuration or a tuple of two paths to the host and container paths. <END_TASK> <USER_TASK:> Description: def get_shared_volume_path(container_map, vol, instance=None): """ Resolves a volume alias of a container configuration or a tuple of two paths to the host and container paths. :param container_map: Container map. :type container_map: dockermap.map.config.main.ContainerMap :param vol: SharedVolume or HostVolume tuple. :type vol: dockermap.map.input.HostVolume | dockermap.map.input.SharedVolume :param instance: Optional instance name. :type instance: unicode | str :return: Tuple of host path and container bind path. :rtype: tuple[unicode | str] """
if isinstance(vol, HostVolume): c_path = resolve_value(vol.path) if is_path(c_path): return c_path, get_host_path(container_map.host.root, vol.host_path, instance) raise ValueError("Host-container-binding must be described by two paths or one alias name.", vol) alias = vol.name volume_config = resolve_value(container_map.volumes.get(alias)) h_path = container_map.host.get_path(alias, instance) if volume_config and h_path: return volume_config.default_path, h_path raise KeyError("No host-volume information found for alias {0}.".format(alias))
<SYSTEM_TASK:> Extracts the mount points and mapped directories or names of a Docker container. <END_TASK> <USER_TASK:> Description: def get_instance_volumes(instance_detail, check_names): """ Extracts the mount points and mapped directories or names of a Docker container. :param instance_detail: Result from a container inspection. :type instance_detail: dict :param check_names: Whether to check for named volumes. :type check_names: bool :return: Dictionary of volumes, with the destination (inside the container) as a key, and the source (external to the container) as values. If ``check_names`` is ``True``, the value contains the mounted volume name instead. :rtype: dict[unicode | str, unicode | str] """
if 'Mounts' in instance_detail: if check_names: return {m['Destination']: m.get('Name') or m['Source'] for m in instance_detail['Mounts']} return {m['Destination']: m['Source'] for m in instance_detail['Mounts']} return instance_detail.get('Volumes') or {}
<SYSTEM_TASK:> Merges items into a list, appends ignoring duplicates but retaining the original order. This modifies the list and <END_TASK> <USER_TASK:> Description: def merge_list(merged_list, items): """ Merges items into a list, appends ignoring duplicates but retaining the original order. This modifies the list and does not return anything. :param merged_list: List to append de-duplicated items to. :type merged_list: list :param items: Items to merge into the list. :type items: collections.Iterable """
if not items: return merged_set = set(merged_list) merged_add = merged_set.add merged_list.extend(item for item in items if item not in merged_set and not merged_add(item))
<SYSTEM_TASK:> Disconnects all containers from a network. <END_TASK> <USER_TASK:> Description: def disconnect_all_containers(self, action, network_name, containers, **kwargs): """ Disconnects all containers from a network. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param network_name: Network name or id. :type network_name: unicode | str :param containers: Container names or ids. :type containers: collections.Iterable[unicode | str] :param kwargs: Additional keyword arguments. :type kwargs: dict """
client = action.client for c_name in containers: disconnect_kwargs = self.get_network_disconnect_kwargs(action, network_name, c_name, kwargs=kwargs) client.disconnect_container_from_network(**disconnect_kwargs)
<SYSTEM_TASK:> Connects a container to a set of configured networks. By default this assumes the container has just been <END_TASK> <USER_TASK:> Description: def connect_networks(self, action, container_name, endpoints, skip_first=False, **kwargs): """ Connects a container to a set of configured networks. By default this assumes the container has just been created, so it will skip the first network that is already considered during creation. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param container_name: Container names or id. :type container_name: unicode | str :param endpoints: Network endpoint configurations. :type endpoints: list[dockermap.map.input.NetworkEndpoint] :param skip_first: Skip the first network passed in ``endpoints``. Defaults to ``False``, but should be set to ``True`` when the container has just been created and the first network has been set up there. :type skip_first: bool :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict """
if not endpoints or (skip_first and len(endpoints) <= 1): return client = action.client map_name = action.config_id.map_name nname = self._policy.nname if skip_first: endpoints = islice(endpoints, 1, None) for network_endpoint in endpoints: network_name = nname(map_name, network_endpoint.network_name) connect_kwargs = self.get_network_connect_kwargs(action, network_name, container_name, network_endpoint, kwargs=kwargs) client.connect_container_to_network(**connect_kwargs)
<SYSTEM_TASK:> Disconnects a container from a set of networks. <END_TASK> <USER_TASK:> Description: def disconnect_networks(self, action, container_name, networks, **kwargs): """ Disconnects a container from a set of networks. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param container_name: Container names or id. :type container_name: unicode | str :param networks: List of network names or ids. :type networks: collections.Iterable[unicode | str] :param kwargs: Additional keyword arguments. :type kwargs: dict """
client = action.client for n_name in networks: disconnect_kwargs = self.get_network_disconnect_kwargs(action, n_name, container_name, kwargs=kwargs) client.disconnect_container_from_network(**disconnect_kwargs)
<SYSTEM_TASK:> Connects a container to all of its configured networks. Assuming that this is typically used after container <END_TASK> <USER_TASK:> Description: def connect_all_networks(self, action, container_name, **kwargs): """ Connects a container to all of its configured networks. Assuming that this is typically used after container creation, where teh first endpoint is already defined, this skips the first configuration. Pass ``skip_first`` as ``False`` to change this. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param container_name: Container names or id. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict """
kwargs.setdefault('skip_first', True) self.connect_networks(action, container_name, action.config.networks, **kwargs)
<SYSTEM_TASK:> Save the string buffer to a file. Finalizes prior to saving. <END_TASK> <USER_TASK:> Description: def save(self, name): """ Save the string buffer to a file. Finalizes prior to saving. :param name: File path. :type name: unicode | str """
self.finalize() with open(name, 'wb+') as f: if six.PY3: f.write(self.fileobj.getbuffer()) else: f.write(self.fileobj.getvalue().encode('utf-8'))
<SYSTEM_TASK:> Copy the contents of the temporary file somewhere else. Finalizes prior to saving. <END_TASK> <USER_TASK:> Description: def save(self, name): """ Copy the contents of the temporary file somewhere else. Finalizes prior to saving. :param name: File path. :type name: unicode | str """
self.finalize() with open(name, 'wb+') as f: buf = self._fileobj.read() while buf: f.write(buf) buf = self._fileobj.read()
<SYSTEM_TASK:> Checks whether the given value represents a path, i.e. a string which starts with an indicator for absolute or <END_TASK> <USER_TASK:> Description: def is_path(value): """ Checks whether the given value represents a path, i.e. a string which starts with an indicator for absolute or relative paths. :param value: Value to check. :return: ``True``, if the value appears to be representing a path. :rtype: bool """
return value and isinstance(value, six.string_types) and (value[0] == posixpath.sep or value[:2] == CURRENT_DIR)
<SYSTEM_TASK:> Wraps the given value in a list. ``None`` returns an empty list. Lists and tuples are returned as lists. Single <END_TASK> <USER_TASK:> Description: def get_list(value): """ Wraps the given value in a list. ``None`` returns an empty list. Lists and tuples are returned as lists. Single strings and registered types are wrapped in a list. :param value: Value to return as a list. :return: List with the provided value(s). :rtype: list """
if value is None: return [] elif value is NotSet: return NotSet elif isinstance(value, (list, tuple)): return list(value) elif isinstance(value, six.string_types + (lazy_type, )) or uses_type_registry(value): return [value] raise ValueError("Invalid type; expected a list, tuple, or string type, found {0}.".format( type(value).__name__))
<SYSTEM_TASK:> Generates input for the ``network_mode`` of a Docker host configuration. If it points at a container, the <END_TASK> <USER_TASK:> Description: def get_network_mode(value): """ Generates input for the ``network_mode`` of a Docker host configuration. If it points at a container, the configuration of the container is returned. :param value: Network mode input. :type value: unicode | str | tuple | list | NoneType :return: Network mode or container to re-use the network stack of. :rtype: unicode | str | tuple | NoneType """
if not value or value == 'disabled': return 'none' if isinstance(value, (tuple, list)): if len(value) == 2: return tuple(value) return ValueError("Tuples or lists need to have length 2 for container network references.") if value in DEFAULT_PRESET_NETWORKS: return value if value.startswith('container:'): return value if value.startswith('/'): return 'container:{0}'.format(value[1:]) ref_name, __, ref_instance = value.partition('.') return ref_name, ref_instance or None
<SYSTEM_TASK:> Converts the given value to a ``UsedVolume`` or ``SharedVolume`` tuple for attached volumes. It <END_TASK> <USER_TASK:> Description: def get_type_item(self, value): """ Converts the given value to a ``UsedVolume`` or ``SharedVolume`` tuple for attached volumes. It accepts strings, lists, tuples, and dicts as input. For strings and collections of a single element, the first item is considered to be an alias for lookup on the map. It is converted to a ``SharedVolume`` tuple. For two-element collections, the first item defines a new volume alias that can be re-used by other instances and the second item is considered to be the mount point for the volume. All attached volumes are considered as read-write access. :param value: Input value for conversion. :return: UsedVolume or SharedVolume tuple. :rtype: UsedVolume | SharedVolume """
if isinstance(value, (UsedVolume, SharedVolume)): if value.readonly: raise ValueError("Attached volumes should not be read-only.") return value elif isinstance(value, six.string_types): return SharedVolume(value) elif isinstance(value, (list, tuple)): v_len = len(value) if v_len == 2: if value[1]: return UsedVolume(value[0], value[1]) return SharedVolume(value[0]) elif v_len == 1: return SharedVolume(value[0]) raise ValueError("Invalid element length; only tuples and lists of length 1-2 can be converted to a " "UsedVolume or SharedVolume tuple; found length {0}.".format(v_len)) elif isinstance(value, dict): v_len = len(value) if v_len == 1: k, v = list(value.items())[0] if k == 'name': return SharedVolume(v) return UsedVolume(k, v) elif 'path' in value: return UsedVolume(**value) return SharedVolume(**value) raise ValueError( "Invalid type; expected a list, tuple, dict, or string type, found {0}.".format(type(value).__name__))
<SYSTEM_TASK:> Iterates over a list of container configuration ids, expanding groups of container configurations. <END_TASK> <USER_TASK:> Description: def expand_groups(config_ids, maps): """ Iterates over a list of container configuration ids, expanding groups of container configurations. :param config_ids: List of container configuration ids. :type config_ids: collections.Iterable[dockermap.map.input.InputConfigId | dockermap.map.input.MapConfigId] :param maps: Extended container maps. :type maps: dict[unicode | str, dockermap.map.config.main.ContainerMap] :return: Expanded MapConfigId tuples. :rtype: collections.Iterable[dockermap.map.input.InputConfigId] """
for config_id in config_ids: if config_id.map_name == '__all__': c_maps = six.iteritems(maps) else: c_maps = (config_id.map_name, maps[config_id.map_name]), if isinstance(config_id, InputConfigId): instance_name = config_id.instance_names elif isinstance(config_id, MapConfigId): instance_name = (config_id.instance_name, ) else: raise ValueError("Expected InputConfigId or MapConfigId tuple; found {0}." "".format(type(config_id).__name__)) for map_name, c_map in c_maps: if config_id.config_name == '__all__' and config_id.config_type == ItemType.CONTAINER: for config_name in six.iterkeys(c_map.containers): yield MapConfigId(config_id.config_type, map_name, config_name, instance_name) else: group = c_map.groups.get(config_id.config_name) if group is not None: for group_item in group: if isinstance(group_item, MapConfigId): yield group_item elif isinstance(group_item, six.string_types): config_name, __, instance = group_item.partition('.') yield MapConfigId(config_id.config_type, map_name, config_name, (instance, ) if instance else instance_name) else: raise ValueError("Invalid group item. Must be string or MapConfigId tuple; " "found {0}.".format(type(group_item).__name__)) else: yield MapConfigId(config_id.config_type, map_name, config_id.config_name, instance_name)
<SYSTEM_TASK:> Iterates over a list of input configuration ids, expanding configured instances if ``None`` is specified. Otherwise <END_TASK> <USER_TASK:> Description: def expand_instances(config_ids, ext_maps): """ Iterates over a list of input configuration ids, expanding configured instances if ``None`` is specified. Otherwise where instance names are specified as a tuple, they are expanded. :param config_ids: Iterable of container configuration ids or (map, config, instance names) tuples. :type config_ids: collections.Iterable[dockermap.map.input.InputConfigId] | collections.Iterable[tuple[unicode | str, unicode | str, unicode | str]] :param ext_maps: Dictionary of extended ContainerMap instances for looking up container configurations. :type ext_maps: dict[unicode | str, ContainerMap] :return: MapConfigId tuples. :rtype: collections.Iterable[dockermap.map.input.MapConfigId] """
for type_map_config, items in itertools.groupby(sorted(config_ids, key=get_map_config), get_map_config): config_type, map_name, config_name = type_map_config instances = _get_nested_instances(items) c_map = ext_maps[map_name] try: c_instances = _get_config_instances(config_type, c_map, config_name) except KeyError: raise KeyError("Configuration not found.", type_map_config) if c_instances and None in instances: for i in c_instances: yield MapConfigId(config_type, map_name, config_name, i) else: for i in instances: yield MapConfigId(config_type, map_name, config_name, i)
<SYSTEM_TASK:> Creates a configured network. <END_TASK> <USER_TASK:> Description: def create_network(self, action, n_name, **kwargs): """ Creates a configured network. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param n_name: Network name. :type n_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict """
c_kwargs = self.get_network_create_kwargs(action, n_name, **kwargs) res = action.client.create_network(**c_kwargs) self._policy.network_names[action.client_name][n_name] = res['Id'] return res
<SYSTEM_TASK:> Removes a network. <END_TASK> <USER_TASK:> Description: def remove_network(self, action, n_name, **kwargs): """ Removes a network. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param n_name: Network name or id. :type n_name: unicode | str :param kwargs: Additional keyword arguments. :type kwargs: dict """
c_kwargs = self.get_network_remove_kwargs(action, n_name, **kwargs) res = action.client.remove_network(**c_kwargs) del self._policy.network_names[action.client_name][n_name] return res
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to create a container. <END_TASK> <USER_TASK:> Description: def get_container_create_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to create a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict | NoneType :return: Resulting keyword arguments. :rtype: dict """
policy = self._policy client_config = action.client_config container_map = action.container_map container_config = action.config image_tag = container_map.get_image(container_config.image or action.config_id.config_name) default_paths = policy.default_volume_paths[action.config_id.map_name] c_kwargs = dict( name=container_name, image=format_image_tag(image_tag), volumes=get_volumes(container_map, container_config, default_paths, client_config.features['volumes']), user=extract_user(container_config.user), ports=[resolve_value(port_binding.exposed_port) for port_binding in container_config.exposes if port_binding.exposed_port], hostname=policy.get_hostname(container_name, action.client_name) if container_map.set_hostname else None, domainname=resolve_value(client_config.get('domainname', container_map.default_domain)) or None, ) if container_config.network_mode == 'none': c_kwargs['network_disabled'] = True elif client_config.features['networks'] and container_config.networks: first_network = container_config.networks[0] c_kwargs['networking_config'] = NetworkingConfig({ policy.nname(action.config_id.map_name, first_network.network_name): EndpointConfig( client_config.version, **self.get_network_create_endpoint_kwargs(action, first_network) ) }) if client_config.features['stop_signal'] and container_config.stop_signal: c_kwargs['stop_signal'] = container_config.stop_signal hc_extra_kwargs = kwargs.pop('host_config', None) if kwargs else None use_host_config = client_config.features['host_config'] if use_host_config: hc_kwargs = self.get_container_host_config_kwargs(action, None, kwargs=hc_extra_kwargs) if hc_kwargs: if use_host_config == USE_HC_MERGE: c_kwargs.update(hc_kwargs) else: c_kwargs['host_config'] = HostConfig(version=client_config.version, **hc_kwargs) if client_config.features['stop_timeout'] and container_config.stop_timeout: c_kwargs['stop_timeout'] = container_config.stop_timeout if client_config.features['healthcheck'] and container_config.healthcheck: c_kwargs['healthcheck'] = container_config.healthcheck._asdict() update_kwargs(c_kwargs, init_options(container_config.create_options), kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to create an attached container. <END_TASK> <USER_TASK:> Description: def get_attached_container_create_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to create an attached container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict | NoneType :return: Resulting keyword arguments. :rtype: dict """
client_config = action.client_config policy = self._policy config_id = action.config_id path = resolve_value(policy.default_volume_paths[config_id.map_name][config_id.instance_name]) user = extract_user(action.config.user) c_kwargs = dict( name=container_name, image=self._policy.base_image, volumes=[path], user=user, network_disabled=True, ) hc_extra_kwargs = kwargs.pop('host_config', None) if kwargs else None use_host_config = client_config.features['host_config'] if use_host_config: hc_kwargs = self.get_attached_container_host_config_kwargs(action, None, kwargs=hc_extra_kwargs) if hc_kwargs: if use_host_config == USE_HC_MERGE: c_kwargs.update(hc_kwargs) else: c_kwargs['host_config'] = HostConfig(version=client_config.version, **hc_kwargs) update_kwargs(c_kwargs, kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to set up the HostConfig or start an attached container. <END_TASK> <USER_TASK:> Description: def get_attached_container_host_config_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to set up the HostConfig or start an attached container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. Set ``None`` when included in kwargs for ``create_container``. :type container_name: unicode | str | NoneType :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict | NoneType :return: Resulting keyword arguments. :rtype: dict """
if container_name: c_kwargs = {'container': container_name} else: c_kwargs = {} update_kwargs(c_kwargs, kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to update the HostConfig of an existing container. <END_TASK> <USER_TASK:> Description: def get_container_update_kwargs(self, action, container_name, update_values, kwargs=None): """ Generates keyword arguments for the Docker client to update the HostConfig of an existing container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param update_values: Dictionary of values to update; i.e. keyword arguments to the Docker client. :type update_values: dict[unicode | str, unicode | str | int | float | decimal.Decimal] :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict | NoneType :return: Resulting keyword arguments. :rtype: dict """
c_kwargs = dict(container=container_name) update_kwargs(c_kwargs, update_values, kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to wait for a container. <END_TASK> <USER_TASK:> Description: def get_container_wait_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to wait for a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict :return: Resulting keyword arguments. :rtype: dict """
c_kwargs = dict(container=container_name) timeout = action.client_config.get('wait_timeout') if timeout is not None: c_kwargs['timeout'] = timeout update_kwargs(c_kwargs, kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to stop a container. <END_TASK> <USER_TASK:> Description: def get_container_stop_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to stop a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict :return: Resulting keyword arguments. :rtype: dict """
c_kwargs = dict( container=container_name, ) stop_timeout = action.config.stop_timeout if stop_timeout is NotSet: timeout = action.client_config.get('stop_timeout') if timeout is not None: c_kwargs['timeout'] = timeout elif stop_timeout is not None: c_kwargs['timeout'] = stop_timeout update_kwargs(c_kwargs, kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to remove a container. <END_TASK> <USER_TASK:> Description: def get_container_remove_kwargs(self, action, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to remove a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict :return: Resulting keyword arguments. :rtype: dict """
c_kwargs = dict(container=container_name) update_kwargs(c_kwargs, kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to create a network. <END_TASK> <USER_TASK:> Description: def get_network_create_kwargs(self, action, network_name, kwargs=None): """ Generates keyword arguments for the Docker client to create a network. :param action: Action configuration. :type action: ActionConfig :param network_name: Network name or id. :type network_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict :return: Resulting keyword arguments. :rtype: dict """
config = action.config c_kwargs = dict( name=network_name, driver=config.driver, options=config.driver_options, ) if config.internal: c_kwargs['internal'] = True driver_opts = init_options(config.driver_options) if driver_opts: c_kwargs['options'] = {option_name: resolve_value(option_value) for option_name, option_value in iteritems(driver_opts)} update_kwargs(c_kwargs, init_options(config.create_options), kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to remove a network. <END_TASK> <USER_TASK:> Description: def get_network_remove_kwargs(self, action, network_name, kwargs=None): """ Generates keyword arguments for the Docker client to remove a network. :param action: Action configuration. :type action: ActionConfig :param network_name: Network name or id. :type network_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict :return: Resulting keyword arguments. :rtype: dict """
c_kwargs = dict(net_id=network_name) update_kwargs(c_kwargs, kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to add a container to a network. <END_TASK> <USER_TASK:> Description: def get_network_connect_kwargs(self, action, network_name, container_name, endpoint_config=None, kwargs=None): """ Generates keyword arguments for the Docker client to add a container to a network. :param action: Action configuration. :type action: ActionConfig :param network_name: Network name or id. :type network_name: unicode | str :param container_name: Container name or id. :type container_name: unicode | str :param endpoint_config: Network endpoint configuration. :type endpoint_config: dockermap.map.input.NetworkEndpoint :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict :return: Resulting keyword arguments. :rtype: dict """
c_kwargs = dict( container=container_name, net_id=network_name, ) if endpoint_config: c_kwargs.update(self.get_network_create_endpoint_kwargs(action, endpoint_config)) update_kwargs(c_kwargs, kwargs) return c_kwargs
<SYSTEM_TASK:> Generates keyword arguments for the Docker client to remove a container from a network. <END_TASK> <USER_TASK:> Description: def get_network_disconnect_kwargs(self, action, network_name, container_name, kwargs=None): """ Generates keyword arguments for the Docker client to remove a container from a network. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param network_name: Network name or id. :type network_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. :type kwargs: dict :return: Resulting keyword arguments. :rtype: dict """
c_kwargs = dict( container=container_name, net_id=network_name, ) update_kwargs(c_kwargs, kwargs) return c_kwargs