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


Python docker.DockerClient方法代码示例

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


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

示例1: getBridgeGateway

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def getBridgeGateway():
    """
    Look up the gateway IP address for the docker bridge network.

    This is the docker0 IP address; it is the IP address of the host from the
    chute's perspective.
    """
    client = docker.DockerClient(base_url="unix://var/run/docker.sock", version='auto')

    network = client.networks.get("bridge")
    for config in network.attrs['IPAM']['Config']:
        if 'Gateway' in config:
            return config['Gateway']

    # Fall back to a default if we could not find it.  This address will work
    # in most places unless Docker changes to use a different address.
    out.warn('Could not find bridge gateway, using default')
    return '172.17.0.1' 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:20,代码来源:dockerapi.py

示例2: _setResourceAllocation

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def _setResourceAllocation(allocation):
    client = docker.DockerClient(base_url="unix://var/run/docker.sock", version='auto')
    for container_name, resources in six.iteritems(allocation):
        out.info("Update chute {} set cpu_shares={}\n".format(
            container_name, resources['cpu_shares']))
        container = client.containers.get(container_name)
        container.update(cpu_shares=resources['cpu_shares'])

        # Using class id 1:1 for prioritized, 1:3 for best effort.
        # Prioritization is implemented in confd/qos.py.  Class-ID is
        # represented in hexadecimal.
        # Reference: https://www.kernel.org/doc/Documentation/cgroup-v1/net_cls.txt
        if resources.get('prioritize_traffic', False):
            classid = "0x10001"
        else:
            classid = "0x10003"

        container = ChuteContainer(container_name)
        try:
            container_id = container.getID()
            fname = "/sys/fs/cgroup/net_cls/docker/{}/net_cls.classid".format(container_id)
            with open(fname, "w") as output:
                output.write(classid)
        except Exception as error:
            out.warn("Error setting traffic class: {}\n".format(error)) 
开发者ID:ParadropLabs,项目名称:Paradrop,代码行数:27,代码来源:dockerapi.py

示例3: __init__

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

示例4: connect

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def connect(self, params={}):
        client_cert = (
            helper.key_to_file(params.get('client_cert').get('secretKey')),
            helper.key_to_file(params.get('client_key').get('secretKey'))
        )
        ca_cert = helper.key_to_file(params.get('ca_cert').get('secretKey'))
        tls_config = docker.tls.TLSConfig(
            client_cert=client_cert,
            ca_cert=ca_cert
        )
        base_url = params.get('url')

        try:
            self.logger.info("Connect: Connecting to {}".format(base_url))
            self.docker_client = docker.DockerClient(
                base_url=base_url,
                tls=tls_config,
                version=params.get('api_version')
            )
        except docker.errors.DockerException:
            raise
        else:
            self.logger.info("Connect: Connected to {} successfully.".format(base_url)) 
开发者ID:rapid7,项目名称:insightconnect-plugins,代码行数:25,代码来源:connection.py

示例5: get_docker_client

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def get_docker_client(base_url=None, retry_read=config.DOCKER_MAX_READ_RETRIES,
                      retry_status_forcelist=(500,)):
    client_key = (retry_read, retry_status_forcelist)
    if client_key not in _DOCKER_CLIENTS:
        client = docker.DockerClient(base_url=base_url or config.DOCKER_URL,
                                     timeout=config.DOCKER_TIMEOUT)
        retries = Retry(total=config.DOCKER_MAX_TOTAL_RETRIES,
                        connect=config.DOCKER_MAX_CONNECT_RETRIES,
                        read=retry_read,
                        method_whitelist=False,
                        status_forcelist=retry_status_forcelist,
                        backoff_factor=config.DOCKER_BACKOFF_FACTOR,
                        raise_on_status=False)
        http_adapter = HTTPAdapter(max_retries=retries)
        client.api.mount('http://', http_adapter)
        _DOCKER_CLIENTS[client_key] = client
    return _DOCKER_CLIENTS[client_key] 
开发者ID:StepicOrg,项目名称:epicbox,代码行数:19,代码来源:utils.py

示例6: _UpdateNode

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def _UpdateNode(self, leader, node_id, node_role, labels={}):
        """ 更新节点信息(Labels、Role等) """

        client = docker.DockerClient(base_url="tcp://{}:{}".format(leader, self.port), version="auto", timeout=self.timeout)

        node_spec = {
            'Availability': 'active',
            'Role': node_role,
            'Labels': labels
        }
        logger.info("Update node spec data is {} for node_id {})".format(node_spec, node_id))

        try:
            node = client.nodes.get(node_id)
            res  = node.update(node_spec)
        except docker.errors.APIError,e:
            logger.error(e, exc_info=True)
            return False 
开发者ID:staugur,项目名称:SwarmOps,代码行数:20,代码来源:Base.py

示例7: create_client

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def create_client():
    """
    Create a client to either a Docker instance.
    """
    kwargs = {
        "base_url": os.environ.get("DOCKER_HOST"),
        "timeout": 15,  # wait a bit, but give up before 30s Heroku request timeout
    }

    if os.environ.get("DOCKER_TLS_VERIFY"):
        kwargs["tls"] = TLSConfig(
            client_cert=(
                env_to_file("DOCKER_CLIENT_CERT"),
                env_to_file("DOCKER_CLIENT_KEY"),
            ),
            ca_cert=env_to_file("DOCKER_CA_CERT"),
            verify=True,
        )

    return docker.DockerClient(**kwargs) 
开发者ID:arxiv-vanity,项目名称:arxiv-vanity,代码行数:22,代码来源:renderer.py

示例8: __init__

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

示例9: create_docker_client

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def create_docker_client():
    # In order to build and push to the minishift registry, it's required that
    # users have configured their shell to use the minishift docker daemon
    # instead of a local daemon:
    # https://docs.openshift.org/latest/minishift/using/docker-daemon.html
    if is_minishift():
        cert_path = os.environ.get('DOCKER_CERT_PATH')
        docker_host = os.environ.get('DOCKER_HOST')
        if docker_host is None or cert_path is None:
            raise Exception("Attempting to target minishift, but missing required \
                            env vars. Try running: \"eval $(minishift docker-env)\"")
        client_cert = os.path.join(cert_path, 'cert.pem')
        client_key = os.path.join(cert_path, 'key.pem')
        ca_cert = os.path.join(cert_path, 'ca.pem')
        tls = docker.tls.TLSConfig(
            ca_cert=ca_cert,
            client_cert=(client_cert, client_key),
            verify=True,
            assert_hostname=False
        )
        client = docker.DockerClient(tls=tls, base_url=docker_host, version='auto')
    else:
        client = docker.DockerClient(base_url='unix://var/run/docker.sock', version='auto')
    return client 
开发者ID:ansibleplaybookbundle,项目名称:ansible-playbook-bundle,代码行数:26,代码来源:engine.py

示例10: create_docker_client

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def create_docker_client(docker_host: str = '', check=True) -> docker.DockerClient:
    """
    Context manager for DockerClient creation

    :param docker_host: DOCKER_HOST arg for DockerClient
    :param check: check if docker is available
    :return: DockerClient instance
    """
    with _docker_host_lock:
        os.environ["DOCKER_HOST"] = docker_host  # The env var DOCKER_HOST is used to configure docker.from_env()
        client = docker.from_env()
    if check and not _is_docker_running(client):
        raise RuntimeError("Docker daemon is unavailable")
    try:
        yield client
    finally:
        client.close() 
开发者ID:zyfra,项目名称:ebonite,代码行数:19,代码来源:utils.py

示例11: __init__

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def __init__(self, master_host, slave_hosts,
                 local_mount_dir, docker_mount_dir):
        # see PyDoc for all_internal_hosts() for an explanation on the
        # difference between an internal and regular host
        self.internal_master = master_host
        self.internal_slaves = slave_hosts
        self._master = master_host + '-' + str(uuid.uuid4())
        self.slaves = [slave + '-' + str(uuid.uuid4())
                       for slave in slave_hosts]
        # the root path for all local mount points; to get a particular
        # container mount point call get_local_mount_dir()
        self.local_mount_dir = local_mount_dir
        self._mount_dir = docker_mount_dir

        kwargs = kwargs_from_env()
        if 'tls' in kwargs:
            kwargs['tls'].assert_hostname = False
        kwargs['timeout'] = 300
        self.client = DockerClient(**kwargs)
        self._user = 'root'
        self._network_name = 'presto-admin-test-' + str(uuid.uuid4())

        DockerCluster.__check_if_docker_exists() 
开发者ID:prestodb,项目名称:presto-admin,代码行数:25,代码来源:docker_cluster.py

示例12: __init__

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def __init__(self, context, spec, build_status=None, docker_version='auto'):
        self.context = context
        self.spec = spec
        self.repo_name = context.repository.split('/')[-1]
        self.commit_hash = context.source['commit']['hash']
        self.build_status = build_status or BuildStatus(
            bitbucket,
            context.source['repository']['full_name'],
            self.commit_hash,
            'badwolf/test',
            url_for('log.build_log', sha=self.commit_hash, _external=True)
        )

        self.docker = DockerClient(
            base_url=current_app.config['DOCKER_HOST'],
            timeout=current_app.config['DOCKER_API_TIMEOUT'],
            version=docker_version,
        ) 
开发者ID:bosondata,项目名称:badwolf,代码行数:20,代码来源:builder.py

示例13: _pull_predefined_dockerimages

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def _pull_predefined_dockerimages(self):
        """
        If the package contains URLs to pre-build Docker images, we download them with this method.
        """
        dc = DockerClient()
        for url in self.remote_docker_image_urls.itervalues():
            # only pull if not present (speedup for development)
            if not FORCE_PULL:
                if len(dc.images.list(name=url)) > 0:
                    LOG.debug("Image %r present. Skipping pull." % url)
                    continue
            LOG.info("Pulling image: %r" % url)
            # this seems to fail with latest docker api version 2.0.2
            # dc.images.pull(url,
            #        insecure_registry=True)
            # using docker cli instead
            cmd = ["docker",
                   "pull",
                   url,
                   ]
            Popen(cmd).wait() 
开发者ID:sonata-nfv,项目名称:son-emu,代码行数:23,代码来源:dummygatekeeper.py

示例14: initiate_remote_docker_connection

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def initiate_remote_docker_connection(self, docker_server_url):
        """
        Docker allows remote access to its API in a number of ways.
        This function takes in a parameter of a server url and attempts to establish a docker connection

        For example 'ssh://admin:pass@192.168.1.0'
        :param docker_server_url:
        :return: void
        """
        try:
            self.client = docker.DockerClient(base_url=docker_server_url)
            self.api_client = docker.APIClient(base_url=docker_server_url)
            LOG.debug("The DockerClient version is {}".format(self.client.version()['Version']))
            self.client.ping()
        except ConnectionError:
            LOG.error('Error connecting to docker')
            raise ValueError("Could not setup Docker connection, is docker running ?") 
开发者ID:ibmresilient,项目名称:resilient-community-apps,代码行数:19,代码来源:docker_utils.py

示例15: check_docker

# 需要导入模块: import docker [as 别名]
# 或者: from docker import DockerClient [as 别名]
def check_docker(self):

        logger.info(f"testing docker API on {DOCKER_SOCKET}…")
        if (
            not DOCKER_SOCKET.exists()
            or not DOCKER_SOCKET.is_socket()
            or not os.access(DOCKER_SOCKET, os.R_OK)
        ):
            logger.critical(f"\tsocket ({DOCKER_SOCKET}) not available.")
            sys.exit(1)
        self.docker = docker.DockerClient(
            base_url=f"unix://{DOCKER_SOCKET}", timeout=DOCKER_CLIENT_TIMEOUT
        )
        try:
            if len(self.docker.containers.list(all=False)) < 1:
                logger.warning("\tno running container, am I out-of-docker?")
        except Exception as exc:
            logger.critical("\tdocker API access failed: exiting.")
            logger.exception(exc)
            sys.exit(1)
        else:
            logger.info("\tdocker API access successful") 
开发者ID:openzim,项目名称:zimfarm,代码行数:24,代码来源:worker.py


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