本文整理汇总了Python中docker.client.Client.containers方法的典型用法代码示例。如果您正苦于以下问题:Python Client.containers方法的具体用法?Python Client.containers怎么用?Python Client.containers使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类docker.client.Client
的用法示例。
在下文中一共展示了Client.containers方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from docker.client import Client [as 别名]
# 或者: from docker.client.Client import containers [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)})
示例2: __init__
# 需要导入模块: from docker.client import Client [as 别名]
# 或者: from docker.client.Client import containers [as 别名]
class Docker:
dockerconf = KOOPLEX.get('docker', {})
def __init__(self):
base_url = self.dockerconf.get('base_url', '')
self.client = Client(base_url = base_url)
logger.debug("Client init")
self.check = None
def list_imagenames(self):
logger.debug("Listing image names")
pattern_imagenamefilter = KOOPLEX.get('docker', {}).get('pattern_imagename_filter', r'^image-%(\w+):\w$')
for image in self.client.images(all = True):
if image['RepoTags'] is None:
continue
for tag in image['RepoTags']:
if re.match(pattern_imagenamefilter, tag):
_, imagename, _ = re.split(pattern_imagenamefilter, tag)
logger.debug("Found image: %s" % imagename)
yield imagename
def list_volumenames(self):
logger.debug("Listing volume names")
volumes = self.client.volumes()
for volume in volumes['Volumes']:
yield volume['Name']
def get_container(self, container):
for item in self.client.containers(all = True):
# docker API prepends '/' in front of container names
if '/' + container.name in item['Names']:
logger.debug("Get container %s" % container.name)
return item
return None
def create_container(self, container):
volumes = [] # the list of mount points in the container
binds = {} # a mapping dictionary of the container mounts
for volume in container.volumes:
logger.debug("container %s, volume %s" % (container, volume))
mp = volume.mountpoint
volumes.append(mp)
binds[volume.name] = { 'bind': mp, 'mode': volume.mode(container.user) }
logger.debug("container %s binds %s" % (container, binds))
host_config = self.client.create_host_config(
binds = binds,
privileged = True,
mem_limit = '2g',
memswap_limit = '170m',
mem_swappiness = 0,
# oom_kill_disable = True,
cpu_shares = 2,
)
network = self.dockerconf.get('network', 'host')
networking_config = { 'EndpointsConfig': { network: {} } }
ports = self.dockerconf.get('container_ports', [ 8000, 9000 ])
imagename = container.image.imagename if container.image else self.dockerconf.get('default_image', 'basic')
args = {
'name': container.name,
'image': imagename,
'detach': True,
'hostname': container.name,
'host_config': host_config,
'networking_config': networking_config,
'environment': container.environment,
'volumes': volumes,
'ports': ports,
}
self.client.create_container(**args)
logger.debug("Container created")
self.managemount(container) #FIXME: check if not called twice
return self.get_container(container)
def _writefile(self, container_name, path, filename, content):
import tarfile
import time
from io import BytesIO
tarstream = BytesIO()
tar = tarfile.TarFile(fileobj = tarstream, mode = 'w')
tarinfo = tarfile.TarInfo(name = filename)
tarinfo.size = len(content)
tarinfo.mtime = time.time()
tar.addfile(tarinfo, BytesIO(content))
tar.close()
tarstream.seek(0)
try:
status = self.client.put_archive(container = container_name, path = path, data = tarstream)
logger.info("container %s put_archive %s/%s returns %s" % (container_name, path, filename, status))
except Exception as e:
logger.error("container %s put_archive %s/%s fails -- %s" % (container_name, path, filename, e))
def managemount(self, container):
from kooplex.lib.fs_dirname import Dirname
path, filename = os.path.split(self.dockerconf.get('mountconf', '/tmp/mount.conf'))
mapper = []
for v in container.volumes:
mapper.extend([ "%s:%s" % (v.volumetype, d) for d in Dirname.containervolume_listfolders(container, v) ])
#NOTE: mounter uses read to process the mapper configuration, thus we need to make sure '\n' terminates the config mapper file
#.........这里部分代码省略.........
示例3: DockerPyClient
# 需要导入模块: from docker.client import Client [as 别名]
# 或者: from docker.client.Client import containers [as 别名]
class DockerPyClient(DockerClient):
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)
def docker_images(self, filters=None):
return self.client.images(filters=filters)
def __id(self, ioc):
if ioc and 'Id' in ioc:
return ioc['Id']
return None
def docker_containers(self):
return [{
'Id': cont['Id'],
'Tag': cont['Image'],
'Image': self.__id(self.image(cont['Image'])),
'Names': cont['Names'],
'Ports': cont['Ports'],
'Created': cont['Created'],
'Command': cont['Command'],
'Status': cont['Status'],
'Running': cont['Status'].startswith('Up ') or cont['Status'].startswith('Restarting ')
} for cont in self.client.containers(all=True)]
def docker_pull(self, image):
(repository, tag) = self.tag(image)
existing = self.image(image)
for line in self.client.pull(repository=repository, stream=True, insecure_registry=True):
parsed = json.loads(line)
self.log.debug('parsed %s' % parsed)
if 'error' in parsed:
raise Exception(parsed['error'])
# Check if image updated
self.flush_images()
newer = self.image(image)
if not existing or (newer['Id'] != existing['Id']):
return True
return False
def docker_run(self, entry):
volumes = ['/var/log/ext']
kwargs = {
'image': entry['image'],
'volumes': volumes,
'detach': True,
'environment': {
'DOCKER_IMAGE': entry['image']
}
}
if 'name' in entry:
kwargs['name'] = entry['name']
if 'env' in entry:
kwargs['environment'].update(entry['env'])
if 'cpu' in entry:
kwargs['cpu_shares'] = entry['cpu']
if 'memory' in entry:
kwargs['mem_limit'] = entry['memory']
if 'entrypoint' in entry:
kwargs['entrypoint'] = entry['entrypoint']
if 'command' in entry:
kwargs['command'] = entry['command']
if 'volumes' in entry:
volumes.extend([vol['containerPath'] for vol in entry['volumes'] if 'containerPath' in vol])
volsFrom = [vol['from'] for vol in entry['volumes'] if 'from' in vol]
if len(volsFrom):
kwargs['volumes_from'] = volsFrom
if 'portMappings' in entry:
kwargs['ports'] = [p['containerPort'] for p in entry['portMappings']]
container = self.client.create_container(**kwargs)
self.docker_start(container['Id'], entry)
return container['Id']
def docker_start(self, container, entry=None):
logsBound = False
binds = {}
#.........这里部分代码省略.........