當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。