本文整理汇总了Python中docker.client.Client类的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_update_headers
def test_update_headers(self):
sample_headers = {
'X-Docker-Locale': 'en-US',
}
def f(self, headers=None):
return headers
client = Client()
client._auth_configs = {}
g = update_headers(f)
assert g(client, headers=None) is None
assert g(client, headers={}) == {}
assert g(client, headers={'Content-type': 'application/json'}) == {
'Content-type': 'application/json',
}
client._auth_configs = {
'HttpHeaders': sample_headers
}
assert g(client, headers=None) == sample_headers
assert g(client, headers={}) == sample_headers
assert g(client, headers={'Content-type': 'application/json'}) == {
'Content-type': 'application/json',
'X-Docker-Locale': 'en-US',
}
示例2: download_docker_image
def download_docker_image(docker_image, target_file, cache=None):
try:
from docker.client import Client
from docker.utils import kwargs_from_env
kwargs = kwargs_from_env()
kwargs['tls'].assert_hostname = False
docker_cli = Client(**kwargs)
image = docker_cli.get_image(docker_image)
image_tar = open(target_file,'w')
image_tar.write(image.data)
image_tar.close()
except Exception as e:
if cache is not None:
cached_file = os.path.join(cache, docker_image.lower().replace('/','-').replace(':','-') + '.tgz')
if os.path.isfile(cached_file):
print 'using cached version of', docker_image
urllib.urlretrieve(cached_file, target_file)
return
print >> sys.stderr, docker_image, 'not found in cache', cache
sys.exit(1)
if isinstance(e, KeyError):
print >> sys.stderr, 'docker not configured on this machine (or environment variables are not properly set)'
else:
print >> sys.stderr, docker_image, 'not found on local machine'
print >> sys.stderr, 'you must either pull the image, or download it and use the --docker-cache option'
sys.exit(1)
示例3: docker_context
def docker_context():
"""Make a docker context"""
host = os.environ.get('DOCKER_HOST')
cert_path = os.environ.get('DOCKER_CERT_PATH')
tls_verify = os.environ.get('DOCKER_TLS_VERIFY')
options = {"timeout": 60}
if host:
options['base_url'] = (host.replace('tcp://', 'https://') if tls_verify else host)
if tls_verify and cert_path:
options['tls'] = docker.tls.TLSConfig(
verify = True
, ca_cert = os.path.join(cert_path, 'ca.pem')
, client_cert = (os.path.join(cert_path, 'cert.pem'), os.path.join(cert_path, 'key.pem'))
, ssl_version = ssl.PROTOCOL_TLSv1
, assert_hostname = False
)
client = DockerClient(**options)
try:
info = client.info()
log.info("Connected to docker daemon\tdriver=%s\tkernel=%s", info["Driver"], info["KernelVersion"])
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as error:
raise BadDockerConnection(base_url=options['base_url'], error=error)
return client
示例4: __init__
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)
示例5: run
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)})
示例6: __init__
def __init__(self):
config = self._load_config()
self.LOCAL_REDIS_HOST = "netcapsule_redis_1"
self.REDIS_HOST = os.environ.get("REDIS_HOST", self.LOCAL_REDIS_HOST)
self.PYWB_HOST = os.environ.get("PYWB_HOST", "netcapsule_pywb_1")
self.C_EXPIRE_TIME = config["init_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.MAX_CONT = config["max_containers"]
self.image_prefix = config["image_prefix"]
self.browser_list = config["browsers"]
self.browser_paths = {}
for browser in self.browser_list:
path = browser["path"]
if path in self.browser_paths:
raise Exception("Already a browser for path {0}".format(path))
self.browser_paths[path] = browser
self.default_browser = config["default_browser"]
self.redirect_paths = config["redirect_paths"]
self.randompages = []
try:
with open(config["random_page_file"]) as fh:
self.randompages = list([line.rstrip() for line in fh])
except Exception as e:
print(e)
self.redis = redis.StrictRedis(host=self.REDIS_HOST)
self.redis.setnx("next_client", "1")
self.redis.setnx("max_containers", self.MAX_CONT)
throttle_samples = config["throttle_samples"]
self.redis.setnx("throttle_samples", throttle_samples)
throttle_max_avg = config["throttle_max_avg"]
self.redis.setnx("throttle_max_avg", throttle_max_avg)
self.redis.setnx("container_expire_secs", config["full_container_expire_secs"])
self.T_EXPIRE_TIME = config["throttle_expire_secs"]
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(assert_hostname=False)
kwargs["version"] = self.VERSION
self.cli = Client(**kwargs)
示例7: download_docker_image
def download_docker_image(docker_image, target_file):
from docker.client import Client
from docker.utils import kwargs_from_env
kwargs = kwargs_from_env()
kwargs['tls'].assert_hostname = False
docker_cli = Client(**kwargs)
image = docker_cli.get_image(docker_image)
image_tar = open(target_file,'w')
image_tar.write(image.data)
image_tar.close()
示例8: __init__
def __init__(self):
config = self._load_config()
self.LOCAL_REDIS_HOST = 'netcapsule_redis_1'
self.REDIS_HOST = os.environ.get('REDIS_HOST', self.LOCAL_REDIS_HOST)
self.PYWB_HOST = os.environ.get('PYWB_HOST', 'netcapsule_pywb_1')
self.C_EXPIRE_TIME = config['init_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.MAX_CONT = config['max_containers']
self.image_prefix = config['image_prefix']
self.browser_list = config['browsers']
self.browser_paths = {}
for browser in self.browser_list:
path = browser['path']
if path in self.browser_paths:
raise Exception('Already a browser for path {0}'.format(path))
self.browser_paths[path] = browser
self.default_browser = config['default_browser']
self.redirect_paths = config['redirect_paths']
self.redis = redis.StrictRedis(host=self.REDIS_HOST)
self.redis.setnx('next_client', '1')
self.redis.setnx('max_containers', self.MAX_CONT)
throttle_samples = config['throttle_samples']
self.redis.setnx('throttle_samples', throttle_samples)
throttle_max_avg = config['throttle_max_avg']
self.redis.setnx('throttle_max_avg', throttle_max_avg)
self.redis.setnx('container_expire_secs',
config['full_container_expire_secs'])
self.T_EXPIRE_TIME = config['throttle_expire_secs']
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(assert_hostname=False)
kwargs['version'] = self.VERSION
self.cli = Client(**kwargs)
示例9: docker_context
def docker_context():
"""Make a docker context"""
base_url = None
if "DOCKER_HOST" in os.environ:
base_url = os.environ["DOCKER_HOST"]
client = DockerClient(base_url=base_url, timeout=5)
try:
info = client.info()
log.info("Connected to docker daemon\tdriver=%s\tkernel=%s", info["Driver"], info["KernelVersion"])
except requests.exceptions.ConnectionError as error:
raise BadDockerConnection(base_url=base_url, error=error)
return client
示例10: download_docker_image
def download_docker_image(docker_image, target_file):
from docker.client import Client
try: # First attempt boot2docker, because it is fail-fast
from docker.utils import kwargs_from_env
kwargs = kwargs_from_env()
kwargs['tls'].assert_hostname = False
docker_cli = Client(**kwargs)
except KeyError as e: # Assume this means we are not using boot2docker
docker_cli = Client(base_url='unix://var/run/docker.sock', tls=False)
image = docker_cli.get_image(docker_image)
image_tar = open(target_file,'w')
image_tar.write(image.data)
image_tar.close()
示例11: docker_context
def docker_context():
"""Make a docker context"""
options = kwargs_from_env(assert_hostname=False)
options["version"] = "auto"
options["timeout"] = int(os.environ.get("DOCKER_CLIENT_TIMEOUT", 180))
client = DockerClient(**options)
try:
info = client.info()
log.info("Connected to docker daemon\tdriver=%s\tkernel=%s", info["Driver"], info["KernelVersion"])
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as error:
raise BadDockerConnection(base_url=options.get('base_url'), error=error)
return client
示例12: handle
def handle(self, *args, **kwargs):
hosts = Host.objects.filter(use_for_building_images=True).order_by('?')
if hosts:
c = DockerClient(base_url=hosts[0].docker_api_endpoint)
for plugin_dict in pool.get_all_plugin_dicts():
result, log = c.build(
tag="docker-service-provisioner/%s:v%s" % (plugin_dict['service'], plugin_dict['version']),
path=urljoin(settings.DOCKER_PROVISION_URL, "dockerfile/%s/%s/" % (plugin_dict['service'], plugin_dict['version']))
)
if result:
print "Converted", plugin_dict['service'], plugin_dict['version'], 'to', result
else:
print "Failed converting", plugin_dict['service'], plugin_dict['version'], 'to', result
else:
raise Exception("No hosts available for building images!")
示例13: _init_docker
def _init_docker():
kwargs = kwargs_from_env()
if 'tls' in kwargs:
# see http://docker-py.readthedocs.org/en/latest/boot2docker/
import requests.packages.urllib3 as urllib3
urllib3.disable_warnings()
kwargs['tls'].assert_hostname = False
docker = Client(**kwargs)
try:
docker.version()
except:
raise UserMessageException("Please set up 'docker' correctly")
return docker
示例14: __init__
def __init__(self, remote, username=None, password=None, email=None):
super(DockerPyClient,self).__init__()
self.client = Client(base_url=remote, version='1.15')
self.log = logging.getLogger(__name__)
self.log.debug('password %s, remote = %s, username=%s', password, remote, username)
if username:
self.client.login(username=username, password=password, email=email)
示例15: __init__
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)