本文整理汇总了Python中docker.errors.DockerException方法的典型用法代码示例。如果您正苦于以下问题:Python errors.DockerException方法的具体用法?Python errors.DockerException怎么用?Python errors.DockerException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类docker.errors
的用法示例。
在下文中一共展示了errors.DockerException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: retry_call
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def retry_call(call, name, logger, retries, *args, **kwargs):
""" call a function call(), retries times, with *args and **kwargs, and with
exponential backoff on failure. if it fails after after retries time, raise
the last exception """
exc = None
for i in range(retries):
try:
logger.info("calling %r, attempt %d/%d", name, i+1, retries)
return call(*args, **kwargs)
except (APIError, DockerException, exceptions.DockerResultError) as exc:
logger.exception("error calling %r, retrying", call)
sleep(2 ** i)
logger.error("failed calling %r after %d tries, giving up", call,
retries)
raise exc
示例2: working_directory
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def working_directory():
docker_client = utils.get_docker_client()
volume_name = 'epicbox-' + str(uuid.uuid4())
log = logger.bind(volume=volume_name)
log.info("Creating new docker volume for working directory")
try:
volume = docker_client.volumes.create(volume_name)
except (RequestException, DockerException) as e:
log.exception("Failed to create a docker volume")
raise exceptions.DockerError(str(e))
log.info("New docker volume is created")
try:
yield _WorkingDirectory(volume=volume_name, node=None)
finally: # Ensure that volume cleanup takes place
log.info("Removing the docker volume")
try:
volume.remove()
except NotFound:
log.warning("Failed to remove the docker volume, it doesn't exist")
except (RequestException, DockerException):
log.exception("Failed to remove the docker volume")
else:
log.info("Docker volume removed")
示例3: inspect_exited_container_state
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def inspect_exited_container_state(container):
try:
container.reload()
except (RequestException, DockerException) as e:
logger.exception("Failed to load the container from the Docker engine",
container=container)
raise exceptions.DockerError(str(e))
started_at = dateutil.parser.parse(container.attrs['State']['StartedAt'])
finished_at = dateutil.parser.parse(container.attrs['State']['FinishedAt'])
duration = finished_at - started_at
duration_seconds = duration.total_seconds()
if duration_seconds < 0:
duration_seconds = -1
return {
'exit_code': container.attrs['State']['ExitCode'],
'duration': duration_seconds,
'oom_killed': container.attrs['State'].get('OOMKilled', False),
}
示例4: running_filter
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def running_filter(self):
"""Return running container objects list, except ouroboros itself"""
running_containers = []
try:
for container in self.client.containers.list(filters={'status': 'running'}):
if self.config.self_update:
running_containers.append(container)
else:
try:
if 'ouroboros' not in container.image.tags[0]:
if container.attrs['HostConfig']['AutoRemove']:
self.logger.debug("Skipping %s due to --rm property.", container.name)
else:
running_containers.append(container)
except IndexError:
self.logger.error("%s has no tags.. you should clean it up! Ignoring.", container.id)
continue
except DockerException:
self.logger.critical("Can't connect to Docker API at %s", self.config.docker_socket)
exit(1)
return running_containers
示例5: pytest_report_header
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [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
示例6: run_docker_container
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def run_docker_container(image: str, timeout: int = 300, command: Optional[str] = None, reraise: bool = False,
mount: Optional[Tuple[str, str]] = None, label: str = 'Docker', include_stderr: bool = True) -> str:
container = None
try:
kwargs = {'mounts': [Mount(*mount, read_only=False, type='bind')]} if mount else {}
client = docker.from_env()
container = client.containers.run(image, command=command, network_disabled=True, detach=True, **kwargs)
container.wait(timeout=timeout)
return container.logs(stderr=include_stderr).decode()
except ReadTimeout:
logging.warning('[{}]: timeout while processing'.format(label))
if reraise:
raise
except (DockerException, IOError):
logging.warning('[{}]: encountered process error while processing'.format(label))
if reraise:
raise
finally:
if container:
with suppress(DockerException):
container.stop()
container.remove()
示例7: get_docker_output
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def get_docker_output(arch_suffix: str, file_path: str, root_path: Path) -> dict:
'''
:return: in the case of no error, the output will have the form
{
'parameter 1': {'stdout': <b64_str>, 'stderr': <b64_str>, 'return_code': <int>},
'parameter 2': {...},
'...',
'strace': {'stdout': <b64_str>, 'stderr': <b64_str>, 'return_code': <int>},
}
in case of an error, there will be an entry 'error' instead of the entries stdout/stderr/return_code
'''
command = '{arch_suffix} {target}'.format(arch_suffix=arch_suffix, target=file_path)
try:
return loads(run_docker_container(
DOCKER_IMAGE, TIMEOUT_IN_SECONDS, command, reraise=True, mount=(CONTAINER_TARGET_PATH, str(root_path)),
label='qemu_exec'
))
except ReadTimeout:
return {'error': 'timeout'}
except (DockerException, IOError):
return {'error': 'process error'}
except JSONDecodeError:
return {'error': 'could not decode result'}
示例8: process_object
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def process_object(self, file_object: FileObject):
with TemporaryDirectory(prefix=self.NAME, dir=get_temp_dir_path(self.config)) as tmp_dir:
file_path = Path(tmp_dir) / file_object.file_name
file_path.write_bytes(file_object.binary)
try:
result = run_docker_container(
DOCKER_IMAGE, TIMEOUT_IN_SECONDS, CONTAINER_TARGET_PATH, reraise=True,
mount=(CONTAINER_TARGET_PATH, str(file_path)), label=self.NAME, include_stderr=False
)
file_object.processed_analysis[self.NAME] = loads(result)
except ReadTimeout:
file_object.processed_analysis[self.NAME]['warning'] = 'Analysis timed out. It might not be complete.'
except (DockerException, IOError):
file_object.processed_analysis[self.NAME]['warning'] = 'Analysis issues. It might not be complete.'
except JSONDecodeError:
logging.error('Could not decode JSON output: {}'.format(repr(result)))
return file_object
示例9: docker_context
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def docker_context():
"""Make a docker context"""
try:
client = docker.from_env(
version="auto",
timeout=int(os.environ.get("DOCKER_CLIENT_TIMEOUT", 180)),
assert_hostname=False,
)
info = client.info()
log.info(
"Connected to docker daemon\tdriver=%s\tkernel=%s",
info["Driver"],
info["KernelVersion"],
)
except (DockerException, APIError) as error:
raise BadDockerConnection(error=error)
return client
示例10: test_retry_success
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def test_retry_success(self):
def fn(counter):
if counter["c"] == 2:
return "yay"
counter["c"] += 1
raise DockerException("fail")
logger = MagicMock()
counter = {"c": 0}
res = retry_call(fn, 'test_retry_success', logger, 3, counter)
self.assertEqual(res, "yay")
self.assertEqual(counter["c"], 2)
示例11: test_retry_failure
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def test_retry_failure(self):
def fn(counter):
counter["c"] += 1
raise DockerException("fail")
logger = MagicMock()
counter = {"c": 0}
self.assertRaises(DockerException, retry_call, fn, 'test_retry_failure', logger, 3, counter)
self.assertEqual(counter["c"], 3)
示例12: _start_container
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def _start_container(self):
"""Start proxy."""
proxy_conf_dir = get_dir('static/proxy')
try:
self.docker_client.images.pull('traefik:{}'.format(self.version))
self.docker_client.containers.run(
'traefik:{}'.format(self.version), remove=True, detach=True,
hostname=self.ct_name, name=self.ct_name,
volumes=[
'/var/run/docker.sock:/var/run/docker.sock',
'{}/traefik.toml:/etc/traefik/traefik.toml'.format(proxy_conf_dir),
'{}/ssl:/etc/traefik/ssl'.format(proxy_conf_dir)],
ports={80: self.ports['http'], 8080: 8080, 443: self.ports['https']})
except DockerException as error:
raise RuntimeError("Can't start proxy ...({})".format(error))
示例13: parse_bytes
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def parse_bytes(n):
try:
return sdk_parse_bytes(n)
except DockerException:
return None
示例14: destroy
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def destroy(sandbox):
"""Destroy a sandbox container.
Kill a running sandbox before removal. Remove the volumes auto-created
and associated with the sandbox container.
:param Sandbox sandbox: A sandbox to destroy.
"""
try:
sandbox.container.remove(v=True, force=True)
except (RequestException, DockerException):
logger.exception("Failed to destroy the sandbox container",
sandbox=sandbox)
else:
logger.info("Sandbox container destroyed", sandbox=sandbox)
示例15: _write_files
# 需要导入模块: from docker import errors [as 别名]
# 或者: from docker.errors import DockerException [as 别名]
def _write_files(container, files):
"""Write files to the working directory in the given container."""
# Retry on 'No such container' since it may happen when the function
# is called immediately after the container is created.
# Retry on 500 Server Error when untar cannot allocate memory.
docker_client = utils.get_docker_client(retry_status_forcelist=(404, 500))
log = logger.bind(files=utils.filter_filenames(files), container=container)
log.info("Writing files to the working directory in container")
mtime = int(time.time())
files_written = []
tarball_fileobj = io.BytesIO()
with tarfile.open(fileobj=tarball_fileobj, mode='w') as tarball:
for file in files:
if not file.get('name') or not isinstance(file['name'], str):
continue
content = file.get('content', b'')
file_info = tarfile.TarInfo(name=file['name'])
file_info.size = len(content)
file_info.mtime = mtime
tarball.addfile(file_info, fileobj=io.BytesIO(content))
files_written.append(file['name'])
try:
docker_client.api.put_archive(container.id, config.DOCKER_WORKDIR,
tarball_fileobj.getvalue())
except (RequestException, DockerException) as e:
log.exception("Failed to extract an archive of files to the working "
"directory in container")
raise exceptions.DockerError(str(e))
log.info("Successfully written files to the working directory",
files_written=files_written)