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

Move config type creation from docker.utils functions to classes in

docker.types
Signed-off-by: 's avatarJoffrey F <joffrey@docker.com>
üst 937a5f3d
...@@ -4,7 +4,9 @@ from datetime import datetime ...@@ -4,7 +4,9 @@ from datetime import datetime
from .. import errors from .. import errors
from .. import utils from .. import utils
from ..utils.utils import create_networking_config, create_endpoint_config from ..types import (
ContainerConfig, EndpointConfig, HostConfig, NetworkingConfig
)
class ContainerApiMixin(object): class ContainerApiMixin(object):
...@@ -430,8 +432,8 @@ class ContainerApiMixin(object): ...@@ -430,8 +432,8 @@ class ContainerApiMixin(object):
) )
config = self.create_container_config( config = self.create_container_config(
image, command, hostname, user, detach, stdin_open, image, command, hostname, user, detach, stdin_open, tty, mem_limit,
tty, mem_limit, ports, environment, dns, volumes, volumes_from, ports, dns, environment, volumes, volumes_from,
network_disabled, entrypoint, cpu_shares, working_dir, domainname, network_disabled, entrypoint, cpu_shares, working_dir, domainname,
memswap_limit, cpuset, host_config, mac_address, labels, memswap_limit, cpuset, host_config, mac_address, labels,
volume_driver, stop_signal, networking_config, healthcheck, volume_driver, stop_signal, networking_config, healthcheck,
...@@ -439,7 +441,7 @@ class ContainerApiMixin(object): ...@@ -439,7 +441,7 @@ class ContainerApiMixin(object):
return self.create_container_from_config(config, name) return self.create_container_from_config(config, name)
def create_container_config(self, *args, **kwargs): def create_container_config(self, *args, **kwargs):
return utils.create_container_config(self._version, *args, **kwargs) return ContainerConfig(self._version, *args, **kwargs)
def create_container_from_config(self, config, name=None): def create_container_from_config(self, config, name=None):
u = self._url("/containers/create") u = self._url("/containers/create")
...@@ -582,7 +584,7 @@ class ContainerApiMixin(object): ...@@ -582,7 +584,7 @@ class ContainerApiMixin(object):
"keyword argument 'version'" "keyword argument 'version'"
) )
kwargs['version'] = self._version kwargs['version'] = self._version
return utils.create_host_config(*args, **kwargs) return HostConfig(*args, **kwargs)
def create_networking_config(self, *args, **kwargs): def create_networking_config(self, *args, **kwargs):
""" """
...@@ -608,7 +610,7 @@ class ContainerApiMixin(object): ...@@ -608,7 +610,7 @@ class ContainerApiMixin(object):
) )
""" """
return create_networking_config(*args, **kwargs) return NetworkingConfig(*args, **kwargs)
def create_endpoint_config(self, *args, **kwargs): def create_endpoint_config(self, *args, **kwargs):
""" """
...@@ -641,7 +643,7 @@ class ContainerApiMixin(object): ...@@ -641,7 +643,7 @@ class ContainerApiMixin(object):
) )
""" """
return create_endpoint_config(self._version, *args, **kwargs) return EndpointConfig(self._version, *args, **kwargs)
@utils.check_resource @utils.check_resource
def diff(self, container): def diff(self, container):
......
...@@ -46,8 +46,7 @@ class NetworkApiMixin(object): ...@@ -46,8 +46,7 @@ class NetworkApiMixin(object):
name (str): Name of the network name (str): Name of the network
driver (str): Name of the driver used to create the network driver (str): Name of the driver used to create the network
options (dict): Driver options as a key-value dictionary options (dict): Driver options as a key-value dictionary
ipam (dict): Optional custom IP scheme for the network. ipam (IPAMConfig): Optional custom IP scheme for the network.
Created with :py:meth:`~docker.utils.create_ipam_config`.
check_duplicate (bool): Request daemon to check for networks with check_duplicate (bool): Request daemon to check for networks with
same name. Default: ``True``. same name. Default: ``True``.
internal (bool): Restrict external access to the network. Default internal (bool): Restrict external access to the network. Default
...@@ -74,11 +73,11 @@ class NetworkApiMixin(object): ...@@ -74,11 +73,11 @@ class NetworkApiMixin(object):
.. code-block:: python .. code-block:: python
>>> ipam_pool = docker.utils.create_ipam_pool( >>> ipam_pool = docker.types.IPAMPool(
subnet='192.168.52.0/24', subnet='192.168.52.0/24',
gateway='192.168.52.254' gateway='192.168.52.254'
) )
>>> ipam_config = docker.utils.create_ipam_config( >>> ipam_config = docker.types.IPAMConfig(
pool_configs=[ipam_pool] pool_configs=[ipam_pool]
) )
>>> docker_client.create_network("network1", driver="bridge", >>> docker_client.create_network("network1", driver="bridge",
......
import logging import logging
from six.moves import http_client from six.moves import http_client
from .. import types
from .. import utils from .. import utils
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
...@@ -50,7 +51,7 @@ class SwarmApiMixin(object): ...@@ -50,7 +51,7 @@ class SwarmApiMixin(object):
force_new_cluster=False, swarm_spec=spec force_new_cluster=False, swarm_spec=spec
) )
""" """
return utils.SwarmSpec(*args, **kwargs) return types.SwarmSpec(*args, **kwargs)
@utils.minimum_version('1.24') @utils.minimum_version('1.24')
def init_swarm(self, advertise_addr=None, listen_addr='0.0.0.0:2377', def init_swarm(self, advertise_addr=None, listen_addr='0.0.0.0:2377',
......
...@@ -2,7 +2,7 @@ import copy ...@@ -2,7 +2,7 @@ import copy
from ..errors import (ContainerError, ImageNotFound, from ..errors import (ContainerError, ImageNotFound,
create_unexpected_kwargs_error) create_unexpected_kwargs_error)
from ..utils import create_host_config from ..types import HostConfig
from .images import Image from .images import Image
from .resource import Collection, Model from .resource import Collection, Model
...@@ -869,7 +869,7 @@ def _create_container_args(kwargs): ...@@ -869,7 +869,7 @@ def _create_container_args(kwargs):
if kwargs: if kwargs:
raise create_unexpected_kwargs_error('run', kwargs) raise create_unexpected_kwargs_error('run', kwargs)
create_kwargs['host_config'] = create_host_config(**host_config_kwargs) create_kwargs['host_config'] = HostConfig(**host_config_kwargs)
# Fill in any kwargs which need processing by create_host_config first # Fill in any kwargs which need processing by create_host_config first
port_bindings = create_kwargs['host_config'].get('PortBindings') port_bindings = create_kwargs['host_config'].get('PortBindings')
......
...@@ -98,7 +98,7 @@ class NetworkCollection(Collection): ...@@ -98,7 +98,7 @@ class NetworkCollection(Collection):
driver (str): Name of the driver used to create the network driver (str): Name of the driver used to create the network
options (dict): Driver options as a key-value dictionary options (dict): Driver options as a key-value dictionary
ipam (dict): Optional custom IP scheme for the network. ipam (dict): Optional custom IP scheme for the network.
Created with :py:meth:`~docker.utils.create_ipam_config`. Created with :py:class:`~docker.types.IPAMConfig`.
check_duplicate (bool): Request daemon to check for networks with check_duplicate (bool): Request daemon to check for networks with
same name. Default: ``True``. same name. Default: ``True``.
internal (bool): Restrict external access to the network. Default internal (bool): Restrict external access to the network. Default
...@@ -125,11 +125,11 @@ class NetworkCollection(Collection): ...@@ -125,11 +125,11 @@ class NetworkCollection(Collection):
.. code-block:: python .. code-block:: python
>>> ipam_pool = docker.utils.create_ipam_pool( >>> ipam_pool = docker.types.IPAMPool(
subnet='192.168.52.0/24', subnet='192.168.52.0/24',
gateway='192.168.52.254' gateway='192.168.52.254'
) )
>>> ipam_config = docker.utils.create_ipam_config( >>> ipam_config = docker.types.IPAMConfig(
pool_configs=[ipam_pool] pool_configs=[ipam_pool]
) )
>>> client.networks.create( >>> client.networks.create(
......
# flake8: noqa # flake8: noqa
from .containers import LogConfig, Ulimit from .containers import ContainerConfig, HostConfig, LogConfig, Ulimit
from .healthcheck import Healthcheck
from .networks import EndpointConfig, IPAMConfig, IPAMPool, NetworkingConfig
from .services import ( from .services import (
ContainerSpec, DriverConfig, EndpointSpec, Mount, Resources, RestartPolicy, ContainerSpec, DriverConfig, EndpointSpec, Mount, Resources, RestartPolicy,
TaskTemplate, UpdateConfig TaskTemplate, UpdateConfig
) )
from .healthcheck import Healthcheck
from .swarm import SwarmSpec, SwarmExternalCA from .swarm import SwarmSpec, SwarmExternalCA
This diff is collapsed.
from .. import errors
from ..utils import normalize_links, version_lt
class EndpointConfig(dict):
def __init__(self, version, aliases=None, links=None, ipv4_address=None,
ipv6_address=None, link_local_ips=None):
if version_lt(version, '1.22'):
raise errors.InvalidVersion(
'Endpoint config is not supported for API version < 1.22'
)
if aliases:
self["Aliases"] = aliases
if links:
self["Links"] = normalize_links(links)
ipam_config = {}
if ipv4_address:
ipam_config['IPv4Address'] = ipv4_address
if ipv6_address:
ipam_config['IPv6Address'] = ipv6_address
if link_local_ips is not None:
if version_lt(version, '1.24'):
raise errors.InvalidVersion(
'link_local_ips is not supported for API version < 1.24'
)
ipam_config['LinkLocalIPs'] = link_local_ips
if ipam_config:
self['IPAMConfig'] = ipam_config
class NetworkingConfig(dict):
def __init__(self, endpoints_config=None):
if endpoints_config:
self["EndpointsConfig"] = endpoints_config
class IPAMConfig(dict):
"""
Create an IPAM (IP Address Management) config dictionary to be used with
:py:meth:`~docker.api.network.NetworkApiMixin.create_network`.
Args:
driver (str): The IPAM driver to use. Defaults to ``default``.
pool_configs (list): A list of pool configurations
(:py:class:`~docker.types.IPAMPool`). Defaults to empty list.
Example:
>>> ipam_config = docker.types.IPAMConfig(driver='default')
>>> network = client.create_network('network1', ipam=ipam_config)
"""
def __init__(self, driver='default', pool_configs=None):
self.update({
'Driver': driver,
'Config': pool_configs or []
})
class IPAMPool(dict):
"""
Create an IPAM pool config dictionary to be added to the
``pool_configs`` parameter of
:py:class:`~docker.types.IPAMConfig`.
Args:
subnet (str): Custom subnet for this IPAM pool using the CIDR
notation. Defaults to ``None``.
iprange (str): Custom IP range for endpoints in this IPAM pool using
the CIDR notation. Defaults to ``None``.
gateway (str): Custom IP address for the pool's gateway.
aux_addresses (dict): A dictionary of ``key -> ip_address``
relationships specifying auxiliary addresses that need to be
allocated by the IPAM driver.
Example:
>>> ipam_pool = docker.types.IPAMPool(
subnet='124.42.0.0/16',
iprange='124.42.0.0/24',
gateway='124.42.0.254',
aux_addresses={
'reserved1': '124.42.1.1'
}
)
>>> ipam_config = docker.types.IPAMConfig(
pool_configs=[ipam_pool])
"""
def __init__(self, subnet=None, iprange=None, gateway=None,
aux_addresses=None):
self.update({
'Subnet': subnet,
'IPRange': iprange,
'Gateway': gateway,
'AuxiliaryAddresses': aux_addresses
})
This diff is collapsed.
...@@ -3,12 +3,10 @@ from .utils import ( ...@@ -3,12 +3,10 @@ from .utils import (
compare_version, convert_port_bindings, convert_volume_binds, compare_version, convert_port_bindings, convert_volume_binds,
mkbuildcontext, tar, exclude_paths, parse_repository_tag, parse_host, mkbuildcontext, tar, exclude_paths, parse_repository_tag, parse_host,
kwargs_from_env, convert_filters, datetime_to_timestamp, kwargs_from_env, convert_filters, datetime_to_timestamp,
create_host_config, create_container_config, parse_bytes, ping_registry, create_host_config, parse_bytes, ping_registry, parse_env_file, version_lt,
parse_env_file, version_lt, version_gte, decode_json_header, split_command, version_gte, decode_json_header, split_command, create_ipam_config,
create_ipam_config, create_ipam_pool, parse_devices, normalize_links, create_ipam_pool, parse_devices, normalize_links, convert_service_networks,
convert_service_networks, format_environment, format_environment,
) )
from ..types import LogConfig, Ulimit
from ..types import SwarmExternalCA, SwarmSpec
from .decorators import check_resource, minimum_version, update_headers from .decorators import check_resource, minimum_version, update_headers
# Compatibility module. See https://github.com/docker/docker-py/issues/1196
import warnings
from ..types import Ulimit, LogConfig # flake8: noqa
warnings.warn('docker.utils.types is now docker.types', ImportWarning)
This diff is collapsed.
...@@ -49,15 +49,6 @@ Networks ...@@ -49,15 +49,6 @@ Networks
:members: :members:
:undoc-members: :undoc-members:
Utilities
~~~~~~~~~
These functions are available under ``docker.utils`` to create arguments
for :py:meth:`create_network`:
.. autofunction:: docker.utils.create_ipam_config
.. autofunction:: docker.utils.create_ipam_pool
Volumes Volumes
------- -------
...@@ -107,3 +98,19 @@ The Docker daemon ...@@ -107,3 +98,19 @@ The Docker daemon
.. autoclass:: DaemonApiMixin .. autoclass:: DaemonApiMixin
:members: :members:
:undoc-members: :undoc-members:
Configuration types
-------------------
.. py:module:: docker.types
.. autoclass:: IPAMConfig
.. autoclass:: IPAMPool
.. autoclass:: ContainerSpec
.. autoclass:: DriverConfig
.. autoclass:: EndpointSpec
.. autoclass:: Mount
.. autoclass:: Resources
.. autoclass:: RestartPolicy
.. autoclass:: TaskTemplate
.. autoclass:: UpdateConfig
...@@ -255,7 +255,7 @@ class CreateContainerTest(BaseAPIIntegrationTest): ...@@ -255,7 +255,7 @@ class CreateContainerTest(BaseAPIIntegrationTest):
self.assertIn('1001', groups) self.assertIn('1001', groups)
def test_valid_log_driver_and_log_opt(self): def test_valid_log_driver_and_log_opt(self):
log_config = docker.utils.LogConfig( log_config = docker.types.LogConfig(
type='json-file', type='json-file',
config={'max-file': '100'} config={'max-file': '100'}
) )
...@@ -274,7 +274,7 @@ class CreateContainerTest(BaseAPIIntegrationTest): ...@@ -274,7 +274,7 @@ class CreateContainerTest(BaseAPIIntegrationTest):
self.assertEqual(container_log_config['Config'], log_config.config) self.assertEqual(container_log_config['Config'], log_config.config)
def test_invalid_log_driver_raises_exception(self): def test_invalid_log_driver_raises_exception(self):
log_config = docker.utils.LogConfig( log_config = docker.types.LogConfig(
type='asdf-nope', type='asdf-nope',
config={} config={}
) )
...@@ -292,7 +292,7 @@ class CreateContainerTest(BaseAPIIntegrationTest): ...@@ -292,7 +292,7 @@ class CreateContainerTest(BaseAPIIntegrationTest):
assert excinfo.value.explanation == expected_msg assert excinfo.value.explanation == expected_msg
def test_valid_no_log_driver_specified(self): def test_valid_no_log_driver_specified(self):
log_config = docker.utils.LogConfig( log_config = docker.types.LogConfig(
type="", type="",
config={'max-file': '100'} config={'max-file': '100'}
) )
...@@ -311,7 +311,7 @@ class CreateContainerTest(BaseAPIIntegrationTest): ...@@ -311,7 +311,7 @@ class CreateContainerTest(BaseAPIIntegrationTest):
self.assertEqual(container_log_config['Config'], log_config.config) self.assertEqual(container_log_config['Config'], log_config.config)
def test_valid_no_config_specified(self): def test_valid_no_config_specified(self):
log_config = docker.utils.LogConfig( log_config = docker.types.LogConfig(
type="json-file", type="json-file",
config=None config=None
) )
......
import docker import docker
from docker.utils import create_ipam_config from docker.types import IPAMConfig, IPAMPool
from docker.utils import create_ipam_pool
import pytest import pytest
from ..helpers import random_name, requires_api_version from ..helpers import random_name, requires_api_version
...@@ -45,10 +44,10 @@ class TestNetworks(BaseAPIIntegrationTest): ...@@ -45,10 +44,10 @@ class TestNetworks(BaseAPIIntegrationTest):
@requires_api_version('1.21') @requires_api_version('1.21')
def test_create_network_with_ipam_config(self): def test_create_network_with_ipam_config(self):
_, net_id = self.create_network( _, net_id = self.create_network(
ipam=create_ipam_config( ipam=IPAMConfig(
driver='default', driver='default',
pool_configs=[ pool_configs=[
create_ipam_pool( IPAMPool(
subnet="172.28.0.0/16", subnet="172.28.0.0/16",
iprange="172.28.5.0/24", iprange="172.28.5.0/24",
gateway="172.28.5.254", gateway="172.28.5.254",
...@@ -217,9 +216,9 @@ class TestNetworks(BaseAPIIntegrationTest): ...@@ -217,9 +216,9 @@ class TestNetworks(BaseAPIIntegrationTest):
@requires_api_version('1.22') @requires_api_version('1.22')
def test_create_with_ipv4_address(self): def test_create_with_ipv4_address(self):
net_name, net_id = self.create_network( net_name, net_id = self.create_network(
ipam=create_ipam_config( ipam=IPAMConfig(
driver='default', driver='default',
pool_configs=[create_ipam_pool(subnet="132.124.0.0/16")], pool_configs=[IPAMPool(subnet="132.124.0.0/16")],
), ),
) )
container = self.client.create_container( container = self.client.create_container(
...@@ -246,9 +245,9 @@ class TestNetworks(BaseAPIIntegrationTest): ...@@ -246,9 +245,9 @@ class TestNetworks(BaseAPIIntegrationTest):
@requires_api_version('1.22') @requires_api_version('1.22')
def test_create_with_ipv6_address(self): def test_create_with_ipv6_address(self):
net_name, net_id = self.create_network( net_name, net_id = self.create_network(
ipam=create_ipam_config( ipam=IPAMConfig(
driver='default', driver='default',
pool_configs=[create_ipam_pool(subnet="2001:389::1/64")], pool_configs=[IPAMPool(subnet="2001:389::1/64")],
), ),
) )
container = self.client.create_container( container = self.client.create_container(
...@@ -353,10 +352,10 @@ class TestNetworks(BaseAPIIntegrationTest): ...@@ -353,10 +352,10 @@ class TestNetworks(BaseAPIIntegrationTest):
@requires_api_version('1.22') @requires_api_version('1.22')
def test_connect_with_ipv4_address(self): def test_connect_with_ipv4_address(self):
net_name, net_id = self.create_network( net_name, net_id = self.create_network(
ipam=create_ipam_config( ipam=IPAMConfig(
driver='default', driver='default',
pool_configs=[ pool_configs=[
create_ipam_pool( IPAMPool(
subnet="172.28.0.0/16", iprange="172.28.5.0/24", subnet="172.28.0.0/16", iprange="172.28.5.0/24",
gateway="172.28.5.254" gateway="172.28.5.254"
) )
...@@ -381,10 +380,10 @@ class TestNetworks(BaseAPIIntegrationTest): ...@@ -381,10 +380,10 @@ class TestNetworks(BaseAPIIntegrationTest):
@requires_api_version('1.22') @requires_api_version('1.22')
def test_connect_with_ipv6_address(self): def test_connect_with_ipv6_address(self):
net_name, net_id = self.create_network( net_name, net_id = self.create_network(
ipam=create_ipam_config( ipam=IPAMConfig(
driver='default', driver='default',
pool_configs=[ pool_configs=[
create_ipam_pool( IPAMPool(
subnet="2001:389::1/64", iprange="2001:389::0/96", subnet="2001:389::1/64", iprange="2001:389::0/96",
gateway="2001:389::ffff" gateway="2001:389::ffff"
) )
......
...@@ -4,7 +4,7 @@ import six ...@@ -4,7 +4,7 @@ import six
from .api_test import BaseAPIClientTest, url_prefix, response from .api_test import BaseAPIClientTest, url_prefix, response
from ..helpers import requires_api_version from ..helpers import requires_api_version
from docker.utils import create_ipam_config, create_ipam_pool from docker.types import IPAMConfig, IPAMPool
try: try:
from unittest import mock from unittest import mock
...@@ -81,9 +81,9 @@ class NetworkTest(BaseAPIClientTest): ...@@ -81,9 +81,9 @@ class NetworkTest(BaseAPIClientTest):
json.loads(post.call_args[1]['data']), json.loads(post.call_args[1]['data']),
{"Name": "foo", "Driver": "bridge", "Options": opts}) {"Name": "foo", "Driver": "bridge", "Options": opts})
ipam_pool_config = create_ipam_pool(subnet="192.168.52.0/24", ipam_pool_config = IPAMPool(subnet="192.168.52.0/24",
gateway="192.168.52.254") gateway="192.168.52.254")
ipam_config = create_ipam_config(pool_configs=[ipam_pool_config]) ipam_config = IPAMConfig(pool_configs=[ipam_pool_config])
self.client.create_network("bar", driver="bridge", self.client.create_network("bar", driver="bridge",
ipam=ipam_config) ipam=ipam_config)
......
...@@ -61,7 +61,7 @@ class ClientTest(unittest.TestCase): ...@@ -61,7 +61,7 @@ class ClientTest(unittest.TestCase):
assert "this method is now on the object APIClient" not in s assert "this method is now on the object APIClient" not in s
def test_call_containers(self): def test_call_containers(self):
client = docker.Client(**kwargs_from_env()) client = docker.DockerClient(**kwargs_from_env())
with self.assertRaises(TypeError) as cm: with self.assertRaises(TypeError) as cm:
client.containers() client.containers()
......
This diff is collapsed.
This diff is collapsed.
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