desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Pauses all processes within this container. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def pause(self):
return self.client.api.pause(self.id)
'Insert a file or folder in this container using a tar archive as source. Args: 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 succeeds. Raises: :py:class:`~docker.errors.APIError` If an error occurs.'
def put_archive(self, path, data):
return self.client.api.put_archive(self.id, path, data)
'Remove this container. Similar to the ``docker rm`` command. Args: 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: :py:class:`docker.errors.APIError` If t...
def remove(self, **kwargs):
return self.client.api.remove_container(self.id, **kwargs)
'Rename this container. Similar to the ``docker rename`` command. Args: name (str): New name for the container Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def rename(self, name):
return self.client.api.rename(self.id, name)
'Resize the tty session. Args: height (int): Height of tty session width (int): Width of tty session Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def resize(self, height, width):
return self.client.api.resize(self.id, height, width)
'Restart this container. Similar to the ``docker restart`` command. Args: 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:`docker.errors.APIError` If the server returns an error.'
def restart(self, **kwargs):
return self.client.api.restart(self.id, **kwargs)
'Start this container. Similar to the ``docker start`` command, but doesn\'t support attach options. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def start(self, **kwargs):
return self.client.api.start(self.id, **kwargs)
'Stream statistics for this container. Similar to the ``docker stats`` command. Args: 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 instead of a stream. True by default. Raises: :py:class:`docker.err...
def stats(self, **kwargs):
return self.client.api.stats(self.id, **kwargs)
'Stops a container. Similar to the ``docker stop`` command. Args: 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.'
def stop(self, **kwargs):
return self.client.api.stop(self.id, **kwargs)
'Display the running processes of the container. Args: 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.'
def top(self, **kwargs):
return self.client.api.top(self.id, **kwargs)
'Unpause all processes within the container. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def unpause(self):
return self.client.api.unpause(self.id)
'Update resource configuration of the containers. Args: 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): CPU shares (relative weight) cpuset_cpus (str)...
def update(self, **kwargs):
return self.client.api.update_container(self.id, **kwargs)
'Block until the container stops, then return its exit code. Similar to the ``docker wait`` command. Args: timeout (int): Request timeout Returns: (int): The exit code of the container. Returns ``-1`` if the API responds without a ``StatusCode`` attribute. Raises: :py:class:`requests.exceptions.ReadTimeout` If the time...
def wait(self, **kwargs):
return self.client.api.wait(self.id, **kwargs)
'Run a container. By default, it will wait for the container to finish and return its logs, similar to ``docker run``. If the ``detach`` argument is ``True``, it will start the container and immediately return a :py:class:`Container` object, similar to ``docker run -d``. Example: Run a container and get its output: >>>...
def run(self, image, command=None, stdout=True, stderr=False, remove=False, **kwargs):
if isinstance(image, Image): image = image.id detach = kwargs.pop('detach', False) if (detach and remove): raise RuntimeError("The options 'detach' and 'remove' cannot be used together.") if (kwargs.get('network') and kwargs.get('network_mode')): raise Run...
'Create a container without starting it. Similar to ``docker create``. Takes the same arguments as :py:meth:`run`, except for ``stdout``, ``stderr``, and ``remove``. Returns: A :py:class:`Container` object. Raises: :py:class:`docker.errors.ImageNotFound` If the specified image does not exist. :py:class:`docker.errors.A...
def create(self, image, command=None, **kwargs):
if isinstance(image, Image): image = image.id kwargs['image'] = image kwargs['command'] = command kwargs['version'] = self.client.api._version create_kwargs = _create_container_args(kwargs) resp = self.client.api.create_container(**create_kwargs) return self.get(resp['Id'])
'Get a container by name or ID. Args: container_id (str): Container name or ID. Returns: A :py:class:`Container` object. Raises: :py:class:`docker.errors.NotFound` If the container does not exist. :py:class:`docker.errors.APIError` If the server returns an error.'
def get(self, container_id):
resp = self.client.api.inspect_container(container_id) return self.prepare_model(resp)
'List containers. Similar to the ``docker ps`` command. Args: all (bool): Show all containers. Only running containers are shown by default since (str): Show only containers created since Id or Name, include non-running ones before (str): Show only container created before Id or Name, include non-running ones limit (in...
def list(self, all=False, before=None, filters=None, limit=(-1), since=None):
resp = self.client.api.containers(all=all, before=before, filters=filters, limit=limit, since=since) return [self.get(r['Id']) for r in resp]
'The service\'s name.'
@property def name(self):
return self.attrs['Spec']['Name']
'The version number of the service. If this is not the same as the server, the :py:meth:`update` function will not work and you will need to call :py:meth:`reload` before calling it again.'
@property def version(self):
return self.attrs.get('Version').get('Index')
'Stop and remove the service. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def remove(self):
return self.client.api.remove_service(self.id)
'List the tasks in this service. Args: filters (dict): A map of filters to process on the tasks list. Valid filters: ``id``, ``name``, ``node``, ``label``, and ``desired-state``. Returns: (:py:class:`list`): List of task dictionaries. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def tasks(self, filters=None):
if (filters is None): filters = {} filters['service'] = self.id return self.client.api.tasks(filters=filters)
'Update a service\'s configuration. Similar to the ``docker service update`` command. Takes the same parameters as :py:meth:`~ServiceCollection.create`. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def update(self, **kwargs):
if ('image' not in kwargs): spec = self.attrs['Spec']['TaskTemplate']['ContainerSpec'] kwargs['image'] = spec['Image'] create_kwargs = _get_create_service_kwargs('update', kwargs) return self.client.api.update_service(self.id, self.version, **create_kwargs)
'Get log stream for the service. Note: This method works only for services with the ``json-file`` or ``journald`` logging drivers. Args: details (bool): Show extra details provided to logs. Default: ``False`` follow (bool): Keep connection open to read logs as they are sent by the Engine. Default: ``False`` stdout (boo...
def logs(self, **kwargs):
is_tty = self.attrs['Spec']['TaskTemplate']['ContainerSpec'].get('TTY', False) return self.client.api.service_logs(self.id, is_tty=is_tty, **kwargs)
'Create a service. Similar to the ``docker service create`` command. Args: image (str): The image name to use for the containers. command (list of str or str): Command to run. args (list of str): Arguments to the command. constraints (list of str): Placement constraints. container_labels (dict): Labels to apply to the ...
def create(self, image, command=None, **kwargs):
kwargs['image'] = image kwargs['command'] = command create_kwargs = _get_create_service_kwargs('create', kwargs) service_id = self.client.api.create_service(**create_kwargs) return self.get(service_id)
'Get a service. Args: service_id (str): The ID of the service. Returns: (:py:class:`Service`): The service. Raises: :py:class:`docker.errors.NotFound` If the service does not exist. :py:class:`docker.errors.APIError` If the server returns an error.'
def get(self, service_id):
return self.prepare_model(self.client.api.inspect_service(service_id))
'List services. Args: filters (dict): Filters to process on the nodes list. Valid filters: ``id`` and ``name``. Default: ``None``. Returns: (list of :py:class:`Service`): The services. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def list(self, **kwargs):
return [self.prepare_model(s) for s in self.client.api.services(**kwargs)]
'The labels of an image as dictionary.'
@property def labels(self):
result = self.attrs['Config'].get('Labels') return (result or {})
'The ID of the image truncated to 10 characters, plus the ``sha256:`` prefix.'
@property def short_id(self):
if self.id.startswith('sha256:'): return self.id[:17] return self.id[:10]
'The image\'s tags.'
@property def tags(self):
tags = self.attrs.get('RepoTags') if (tags is None): tags = [] return [tag for tag in tags if (tag != '<none>:<none>')]
'Show the history of an image. Returns: (str): The history of the image. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def history(self):
return self.client.api.history(self.id)
'Get a tarball of an image. Similar to the ``docker save`` command. 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.images.get("fedora:latest") >>> resp = image.save() >>> f = open(\'/tmp/f...
def save(self):
return self.client.api.get_image(self.id)
'Tag this image into a repository. Similar to the ``docker tag`` command. Args: repository (str): The repository to set for the tag tag (str): The tag name force (bool): Force Raises: :py:class:`docker.errors.APIError` If the server returns an error. Returns: (bool): ``True`` if successful'
def tag(self, repository, tag=None, **kwargs):
return self.client.api.tag(self.id, repository, tag=tag, **kwargs)
'Build an image and return it. Similar to the ``docker build`` command. Either ``path`` or ``fileobj`` must be set. If you have a tar file for the Docker build context (including a Dockerfile) already, pass a readable file-like object to ``fileobj`` and also pass ``custom_context=True``. If the stream is compressed als...
def build(self, **kwargs):
resp = self.client.api.build(**kwargs) if isinstance(resp, six.string_types): return self.get(resp) last_event = None image_id = None for chunk in json_stream(resp): if ('error' in chunk): raise BuildError(chunk['error']) if ('stream' in chunk): match ...
'Gets an image. Args: name (str): The name of the image. Returns: (:py:class:`Image`): The image. Raises: :py:class:`docker.errors.ImageNotFound` If the image does not exist. :py:class:`docker.errors.APIError` If the server returns an error.'
def get(self, name):
return self.prepare_model(self.client.api.inspect_image(name))
'List images on the server. Args: name (str): Only show images belonging to the repository ``name`` all (bool): Show intermediate image layers. By default, these are filtered out. filters (dict): Filters to be processed on the image list. Available filters: - ``dangling`` (bool) - ``label`` (str): format either ``key``...
def list(self, name=None, all=False, filters=None):
resp = self.client.api.images(name=name, all=all, filters=filters) return [self.prepare_model(r) for r in resp]
'Load an image that was previously saved using :py:meth:`~docker.models.images.Image.save` (or ``docker save``). Similar to ``docker load``. Args: data (binary): Image data to be loaded. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def load(self, data):
return self.client.api.load_image(data)
'Pull an image of the given name and return it. Similar to the ``docker pull`` command. If you want to get the raw pull output, use the :py:meth:`~docker.api.image.ImageApiMixin.pull` method in the low-level API. Args: repository (str): The repository to pull tag (str): The tag to pull insecure_registry (bool): Use an ...
def pull(self, name, tag=None, **kwargs):
self.client.api.pull(name, tag=tag, **kwargs) return self.get(('{0}:{1}'.format(name, tag) if tag else name))
'The version number of the swarm. If this is not the same as the server, the :py:meth:`update` function will not work and you will need to call :py:meth:`reload` before calling it again.'
@property def version(self):
return self.attrs.get('Version').get('Index')
'Initialize a new swarm on this Engine. Args: advertise_addr (str): Externally reachable address advertised to other nodes. This can either be an address/port combination in the form ``192.168.1.1:4567``, or an interface followed by a port number, like ``eth0:4567``. If the port number is omitted, the port number from ...
def init(self, advertise_addr=None, listen_addr='0.0.0.0:2377', force_new_cluster=False, **kwargs):
init_kwargs = {'advertise_addr': advertise_addr, 'listen_addr': listen_addr, 'force_new_cluster': force_new_cluster} init_kwargs['swarm_spec'] = SwarmSpec(**kwargs) self.client.api.init_swarm(**init_kwargs) self.reload()
'Inspect the swarm on the server and store the response in :py:attr:`attrs`. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def reload(self):
self.attrs = self.client.api.inspect_swarm()
'Update the swarm\'s configuration. It takes the same arguments as :py:meth:`init`, except ``advertise_addr``, ``listen_addr``, and ``force_new_cluster``. In addition, it takes these arguments: Args: rotate_worker_token (bool): Rotate the worker join token. Default: ``False``. rotate_manager_token (bool): Rotate the ma...
def update(self, rotate_worker_token=False, rotate_manager_token=False, **kwargs):
if (kwargs.get('node_cert_expiry') is None): kwargs['node_cert_expiry'] = 7776000000000000 return self.client.api.update_swarm(version=self.version, swarm_spec=SwarmSpec(**kwargs), rotate_worker_token=rotate_worker_token, rotate_manager_token=rotate_manager_token)
'Remove this secret. Raises: :py:class:`docker.errors.APIError` If secret failed to remove.'
def remove(self):
return self.client.api.remove_secret(self.id)
'Get a secret. Args: secret_id (str): Secret ID. Returns: (:py:class:`Secret`): The secret. Raises: :py:class:`docker.errors.NotFound` If the secret does not exist. :py:class:`docker.errors.APIError` If the server returns an error.'
def get(self, secret_id):
return self.prepare_model(self.client.api.inspect_secret(secret_id))
'List secrets. Similar to the ``docker secret ls`` command. Args: filters (dict): Server-side list filtering options. Returns: (list of :py:class:`Secret`): The secrets. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def list(self, **kwargs):
resp = self.client.api.secrets(**kwargs) return [self.prepare_model(obj) for obj in resp]
'The ID of the object.'
@property def id(self):
return self.attrs.get(self.id_attribute)
'The ID of the object, truncated to 10 characters.'
@property def short_id(self):
return self.id[:10]
'Load this object from the server again and update ``attrs`` with the new data.'
def reload(self):
new_model = self.collection.get(self.id) self.attrs = new_model.attrs
'Create a model from a set of attributes.'
def prepare_model(self, attrs):
if isinstance(attrs, Model): attrs.client = self.client attrs.collection = self return attrs elif isinstance(attrs, dict): return self.model(attrs=attrs, client=self.client, collection=self) else: raise Exception(("Can't create %s from %s" % (self.model.__...
'Get data usage information. Returns: (dict): A dictionary representing different resource categories and their respective data usage. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.25') def df(self):
url = self._url('/system/df') return self._result(self._get(url), True)
'Get real-time events from the server. Similar to the ``docker events`` command. Args: since (UTC datetime or int): Get events from this point until (UTC datetime or int): Get events until this point filters (dict): Filter the events by event time, container or image decode (bool): If set to true, stream will be decode...
def events(self, since=None, until=None, filters=None, decode=None):
if isinstance(since, datetime): since = utils.datetime_to_timestamp(since) if isinstance(until, datetime): until = utils.datetime_to_timestamp(until) if filters: filters = utils.convert_filters(filters) params = {'since': since, 'until': until, 'filters': filters} url = self....
'Display system-wide information. Identical to the ``docker info`` command. Returns: (dict): The info as a dict Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def info(self):
return self._result(self._get(self._url('/info')), True)
'Authenticate with a registry. Similar to the ``docker login`` command. Args: username (str): The registry username password (str): The plaintext password email (str): The email for the registry account registry (str): URL to the registry. E.g. ``https://index.docker.io/v1/`` reauth (bool): Whether or not to refresh e...
def login(self, username, password=None, email=None, registry=None, reauth=False, insecure_registry=False, dockercfg_path=None):
if insecure_registry: warnings.warn(INSECURE_REGISTRY_DEPRECATION_WARNING.format('login()'), DeprecationWarning) if (dockercfg_path and os.path.exists(dockercfg_path)): self._auth_configs = auth.load_config(dockercfg_path) elif (not self._auth_configs): self._auth_configs = auth.load...
'Checks the server is responsive. An exception will be raised if it isn\'t responding. Returns: (bool) The response from the server. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def ping(self):
return (self._result(self._get(self._url('/_ping'))) == 'OK')
'Returns version information from the server. Similar to the ``docker version`` command. Returns: (dict): The server version information Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def version(self, api_version=True):
url = self._url('/version', versioned_api=api_version) return self._result(self._get(url), json=True)
'Create a service. Args: task_template (TaskTemplate): Specification of the task to start as part of the new service. name (string): User-defined name for the service. Optional. labels (dict): A map of labels to associate with the service. Optional. mode (ServiceMode): Scheduling mode for the service (replicated or glo...
@utils.minimum_version('1.24') def create_service(self, task_template, name=None, labels=None, mode=None, update_config=None, networks=None, endpoint_config=None, endpoint_spec=None):
if (endpoint_config is not None): warnings.warn('endpoint_config has been renamed to endpoint_spec.', DeprecationWarning) endpoint_spec = endpoint_config _check_api_features(self._version, task_template, update_config) url = self._url('/services/create') headers = {} i...
'Return information about a service. Args: service (str): Service name or ID Returns: ``True`` if successful. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.24') @utils.check_resource('service') def inspect_service(self, service):
url = self._url('/services/{0}', service) return self._result(self._get(url), True)
'Retrieve information about a task. Args: task (str): Task ID Returns: (dict): Information about the task. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.24') @utils.check_resource('task') def inspect_task(self, task):
url = self._url('/tasks/{0}', task) return self._result(self._get(url), True)
'Stop and remove a service. Args: service (str): Service name or ID Returns: ``True`` if successful. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.24') @utils.check_resource('service') def remove_service(self, service):
url = self._url('/services/{0}', service) resp = self._delete(url) self._raise_for_status(resp) return True
'List services. Args: filters (dict): Filters to process on the nodes list. Valid filters: ``id`` and ``name``. Default: ``None``. Returns: A list of dictionaries containing data about each service. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.24') def services(self, filters=None):
params = {'filters': (utils.convert_filters(filters) if filters else None)} url = self._url('/services') return self._result(self._get(url, params=params), True)
'Get log stream for a service. Note: This endpoint works only for services with the ``json-file`` or ``journald`` logging drivers. Args: service (str): ID or name of the service details (bool): Show extra details provided to logs. Default: ``False`` follow (bool): Keep connection open to read logs as they are sent by t...
@utils.minimum_version('1.25') @utils.check_resource('service') def service_logs(self, service, details=False, follow=False, stdout=False, stderr=False, since=0, timestamps=False, tail='all', is_tty=None):
params = {'details': details, 'follow': follow, 'stdout': stdout, 'stderr': stderr, 'since': since, 'timestamps': timestamps, 'tail': tail} url = self._url('/services/{0}/logs', service) res = self._get(url, params=params, stream=True) if (is_tty is None): is_tty = self.inspect_service(service)[...
'Retrieve a list of tasks. Args: filters (dict): A map of filters to process on the tasks list. Valid filters: ``id``, ``name``, ``service``, ``node``, ``label`` and ``desired-state``. Returns: (:py:class:`list`): List of task dictionaries. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.24') def tasks(self, filters=None):
params = {'filters': (utils.convert_filters(filters) if filters else None)} url = self._url('/tasks') return self._result(self._get(url, params=params), True)
'Update a service. Args: service (string): A service identifier (either its name or service ID). version (int): The version number of the service object being updated. This is required to avoid conflicting writes. task_template (TaskTemplate): Specification of the updated task to start as part of the service. name (str...
@utils.minimum_version('1.24') @utils.check_resource('service') def update_service(self, service, version, task_template=None, name=None, labels=None, mode=None, update_config=None, networks=None, endpoint_config=None, endpoint_spec=None):
if (endpoint_config is not None): warnings.warn('endpoint_config has been renamed to endpoint_spec.', DeprecationWarning) endpoint_spec = endpoint_config _check_api_features(self._version, task_template, update_config) url = self._url('/services/{0}/update', service) data ...
'Similar to the ``docker build`` command. Either ``path`` or ``fileobj`` needs to be set. ``path`` can be a local path (to a directory containing a Dockerfile) or a remote URL. ``fileobj`` must be a readable file-like object to a Dockerfile. If you have a tar file for the Docker build context (including a Dockerfile) a...
def build(self, path=None, tag=None, quiet=False, fileobj=None, nocache=False, rm=False, stream=False, timeout=None, custom_context=False, encoding=None, pull=False, forcerm=False, dockerfile=None, container_limits=None, decode=False, buildargs=None, gzip=False, shmsize=None, labels=None, cache_from=None, target=None, ...
remote = context = None headers = {} container_limits = (container_limits or {}) if ((path is None) and (fileobj is None)): raise TypeError('Either path or fileobj needs to be provided.') if (gzip and (encoding is not None)): raise errors.DockerException('Can ...
'Prepare the kwargs for an HTTP request by inserting the timeout parameter, if not already present.'
def _set_request_timeout(self, kwargs):
kwargs.setdefault('timeout', self.timeout) return kwargs
'Raises stored :class:`APIError`, if one occurred.'
def _raise_for_status(self, response):
try: response.raise_for_status() except requests.exceptions.HTTPError as e: raise create_api_error_from_http_exception(e)
'Generator for data coming from a chunked-encoded HTTP response.'
def _stream_helper(self, response, decode=False):
if response.raw._fp.chunked: if decode: for chunk in json_stream(self._stream_helper(response, False)): (yield chunk) else: reader = response.raw while (not reader.closed): data = reader.read(1) if (not data): ...
'A generator of multiplexed data blocks read from a buffered response.'
def _multiplexed_buffer_helper(self, response):
buf = self._result(response, binary=True) buf_length = len(buf) walker = 0 while True: if ((buf_length - walker) < STREAM_HEADER_SIZE_BYTES): break header = buf[walker:(walker + STREAM_HEADER_SIZE_BYTES)] (_, length) = struct.unpack_from('>BxxxL', header) star...
'A generator of multiplexed data blocks coming from a response stream.'
def _multiplexed_response_stream_helper(self, response):
socket = self._get_raw_response_socket(response) self._disable_socket_timeout(socket) while True: header = response.raw.read(STREAM_HEADER_SIZE_BYTES) if (not header): break (_, length) = struct.unpack('>BxxxL', header) if (not length): continue ...
'Stream raw output for API versions below 1.6'
def _stream_raw_result_old(self, response):
self._raise_for_status(response) for line in response.iter_lines(chunk_size=1, decode_unicode=True): if line: (yield line)
'Stream result for TTY-enabled container above API 1.6'
def _stream_raw_result(self, response):
self._raise_for_status(response) for out in response.iter_content(chunk_size=1, decode_unicode=True): (yield out)
'Depending on the combination of python version and whether we\'re connecting over http or https, we might need to access _sock, which may or may not exist; or we may need to just settimeout on socket itself, which also may or may not have settimeout on it. To avoid missing the correct one, we try both. We also do not ...
def _disable_socket_timeout(self, socket):
sockets = [socket, getattr(socket, '_sock', None)] for s in sockets: if (not hasattr(s, 'settimeout')): continue timeout = (-1) if hasattr(s, 'gettimeout'): timeout = s.gettimeout() if ((timeout is None) or (timeout == 0.0)): continue s...
'Force a reload of the auth configuration Args: dockercfg_path (str): Use a custom path for the Docker config file (default ``$HOME/.docker/config.json`` if present, otherwise``$HOME/.dockercfg``) Returns: None'
def reload_config(self, dockercfg_path=None):
self._auth_configs = auth.load_config(dockercfg_path)
'Sets up an exec instance in a running container. Args: container (str): Target container where exec instance will be created cmd (str or list): Command to be executed stdout (bool): Attach to stdout. Default: ``True`` stderr (bool): Attach to stderr. Default: ``True`` stdin (bool): Attach to stdin. Default: ``False`` ...
@utils.minimum_version('1.15') @utils.check_resource('container') def exec_create(self, container, cmd, stdout=True, stderr=True, stdin=False, tty=False, privileged=False, user='', environment=None):
if (privileged and utils.version_lt(self._version, '1.19')): raise errors.InvalidVersion('Privileged exec is not supported in API < 1.19') if (user and utils.version_lt(self._version, '1.19')): raise errors.InvalidVersion('User-specific exec is not supported ...
'Return low-level information about an exec command. Args: exec_id (str): ID of the exec instance Returns: (dict): Dictionary of values returned by the endpoint. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.16') def exec_inspect(self, exec_id):
if isinstance(exec_id, dict): exec_id = exec_id.get('Id') res = self._get(self._url('/exec/{0}/json', exec_id)) return self._result(res, True)
'Resize the tty session used by the specified exec command. Args: exec_id (str): ID of the exec instance height (int): Height of tty session width (int): Width of tty session'
@utils.minimum_version('1.15') def exec_resize(self, exec_id, height=None, width=None):
if isinstance(exec_id, dict): exec_id = exec_id.get('Id') params = {'h': height, 'w': width} url = self._url('/exec/{0}/resize', exec_id) res = self._post(url, params=params) self._raise_for_status(res)
'Start a previously set up exec instance. Args: exec_id (str): ID of the exec instance detach (bool): If true, detach from the exec command. Default: False tty (bool): Allocate a pseudo-TTY. Default: False stream (bool): Stream response data. Default: False Returns: (generator or str): If ``stream=True``, a generator y...
@utils.minimum_version('1.15') @utils.check_resource('exec_id') def exec_start(self, exec_id, detach=False, tty=False, stream=False, socket=False):
data = {'Tty': tty, 'Detach': detach} headers = ({} if detach else {'Connection': 'Upgrade', 'Upgrade': 'tcp'}) res = self._post_json(self._url('/exec/{0}/start', exec_id), headers=headers, data=data, stream=True) if detach: return self._result(res) if socket: return self._get_raw_re...
'List volumes currently registered by the docker daemon. Similar to the ``docker volume ls`` command. Args: filters (dict): Server-side list filtering options. Returns: (dict): Dictionary with list of volume objects as value of the ``Volumes`` key. Raises: :py:class:`docker.errors.APIError` If the server returns an err...
@utils.minimum_version('1.21') def volumes(self, filters=None):
params = {'filters': (utils.convert_filters(filters) if filters else None)} url = self._url('/volumes') return self._result(self._get(url, params=params), True)
'Create and register a named volume Args: name (str): Name of the volume driver (str): Name of the driver used to create the volume driver_opts (dict): Driver options as a key-value dictionary labels (dict): Labels to set on the volume Returns: (dict): The created volume reference object Raises: :py:class:`docker.error...
@utils.minimum_version('1.21') def create_volume(self, name=None, driver=None, driver_opts=None, labels=None):
url = self._url('/volumes/create') if ((driver_opts is not None) and (not isinstance(driver_opts, dict))): raise TypeError('driver_opts must be a dictionary') data = {'Name': name, 'Driver': driver, 'DriverOpts': driver_opts} if (labels is not None): if (utils.compare_version...
'Retrieve volume info by name. Args: name (str): volume name Returns: (dict): Volume information dictionary Raises: :py:class:`docker.errors.APIError` If the server returns an error. Example: >>> cli.inspect_volume(\'foobar\') {u\'Driver\': u\'local\', u\'Mountpoint\': u\'/var/lib/docker/volumes/foobar/_data\', u\'Name...
@utils.minimum_version('1.21') def inspect_volume(self, name):
url = self._url('/volumes/{0}', name) return self._result(self._get(url), True)
'Delete unused volumes Args: filters (dict): Filters to process on the prune list. Returns: (dict): A dict containing a list of deleted volume names 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_volumes(self, filters=None):
params = {} if filters: params['filters'] = utils.convert_filters(filters) url = self._url('/volumes/prune') return self._result(self._post(url, params=params), True)
'Remove a volume. Similar to the ``docker volume rm`` command. Args: name (str): The volume\'s name force (bool): Force removal of volumes that were already removed out of band by the volume driver plugin. Raises: :py:class:`docker.errors.APIError` If volume failed to remove.'
@utils.minimum_version('1.21') def remove_volume(self, name, force=False):
params = {} if force: if utils.version_lt(self._version, '1.25'): raise errors.InvalidVersion('force removal was introduced in API 1.25') params = {'force': force} url = self._url('/volumes/{0}', name, params=params) resp = self._delete(url) self._raise_...
'Create a ``docker.types.SwarmSpec`` instance that can be used as the ``swarm_spec`` argument in :py:meth:`~docker.api.swarm.SwarmApiMixin.init_swarm`. Args: task_history_retention_limit (int): Maximum number of tasks history stored. snapshot_interval (int): Number of logs entries between snapshot. keep_old_snapshots (...
def create_swarm_spec(self, *args, **kwargs):
return types.SwarmSpec(*args, **kwargs)
'Initialize a new Swarm using the current connected engine as the first node. Args: advertise_addr (string): Externally reachable address advertised to other nodes. This can either be an address/port combination in the form ``192.168.1.1:4567``, or an interface followed by a port number, like ``eth0:4567``. If the port...
@utils.minimum_version('1.24') def init_swarm(self, advertise_addr=None, listen_addr='0.0.0.0:2377', force_new_cluster=False, swarm_spec=None):
url = self._url('/swarm/init') if ((swarm_spec is not None) and (not isinstance(swarm_spec, dict))): raise TypeError('swarm_spec must be a dictionary') data = {'AdvertiseAddr': advertise_addr, 'ListenAddr': listen_addr, 'ForceNewCluster': force_new_cluster, 'Spec': swarm_spec} respon...
'Retrieve low-level information about the current swarm. Returns: A dictionary containing data about the swarm. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.24') def inspect_swarm(self):
url = self._url('/swarm') return self._result(self._get(url), True)
'Retrieve low-level information about a swarm node Args: node_id (string): ID of the node to be inspected. Returns: A dictionary containing data about this node. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.check_resource('node_id') @utils.minimum_version('1.24') def inspect_node(self, node_id):
url = self._url('/nodes/{0}', node_id) return self._result(self._get(url), True)
'Make this Engine join a swarm that has already been created. Args: remote_addrs (:py:class:`list`): Addresses of one or more manager nodes already participating in the Swarm to join. join_token (string): Secret token for joining this Swarm. listen_addr (string): Listen address used for inter-manager communication if t...
@utils.minimum_version('1.24') def join_swarm(self, remote_addrs, join_token, listen_addr=None, advertise_addr=None):
data = {'RemoteAddrs': remote_addrs, 'ListenAddr': listen_addr, 'JoinToken': join_token, 'AdvertiseAddr': advertise_addr} url = self._url('/swarm/join') response = self._post_json(url, data=data) self._raise_for_status(response) return True
'Leave a swarm. Args: force (bool): Leave the swarm even if this node is a manager. Default: ``False`` Returns: ``True`` if the request went through. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.24') def leave_swarm(self, force=False):
url = self._url('/swarm/leave') response = self._post(url, params={'force': force}) if (force and (response.status_code == http_client.NOT_ACCEPTABLE)): return True if (force and (response.status_code == http_client.SERVICE_UNAVAILABLE)): return True self._raise_for_status(response) ...
'List swarm nodes. Args: filters (dict): Filters to process on the nodes list. Valid filters: ``id``, ``name``, ``membership`` and ``role``. Default: ``None`` Returns: A list of dictionaries containing data about each swarm node. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
@utils.minimum_version('1.24') def nodes(self, filters=None):
url = self._url('/nodes') params = {} if filters: params['filters'] = utils.convert_filters(filters) return self._result(self._get(url, params=params), True)
'Remove a node from the swarm. Args: node_id (string): ID of the node to be removed. force (bool): Force remove an active node. Default: `False` Raises: :py:class:`docker.errors.NotFound` If the node referenced doesn\'t exist in the swarm. :py:class:`docker.errors.APIError` If the server returns an error. Returns: `Tru...
@utils.check_resource('node_id') @utils.minimum_version('1.24') def remove_node(self, node_id, force=False):
url = self._url('/nodes/{0}', node_id) params = {'force': force} res = self._delete(url, params=params) self._raise_for_status(res) return True
'Update the Node\'s configuration Args: node_id (string): ID of the node to be updated. version (int): The version number of the node object being updated. This is required to avoid conflicting writes. node_spec (dict): Configuration settings to update. Any values not provided will be removed. Default: ``None`` Returns...
@utils.minimum_version('1.24') def update_node(self, node_id, version, node_spec=None):
url = self._url('/nodes/{0}/update?version={1}', node_id, str(version)) res = self._post_json(url, data=node_spec) self._raise_for_status(res) return True
'Update the Swarm\'s configuration Args: version (int): The version number of the swarm object being updated. This is required to avoid conflicting writes. swarm_spec (dict): Configuration settings to update. Use :py:meth:`~docker.api.swarm.SwarmApiMixin.create_swarm_spec` to generate a valid configuration. Default: ``...
@utils.minimum_version('1.24') def update_swarm(self, version, swarm_spec=None, rotate_worker_token=False, rotate_manager_token=False):
url = self._url('/swarm/update') response = self._post_json(url, data=swarm_spec, params={'rotateWorkerToken': rotate_worker_token, 'rotateManagerToken': rotate_manager_token, 'version': version}) self._raise_for_status(response) return True
'Create a secret Args: name (string): Name of the secret data (bytes): Secret data to be stored labels (dict): A mapping of labels to assign to the secret Returns (dict): ID of the newly created secret'
@utils.minimum_version('1.25') def create_secret(self, name, data, labels=None):
if (not isinstance(data, bytes)): data = data.encode('utf-8') data = base64.b64encode(data) if six.PY3: data = data.decode('ascii') body = {'Data': data, 'Name': name, 'Labels': labels} url = self._url('/secrets/create') return self._result(self._post_json(url, data=body), True)
'Retrieve secret metadata Args: id (string): Full ID of the secret to remove Returns (dict): A dictionary of metadata Raises: :py:class:`docker.errors.NotFound` if no secret with that ID exists'
@utils.minimum_version('1.25') @utils.check_resource('id') def inspect_secret(self, id):
url = self._url('/secrets/{0}', id) return self._result(self._get(url), True)
'Remove a secret Args: id (string): Full ID of the secret to remove Returns (boolean): True if successful Raises: :py:class:`docker.errors.NotFound` if no secret with that ID exists'
@utils.minimum_version('1.25') @utils.check_resource('id') def remove_secret(self, id):
url = self._url('/secrets/{0}', id) res = self._delete(url) self._raise_for_status(res) return True
'List secrets Args: filters (dict): A map of filters to process on the secrets list. Available filters: ``names`` Returns (list): A list of secrets'
@utils.minimum_version('1.25') def secrets(self, filters=None):
url = self._url('/secrets') params = {} if filters: params['filters'] = utils.convert_filters(filters) return self._result(self._get(url, params=params), True)
'Configure a plugin. Args: name (string): The name of the plugin. The ``:latest`` tag is optional, and is the default if omitted. options (dict): A key-value mapping of options Returns: ``True`` if successful'
@utils.minimum_version('1.25') @utils.check_resource('name') def configure_plugin(self, name, options):
url = self._url('/plugins/{0}/set', name) data = options if isinstance(data, dict): data = ['{0}={1}'.format(k, v) for (k, v) in six.iteritems(data)] res = self._post_json(url, data=data) self._raise_for_status(res) return True
'Create a new plugin. Args: name (string): The name of the plugin. The ``:latest`` tag is optional, and is the default if omitted. plugin_data_dir (string): Path to the plugin data directory. Plugin data directory must contain the ``config.json`` manifest file and the ``rootfs`` directory. gzip (bool): Compress the con...
@utils.minimum_version('1.25') def create_plugin(self, name, plugin_data_dir, gzip=False):
url = self._url('/plugins/create') with utils.create_archive(root=plugin_data_dir, gzip=gzip) as archv: res = self._post(url, params={'name': name}, data=archv) self._raise_for_status(res) return True
'Disable an installed plugin. Args: name (string): The name of the plugin. The ``:latest`` tag is optional, and is the default if omitted. Returns: ``True`` if successful'
@utils.minimum_version('1.25') def disable_plugin(self, name):
url = self._url('/plugins/{0}/disable', name) res = self._post(url) self._raise_for_status(res) return True
'Enable an installed plugin. Args: name (string): The name of the plugin. The ``:latest`` tag is optional, and is the default if omitted. timeout (int): Operation timeout (in seconds). Default: 0 Returns: ``True`` if successful'
@utils.minimum_version('1.25') def enable_plugin(self, name, timeout=0):
url = self._url('/plugins/{0}/enable', name) params = {'timeout': timeout} res = self._post(url, params=params) self._raise_for_status(res) return True
'Retrieve plugin metadata. Args: name (string): The name of the plugin. The ``:latest`` tag is optional, and is the default if omitted. Returns: A dict containing plugin info'
@utils.minimum_version('1.25') def inspect_plugin(self, name):
url = self._url('/plugins/{0}/json', name) return self._result(self._get(url), True)