当前位置: 首页>>代码示例>>Python>>正文


Python docker.APIClient方法代码示例

本文整理汇总了Python中docker.APIClient方法的典型用法代码示例。如果您正苦于以下问题:Python docker.APIClient方法的具体用法?Python docker.APIClient怎么用?Python docker.APIClient使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在docker的用法示例。


在下文中一共展示了docker.APIClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def __init__(self):
        """ Connnects to the docker daemon"""
        # will be used as the tag on the docker image
        self.problem_name = sanitize_name(self.name)
        # use an explicit remote docker daemon per the configuration
        try:
            tls_config = docker.tls.TLSConfig(
                ca_cert=self.docker_ca_cert,
                client_cert=(self.docker_client_cert, self.docker_client_key),
                verify=True)

            self.client = docker.DockerClient(base_url=self.docker_host, tls=tls_config)
            self.api_client = docker.APIClient(base_url=self.docker_host, tls=tls_config)
            logger.debug("Connecting to docker daemon with config")

        # Docker options not set in configuration so use the environment to
        # configure (could be local or remote)
        except AttributeError:
            logger.debug("Connecting to docker daemon with env")
            self.client = docker.from_env()

        # throws an exception if the server returns an error: docker.errors.APIError
        self.client.ping() 
开发者ID:picoCTF,项目名称:picoCTF,代码行数:25,代码来源:docker.py

示例2: test_docker_tasker

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def test_docker_tasker(autoversion, base_url_arg):
    mock_docker()
    base_url = 'unix://var/run/docker.sock'
    kwargs = {}
    if base_url_arg:
        kwargs['base_url'] = base_url
    else:
        os.environ['DOCKER_CONNECTION'] = base_url

    expected_kwargs = {'base_url': base_url, 'timeout': 120}
    if autoversion:
        setattr(docker, 'AutoVersionClient', 'auto')
        expected_kwargs['version'] = 'auto'

    (flexmock(docker.APIClient)
        .should_receive('__init__')
        .with_args(**expected_kwargs)
        .once())

    DockerTasker(**kwargs)

    os.environ.pop('DOCKER_CONNECTION', None)
    if autoversion:
        delattr(docker, 'AutoVersionClient') 
开发者ID:containerbuildsystem,项目名称:atomic-reactor,代码行数:26,代码来源:test_tasker.py

示例3: test_timeout

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def test_timeout(timeout, expected_timeout):
    if not hasattr(docker, 'APIClient'):
        setattr(docker, 'APIClient', docker.Client)

    expected_kwargs = {
        'timeout': expected_timeout
    }
    if hasattr(docker, 'AutoVersionClient'):
        expected_kwargs['version'] = 'auto'

    (flexmock(docker.APIClient)
        .should_receive('__init__')
        .with_args(**expected_kwargs)
        .once())

    kwargs = {}
    if timeout is not None:
        kwargs['timeout'] = timeout

    DockerTasker(**kwargs) 
开发者ID:containerbuildsystem,项目名称:atomic-reactor,代码行数:22,代码来源:test_tasker.py

示例4: test_rpmqa_plugin_skip

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def test_rpmqa_plugin_skip(docker_tasker):  # noqa
    """
    Test skipping the plugin if workflow.image_components is already set
    """
    mock_docker()
    workflow = DockerBuildWorkflow(TEST_IMAGE, source=SOURCE)
    workflow.source = StubSource()
    workflow.builder = StubInsideBuilder().for_workflow(workflow)

    image_components = {
        'type': 'rpm',
        'name': 'something'
    }
    setattr(workflow, 'image_components', image_components)

    flexmock(docker.APIClient, logs=mock_logs_raise)
    runner = PostBuildPluginsRunner(docker_tasker, workflow,
                                    [{"name": PostBuildRPMqaPlugin.key,
                                      "args": {'image_id': TEST_IMAGE}}])
    results = runner.run()
    assert results[PostBuildRPMqaPlugin.key] is None
    assert workflow.image_components == image_components 
开发者ID:containerbuildsystem,项目名称:atomic-reactor,代码行数:24,代码来源:test_rpmqa.py

示例5: test_no_auto_remove

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def test_no_auto_remove(self, types_mock, client_class_mock):

        mock_obj = mock.Mock()

        client_mock = mock.Mock(spec=APIClient)
        client_mock.create_service.return_value = {'ID': 'some_id'}
        client_mock.images.return_value = []
        client_mock.pull.return_value = [b'{"status":"pull log"}']
        client_mock.tasks.return_value = [{'Status': {'State': 'complete'}}]
        types_mock.TaskTemplate.return_value = mock_obj
        types_mock.ContainerSpec.return_value = mock_obj
        types_mock.RestartPolicy.return_value = mock_obj
        types_mock.Resources.return_value = mock_obj

        client_class_mock.return_value = client_mock

        operator = DockerSwarmOperator(image='', auto_remove=False, task_id='unittest', enable_logging=False)
        operator.execute(None)

        self.assertEqual(
            client_mock.remove_service.call_count, 0,
            'Docker service being removed even when `auto_remove` set to `False`'
        ) 
开发者ID:apache,项目名称:airflow,代码行数:25,代码来源:test_docker_swarm.py

示例6: test_failed_service_raises_error

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def test_failed_service_raises_error(self, types_mock, client_class_mock):

        mock_obj = mock.Mock()

        client_mock = mock.Mock(spec=APIClient)
        client_mock.create_service.return_value = {'ID': 'some_id'}
        client_mock.images.return_value = []
        client_mock.pull.return_value = [b'{"status":"pull log"}']
        client_mock.tasks.return_value = [{'Status': {'State': 'failed'}}]
        types_mock.TaskTemplate.return_value = mock_obj
        types_mock.ContainerSpec.return_value = mock_obj
        types_mock.RestartPolicy.return_value = mock_obj
        types_mock.Resources.return_value = mock_obj

        client_class_mock.return_value = client_mock

        operator = DockerSwarmOperator(image='', auto_remove=False, task_id='unittest', enable_logging=False)
        msg = "Service failed: {'ID': 'some_id'}"
        with self.assertRaises(AirflowException) as error:
            operator.execute(None)
        self.assertEqual(str(error.exception), msg) 
开发者ID:apache,项目名称:airflow,代码行数:23,代码来源:test_docker_swarm.py

示例7: test_execute_tls

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def test_execute_tls(self, client_class_mock, tls_class_mock):
        client_mock = mock.Mock(spec=APIClient)
        client_mock.create_container.return_value = {'Id': 'some_id'}
        client_mock.create_host_config.return_value = mock.Mock()
        client_mock.images.return_value = []
        client_mock.attach.return_value = []
        client_mock.pull.return_value = []
        client_mock.wait.return_value = {"StatusCode": 0}

        client_class_mock.return_value = client_mock
        tls_mock = mock.Mock()
        tls_class_mock.return_value = tls_mock

        operator = DockerOperator(docker_url='tcp://127.0.0.1:2376', image='ubuntu',
                                  owner='unittest', task_id='unittest', tls_client_cert='cert.pem',
                                  tls_ca_cert='ca.pem', tls_client_key='key.pem')
        operator.execute(None)

        tls_class_mock.assert_called_once_with(assert_hostname=None, ca_cert='ca.pem',
                                               client_cert=('cert.pem', 'key.pem'),
                                               ssl_version=None, verify=True)

        client_class_mock.assert_called_once_with(base_url='https://127.0.0.1:2376',
                                                  tls=tls_mock, version=None) 
开发者ID:apache,项目名称:airflow,代码行数:26,代码来源:test_docker.py

示例8: __init__

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def __init__(self):
        self._containers = None
        self._images = None  # displayed images
        self._all_images = None  # docker images -a
        self._df = None

        kwargs = {"version": "auto"}
        kwargs.update(docker.utils.kwargs_from_env(assert_hostname=False))

        try:
            APIClientClass = docker.Client  # 1.x
        except AttributeError:
            APIClientClass = docker.APIClient  # 2.x

        try:
            self.client = APIClientClass(**kwargs)
        except docker.errors.DockerException as ex:
            raise TerminateApplication("can't establish connection to docker daemon: {0}".format(str(ex)))

        self.scratch_image = RootImage(self)

    # backend queries 
开发者ID:TomasTomecek,项目名称:sen,代码行数:24,代码来源:docker_backend.py

示例9: __init__

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def __init__(self, image=DEFAULT_IMAGE, container_timeout=3600,
                 container_expire=3000, container_prefix=None,
                 docker_client=None):
        self._image = image
        self._container_timeout = container_timeout
        self._container_expire = container_expire

        if container_prefix:
            self._container_prefix = container_prefix
        elif os.environ.get(CONTAINER_PREFIX_ENV):
            self._container_prefix = os.environ[CONTAINER_PREFIX_ENV]
        else:
            self._container_prefix = DEFAULT_CONTAINER_PREFIX

        self._docker_client = docker_client or docker.APIClient(
            **docker.utils.kwargs_from_env(assert_hostname=False)
        )
        self._lock = threading.RLock()
        self._reset_container() 
开发者ID:worstcase,项目名称:blockade,代码行数:21,代码来源:host.py

示例10: prepare_image

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def prepare_image(update, service):
    """
    Prepare a Docker image for execution.

    This is usually the longest operation during a chute installation, so
    instead of running this step in the update thread, we spin off a worker
    thread and return a Deferred. This will suspend processing of the current
    update until the worker thread finishes.
    """
    client = docker.APIClient(base_url="unix://var/run/docker.sock", version='auto')

    image_name = service.get_image_name()

    def call(func, *args, **kwargs):
        return func(*args, **kwargs)

    if settings.CONCURRENT_BUILDS:
        wrapper = deferToThread
    else:
        wrapper = call

    if service.type == "image":
        return wrapper(_pull_image, update, client, image_name)

    elif service.type == "inline":
        return wrapper(_build_image, update, service, client, True,
                rm=True, tag=image_name, fileobj=service.dockerfile)

    else:
        return wrapper(_build_image, update, service, client, False,
                rm=True, tag=image_name, path=update.workdir) 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:33,代码来源:dockerapi.py

示例11: remove_image

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def remove_image(update, service):
    """
    Remove a Docker image.
    """
    client = docker.APIClient(base_url="unix://var/run/docker.sock", version='auto')

    image_name = service.get_image_name()
    out.info("Removing image {}\n".format(image_name))

    try:
        client = docker.DockerClient(base_url="unix://var/run/docker.sock",
                version='auto')
        client.images.remove(image=image_name)
    except Exception as error:
        out.warn("Error removing image: {}".format(error)) 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:17,代码来源:dockerapi.py

示例12: inspect

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def inspect(self):
        """
        Return the full container status from Docker.
        """
        client = docker.APIClient(base_url=self.docker_url, version='auto')
        try:
            info = client.inspect_container(self.name)
            return info
        except docker.errors.NotFound:
            raise ChuteNotFound("The chute could not be found.") 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:12,代码来源:chutecontainer.py

示例13: _new_exec_client

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def _new_exec_client(self, container, token, uuid, exec_id):
        exec_instance = None
        for e in container.exec_instances:
            if token == e.token and exec_id == e.exec_id:
                exec_instance = e

        if not exec_instance:
            raise exception.InvalidWebsocketToken(token)

        access_url = '%s?token=%s&uuid=%s' % (CONF.websocket_proxy.base_url,
                                              token, uuid)

        self._verify_origin(access_url)

        client = docker.APIClient(base_url=exec_instance.url)
        tsock = client.exec_start(exec_id, socket=True, tty=True)
        if hasattr(tsock, "_sock"):
            # NOTE(hongbin): dockerpy returns different socket class depending
            # on python version and base_url (see _get_raw_response_socket) so
            # we need to handle it in here.
            tsock = tsock._sock

        try:
            self.do_proxy(tsock)
        finally:
            if tsock:
                tsock.shutdown(socket.SHUT_RDWR)
                tsock.close()
                self.vmsg(_("%s: Closed target") % exec_instance.url) 
开发者ID:openstack,项目名称:zun,代码行数:31,代码来源:websocketproxy.py

示例14: setUp

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def setUp(self):
        super(BaseFullStackTestCase, self).setUp()

        self.docker = docker.APIClient(base_url='tcp://0.0.0.0:2375')
        try:
            self.zun = utils.get_zun_client_from_env()
        except Exception as e:
            # We may missing or didn't source configured openrc file.
            message = ("Missing environment variable %s in your local."
                       "Please add it and also check other missing "
                       "environment variables. After that please source "
                       "the openrc file. "
                       "Trying credentials from DevStack cloud.yaml ...")
            LOG.warning(message, e.args[0])
            self.zun = utils.get_zun_client_from_creds() 
开发者ID:openstack,项目名称:zun,代码行数:17,代码来源:base.py

示例15: get_clients

# 需要导入模块: import docker [as 别名]
# 或者: from docker import APIClient [as 别名]
def get_clients():
    """
    Get a high level and a low level docker client connection,

    Ensures that only one global docker client exists per thread. If the client
    does not exist a new one is created and returned.
    """

    global __client, __api_client
    if not __client or not __api_client:
        try:
            conf = current_app.config

            # use an explicit remote docker daemon per the configuration
            opts = ["DOCKER_HOST", "DOCKER_CA", "DOCKER_CLIENT", "DOCKER_KEY"]
            if all([o in conf for o in opts]):
                host, ca, client, key = [conf[o] for o in opts]

                log.debug("Connecting to docker daemon with config")
                tls_config = docker.tls.TLSConfig(ca_cert=ca, client_cert=(client, key), verify=True)
                __api_client = docker.APIClient(base_url=host, tls=tls_config)
                __client = docker.DockerClient(base_url=host, tls=tls_config)

            # Docker options not set in configuration so attempt to use unix socket
            else:
                log.debug("Connecting to docker daemon on local unix socket")
                __api_client = docker.APIClient(base_url="unix:///var/run/docker.sock")
                __client = docker.DockerClient(base_url="unix:///var/run/docker.sock")

            # ensure a responsive connection
            __client.ping()
        except docker.errors.APIError as e:
            log.debug("Could not connect to docker daemon:" + e)
            raise PicoException(
                "On Demand backend unavailible. Please contact an admin."
            )

    return __client, __api_client 
开发者ID:picoCTF,项目名称:picoCTF,代码行数:40,代码来源:docker.py


注:本文中的docker.APIClient方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。