Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_sample(tmpdir, docker_client):
path = str(tmpdir.join('shipwright-sample'))
source = pkg_resources.resource_filename(
__name__,
'examples/shipwright-sample',
)
repo = create_repo(path, source)
tag = repo.head.ref.commit.hexsha[:12]
client_cfg = docker_utils.kwargs_from_env()
cli = docker_client
try:
shipw_cli.run(
path=path,
client_cfg=client_cfg,
arguments=get_defaults(),
environ={},
)
service1, shared, base = (
cli.images(name='shipwright/service1') +
cli.images(name='shipwright/shared') +
cli.images(name='shipwright/base')
)
def test_exact(tmpdir, docker_client):
path = str(tmpdir.join('shipwright-sample'))
source = pkg_resources.resource_filename(
__name__,
'examples/shipwright-sample',
)
create_repo(path, source)
client_cfg = docker_utils.kwargs_from_env()
cli = docker_client
args = get_defaults()
args['--exact'] = [
'shipwright/base',
]
try:
shipw_cli.run(
path=path,
client_cfg=client_cfg,
arguments=args,
environ={},
)
def setUp(self):
self.logger = logging.getLogger(type(self).__name__)
self.client = docker.Client(**docker.utils.kwargs_from_env(assert_hostname=False))
options = mock.Mock()
options.debug = False
options.config = ['images.test-*.grace_time=1s']
options.config_path = None
options.image_gracetime = '1d'
self.options = options
self.containers = set()
self.images = set()
def push_image(self):
"""Push docker image to registry"""
client = docker.APIClient(version='auto', **kwargs_from_env())
# Build a progress setup for each layer, and only emit per-layer
# info every 1.5s
layers = {}
last_emit_time = time.time()
for line in client.push(self.output_image_spec, stream=True):
progress = json.loads(line.decode('utf-8'))
if 'error' in progress:
self.log.error(progress['error'], extra=dict(phase='failed'))
sys.exit(1)
if 'id' not in progress:
continue
if 'progressDetail' in progress and progress['progressDetail']:
layers[progress['id']] = progress['progressDetail']
else:
layers[progress['id']] = progress['status']
if time.time() - last_emit_time > 1.5:
LOG.info('Waiting for daemon threads exit. Push Ctrl + c again to'
' force exit')
for t in threads:
if t.is_alive():
LOG.debug('Waiting thread %s to exit', t.name)
# NOTE(Jeffrey4l): Python Bug: When join without timeout,
# KeyboardInterrupt is never sent.
t.join(0xffff)
LOG.debug('Thread %s exits', t.name)
except KeyboardInterrupt:
LOG.warning('Force exits')
class DockerTask(task.Task):
docker_kwargs = docker.utils.kwargs_from_env()
def __init__(self):
super(DockerTask, self).__init__()
self._dc = None
@property
def dc(self):
if self._dc is not None:
return self._dc
docker_kwargs = self.docker_kwargs.copy()
self._dc = docker.APIClient(version='auto', **docker_kwargs)
return self._dc
class Image(object):
def __init__(self, name, canonical_name, path, parent_name='',
def docker_client():
"""Create a Docker client instance or return an existing one."""
global _DOCKER_CLIENT # pylint: disable = global-statement
if _DOCKER_CLIENT:
return _DOCKER_CLIENT
else:
# assert_hostname=False is required when using boot2docker, it's taken as a hint from Fig: https://github.com/docker/fig/blob/master/compose/cli/docker_client.py#L29
_DOCKER_CLIENT = Client(**kwargs_from_env(assert_hostname=False))
return _DOCKER_CLIENT
def client():
return docker.Client(**docker.utils.kwargs_from_env(assert_hostname=False))
config = Config(options.config, options.config_path)
def output_from_cmd(cmd, challenge, docker_version=None, docker_base_url=None, tls_settings=None):
if tls_settings:
tls_config = docker.tls.TLSConfig(**tls_settings)
else:
tls_config = None
if environ.get('DOCKER_MACHINE_NAME') is None:
client = docker.DockerClient(version=docker_version, base_url=docker_base_url, tls=tls_config)
else:
client = docker.DockerClient(**kwargs_from_env(assert_hostname=False))
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))
def docker_client(environment, version=None, tls_config=None, host=None,
tls_version=None):
"""
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
if 'DOCKER_CLIENT_TIMEOUT' in environment:
log.warn("The DOCKER_CLIENT_TIMEOUT environment variable is deprecated. "
"Please use COMPOSE_HTTP_TIMEOUT instead.")
try:
kwargs = kwargs_from_env(environment=environment, ssl_version=tls_version)
except TLSParameterError:
raise UserError(
"TLS configuration is invalid - make sure your DOCKER_TLS_VERIFY "
"and DOCKER_CERT_PATH are set correctly.\n"
"You might need to run `eval \"$(docker-machine env default)\"`")
if host:
kwargs['base_url'] = host
if tls_config:
kwargs['tls'] = tls_config
if version:
kwargs['version'] = version
timeout = environment.get('COMPOSE_HTTP_TIMEOUT')
if timeout:
"""Docker functions to get info about containers"""
from docker import APIClient, client as DockerClient, utils, errors
from requests.exceptions import ConnectionError
cts_info = dict()
running_cts = 0
params = utils.kwargs_from_env()
base_url = None if 'base_url' not in params else params['base_url']
tls = None if 'tls' not in params else params['tls']
apiclient = APIClient(base_url=base_url, tls=tls)
client = DockerClient.from_env()
def block_ct_ports(service: str, ports: list, project_name: str) -> tuple:
try:
ct = client.containers.get(get_ct_item(service, 'id'))
except Exception:
return (False, '{} is not started, no port to block'.format(service))
iptables = ct.exec_run(['which', 'iptables']).decode().strip()
if iptables == '':
return (True, "Can't block ports on {}, is iptables installed ?".format(service))