Kaydet (Commit) f5ac10c4 authored tarafından Joffrey F's avatar Joffrey F

Rename Client -> DockerClient

Replace references to old Client with APIClient
Moved contents of services.md to appropriate locations
Signed-off-by: 's avatarJoffrey F <joffrey@docker.com>
üst c66c7f8b
# flake8: noqa
from .api import APIClient
from .client import Client, from_env
from .client import DockerClient, from_env
from .version import version, version_info
__version__ = version
......
......@@ -32,7 +32,7 @@ class BuildApiMixin(object):
Example:
>>> from io import BytesIO
>>> from docker import Client
>>> from docker import APIClient
>>> dockerfile = '''
... # Shared Volume
... FROM busybox:buildroot-2014.02
......@@ -40,7 +40,7 @@ class BuildApiMixin(object):
... CMD ["/bin/sh"]
... '''
>>> f = BytesIO(dockerfile.encode('utf-8'))
>>> cli = Client(base_url='tcp://127.0.0.1:2375')
>>> cli = APIClient(base_url='tcp://127.0.0.1:2375')
>>> response = [line for line in cli.build(
... fileobj=f, rm=True, tag='yourname/volume'
... )]
......
......@@ -215,7 +215,7 @@ class ContainerApiMixin(object):
"""
if utils.version_gte(self._version, '1.20'):
warnings.warn(
'Client.copy() is deprecated for API version >= 1.20, '
'APIClient.copy() is deprecated for API version >= 1.20, '
'please use get_archive() instead',
DeprecationWarning
)
......
......@@ -77,7 +77,7 @@ class SwarmApiMixin(object):
force_new_cluster (bool): Force creating a new Swarm, even if
already part of one. Default: False
swarm_spec (dict): Configuration settings of the new Swarm. Use
``Client.create_swarm_spec`` to generate a valid
``APIClient.create_swarm_spec`` to generate a valid
configuration. Default: None
Returns:
......
......@@ -9,14 +9,14 @@ from .models.volumes import VolumeCollection
from .utils import kwargs_from_env
class Client(object):
class DockerClient(object):
"""
A client for communicating with a Docker server.
Example:
>>> import docker
>>> client = Client(base_url='unix://var/run/docker.sock')
>>> client = docker.DockerClient(base_url='unix://var/run/docker.sock')
Args:
base_url (str): URL to the Docker server. For example,
......@@ -155,7 +155,7 @@ class Client(object):
version.__doc__ = APIClient.version.__doc__
def __getattr__(self, name):
s = ["'Client' object has no attribute '{}'".format(name)]
s = ["'DockerClient' object has no attribute '{}'".format(name)]
# If a user calls a method on APIClient, they
if hasattr(APIClient, name):
s.append("In docker-py 2.0, this method is now on the object "
......@@ -164,4 +164,4 @@ class Client(object):
raise AttributeError(' '.join(s))
from_env = Client.from_env
from_env = DockerClient.from_env
......@@ -238,7 +238,7 @@ class ImageCollection(Collection):
tag (str): The tag to pull
insecure_registry (bool): Use an insecure registry
auth_config (dict): Override the credentials that
:py:meth:`~docker.client.Client.login` has set for
:py:meth:`~docker.client.DockerClient.login` has set for
this request. ``auth_config`` should contain the ``username``
and ``password`` keys to be valid.
......
......@@ -4,6 +4,26 @@ from .. import errors
class TaskTemplate(dict):
"""
Describe the task specification to be used when creating or updating a
service.
Args:
* container_spec (dict): Container settings for containers started as part
of this task. See the :py:class:`~docker.types.services.ContainerSpec`
for details.
* log_driver (dict): Log configuration for containers created as part of
the service. See the :py:class:`~docker.types.services.DriverConfig`
class for details.
* resources (dict): Resource requirements which apply to each individual
container created as part of the service. See the
:py:class:`~docker.types.services.Resources` class for details.
* restart_policy (dict): Specification for the restart policy which applies
to containers created as part of this service. See the
:py:class:`~docker.types.services.RestartPolicy` class for details.
* placement (list): A list of constraints.
"""
def __init__(self, container_spec, resources=None, restart_policy=None,
placement=None, log_driver=None):
self['ContainerSpec'] = container_spec
......@@ -36,6 +56,25 @@ class TaskTemplate(dict):
class ContainerSpec(dict):
"""
Describes the behavior of containers that are part of a task, and is used
when declaring a :py:class:`~docker.types.services.TaskTemplate`.
Args:
* image (string): The image name to use for the container.
* command (string or list): The command to be run in the image.
* args (list): Arguments to the command.
* env (dict): Environment variables.
* dir (string): The working directory for commands to run in.
* user (string): The user inside the container.
* labels (dict): A map of labels to associate with the service.
* mounts (list): A list of specifications for mounts to be added to
containers created as part of the service. See the
:py:class:`~docker.types.services.Mount` class for details.
* stop_grace_period (int): Amount of time to wait for the container to
terminate before forcefully killing it.
"""
def __init__(self, image, command=None, args=None, env=None, workdir=None,
user=None, labels=None, mounts=None, stop_grace_period=None):
from ..utils import split_command # FIXME: circular import
......@@ -66,6 +105,28 @@ class ContainerSpec(dict):
class Mount(dict):
"""
Describes a mounted folder's configuration inside a container. A list of
``Mount``s would be used as part of a
:py:class:`~docker.types.services.ContainerSpec`.
Args:
* target (string): Container path.
* source (string): Mount source (e.g. a volume name or a host path).
* type (string): The mount type (``bind`` or ``volume``).
Default: ``volume``.
* read_only (bool): Whether the mount should be read-only.
* propagation (string): A propagation mode with the value ``[r]private``,
``[r]shared``, or ``[r]slave``. Only valid for the ``bind`` type.
* no_copy (bool): False if the volume should be populated with the data
from the target. Default: ``False``. Only valid for the ``volume`` type.
* labels (dict): User-defined name and labels for the volume. Only valid
for the ``volume`` type.
* driver_config (dict): Volume driver configuration.
See the :py:class:`~docker.types.services.DriverConfig` class for
details. Only valid for the ``volume`` type.
"""
def __init__(self, target, source, type='volume', read_only=False,
propagation=None, no_copy=False, labels=None,
driver_config=None):
......@@ -120,6 +181,17 @@ class Mount(dict):
class Resources(dict):
"""
Configures resource allocation for containers when made part of a
:py:class:`~docker.types.services.ContainerSpec`.
Args:
* cpu_limit (int): CPU limit in units of 10^9 CPU shares.
* mem_limit (int): Memory limit in Bytes.
* cpu_reservation (int): CPU reservation in units of 10^9 CPU shares.
* mem_reservation (int): Memory reservation in Bytes.
"""
def __init__(self, cpu_limit=None, mem_limit=None, cpu_reservation=None,
mem_reservation=None):
limits = {}
......@@ -140,6 +212,19 @@ class Resources(dict):
class UpdateConfig(dict):
"""
Used to specify the way container updates should be performed by a service.
Args:
* parallelism (int): Maximum number of tasks to be updated in one iteration
(0 means unlimited parallelism). Default: 0.
* delay (int): Amount of time between updates.
* failure_action (string): Action to take if an updated task fails to run,
or stops running during the update. Acceptable values are ``continue``
and ``pause``. Default: ``continue``
"""
def __init__(self, parallelism=0, delay=None, failure_action='continue'):
self['Parallelism'] = parallelism
if delay is not None:
......@@ -161,6 +246,19 @@ class RestartConditionTypesEnum(object):
class RestartPolicy(dict):
"""
Used when creating a :py:class:`~docker.types.services.ContainerSpec`,
dictates whether a container should restart after stopping or failing.
* condition (string): Condition for restart (``none``, ``on-failure``,
or ``any``). Default: `none`.
* delay (int): Delay between restart attempts. Default: 0
* attempts (int): Maximum attempts to restart a given container before
giving up. Default value is 0, which is ignored.
* window (int): Time window used to evaluate the restart policy. Default
value is 0, which is unbounded.
"""
condition_types = RestartConditionTypesEnum
def __init__(self, condition=RestartConditionTypesEnum.NONE, delay=0,
......@@ -177,6 +275,17 @@ class RestartPolicy(dict):
class DriverConfig(dict):
"""
Indicates which driver to use, as well as its configuration. Can be used
as ``log_driver`` in a :py:class:`~docker.types.services.ContainerSpec`,
and for the `driver_config` in a volume
:py:class:`~docker.types.services.Mount`.
Args:
* name (string): Name of the driver to use.
* options (dict): Driver-specific options. Default: ``None``.
"""
def __init__(self, name, options=None):
self['Name'] = name
if options:
......@@ -184,6 +293,19 @@ class DriverConfig(dict):
class EndpointSpec(dict):
"""
Describes properties to access and load-balance a service.
Args:
* mode (string): The mode of resolution to use for internal load balancing
between tasks (``'vip'`` or ``'dnsrr'``). Defaults to ``'vip'`` if not
provided.
* ports (dict): Exposed ports that this service is accessible on from the
outside, in the form of ``{ target_port: published_port }`` or
``{ target_port: (published_port, protocol) }``. Ports can only be
provided if the ``vip`` resolution mode is used.
"""
def __init__(self, mode=None, ports=None):
if ports:
self['Ports'] = convert_service_ports(ports)
......
......@@ -697,7 +697,7 @@ def create_host_config(binds=None, port_bindings=None, lxc_conf=None,
if not version:
warnings.warn(
'docker.utils.create_host_config() is deprecated. Please use '
'Client.create_host_config() instead.'
'APIClient.create_host_config() instead.'
)
version = constants.DEFAULT_DOCKER_API_VERSION
......
......@@ -6,14 +6,14 @@ Client
Creating a client
-----------------
To communicate with the Docker daemon, you first need to instantiate a client. The easiest way to do that is by calling the function :py:func:`~docker.client.from_env`. It can also be configured manually by instantiating a :py:class:`~docker.client.Client` class.
To communicate with the Docker daemon, you first need to instantiate a client. The easiest way to do that is by calling the function :py:func:`~docker.client.from_env`. It can also be configured manually by instantiating a :py:class:`~docker.client.DockerClient` class.
.. autofunction:: from_env()
Client reference
----------------
.. autoclass:: Client()
.. autoclass:: DockerClient()
.. autoattribute:: containers
.. autoattribute:: images
......
# Swarm services
Starting with Engine version 1.12 (API 1.24), it is possible to manage services
using the Docker Engine API. Note that the engine needs to be part of a
[Swarm cluster](swarm.md) before you can use the service-related methods.
## Creating a service
The `Client.create_service` method lets you create a new service inside the
cluster. The method takes several arguments, `task_template` being mandatory.
This dictionary of values is most easily produced by instantiating a
`TaskTemplate` object.
```python
container_spec = docker.types.ContainerSpec(
image='busybox', command=['echo', 'hello']
)
task_tmpl = docker.types.TaskTemplate(container_spec)
service_id = client.create_service(task_tmpl, name=name)
```
## Listing services
List all existing services using the `Client.services` method.
```python
client.services(filters={'name': 'mysql'})
```
## Retrieving service configuration
To retrieve detailed information and configuration for a specific service, you
may use the `Client.inspect_service` method using the service's ID or name.
```python
client.inspect_service(service='my_service_name')
```
## Updating service configuration
The `Client.update_service` method lets you update a service's configuration.
The mandatory `version` argument (used to prevent concurrent writes) can be
retrieved using `Client.inspect_service`.
```python
container_spec = docker.types.ContainerSpec(
image='busybox', command=['echo', 'hello world']
)
task_tmpl = docker.types.TaskTemplate(container_spec)
svc_version = client.inspect_service(svc_id)['Version']['Index']
client.update_service(
svc_id, svc_version, name='new_name', task_template=task_tmpl
)
```
## Removing a service
A service may be removed simply using the `Client.remove_service` method.
Either the service name or service ID can be used as argument.
```python
client.remove_service('my_service_name')
```
## Service API documentation
### Client.create_service
Create a service.
**Params:**
* task_template (dict): Specification of the task to start as part of the new
service. See the [TaskTemplate class](#TaskTemplate) for details.
* name (string): User-defined name for the service. Optional.
* labels (dict): A map of labels to associate with the service. Optional.
* mode (string): Scheduling mode for the service (`replicated` or `global`).
Defaults to `replicated`.
* update_config (dict): Specification for the update strategy of the service.
See the [UpdateConfig class](#UpdateConfig) for details. Default: `None`.
* networks (list): List of network names or IDs to attach the service to.
Default: `None`.
* endpoint_spec (dict): Properties that can be configured to access and load
balance a service. Default: `None`.
**Returns:** A dictionary containing an `ID` key for the newly created service.
### Client.inspect_service
Return information on a service.
**Params:**
* service (string): A service identifier (either its name or service ID)
**Returns:** `True` if successful. Raises an `APIError` otherwise.
### Client.remove_service
Stop and remove a service.
**Params:**
* service (string): A service identifier (either its name or service ID)
**Returns:** `True` if successful. Raises an `APIError` otherwise.
### Client.services
List services.
**Params:**
* 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.
### Client.update_service
Update a service.
**Params:**
* 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 (dict): Specification of the updated task to start as part of
the service. See the [TaskTemplate class](#TaskTemplate) for details.
* name (string): New name for the service. Optional.
* labels (dict): A map of labels to associate with the service. Optional.
* mode (string): Scheduling mode for the service (`replicated` or `global`).
Defaults to `replicated`.
* update_config (dict): Specification for the update strategy of the service.
See the [UpdateConfig class](#UpdateConfig) for details. Default: `None`.
* networks (list): List of network names or IDs to attach the service to.
Default: `None`.
* endpoint_spec (dict): Properties that can be configured to access and load
balance a service. Default: `None`.
**Returns:** `True` if successful. Raises an `APIError` otherwise.
### Configuration objects (`docker.types`)
#### ContainerSpec
A `ContainerSpec` object describes the behavior of containers that are part
of a task, and is used when declaring a `TaskTemplate`.
**Params:**
* image (string): The image name to use for the container.
* command (string or list): The command to be run in the image.
* args (list): Arguments to the command.
* env (dict): Environment variables.
* dir (string): The working directory for commands to run in.
* user (string): The user inside the container.
* labels (dict): A map of labels to associate with the service.
* mounts (list): A list of specifications for mounts to be added to containers
created as part of the service. See the [Mount class](#Mount) for details.
* stop_grace_period (int): Amount of time to wait for the container to
terminate before forcefully killing it.
#### DriverConfig
A `LogDriver` object indicates which driver to use, as well as its
configuration. It can be used for the `log_driver` in a `ContainerSpec`,
and for the `driver_config` in a volume `Mount`.
**Params:**
* name (string): Name of the logging driver to use.
* options (dict): Driver-specific options. Default: `None`.
#### EndpointSpec
An `EndpointSpec` object describes properties to access and load-balance a
service.
**Params:**
* mode (string): The mode of resolution to use for internal load balancing
between tasks (`'vip'` or `'dnsrr'`). Defaults to `'vip'` if not provided.
* ports (dict): Exposed ports that this service is accessible on from the
outside, in the form of `{ target_port: published_port }` or
`{ target_port: (published_port, protocol) }`. Ports can only be provided if
the `vip` resolution mode is used.
#### Mount
A `Mount` object describes a mounted folder's configuration inside a
container. A list of `Mount`s would be used as part of a `ContainerSpec`.
* target (string): Container path.
* source (string): Mount source (e.g. a volume name or a host path).
* type (string): The mount type (`bind` or `volume`). Default: `volume`.
* read_only (bool): Whether the mount should be read-only.
* propagation (string): A propagation mode with the value `[r]private`,
`[r]shared`, or `[r]slave`. Only valid for the `bind` type.
* no_copy (bool): False if the volume should be populated with the data from
the target. Default: `False`. Only valid for the `volume` type.
* labels (dict): User-defined name and labels for the volume. Only valid for
the `volume` type.
* driver_config (dict): Volume driver configuration.
See the [DriverConfig class](#DriverConfig) for details. Only valid for the
`volume` type.
#### Resources
A `Resources` object configures resource allocation for containers when
made part of a `ContainerSpec`.
**Params:**
* cpu_limit (int): CPU limit in units of 10^9 CPU shares.
* mem_limit (int): Memory limit in Bytes.
* cpu_reservation (int): CPU reservation in units of 10^9 CPU shares.
* mem_reservation (int): Memory reservation in Bytes.
#### RestartPolicy
A `RestartPolicy` object is used when creating a `ContainerSpec`. It dictates
whether a container should restart after stopping or failing.
* condition (string): Condition for restart (`none`, `on-failure`, or `any`).
Default: `none`.
* delay (int): Delay between restart attempts. Default: 0
* attempts (int): Maximum attempts to restart a given container before giving
up. Default value is 0, which is ignored.
* window (int): Time window used to evaluate the restart policy. Default value
is 0, which is unbounded.
#### TaskTemplate
A `TaskTemplate` object can be used to describe the task specification to be
used when creating or updating a service.
**Params:**
* container_spec (dict): Container settings for containers started as part of
this task. See the [ContainerSpec class](#ContainerSpec) for details.
* log_driver (dict): Log configuration for containers created as part of the
service. See the [DriverConfig class](#DriverConfig) for details.
* resources (dict): Resource requirements which apply to each individual
container created as part of the service. See the
[Resources class](#Resources) for details.
* restart_policy (dict): Specification for the restart policy which applies
to containers created as part of this service. See the
[RestartPolicy class](#RestartPolicy) for details.
* placement (list): A list of constraints.
#### UpdateConfig
An `UpdateConfig` object can be used to specify the way container updates
should be performed by a service.
**Params:**
* parallelism (int): Maximum number of tasks to be updated in one iteration
(0 means unlimited parallelism). Default: 0.
* delay (int): Amount of time between updates.
* failure_action (string): Action to take if an updated task fails to run, or
stops running during the update. Acceptable values are `continue` and
`pause`. Default: `continue`
......@@ -3,7 +3,7 @@ Using TLS
.. py:module:: docker.tls
Both the main :py:class:`~docker.client.Client` and low-level
Both the main :py:class:`~docker.client.DockerClient` and low-level
:py:class:`~docker.api.client.APIClient` can connect to the Docker daemon with TLS.
This is all configured automatically for you if you're using :py:func:`~docker.client.from_env`, but if you need some extra control it is possible to configure it manually by using a :py:class:`TLSConfig` object.
......@@ -16,7 +16,7 @@ For example, to check the server against a specific CA certificate:
.. code-block:: python
tls_config = docker.tls.TLSConfig(ca_cert='/path/to/ca.pem')
client = docker.Client(base_url='<https_url>', tls=tls_config)
client = docker.DockerClient(base_url='<https_url>', tls=tls_config)
This is the equivalent of ``docker --tlsverify --tlscacert /path/to/ca.pem ...``.
......@@ -27,7 +27,7 @@ To authenticate with client certs:
tls_config = docker.tls.TLSConfig(
client_cert=('/path/to/client-cert.pem', '/path/to/client-key.pem')
)
client = docker.Client(base_url='<https_url>', tls=tls_config)
client = docker.DockerClient(base_url='<https_url>', tls=tls_config)
This is the equivalent of ``docker --tls --tlscert /path/to/client-cert.pem --tlskey /path/to/client-key.pem ...``.
......
# Swarm services
Starting with Engine version 1.12 (API 1.24), it is possible to manage services
using the Docker Engine API. Note that the engine needs to be part of a
[Swarm cluster](../swarm.rst) before you can use the service-related methods.
## Creating a service
The `APIClient.create_service` method lets you create a new service inside the
cluster. The method takes several arguments, `task_template` being mandatory.
This dictionary of values is most easily produced by instantiating a
`TaskTemplate` object.
```python
container_spec = docker.types.ContainerSpec(
image='busybox', command=['echo', 'hello']
)
task_tmpl = docker.types.TaskTemplate(container_spec)
service_id = client.create_service(task_tmpl, name=name)
```
## Listing services
List all existing services using the `APIClient.services` method.
```python
client.services(filters={'name': 'mysql'})
```
## Retrieving service configuration
To retrieve detailed information and configuration for a specific service, you
may use the `APIClient.inspect_service` method using the service's ID or name.
```python
client.inspect_service(service='my_service_name')
```
## Updating service configuration
The `APIClient.update_service` method lets you update a service's configuration.
The mandatory `version` argument (used to prevent concurrent writes) can be
retrieved using `APIClient.inspect_service`.
```python
container_spec = docker.types.ContainerSpec(
image='busybox', command=['echo', 'hello world']
)
task_tmpl = docker.types.TaskTemplate(container_spec)
svc_version = client.inspect_service(svc_id)['Version']['Index']
client.update_service(
svc_id, svc_version, name='new_name', task_template=task_tmpl
)
```
## Removing a service
A service may be removed simply using the `APIClient.remove_service` method.
Either the service name or service ID can be used as argument.
```python
client.remove_service('my_service_name')
```
\ No newline at end of file
......@@ -50,13 +50,13 @@ class ClientTest(unittest.TestCase):
with self.assertRaises(AttributeError) as cm:
client.create_container()
s = str(cm.exception)
assert "'Client' object has no attribute 'create_container'" in s
assert "'DockerClient' object has no attribute 'create_container'" in s
assert "this method is now on the object APIClient" in s
with self.assertRaises(AttributeError) as cm:
client.abcdef()
s = str(cm.exception)
assert "'Client' object has no attribute 'abcdef'" in s
assert "'DockerClient' object has no attribute 'abcdef'" in s
assert "this method is now on the object APIClient" not in s
......
......@@ -56,6 +56,6 @@ def make_fake_client():
"""
Returns a Client with a fake APIClient.
"""
client = docker.Client()
client = docker.DockerClient()
client.api = make_fake_api_client()
return client
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment