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


Python docker.errors方法代码示例

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


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

示例1: test_export

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def test_export(docker_tasker, no_container):
    if MOCK:
        mock_docker()

    container_dict = docker_tasker.create_container(INPUT_IMAGE, command=["/bin/bash"])
    container_id = container_dict['Id']

    try:
        if no_container:
            with pytest.raises(docker.errors.APIError):
                docker_tasker.export_container('NOT_THERE')
        else:
            export_generator = docker_tasker.export_container(container_id)
            for _ in export_generator:
                pass
    finally:
        docker_tasker.remove_container(container_id) 
开发者ID:containerbuildsystem,项目名称:atomic-reactor,代码行数:19,代码来源:test_tasker.py

示例2: test_retry_method

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def test_retry_method(retry_times):
    my_args = ('some', 'new')
    my_kwargs = {'one': 'first', 'two': 'second'}

    (flexmock(sys.modules[__name__])
        .should_call('my_func')
        .with_args(*my_args, **my_kwargs)
        .times(retry_times + 1))
    (flexmock(time)
        .should_receive('sleep')
        .and_return(None))

    if retry_times >= 0:
        with pytest.raises(docker.errors.APIError):
            retry(my_func, *my_args, retry=retry_times, **my_kwargs)
    else:
        retry(my_func, *my_args, retry=retry_times, **my_kwargs) 
开发者ID:containerbuildsystem,项目名称:atomic-reactor,代码行数:19,代码来源:test_tasker.py

示例3: __init__

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [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

示例4: __init__

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def __init__(self, docker_config: DockerHostConfig, mock_client=None) -> None:
        self.name = docker_config.name
        self.docker_config = docker_config
        if not docker_config.tls:
            tls = None
        else:
            tls = docker.tls.TLSConfig(client_cert=(docker_config.tls_cert, docker_config.tls_key), verify=docker_config.tls_ca)

        # Simplify testing
        if mock_client is not None:
            self.cli = mock_client
            return

        try:
            self.cli = docker.DockerClient(base_url=docker_config.address, version="auto", tls=tls)
        except docker.errors.DockerException as e:
            raise ZoeException("Cannot connect to Docker host {} at address {}: {}".format(docker_config.name, docker_config.address, str(e))) 
开发者ID:DistributedSystemsGroup,项目名称:zoe,代码行数:19,代码来源:api_client.py

示例5: terminate_container

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def terminate_container(self, docker_id: str, delete=False) -> None:
        """
        Terminate a container.

        :param docker_id: The container to terminate
        :type docker_id: str
        :param delete: If True, also delete the container files
        :type delete: bool
        :return: None
        """
        try:
            cont = self.cli.containers.get(docker_id)
        except docker.errors.NotFound:
            return

        try:
            if delete:
                cont.remove(force=True)
            else:
                cont.stop(timeout=5)
        except docker.errors.NotFound:
            pass
        except docker.errors.APIError as e:
            log.warning(str(e)) 
开发者ID:DistributedSystemsGroup,项目名称:zoe,代码行数:26,代码来源:api_client.py

示例6: list

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def list(self, only_label=None, status=None) -> List[dict]:
        """
        List running or defined containers.

        :param only_label: filter containers with only a certain label
        :param status: filter containers with only a certain status (one of restarting, running, paused, exited)
        :return: a list of containers
        """
        filters = {}
        if only_label is not None:
            filters['label'] = only_label
        if status is not None:
            filters['status'] = status
        try:
            ret = self.cli.containers.list(all=True, filters=filters)
        except docker.errors.APIError as ex:
            raise ZoeException(str(ex))
        except requests.exceptions.RequestException as ex:
            raise ZoeException(str(ex))
        conts = []
        for cont_info in ret:
            conts.append(self._container_summary(cont_info))

        return conts 
开发者ID:DistributedSystemsGroup,项目名称:zoe,代码行数:26,代码来源:api_client.py

示例7: stats

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def stats(self, docker_id: str, stream: bool):
        """Retrieves container stats based on resource usage."""
        try:
            cont = self.cli.containers.get(docker_id)
        except docker.errors.NotFound:
            raise ZoeException('Container not found')
        except docker.errors.APIError as e:
            raise ZoeException('Docker API error: {}'.format(e))

        try:
            return cont.stats(stream=stream)
        except docker.errors.APIError as e:
            raise ZoeException('Docker API error: {}'.format(e))
        except requests.exceptions.ReadTimeout:
            raise ZoeException('Read timeout')
        except ValueError:
            raise ZoeException('Docker API decoding error') 
开发者ID:DistributedSystemsGroup,项目名称:zoe,代码行数:19,代码来源:api_client.py

示例8: logs

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def logs(self, docker_id: str, stream: bool, follow=None):
        """
        Retrieves the logs of the selected container.

        :param docker_id:
        :param stream:
        :param follow:
        :return:
        """
        try:
            cont = self.cli.containers.get(docker_id)
        except (docker.errors.NotFound, docker.errors.APIError):
            return None

        try:
            return cont.logs(stdout=True, stderr=True, follow=follow, stream=stream, timestamps=True, tail='all')
        except docker.errors.APIError:
            return None 
开发者ID:DistributedSystemsGroup,项目名称:zoe,代码行数:20,代码来源:api_client.py

示例9: update

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def update(self, docker_id, cpu_quota=None, mem_reservation=None, mem_limit=None):
        """Update the resource reservation for a container."""
        kwargs = {}
        if cpu_quota is not None:
            kwargs['cpu_quota'] = cpu_quota
        if mem_reservation is not None:
            kwargs['mem_reservation'] = mem_reservation
        if mem_limit is not None:
            kwargs['mem_limit'] = mem_limit

        try:
            cont = self.cli.containers.get(docker_id)
        except (docker.errors.NotFound, docker.errors.APIError):
            return

        try:
            cont.update(**kwargs)
        except docker.errors.APIError:
            pass 
开发者ID:DistributedSystemsGroup,项目名称:zoe,代码行数:21,代码来源:api_client.py

示例10: build_apb

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def build_apb(project, dockerfile=None, tag=None):
    if dockerfile is None:
        dockerfile = "Dockerfile"
    spec = get_spec(project)
    if 'version' not in spec:
        print("APB spec does not have a listed version. Please update apb.yml")
        exit(1)

    if not tag:
        tag = spec['name']

    update_dockerfile(project, dockerfile)

    print("Building APB using tag: [%s]" % tag)

    try:
        client = create_docker_client()
        client.images.build(path=project, tag=tag, dockerfile=dockerfile)
    except docker.errors.DockerException:
        print("Error accessing the docker API. Is the daemon running?")
        raise

    print("Successfully built APB image: %s" % tag)
    return tag 
开发者ID:ansibleplaybookbundle,项目名称:ansible-playbook-bundle,代码行数:26,代码来源:engine.py

示例11: image_available

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def image_available(self) -> bool:
        """Do we currently see an up-to-date Docker image?

        Returns:
            True if we've gotten an Image ID stored.
        """
        if not self._image_id:
            try:
                self._image_id = self._client.images.get(name=self.image_tag).id
                return True
            except docker.errors.ImageNotFound:
                return False
        else:
            return True

    # Working with Containers 
开发者ID:gigantum,项目名称:gigantum-client,代码行数:18,代码来源:local_container.py

示例12: pytest_report_header

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def pytest_report_header(config):
    logger = get_logger('report_header')
    msg = []
    try:
        client = create_client()
        metadata = client.api.inspect_container('pytest_inline_scan')
    except docker.errors.NotFound:
        logger.info("No running container was found, can't add info to report header")
        metadata = {'Config': {'Labels': {}}}
        msg = ['Docker: Anchore inline_scan container not running yet']
    except DockerException as e:
        logger.exception('Unable to connect to a docker socket')
        msg = ['Anchore Version: Unable to connect to a docker socket']
        msg.append('Error: %s' % str(e))
        return msg

    labels = metadata['Config']['Labels']
    version = labels.get('version', 'unknown')
    commit = labels.get('anchore_commit', 'unknown')

    msg.extend([
       'Anchore Version: %s' % version,
       'Anchore Commit: %s' % commit
    ])
    return msg 
开发者ID:anchore,项目名称:anchore-cli,代码行数:27,代码来源:conftest.py

示例13: testDockerPipeChainErrorDetection

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def testDockerPipeChainErrorDetection(self, disableCaching=True):
        """
        By default, executing cmd1 | cmd2 | ... | cmdN, will only return an
        error if cmdN fails.  This can lead to all manor of errors being
        silently missed.  This tests to make sure that the piping API for
        dockerCall() throws an exception if non-last commands in the chain fail.
        """
        options = Job.Runner.getDefaultOptions(os.path.join(self.tempDir,
                                                            'jobstore'))
        options.logLevel = self.dockerTestLogLevel
        options.workDir = self.tempDir
        options.clean = 'always'
        options.caching = disableCaching
        A = Job.wrapJobFn(_testDockerPipeChainErrorFn)
        rv = Job.Runner.startToil(A, options)
        assert rv == True 
开发者ID:DataBiosphere,项目名称:toil,代码行数:18,代码来源:dockerTest.py

示例14: docker_logs

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def docker_logs(self, container_id, show_stdout, show_stderr, follow):
        try:
            return (self.cli.logs(container=container_id, stdout=show_stdout, stderr=show_stderr, follow=follow))\
                   .decode('utf-8')
        except docker.errors.APIError as ex:
            if "configured logging reader does not support reading" in str(ex):
                message = "Docker logging driver is not set to be 'json-file' or 'journald'"
                DagdaLogger.get_logger().error(message)
                raise DagdaError(message)
            else:
                message = "Unexpected exception of type {0} occurred: {1!r}" \
                    .format(type(ex).__name__, str(ex))
                DagdaLogger.get_logger().error(message)
                raise ex

    # Creates container and return the container id 
开发者ID:eliasgranderubio,项目名称:dagda,代码行数:18,代码来源:docker_driver.py

示例15: test_handle_missing_squash_cache

# 需要导入模块: import docker [as 别名]
# 或者: from docker import errors [as 别名]
def test_handle_missing_squash_cache(experimental_daemon, squashcache):
    run_docker_make("-f data/secret-squash.yml cache-test invisible-secret")
    client = helpers.get_client()
    cachelayer = client.images.get("invisible-secret")
    firstimg = client.images.get("cache-test")
    for _id in ("cache-test", firstimg.id, "invisible_secret", cachelayer.id):
        try:
            client.images.remove(_id)
        except docker.errors.ImageNotFound:
            pass

    # Make sure the image can rebuild even if original layers are missing
    run_docker_make("-f data/secret-squash.yml cache-test")

    # Sanity check - makes sure that the first image was in fact removed and not used for cache
    assert client.images.get("cache-test").id != firstimg.id 
开发者ID:avirshup,项目名称:DockerMake,代码行数:18,代码来源:test_features.py


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