當前位置: 首頁>>代碼示例>>Python>>正文


Python Client.inspect_container方法代碼示例

本文整理匯總了Python中docker.client.Client.inspect_container方法的典型用法代碼示例。如果您正苦於以下問題:Python Client.inspect_container方法的具體用法?Python Client.inspect_container怎麽用?Python Client.inspect_container使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在docker.client.Client的用法示例。


在下文中一共展示了Client.inspect_container方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: run

# 需要導入模塊: from docker.client import Client [as 別名]
# 或者: from docker.client.Client import inspect_container [as 別名]
    def run(self,
            ssl_env_name='STUNNEL_SSL'):
        """
           Run a container scan for a variable containing a certificate env dictionary

            Args:
                ssl_env_name(string): The string containing the certificate env
        """
        cli = Client(base_url='unix://var/run/docker.sock')
        for container in cli.containers():
          container_details = cli.inspect_container(container.get('Id'))
          container_envs = container_details.get('Config').get('Env')
          env_ssl = [ env for env in container_envs if ssl_env_name in env]
          if len(env_ssl) > 0:
            env_cert = env_ssl[0].split('=', 1)[1]
            env_json = json.loads(env_cert)
            raw_ssl = env_json.get('cert')
            cert = c.load_certificate(c.FILETYPE_PEM, raw_ssl)
            not_after = cert.get_notAfter()
            not_after_date = self.get_cert_time(not_after)
            has_expired = cert.has_expired()
            signature_algorithm = cert.get_signature_algorithm()
            self.logger.info("Found stunnel container envs", 
                             extra={'notAfter': '{}'.format(not_after),
                                    'notAfterDate': '{}'.format(not_after_date),
                                    'hasExpired': '{}'.format(has_expired),
                                    'containerId': '{}'.format(container.get('Id')),
                                    'signatureAlgorithm': '{}'.format(signature_algorithm)})
開發者ID:ministryofjustice,項目名稱:logstash-formula,代碼行數:30,代碼來源:stunnel_scanner.py

示例2: __init__

# 需要導入模塊: from docker.client import Client [as 別名]
# 或者: from docker.client.Client import inspect_container [as 別名]
class Runner:
    """
    This class is in charge of loading test suites and runs them on different environments

    """
    STOP_TIMEOUT = 3

    def __init__(self, cfg):
        from docker.client import Client
        from docker.utils import kwargs_from_env

        self.config = cfg
        docker_kwargs = kwargs_from_env()
        docker_kwargs['tls'].assert_hostname = False
        self.docker = Client(**docker_kwargs)


    def run(self, build, *tests):
        """
        Run all the test suites passed in as parameters on the given build
        This method will start a container of the build, run the tests and stop it

        """
        from docker.utils import create_host_config

        print("Running tests on {}".format(build.name))
        ports = self.config['environment']['ports']
        host = self.config['global'].get('docker_host', os.getenv('DOCKER_HOST').split('/')[-1].split(':')[0])
        container = self.docker.create_container(
                image=build.docker_tag,
                command='/bin/bash -c "nc -l 8080"',
                ports=ports,
                host_config=create_host_config(port_bindings=dict(zip(ports, [None] * len(ports))))
            ).get('Id')
        self.docker.start(container)
        info = self.docker.inspect_container(container)
        port_bindings = {port: bind[0]['HostPort'] for port, bind in info['NetworkSettings']['Ports'].items()}
        for test in tests:
            test.run(host, port_bindings, build.context)
        self.docker.stop(container, timeout=self.STOP_TIMEOUT)
        log_file_path = os.path.join(self.config['global'].get('logs_dir', '/tmp'), '{}.log'.format(build.name))
        with open(log_file_path, 'wb') as logs:
            logs.write(self.docker.logs(container, stdout=True, stderr=True, stream=False))
        print("Container logs wrote to {}".format(log_file_path))
開發者ID:quanta-computing,項目名稱:quanta-php-module,代碼行數:46,代碼來源:runner.py

示例3: DockerDaemon

# 需要導入模塊: from docker.client import Client [as 別名]
# 或者: from docker.client.Client import inspect_container [as 別名]
class DockerDaemon():

    def __init__(self, db):
        self.client = Client()
        self.db = db

    def get_events(self):
        events = self.client.events(decode=True)

        for event in events:
            if event:
                if event.get('status') in ['start', 'die']:
                    self.send_container_status(event)

    def send_container_status(self, event):
        event['container'] = self.get_container(event.get('id'))
        key = '%s_%s' % (event.get('id'), event.get('status'))
        self.db.set(key, event)

    def get_container(self, id):
        return self.client.inspect_container(id)
開發者ID:agassner,項目名稱:docker-events,代碼行數:23,代碼來源:events.py

示例4: DockerController

# 需要導入模塊: from docker.client import Client [as 別名]
# 或者: from docker.client.Client import inspect_container [as 別名]

#.........這裏部分代碼省略.........

        time_key = 't:' + client_id
        self.redis.setex(time_key, self.T_EXPIRE_TIME, dur)

        throttle_samples = int(self.redis.get('throttle_samples'))
        print('INIT DUR: ' + str(dur))
        self.redis.lpush('init_timings', time_key)
        self.redis.ltrim('init_timings', 0, throttle_samples - 1)

        return info

    def new_container(self, browser_id, env=None, default_host=None):
        browser = self.browser_paths.get(browser_id)

        # get default browser
        if not browser:
            browser = self.browser_paths.get(self.default_browser)

        container = self.cli.create_container(image=self.image_prefix + '/' + browser['id'],
                                              ports=[self.VNC_PORT, self.CMD_PORT],
                                              environment=env,
                                             )
        short_id = None
        try:
            id_ = container.get('Id')
            short_id = id_[:12]

            res = self.cli.start(container=id_,
                                 port_bindings={self.VNC_PORT: None, self.CMD_PORT: None},
                                 volumes_from=['netcapsule_shared_data_1'],
                                 network_mode='netcapsule',
                                )

            info = self.cli.inspect_container(id_)
            ip = info['NetworkSettings']['IPAddress']
            if not ip:
                ip = info['NetworkSettings']['Networks']['netcapsule']['IPAddress']

            #self.redis.hset('all_containers', short_id, ip)
            self.redis.incr('num_containers')
            self.redis.setex('c:' + short_id, self.C_EXPIRE_TIME, 1)

            return {'vnc_host': self._get_host_port(info, self.VNC_PORT, default_host),
                    'cmd_host': self._get_host_port(info, self.CMD_PORT, default_host),
                   }
        except Exception as e:
            if short_id:
                self.remove_container(short_id)

            traceback.print_exc(e)
            return {}

    def remove_container(self, short_id, ip=None):
        print('REMOVING ' + short_id)
        try:
            self.cli.remove_container(short_id, force=True)
        except Exception as e:
            print(e)

        #self.redis.hdel('all_containers', short_id)
        self.redis.delete('c:' + short_id)

        if ip:
            ip_keys = self.redis.keys(ip + ':*')
            for key in ip_keys:
                self.redis.delete(key)
開發者ID:waibo,項目名稱:netcapsule,代碼行數:70,代碼來源:main.py

示例5: DockerController

# 需要導入模塊: from docker.client import Client [as 別名]
# 或者: from docker.client.Client import inspect_container [as 別名]
class DockerController(object):
    def _load_config(self):
        with open('./config.yaml') as fh:
            config = yaml.load(fh)
        return config

    def __init__(self):
        config = self._load_config()

        self.REDIS_HOST = config['redis_host']
        self.PYWB_HOST = config['pywb_host']
        self.C_EXPIRE_TIME = config['container_expire_secs']
        self.Q_EXPIRE_TIME = config['queue_expire_secs']
        self.REMOVE_EXP_TIME = config['remove_expired_secs']
        self.VERSION = config['api_version']

        self.VNC_PORT = config['vnc_port']
        self.CMD_PORT = config['cmd_port']

        self.image_prefix = config['image_prefix']
        self.browsers = config['browsers']

        self.redis = redis.StrictRedis(host=self.REDIS_HOST)

        self.redis.setnx('next_client', '1')

        if os.path.exists('/var/run/docker.sock'):
            self.cli = Client(base_url='unix://var/run/docker.sock',
                              version=self.VERSION)
        else:
            kwargs = kwargs_from_env()
            kwargs['tls'].assert_hostname = False
            kwargs['version'] = self.VERSION
            self.cli = Client(**kwargs)

    def new_container(self, browser, env=None):
        tag = self.browsers.get(browser)

        # get default browser
        if not tag:
            tag = self.browsers['']

        container = self.cli.create_container(image=self.image_prefix + '/' + tag,
                                              ports=[self.VNC_PORT, self.CMD_PORT],
                                              environment=env,
                                             )
        id_ = container.get('Id')

        res = self.cli.start(container=id_,
                             port_bindings={self.VNC_PORT: None, self.CMD_PORT: None},
                             links={self.PYWB_HOST: self.PYWB_HOST,
                                    self.REDIS_HOST: self.REDIS_HOST},
                             volumes_from=['netcapsule_shared_data_1'],
                            )

        vnc_port = self.cli.port(id_, self.VNC_PORT)
        vnc_port = vnc_port[0]['HostPort']

        cmd_port = self.cli.port(id_, self.CMD_PORT)
        cmd_port = cmd_port[0]['HostPort']

        info = self.cli.inspect_container(id_)
        ip = info['NetworkSettings']['IPAddress']

        short_id = id_[:12]
        self.redis.hset('all_containers', short_id, ip)
        self.redis.setex('c:' + short_id, self.C_EXPIRE_TIME, 1)

        return vnc_port, cmd_port

    def remove_container(self, short_id, ip):
        print('REMOVING ' + short_id)
        try:
            self.cli.remove_container(short_id, force=True)
        except Exception as e:
            print(e)

        self.redis.hdel('all_containers', short_id)
        self.redis.delete('c:' + short_id)

        ip_keys = self.redis.keys(ip +':*')
        for key in ip_keys:
            self.redis.delete(key)

    def remove_all(self, check_expired=False):
        all_containers = self.redis.hgetall('all_containers')

        for short_id, ip in all_containers.iteritems():
            if check_expired:
                remove = not self.redis.get('c:' + short_id)
            else:
                remove = True

            if remove:
                self.remove_container(short_id, ip)

    def add_new_client(self):
        #client_id = base64.b64encode(os.urandom(27))
        #self.redis.rpush('q:clients', client_id)
        client_id = self.redis.incr('clients')
#.........這裏部分代碼省略.........
開發者ID:pombredanne,項目名稱:netcapsule,代碼行數:103,代碼來源:main.py

示例6: DockerController

# 需要導入模塊: from docker.client import Client [as 別名]
# 或者: from docker.client.Client import inspect_container [as 別名]

#.........這裏部分代碼省略.........

        time_key = "t:" + client_id
        self.redis.setex(time_key, self.T_EXPIRE_TIME, dur)

        throttle_samples = int(self.redis.get("throttle_samples"))
        print("INIT DUR: " + str(dur))
        self.redis.lpush("init_timings", time_key)
        self.redis.ltrim("init_timings", 0, throttle_samples - 1)

        return info

    def new_container(self, browser_id, env=None, default_host=None):
        browser = self.browser_paths.get(browser_id)

        # get default browser
        if not browser:
            browser = self.browser_paths.get(self.default_browser)

        container = self.cli.create_container(
            image=self.image_prefix + "/" + browser["id"], ports=[self.VNC_PORT, self.CMD_PORT], environment=env
        )
        short_id = None
        try:
            id_ = container.get("Id")
            short_id = id_[:12]

            res = self.cli.start(
                container=id_,
                port_bindings={self.VNC_PORT: None, self.CMD_PORT: None},
                volumes_from=["netcapsule_shared_data_1"],
                network_mode="netcapsule",
            )

            info = self.cli.inspect_container(id_)
            ip = info["NetworkSettings"]["IPAddress"]
            if not ip:
                ip = info["NetworkSettings"]["Networks"]["netcapsule"]["IPAddress"]

            self.redis.hset("all_containers", short_id, ip)
            self.redis.setex("c:" + short_id, self.C_EXPIRE_TIME, 1)

            return {
                "vnc_host": self._get_host_port(info, self.VNC_PORT, default_host),
                "cmd_host": self._get_host_port(info, self.CMD_PORT, default_host),
            }
        except Exception as e:
            if short_id:
                self.remove_container(short_id)

            traceback.print_exc(e)
            return {}

    def remove_container(self, short_id, ip=None):
        print("REMOVING " + short_id)
        try:
            self.cli.remove_container(short_id, force=True)
        except Exception as e:
            traceback.print_exc(e)

        self.redis.hdel("all_containers", short_id)
        self.redis.delete("c:" + short_id)

        if ip:
            ip_keys = self.redis.keys(ip + ":*")
            for key in ip_keys:
                self.redis.delete(key)
開發者ID:sunfun,項目名稱:netcapsule,代碼行數:70,代碼來源:main.py

示例7: DockerController

# 需要導入模塊: from docker.client import Client [as 別名]
# 或者: from docker.client.Client import inspect_container [as 別名]

#.........這裏部分代碼省略.........
        info = dc.new_container(browser, env, host)
        end = time.time()
        dur = end - start

        time_key = 't:' + client_id
        self.redis.setex(time_key, self.T_EXPIRE_TIME, dur)

        throttle_samples = int(self.redis.get('throttle_samples'))
        print('INIT DUR: ' + str(dur))
        self.redis.lpush('init_timings', time_key)
        self.redis.ltrim('init_timings', 0, throttle_samples - 1)

        return info

    def new_container(self, browser_id, env=None, default_host=None):
        browser = self.browser_paths.get(browser_id)

        # get default browser
        if not browser:
            browser = self.browser_paths.get(self.default_browser)

        container = self.cli.create_container(image=self.image_prefix + '/' + browser['id'],
                                              ports=[self.VNC_PORT, self.CMD_PORT],
                                              environment=env,
                                             )
        id_ = container.get('Id')

        res = self.cli.start(container=id_,
                             port_bindings={self.VNC_PORT: None, self.CMD_PORT: None},
                             volumes_from=['netcapsule_shared_data_1'],
                             network_mode='netcapsule',
                            )

        info = self.cli.inspect_container(id_)
        ip = info['NetworkSettings']['IPAddress']
        if not ip:
            ip = info['NetworkSettings']['Networks']['netcapsule']['IPAddress']

        short_id = id_[:12]
        self.redis.hset('all_containers', short_id, ip)
        self.redis.setex('c:' + short_id, self.C_EXPIRE_TIME, 1)

        return {'vnc_host': self._get_host_port(info, self.VNC_PORT, default_host),
                'cmd_host': self._get_host_port(info, self.CMD_PORT, default_host),
               }

    def remove_container(self, short_id, ip):
        print('REMOVING ' + short_id)
        try:
            self.cli.remove_container(short_id, force=True)
        except Exception as e:
            print(e)

        self.redis.hdel('all_containers', short_id)
        self.redis.delete('c:' + short_id)

        ip_keys = self.redis.keys(ip + ':*')
        for key in ip_keys:
            self.redis.delete(key)

    def remove_all(self, check_expired=False):
        all_containers = self.redis.hgetall('all_containers')

        for short_id, ip in all_containers.iteritems():
            if check_expired:
                remove = not self.redis.get('c:' + short_id)
開發者ID:GovanifY,項目名稱:netcapsule,代碼行數:70,代碼來源:main.py

示例8: DockerController

# 需要導入模塊: from docker.client import Client [as 別名]
# 或者: from docker.client.Client import inspect_container [as 別名]
class DockerController(object):
    def _load_config(self):
        with open('./config.yaml') as fh:
            config = yaml.load(fh)
        return config

    def __init__(self):
        config = self._load_config()

        self.REDIS_HOST = config['redis_host']
        self.PYWB_HOST = config['pywb_host']
        self.EXPIRE_TIME = config['expire_secs']
        self.REMOVE_EXP_TIME = config['remove_expired_secs']
        self.VERSION = config['api_version']

        self.VNC_PORT = config['vnc_port']
        self.CMD_PORT = config['cmd_port']

        self.image_prefix = config['image_prefix']
        self.browsers = config['browsers']

        self.redis = redis.StrictRedis(host=self.REDIS_HOST)

        if os.path.exists('/var/run/docker.sock'):
            self.cli = Client(base_url='unix://var/run/docker.sock',
                              version=self.VERSION)
        else:
            kwargs = kwargs_from_env()
            kwargs['tls'].assert_hostname = False
            kwargs['version'] = self.VERSION
            self.cli = Client(**kwargs)

    def new_container(self, browser, env=None):
        tag = self.browsers.get(browser)

        # get default browser
        if not tag:
            tag = self.browsers['']

        container = self.cli.create_container(image=self.image_prefix + '/' + tag,
                                              ports=[self.VNC_PORT, self.CMD_PORT],
                                              environment=env)
        id_ = container.get('Id')

        res = self.cli.start(container=id_,
                             port_bindings={self.VNC_PORT: None, self.CMD_PORT: None},
                             links={self.PYWB_HOST: self.PYWB_HOST,
                                    self.REDIS_HOST: self.REDIS_HOST})

        vnc_port = self.cli.port(id_, self.VNC_PORT)
        vnc_port = vnc_port[0]['HostPort']

        cmd_port = self.cli.port(id_, self.CMD_PORT)
        cmd_port = cmd_port[0]['HostPort']

        info = self.cli.inspect_container(id_)
        ip = info['NetworkSettings']['IPAddress']

        short_id = id_[:12]
        self.redis.hset('all_containers', short_id, ip)
        self.redis.setex('c:' + short_id, self.EXPIRE_TIME, 1)

        return vnc_port, cmd_port

    def remove_container(self, short_id, ip):
        print('REMOVING ' + short_id)
        try:
            self.cli.remove_container(short_id, force=True)
        except Exception as e:
            print(e)

        self.redis.hdel('all_containers', short_id)
        self.redis.delete('c:' + short_id)

        ip_keys = self.redis.keys(ip +':*')
        for key in ip_keys:
            self.redis.delete(key)

    def remove_all(self, check_expired=False):
        all_containers = self.redis.hgetall('all_containers')

        for short_id, ip in all_containers.iteritems():
            if check_expired:
                remove = not self.redis.get('c:' + short_id)
            else:
                remove = True

            if remove:
                self.remove_container(short_id, ip)
開發者ID:ibnesayeed,項目名稱:netcapsule,代碼行數:91,代碼來源:main.py


注:本文中的docker.client.Client.inspect_container方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。