desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Pull and install a plugin. After the plugin is installed, it can be enabled using :py:meth:`~enable_plugin`. Args: remote (string): Remote reference for the plugin to install. The ``:latest`` tag is optional, and is the default if omitted. privileges (list): A list of privileges the user consents to grant to the plugi...
@utils.minimum_version('1.25') def pull_plugin(self, remote, privileges, name=None):
url = self._url('/plugins/pull') params = {'remote': remote} if name: params['name'] = name headers = {} (registry, repo_name) = auth.resolve_repository_name(remote) header = auth.get_config_header(self, registry) if header: headers['X-Registry-Auth'] = header response = ...
'Retrieve a list of installed plugins. Returns: A list of dicts, one per plugin'
@utils.minimum_version('1.25') def plugins(self):
url = self._url('/plugins') return self._result(self._get(url), True)
'Retrieve list of privileges to be granted to a plugin. Args: name (string): Name of the remote plugin to examine. The ``:latest`` tag is optional, and is the default if omitted. Returns: A list of dictionaries representing the plugin\'s permissions'
@utils.minimum_version('1.25') def plugin_privileges(self, name):
params = {'remote': name} url = self._url('/plugins/privileges') return self._result(self._get(url, params=params), True)
'Push a plugin to the registry. Args: name (string): Name of the plugin to upload. The ``:latest`` tag is optional, and is the default if omitted. Returns: ``True`` if successful'
@utils.minimum_version('1.25') @utils.check_resource('name') def push_plugin(self, name):
url = self._url('/plugins/{0}/pull', name) headers = {} (registry, repo_name) = auth.resolve_repository_name(name) header = auth.get_config_header(self, registry) if header: headers['X-Registry-Auth'] = header res = self._post(url, headers=headers) self._raise_for_status(res) ret...
'Remove an installed plugin. Args: name (string): Name of the plugin to remove. The ``:latest`` tag is optional, and is the default if omitted. force (bool): Disable the plugin before removing. This may result in issues if the plugin is in use by a container. Returns: ``True`` if successful'
@utils.minimum_version('1.25') @utils.check_resource('name') def remove_plugin(self, name, force=False):
url = self._url('/plugins/{0}', name) res = self._delete(url, params={'force': force}) self._raise_for_status(res) return True
'Upgrade an installed plugin. Args: name (string): Name of the plugin to upgrade. The ``:latest`` tag is optional and is the default if omitted. remote (string): Remote reference to upgrade to. The ``:latest`` tag is optional and is the default if omitted. privileges (list): A list of privileges the user consents to gr...
@utils.minimum_version('1.26') @utils.check_resource('name') def upgrade_plugin(self, name, remote, privileges):
url = self._url('/plugins/{0}/upgrade', name) params = {'remote': remote} headers = {} (registry, repo_name) = auth.resolve_repository_name(remote) header = auth.get_config_header(self, registry) if header: headers['X-Registry-Auth'] = header response = self._post_json(url, params=pa...
'List networks. Similar to the ``docker networks ls`` command. Args: names (:py:class:`list`): List of names to filter by ids (:py:class:`list`): List of ids to filter by filters (dict): Filters to be processed on the network list. Available filters: - ``driver=[<driver-name>]`` Matches a network\'s driver. - ``label=[...
@minimum_version('1.21') def networks(self, names=None, ids=None, filters=None):
if (filters is None): filters = {} if names: filters['name'] = names if ids: filters['id'] = ids params = {'filters': utils.convert_filters(filters)} url = self._url('/networks') res = self._get(url, params=params) return self._result(res, json=True)
'Create a network. Similar to the ``docker network create``. Args: name (str): Name of the network driver (str): Name of the driver used to create the network options (dict): Driver options as a key-value dictionary ipam (IPAMConfig): Optional custom IP scheme for the network. check_duplicate (bool): Request daemon to ...
@minimum_version('1.21') def create_network(self, name, driver=None, options=None, ipam=None, check_duplicate=None, internal=False, labels=None, enable_ipv6=False, attachable=None, scope=None, ingress=None):
if ((options is not None) and (not isinstance(options, dict))): raise TypeError('options must be a dictionary') data = {'Name': name, 'Driver': driver, 'Options': options, 'IPAM': ipam, 'CheckDuplicate': check_duplicate} if (labels is not None): if version_lt(self._version, '1.23...
'Delete unused networks Args: filters (dict): Filters to process on the prune list. Returns: (dict): A dict containing a list of deleted network names and the amount of disk space reclaimed in bytes. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@minimum_version('1.25') def prune_networks(self, filters=None):
params = {} if filters: params['filters'] = utils.convert_filters(filters) url = self._url('/networks/prune') return self._result(self._post(url, params=params), True)
'Remove a network. Similar to the ``docker network rm`` command. Args: net_id (str): The network\'s id'
@minimum_version('1.21') @check_resource('net_id') def remove_network(self, net_id):
url = self._url('/networks/{0}', net_id) res = self._delete(url) self._raise_for_status(res)
'Get detailed information about a network. Args: net_id (str): ID of network verbose (bool): Show the service details across the cluster in swarm mode.'
@minimum_version('1.21') @check_resource('net_id') def inspect_network(self, net_id, verbose=None):
params = {} if (verbose is not None): if version_lt(self._version, '1.28'): raise InvalidVersion('verbose was introduced in API 1.28') params['verbose'] = verbose url = self._url('/networks/{0}', net_id) res = self._get(url, params=params) return self._resu...
'Connect a container to a network. Args: container (str): container-id/name to be connected to the network net_id (str): network id aliases (:py:class:`list`): A list of aliases for this endpoint. Names in that list can be used within the network to reach the container. Defaults to ``None``. links (:py:class:`list`): A...
@check_resource('container') @minimum_version('1.21') def connect_container_to_network(self, container, net_id, ipv4_address=None, ipv6_address=None, aliases=None, links=None, link_local_ips=None):
data = {'Container': container, 'EndpointConfig': self.create_endpoint_config(aliases=aliases, links=links, ipv4_address=ipv4_address, ipv6_address=ipv6_address, link_local_ips=link_local_ips)} url = self._url('/networks/{0}/connect', net_id) res = self._post_json(url, data=data) self._raise_for_status(...
'Disconnect a container from a network. Args: container (str): container ID or name to be disconnected from the network net_id (str): network ID force (bool): Force the container to disconnect from a network. Default: ``False``'
@check_resource('container') @minimum_version('1.21') def disconnect_container_from_network(self, container, net_id, force=False):
data = {'Container': container} if force: if version_lt(self._version, '1.22'): raise InvalidVersion('Forced disconnect was introduced in API 1.22') data['Force'] = force url = self._url('/networks/{0}/disconnect', net_id) res = self._post_json(url, data=dat...
'Get a tarball of an image. Similar to the ``docker save`` command. Args: image (str): Image name to get Returns: (urllib3.response.HTTPResponse object): The response from the daemon. Raises: :py:class:`docker.errors.APIError` If the server returns an error. Example: >>> image = cli.get_image("fedora:latest") >>> f = o...
@utils.check_resource('image') def get_image(self, image):
res = self._get(self._url('/images/{0}/get', image), stream=True) self._raise_for_status(res) return res.raw
'Show the history of an image. Args: image (str): The image to show history for Returns: (str): The history of the image Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('image') def history(self, image):
res = self._get(self._url('/images/{0}/history', image)) return self._result(res, True)
'List images. Similar to the ``docker images`` command. Args: name (str): Only show images belonging to the repository ``name`` quiet (bool): Only return numeric IDs as a list. all (bool): Show intermediate image layers. By default, these are filtered out. filters (dict): Filters to be processed on the image list. Avai...
def images(self, name=None, quiet=False, all=False, viz=False, filters=None):
if viz: if (utils.compare_version('1.7', self._version) >= 0): raise Exception('Viz output is not supported in API >= 1.7!') return self._result(self._get(self._url('images/viz'))) params = {'filter': name, 'only_ids': (1 if quiet else 0), 'all': (1 if all els...
'Import an image. Similar to the ``docker import`` command. If ``src`` is a string or unicode string, it will first be treated as a path to a tarball on the local system. If there is an error reading from that file, ``src`` will be treated as a URL instead to fetch the image from. You can also pass an open file handle ...
def import_image(self, src=None, repository=None, tag=None, image=None, changes=None, stream_src=False):
if (not (src or image)): raise errors.DockerException('Must specify src or image to import from') u = self._url('/images/create') params = _import_image_params(repository, tag, image, src=(src if isinstance(src, six.string_types) else None), changes=changes) headers = {'Cont...
'Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but allows importing in-memory bytes data. Args: data (bytes collection): Bytes collection containing valid tar data repository (str): The repository to create tag (str): The tag to apply'
def import_image_from_data(self, data, repository=None, tag=None, changes=None):
u = self._url('/images/create') params = _import_image_params(repository, tag, src='-', changes=changes) headers = {'Content-Type': 'application/tar'} return self._result(self._post(u, data=data, params=params, headers=headers, timeout=None))
'Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only supports importing from a tar file on disk. Args: filename (str): Full path to a tar file. repository (str): The repository to create tag (str): The tag to apply Raises: IOError: File does not exist.'
def import_image_from_file(self, filename, repository=None, tag=None, changes=None):
return self.import_image(src=filename, repository=repository, tag=tag, changes=changes)
'Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only supports importing from a URL. Args: url (str): A URL pointing to a tar file. repository (str): The repository to create tag (str): The tag to apply'
def import_image_from_url(self, url, repository=None, tag=None, changes=None):
return self.import_image(src=url, repository=repository, tag=tag, changes=changes)
'Like :py:meth:`~docker.api.image.ImageApiMixin.import_image`, but only supports importing from another image, like the ``FROM`` Dockerfile parameter. Args: image (str): Image name to import from repository (str): The repository to create tag (str): The tag to apply'
def import_image_from_image(self, image, repository=None, tag=None, changes=None):
return self.import_image(image=image, repository=repository, tag=tag, changes=changes)
'Get detailed information about an image. Similar to the ``docker inspect`` command, but only for containers. Args: container (str): The container to inspect Returns: (dict): Similar to the output of ``docker inspect``, but as a single dict Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('image') def inspect_image(self, image):
return self._result(self._get(self._url('/images/{0}/json', image)), True)
'Load an image that was previously saved using :py:meth:`~docker.api.image.ImageApiMixin.get_image` (or ``docker save``). Similar to ``docker load``. Args: data (binary): Image data to be loaded.'
def load_image(self, data):
res = self._post(self._url('/images/load'), data=data) self._raise_for_status(res)
'Delete unused images Args: filters (dict): Filters to process on the prune list. Available filters: - dangling (bool): When set to true (or 1), prune only unused and untagged images. Returns: (dict): A dict containing a list of deleted image IDs and the amount of disk space reclaimed in bytes. Raises: :py:class:`dock...
@utils.minimum_version('1.25') def prune_images(self, filters=None):
url = self._url('/images/prune') params = {} if (filters is not None): params['filters'] = utils.convert_filters(filters) return self._result(self._post(url, params=params), True)
'Pulls an image. Similar to the ``docker pull`` command. Args: repository (str): The repository to pull tag (str): The tag to pull stream (bool): Stream the output as a generator insecure_registry (bool): Use an insecure registry auth_config (dict): Override the credentials that :py:meth:`~docker.api.daemon.DaemonApiMi...
def pull(self, repository, tag=None, stream=False, insecure_registry=False, auth_config=None, decode=False):
if insecure_registry: warnings.warn(INSECURE_REGISTRY_DEPRECATION_WARNING.format('pull()'), DeprecationWarning) if (not tag): (repository, tag) = utils.parse_repository_tag(repository) (registry, repo_name) = auth.resolve_repository_name(repository) params = {'tag': tag, 'fromImage': rep...
'Push an image or a repository to the registry. Similar to the ``docker push`` command. Args: repository (str): The repository to push to tag (str): An optional tag to push stream (bool): Stream the output as a blocking generator insecure_registry (bool): Use ``http://`` to connect to the registry auth_config (dict): O...
def push(self, repository, tag=None, stream=False, insecure_registry=False, auth_config=None, decode=False):
if insecure_registry: warnings.warn(INSECURE_REGISTRY_DEPRECATION_WARNING.format('push()'), DeprecationWarning) if (not tag): (repository, tag) = utils.parse_repository_tag(repository) (registry, repo_name) = auth.resolve_repository_name(repository) u = self._url('/images/{0}/push', repo...
'Remove an image. Similar to the ``docker rmi`` command. Args: image (str): The image to remove force (bool): Force removal of the image noprune (bool): Do not delete untagged parents'
@utils.check_resource('image') def remove_image(self, image, force=False, noprune=False):
params = {'force': force, 'noprune': noprune} res = self._delete(self._url('/images/{0}', image), params=params) self._raise_for_status(res)
'Search for images on Docker Hub. Similar to the ``docker search`` command. Args: term (str): A term to search for. Returns: (list of dicts): The response of the search. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def search(self, term):
return self._result(self._get(self._url('/images/search'), params={'term': term}), True)
'Tag an image into a repository. Similar to the ``docker tag`` command. Args: image (str): The image to tag repository (str): The repository to set for the tag tag (str): The tag name force (bool): Force Returns: (bool): ``True`` if successful Raises: :py:class:`docker.errors.APIError` If the server returns an error. E...
@utils.check_resource('image') def tag(self, image, repository, tag=None, force=False):
params = {'tag': tag, 'repo': repository, 'force': (1 if force else 0)} url = self._url('/images/{0}/tag', image) res = self._post(url, params=params) self._raise_for_status(res) return (res.status_code == 201)
'Attach to a container. The ``.logs()`` function is a wrapper around this method, which you can use instead if you want to fetch/stream container output without first retrieving the entire backlog. Args: container (str): The container to attach to. stdout (bool): Include stdout. stderr (bool): Include stderr. stream (b...
@utils.check_resource('container') def attach(self, container, stdout=True, stderr=True, stream=False, logs=False):
params = {'logs': ((logs and 1) or 0), 'stdout': ((stdout and 1) or 0), 'stderr': ((stderr and 1) or 0), 'stream': ((stream and 1) or 0)} headers = {'Connection': 'Upgrade', 'Upgrade': 'tcp'} u = self._url('/containers/{0}/attach', container) response = self._post(u, headers=headers, params=params, stre...
'Like ``attach``, but returns the underlying socket-like object for the HTTP request. Args: container (str): The container to attach to. params (dict): Dictionary of request parameters (e.g. ``stdout``, ``stderr``, ``stream``). ws (bool): Use websockets instead of raw HTTP. Raises: :py:class:`docker.errors.APIError` If...
@utils.check_resource('container') def attach_socket(self, container, params=None, ws=False):
if (params is None): params = {'stdout': 1, 'stderr': 1, 'stream': 1} if ws: return self._attach_websocket(container, params) headers = {'Connection': 'Upgrade', 'Upgrade': 'tcp'} u = self._url('/containers/{0}/attach', container) return self._get_raw_response_socket(self.post(u, Non...
'Commit a container to an image. Similar to the ``docker commit`` command. Args: container (str): The image hash of the container repository (str): The repository to push the image to tag (str): The tag to push message (str): A commit message author (str): The name of the author changes (str): Dockerfile instructions t...
@utils.check_resource('container') def commit(self, container, repository=None, tag=None, message=None, author=None, changes=None, conf=None):
params = {'container': container, 'repo': repository, 'tag': tag, 'comment': message, 'author': author, 'changes': changes} u = self._url('/commit') return self._result(self._post_json(u, data=conf, params=params), json=True)
'List containers. Similar to the ``docker ps`` command. Args: quiet (bool): Only display numeric Ids all (bool): Show all containers. Only running containers are shown by default trunc (bool): Truncate output latest (bool): Show only the latest created container, include non-running ones. since (str): Show only contain...
def containers(self, quiet=False, all=False, trunc=False, latest=False, since=None, before=None, limit=(-1), size=False, filters=None):
params = {'limit': (1 if latest else limit), 'all': (1 if all else 0), 'size': (1 if size else 0), 'trunc_cmd': (1 if trunc else 0), 'since': since, 'before': before} if filters: params['filters'] = utils.convert_filters(filters) u = self._url('/containers/json') res = self._result(self._get(u, ...
'Identical to the ``docker cp`` command. Get files/folders from the container. **Deprecated for API version >= 1.20.** Use :py:meth:`~ContainerApiMixin.get_archive` instead. Args: container (str): The container to copy from resource (str): The path within the container Returns: The contents of the file as a string Rais...
@utils.check_resource('container') def copy(self, container, resource):
if utils.version_gte(self._version, '1.20'): warnings.warn('APIClient.copy() is deprecated for API version >= 1.20, please use get_archive() instead', DeprecationWarning) res = self._post_json(self._url('/containers/{0}/copy', container), data={'Resource': resource}, str...
'Creates a container. Parameters are similar to those for the ``docker run`` command except it doesn\'t support the attach options (``-a``). The arguments that are passed directly to this function are host-independent configuration options. Host-specific configuration is passed with the `host_config` argument. You\'ll ...
def create_container(self, image, command=None, hostname=None, user=None, detach=False, stdin_open=False, tty=False, mem_limit=None, ports=None, environment=None, dns=None, volumes=None, volumes_from=None, network_disabled=False, name=None, entrypoint=None, cpu_shares=None, working_dir=None, domainname=None, memswap_li...
if isinstance(volumes, six.string_types): volumes = [volumes] if (host_config and (utils.compare_version('1.15', self._version) < 0)): raise errors.InvalidVersion('host_config is not supported in API < 1.15') config = self.create_container_config(image, command, hostname...
'Create a dictionary for the ``host_config`` argument to :py:meth:`create_container`. Args: auto_remove (bool): enable auto-removal of the container on daemon side when the container\'s process exits. binds (dict): Volumes to bind. See :py:meth:`create_container` for more information. blkio_weight_device: Block IO weig...
def create_host_config(self, *args, **kwargs):
if (not kwargs): kwargs = {} if ('version' in kwargs): raise TypeError("create_host_config() got an unexpected keyword argument 'version'") kwargs['version'] = self._version return HostConfig(*args, **kwargs)
'Create a networking config dictionary to be used as the ``networking_config`` parameter in :py:meth:`create_container`. Args: endpoints_config (dict): A dictionary mapping network names to endpoint configurations generated by :py:meth:`create_endpoint_config`. Returns: (dict) A networking config. Example: >>> docker_c...
def create_networking_config(self, *args, **kwargs):
return NetworkingConfig(*args, **kwargs)
'Create an endpoint config dictionary to be used with :py:meth:`create_networking_config`. Args: aliases (:py:class:`list`): A list of aliases for this endpoint. Names in that list can be used within the network to reach the container. Defaults to ``None``. links (:py:class:`list`): A list of links for this endpoint. C...
def create_endpoint_config(self, *args, **kwargs):
return EndpointConfig(self._version, *args, **kwargs)
'Inspect changes on a container\'s filesystem. Args: container (str): The container to diff Returns: (str) Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('container') def diff(self, container):
return self._result(self._get(self._url('/containers/{0}/changes', container)), True)
'Export the contents of a filesystem as a tar archive. Args: container (str): The container to export Returns: (str): The filesystem tar archive Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('container') def export(self, container):
res = self._get(self._url('/containers/{0}/export', container), stream=True) self._raise_for_status(res) return res.raw
'Retrieve a file or folder from a container in the form of a tar archive. Args: container (str): The container where the file is located path (str): Path to the file or folder to retrieve Returns: (tuple): First element is a raw tar data stream. Second element is a dict containing ``stat`` information on the specified ...
@utils.check_resource('container') @utils.minimum_version('1.20') def get_archive(self, container, path):
params = {'path': path} url = self._url('/containers/{0}/archive', container) res = self._get(url, params=params, stream=True) self._raise_for_status(res) encoded_stat = res.headers.get('x-docker-container-path-stat') return (res.raw, (utils.decode_json_header(encoded_stat) if encoded_stat else ...
'Identical to the `docker inspect` command, but only for containers. Args: container (str): The container to inspect Returns: (dict): Similar to the output of `docker inspect`, but as a single dict Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('container') def inspect_container(self, container):
return self._result(self._get(self._url('/containers/{0}/json', container)), True)
'Kill a container or send a signal to a container. Args: container (str): The container to kill signal (str or int): The signal to send. Defaults to ``SIGKILL`` Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('container') def kill(self, container, signal=None):
url = self._url('/containers/{0}/kill', container) params = {} if (signal is not None): if (not isinstance(signal, six.string_types)): signal = int(signal) params['signal'] = signal res = self._post(url, params=params) self._raise_for_status(res)
'Get logs from a container. Similar to the ``docker logs`` command. The ``stream`` parameter makes the ``logs`` function return a blocking generator you can iterate over to retrieve log output as it happens. Args: container (str): The container to get logs from stdout (bool): Get ``STDOUT`` stderr (bool): Get ``STDERR`...
@utils.check_resource('container') def logs(self, container, stdout=True, stderr=True, stream=False, timestamps=False, tail='all', since=None, follow=None):
if (utils.compare_version('1.11', self._version) >= 0): if (follow is None): follow = stream params = {'stderr': ((stderr and 1) or 0), 'stdout': ((stdout and 1) or 0), 'timestamps': ((timestamps and 1) or 0), 'follow': ((follow and 1) or 0)} if (utils.compare_version('1.13', sel...
'Pauses all processes within a container. Args: container (str): The container to pause Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('container') def pause(self, container):
url = self._url('/containers/{0}/pause', container) res = self._post(url) self._raise_for_status(res)
'Lookup the public-facing port that is NAT-ed to ``private_port``. Identical to the ``docker port`` command. Args: container (str): The container to look up private_port (int): The private port to inspect Returns: (list of dict): The mapping for the host ports Raises: :py:class:`docker.errors.APIError` If the server re...
@utils.check_resource('container') def port(self, container, private_port):
res = self._get(self._url('/containers/{0}/json', container)) self._raise_for_status(res) json_ = res.json() private_port = str(private_port) h_ports = None port_settings = json_.get('NetworkSettings', {}).get('Ports') if (port_settings is None): return None if ('/' in private_po...
'Insert a file or folder in an existing container using a tar archive as source. Args: container (str): The container where the file(s) will be extracted path (str): Path inside the container where the file(s) will be extracted. Must exist. data (bytes): tar data to be extracted Returns: (bool): True if the call succee...
@utils.check_resource('container') @utils.minimum_version('1.20') def put_archive(self, container, path, data):
params = {'path': path} url = self._url('/containers/{0}/archive', container) res = self._put(url, params=params, data=data) self._raise_for_status(res) return (res.status_code == 200)
'Delete stopped containers Args: filters (dict): Filters to process on the prune list. Returns: (dict): A dict containing a list of deleted container IDs and the amount of disk space reclaimed in bytes. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.25') def prune_containers(self, filters=None):
params = {} if filters: params['filters'] = utils.convert_filters(filters) url = self._url('/containers/prune') return self._result(self._post(url, params=params), True)
'Remove a container. Similar to the ``docker rm`` command. Args: container (str): The container to remove v (bool): Remove the volumes associated with the container link (bool): Remove the specified link and not the underlying container force (bool): Force the removal of a running container (uses ``SIGKILL``) Raises: :...
@utils.check_resource('container') def remove_container(self, container, v=False, link=False, force=False):
params = {'v': v, 'link': link, 'force': force} res = self._delete(self._url('/containers/{0}', container), params=params) self._raise_for_status(res)
'Rename a container. Similar to the ``docker rename`` command. Args: container (str): ID of the container to rename name (str): New name for the container Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.17') @utils.check_resource('container') def rename(self, container, name):
url = self._url('/containers/{0}/rename', container) params = {'name': name} res = self._post(url, params=params) self._raise_for_status(res)
'Resize the tty session. Args: container (str or dict): The container to resize height (int): Height of tty session width (int): Width of tty session Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('container') def resize(self, container, height, width):
params = {'h': height, 'w': width} url = self._url('/containers/{0}/resize', container) res = self._post(url, params=params) self._raise_for_status(res)
'Restart a container. Similar to the ``docker restart`` command. Args: container (str or dict): The container to restart. If a dict, the ``Id`` key is used. timeout (int): Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds. Raises: :py:class:`...
@utils.check_resource('container') def restart(self, container, timeout=10):
params = {'t': timeout} url = self._url('/containers/{0}/restart', container) res = self._post(url, params=params) self._raise_for_status(res)
'Start a container. Similar to the ``docker start`` command, but doesn\'t support attach options. **Deprecation warning:** Passing configuration options in ``start`` is no longer supported. Users are expected to provide host config options in the ``host_config`` parameter of :py:meth:`~ContainerApiMixin.create_containe...
@utils.check_resource('container') def start(self, container, *args, **kwargs):
if (args or kwargs): raise errors.DeprecatedMethod('Providing configuration in the start() method is no longer supported. Use the host_config param in create_container instead.') url = self._url('/containers/{0}/start', container) res = self._post(url)...
'Stream statistics for a specific container. Similar to the ``docker stats`` command. Args: container (str): The container to stream statistics from decode (bool): If set to true, stream will be decoded into dicts on the fly. False by default. stream (bool): If set to false, only the current stats will be returned inst...
@utils.minimum_version('1.17') @utils.check_resource('container') def stats(self, container, decode=None, stream=True):
url = self._url('/containers/{0}/stats', container) if stream: return self._stream_helper(self._get(url, stream=True), decode=decode) else: return self._result(self._get(url, params={'stream': False}), json=True)
'Stops a container. Similar to the ``docker stop`` command. Args: container (str): The container to stop timeout (int): Timeout in seconds to wait for the container to stop before sending a ``SIGKILL``. Default: 10 Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('container') def stop(self, container, timeout=10):
params = {'t': timeout} url = self._url('/containers/{0}/stop', container) res = self._post(url, params=params, timeout=(timeout + (self.timeout or 0))) self._raise_for_status(res)
'Display the running processes of a container. Args: container (str): The container to inspect ps_args (str): An optional arguments passed to ps (e.g. ``aux``) Returns: (str): The output of the top Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('container') def top(self, container, ps_args=None):
u = self._url('/containers/{0}/top', container) params = {} if (ps_args is not None): params['ps_args'] = ps_args return self._result(self._get(u, params=params), True)
'Unpause all processes within a container. Args: container (str): The container to unpause'
@utils.check_resource('container') def unpause(self, container):
url = self._url('/containers/{0}/unpause', container) res = self._post(url) self._raise_for_status(res)
'Update resource configs of one or more containers. Args: container (str): The container to inspect blkio_weight (int): Block IO (relative weight), between 10 and 1000 cpu_period (int): Limit CPU CFS (Completely Fair Scheduler) period cpu_quota (int): Limit CPU CFS (Completely Fair Scheduler) quota cpu_shares (int): CP...
@utils.minimum_version('1.22') @utils.check_resource('container') def update_container(self, container, blkio_weight=None, cpu_period=None, cpu_quota=None, cpu_shares=None, cpuset_cpus=None, cpuset_mems=None, mem_limit=None, mem_reservation=None, memswap_limit=None, kernel_memory=None, restart_policy=None):
url = self._url('/containers/{0}/update', container) data = {} if blkio_weight: data['BlkioWeight'] = blkio_weight if cpu_period: data['CpuPeriod'] = cpu_period if cpu_shares: data['CpuShares'] = cpu_shares if cpu_quota: data['CpuQuota'] = cpu_quota if cpuset_...
'Block until a container stops, then return its exit code. Similar to the ``docker wait`` command. Args: container (str or dict): The container to wait on. If a dict, the ``Id`` key is used. timeout (int): Request timeout Returns: (int): The exit code of the container. Returns ``-1`` if the API responds without a ``Sta...
@utils.check_resource('container') def wait(self, container, timeout=None):
url = self._url('/containers/{0}/wait', container) res = self._post(url, timeout=timeout) self._raise_for_status(res) json_ = res.json() if ('StatusCode' in json_): return json_['StatusCode'] return (-1)
'Configure a client with these TLS options.'
def configure_client(self, client):
client.ssl_version = self.ssl_version if (self.verify and self.ca_cert): client.verify = self.ca_cert else: client.verify = self.verify if self.cert: client.cert = self.cert client.mount('https://', SSLAdapter(ssl_version=self.ssl_version, assert_hostname=self.assert_hostname...
'Return a client configured from environment variables. The environment variables used are the same as those used by the Docker command-line client. They are: .. envvar:: DOCKER_HOST The URL to the Docker host. .. envvar:: DOCKER_TLS_VERIFY Verify the host against a CA certificate. .. envvar:: DOCKER_CERT_PATH A path t...
@classmethod def from_env(cls, **kwargs):
timeout = kwargs.pop('timeout', DEFAULT_TIMEOUT_SECONDS) version = kwargs.pop('version', None) return cls(timeout=timeout, version=version, **kwargs_from_env(**kwargs))
'An object for managing containers on the server. See the :doc:`containers documentation <containers>` for full details.'
@property def containers(self):
return ContainerCollection(client=self)
'An object for managing images on the server. See the :doc:`images documentation <images>` for full details.'
@property def images(self):
return ImageCollection(client=self)
'An object for managing networks on the server. See the :doc:`networks documentation <networks>` for full details.'
@property def networks(self):
return NetworkCollection(client=self)
'An object for managing nodes on the server. See the :doc:`nodes documentation <nodes>` for full details.'
@property def nodes(self):
return NodeCollection(client=self)
'An object for managing plugins on the server. See the :doc:`plugins documentation <plugins>` for full details.'
@property def plugins(self):
return PluginCollection(client=self)
'An object for managing secrets on the server. See the :doc:`secrets documentation <secrets>` for full details.'
@property def secrets(self):
return SecretCollection(client=self)
'An object for managing services on the server. See the :doc:`services documentation <services>` for full details.'
@property def services(self):
return ServiceCollection(client=self)
'An object for managing a swarm on the server. See the :doc:`swarm documentation <swarm>` for full details.'
@property def swarm(self):
return Swarm(client=self)
'An object for managing volumes on the server. See the :doc:`volumes documentation <volumes>` for full details.'
@property def volumes(self):
return VolumeCollection(client=self)
'Ensure assert_hostname is set correctly on our pool We already take care of a normal poolmanager via init_poolmanager But we still need to take care of when there is a proxy poolmanager'
def get_connection(self, *args, **kwargs):
conn = super(SSLAdapter, self).get_connection(*args, **kwargs) if (conn.assert_hostname != self.assert_hostname): conn.assert_hostname = self.assert_hostname return conn
'Test no warnings are produced when using the client.'
def test_resource_warnings(self):
with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') client = docker.APIClient(version='auto', **kwargs_from_env()) client.images() client.close() del client assert (len(w) == 0), 'No warnings produced: {0}'.format(w[0].message)
'Yields a stream that is valid tar data of size n_bytes.'
@contextlib.contextmanager def dummy_tar_stream(self, n_bytes):
with tempfile.NamedTemporaryFile() as tar_file: self.write_dummy_tar_content(n_bytes, tar_file) tar_file.seek(0) (yield tar_file)
'Yields the name of a valid tar file of size n_bytes.'
@contextlib.contextmanager def dummy_tar_file(self, n_bytes):
with tempfile.NamedTemporaryFile(delete=False) as tar_file: self.write_dummy_tar_content(n_bytes, tar_file) tar_file.seek(0) (yield tar_file.name)
'Serve data from an IO stream over HTTP.'
@contextlib.contextmanager def temporary_http_file_server(self, stream):
class Handler(BaseHTTPServer.BaseHTTPRequestHandler, ): def do_GET(self): self.send_response(200) self.send_header('Content-Type', 'application/x-tar') self.end_headers() shutil.copyfileobj(stream, self.wfile) server = socketserver.TCPServer(('', 0), Handl...
'The status_code property is present with 200 response.'
def test_status_code_200(self):
resp = requests.Response() resp.status_code = 200 err = APIError('', response=resp) assert (err.status_code == 200)
'The status_code property is present with 400 response.'
def test_status_code_400(self):
resp = requests.Response() resp.status_code = 400 err = APIError('', response=resp) assert (err.status_code == 400)
'The status_code property is present with 500 response.'
def test_status_code_500(self):
resp = requests.Response() resp.status_code = 500 err = APIError('', response=resp) assert (err.status_code == 500)
'Report not server error on 200 response.'
def test_is_server_error_200(self):
resp = requests.Response() resp.status_code = 200 err = APIError('', response=resp) assert (err.is_server_error() is False)
'Report not server error on 300 response.'
def test_is_server_error_300(self):
resp = requests.Response() resp.status_code = 300 err = APIError('', response=resp) assert (err.is_server_error() is False)
'Report not server error on 400 response.'
def test_is_server_error_400(self):
resp = requests.Response() resp.status_code = 400 err = APIError('', response=resp) assert (err.is_server_error() is False)
'Report server error on 500 response.'
def test_is_server_error_500(self):
resp = requests.Response() resp.status_code = 500 err = APIError('', response=resp) assert (err.is_server_error() is True)
'Report not client error on 500 response.'
def test_is_client_error_500(self):
resp = requests.Response() resp.status_code = 500 err = APIError('', response=resp) assert (err.is_client_error() is False)
'Report client error on 400 response.'
def test_is_client_error_400(self):
resp = requests.Response() resp.status_code = 400 err = APIError('', response=resp) assert (err.is_client_error() is True)
'The massage does not contain stderr'
def test_container_without_stderr(self):
client = make_fake_client() container = client.containers.get(FAKE_CONTAINER_ID) command = 'echo Hello World' exit_status = 42 image = FAKE_IMAGE_ID stderr = None err = ContainerError(container, exit_status, command, image, stderr) msg = "Command '{}' in image '{}' r...
'The massage contains stderr'
def test_container_with_stderr(self):
client = make_fake_client() container = client.containers.get(FAKE_CONTAINER_ID) command = 'echo Hello World' exit_status = 42 image = FAKE_IMAGE_ID stderr = 'Something went wrong' err = ContainerError(container, exit_status, command, image, stderr) msg = "Command '{}' ...
'Test that environment variables are passed through to utils.kwargs_from_env(). KwargsFromEnvTest tests that environment variables are parsed correctly.'
def test_from_env(self):
os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376', DOCKER_CERT_PATH=TEST_CERT_DIR, DOCKER_TLS_VERIFY='1') client = docker.from_env() self.assertEqual(client.api.base_url, 'https://192.168.59.103:2376')
'Test that the timeout is disabled on a generic socket object.'
def test_disable_socket_timeout(self):
socket = self.DummySocket() self.client._disable_socket_timeout(socket) self.assertEqual(socket.timeout, None)
'Test that the timeouts are disabled on a generic socket object and it\'s _sock object if present.'
def test_disable_socket_timeout2(self):
socket = self.DummySocket() socket._sock = self.DummySocket() self.client._disable_socket_timeout(socket) self.assertEqual(socket.timeout, None) self.assertEqual(socket._sock.timeout, None)
'Test that a non-blocking socket does not get set to blocking.'
def test_disable_socket_timout_non_blocking(self):
socket = self.DummySocket() socket._sock = self.DummySocket(0.0) self.client._disable_socket_timeout(socket) self.assertEqual(socket.timeout, None) self.assertEqual(socket._sock.timeout, 0.0)
'Generates a temporary file for tests with the content of \'file_content\' and returns the filename. Don\'t forget to unlink the file with os.unlink() after.'
def generate_tempfile(self, file_content=None):
local_tempfile = tempfile.NamedTemporaryFile(delete=False) local_tempfile.write(file_content.encode('UTF-8')) local_tempfile.close() return local_tempfile.name
'Even if the .dockerignore file explicitly says to exclude Dockerfile and/or .dockerignore, don\'t exclude them from the actual tar file.'
def test_exclude_dockerfile_dockerignore(self):
assert (self.exclude(['Dockerfile', '.dockerignore']) == convert_paths(self.all_paths))
'If we\'re using a custom Dockerfile, make sure that\'s not excluded.'
def test_exclude_custom_dockerfile(self):
assert (self.exclude(['*'], dockerfile='Dockerfile.alt') == set(['Dockerfile.alt', '.dockerignore'])) assert (self.exclude(['*'], dockerfile='foo/Dockerfile3') == convert_paths(set(['foo/Dockerfile3', '.dockerignore'])))
'When the Compose file specifies a trailing slash in the container path, make sure we copy the volume over when recreating.'
def test_recreate_preserves_volume_with_trailing_slash(self):
service = self.create_service(u'data', volumes=[VolumeSpec.parse(u'/data/')]) old_container = create_and_start_container(service) volume_path = old_container.get_mount(u'/data')[u'Source'] new_container = service.recreate_container(old_container) self.assertEqual(new_container.get_mount(u'/data')[u'...
'When an image specifies a volume, and the Compose file specifies a host path but adds a trailing slash, make sure that we don\'t create duplicate binds.'
def test_duplicate_volume_trailing_slash(self):
host_path = u'/tmp/data' container_path = u'/data' volumes = [VolumeSpec.parse(u'{}:{}/'.format(host_path, container_path))] tmp_container = self.client.create_container(u'busybox', u'true', volumes={container_path: {}}, labels={u'com.docker.compose.test_image': u'true'}, host_config={}) image = sel...
'Given there are some stopped containers and scale is called with a desired number that is the same as the number of stopped containers, test that those containers are restarted and not removed/recreated.'
@pytest.mark.skipif(SWARM_SKIP_CONTAINERS_ALL, reason=u'Swarm /containers/json bug') def test_scale_with_stopped_containers(self):
service = self.create_service(u'web') next_number = service._next_container_number() valid_numbers = [next_number, (next_number + 1)] service.create_container(number=next_number) service.create_container(number=(next_number + 1)) with mock.patch(u'sys.stderr', new_callable=StringIO) as mock_stde...
'Given there are some stopped containers and scale is called with a desired number that is greater than the number of stopped containers, test that those containers are restarted and required number are created.'
def test_scale_with_stopped_containers_and_needing_creation(self):
service = self.create_service(u'web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) for container in service.containers(): self.assertFalse(container.is_running) with mock.patch(u'sys.stderr', new_callable=StringIO) as mock_stderr: ...
'Test that when scaling if the API returns an error, that error is handled and the remaining threads continue.'
def test_scale_with_api_error(self):
service = self.create_service(u'web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) with mock.patch(u'compose.container.Container.create', side_effect=APIError(message=u'testing', response={}, explanation=u'Boom')): with mock.patch(u'sys....
'Test that when scaling if the API returns an error, that is not of type APIError, that error is re-raised.'
def test_scale_with_unexpected_exception(self):
service = self.create_service(u'web') next_number = service._next_container_number() service.create_container(number=next_number, quiet=True) with mock.patch(u'compose.container.Container.create', side_effect=ValueError(u'BOOM')): with self.assertRaises(ValueError): service.scale(3) ...
'Test that calling scale with a desired number that is equal to the number of containers already running results in no change.'
@mock.patch(u'compose.service.log') def test_scale_with_desired_number_already_achieved(self, mock_log):
service = self.create_service(u'web') next_number = service._next_container_number() container = service.create_container(number=next_number, quiet=True) container.start() container.inspect() assert container.is_running assert (len(service.containers()) == 1) service.scale(1) assert ...