Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
The fixture should yield a setup helper, and afterwards tear down the
helper.
"""
fixture_gen = docker_helper()
helper = next(fixture_gen)
assert isinstance(helper, DockerHelper)
# Test we can create a container; if we can the helper must be set
# up
container = helper.containers.create('test', IMG)
# Test things are torn down
with pytest.raises(StopIteration):
next(fixture_gen)
with pytest.raises(docker.errors.NotFound):
container.reload()
def delete(self):
if self._container:
try:
self._container.stop()
except docker.errors.NotFound:
pass # container has already stopped
def test_get_image_exists_not(self):
"""Negative test for get image"""
with self.assertRaises(errors.NotFound):
response = self.client.images.get("image_does_not_exists")
collections.deque(response)
def _raise_for_status(self, response, explanation=None):
"""Raises stored :class:`APIError`, if one occurred."""
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 404:
raise errors.NotFound(e, response, explanation=explanation)
raise errors.APIError(e, response, explanation=explanation)
b64cmd = b64encode(cmd)
challenge_dir = path.join(BASE_WORKING_DIR, challenge['slug'])
docker_cmd = "/ro_volume/runcmd -slug {slug} {b64cmd}".format(
slug=challenge['slug'],
b64cmd=b64cmd)
with timeout(seconds=DOCKER_TIMEOUT):
try:
LOG.warn("Running `{}` in container".format(docker_cmd))
output = client.containers.run('registry.gitlab.com/jarv/cmdchallenge', docker_cmd, working_dir=challenge_dir, **DOCKER_OPTS)
except SSLError as e:
LOG.exception("SSL validation error connecting to {}".format(docker_base_url))
raise DockerValidationError("SSL Error")
except ContainerError as e:
LOG.exception("Container error")
raise DockerValidationError("There was a problem executing the command, return code: {}".format(e.exit_status))
except NotFound as e:
LOG.exception("NotFound error")
raise DockerValidationError(e.explanation)
except CommandTimeoutError as e:
LOG.exception("CommandTimeout error")
raise DockerValidationError("Command timed out")
except APIError as e:
LOG.exception("Docker API error")
raise DockerValidationError("Docker API error")
except ConnectionError as e:
LOG.exception("Docker ConnectionError")
raise DockerValidationError("Docker connection error")
try:
output_json = json.loads(output)
except ValueError as e:
LOG.exception("JSON decode error")
raise DockerValidationError("Command failure")
def remove(self):
if self.running():
self.stop()
try:
self.client.remove_container(self.container, v=True, force=True)
except docker.errors.NotFound:
# the reaper may already have kicked in to delete the stoped container
pass
except docker.errors.APIError:
# removal already in progress
pass
self.container = None
def _run_pull(self):
from docker import errors
try:
self._disable_button('Pulling...')
self.status.value = self.LOADER
self.msg.value = 'Starting download.'
try:
response = self._client.pull(self.image, stream=True, decode=True)
self._watch_pull_logs(response)
except errors.NotFound as exc:
self._err = True
self.msg.value = 'ERROR: %s' % exc.explanation
except Exception as e:
self._err = True
self.msg = str(e)
raise
finally:
self._set_status_value()
self._reactivate_button()
if not self._err:
self.msg.value = 'Pull successful.'
client = docker_client()
# Try looking at the container mapping cache first
container_id = CONTAINER_MAPPING.get(ip)
if container_id:
log.info('Container id for IP {0} in cache'.format(ip))
try:
with PrintingBlockTimer('Container inspect'):
container = client.inspect_container(container_id)
# Only return a cached container if it is running.
if container['State']['Running']:
return container
else:
log.error('Container id {0} is no longer running'.format(ip))
if ip in CONTAINER_MAPPING:
del CONTAINER_MAPPING[ip]
except docker.errors.NotFound:
msg = 'Container id {0} no longer mapped to {1}'
log.error(msg.format(container_id, ip))
if ip in CONTAINER_MAPPING:
del CONTAINER_MAPPING[ip]
_fqdn = None
with PrintingBlockTimer('Reverse DNS'):
if app.config['ROLE_REVERSE_LOOKUP']:
try:
_fqdn = socket.gethostbyaddr(ip)[0]
except socket.error as e:
log.error('gethostbyaddr failed: {0}'.format(e.args))
pass
with PrintingBlockTimer('Container fetch'):
_ids = [c['Id'] for c in client.containers()]
def terminate_container_resources(self):
"""Terminate any artifacts created on behalf of the container's lifetime."""
# Remove the container
result = True # Since we run containers with remove=True, we'll be optimistic
container = self._get_container()
if container:
try:
container.remove(force=True) # Container still exists, attempt forced removal
except Exception as err:
self.log.debug("Container termination for container: {} raised exception: {}".
format(container.name, err))
if isinstance(err, NotFound):
pass # okay if its not found
else:
result = False
self.log.warning("Error occurred removing container: {}".format(err))
if result:
self.log.debug("{}.terminate_container_resources, container {}, kernel ID: {} has been terminated.".
format(self.__class__.__name__, self.container_name, self.kernel_id))
self.container_name = None
result = None # maintain jupyter contract
else:
self.log.warning("{}.terminate_container_resources, container {}, kernel ID: {} has not been terminated.".
format(self.__class__.__name__, self.container_name, self.kernel_id))
return result
def stop_docker():
import docker
print('Stopping TradingBot Docker container...')
client = docker.from_env()
try:
container = client.containers.get(DOCKER_CONTAINER_NAME)
container.kill()
except docker.errors.NotFound as err:
print('Docker container {} not found!'.format(DOCKER_CONTAINER_NAME))
except docker.errors.APIError as err:
print('Unable to kill {}: {}'.format(DOCKER_CONTAINER_NAME, err))