Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def exec_command(cls, command, project, service, timeout_seconds=60):
"""Executes the command in the project and service container running under
docker-compose.
Throws ContainerUnavailableError if the retry limit is reached.
Args:
command: The command to be executed in the container
project: Name of the project the container is hosting
service: Name of the service that the container is hosting
timeout_seconds: Retry time limit to wait for containers to start
Default in seconds: 60
"""
docker_client = Client(version='auto')
container_id = cls._get_container_id(project, service, docker_client, timeout_seconds)
exec_id = docker_client.exec_create(container_id, command)['Id']
docker_client.exec_start(exec_id)
def addif(self, ctn, ip_addr=''):
_name = ctn.next_if_name()
self.ctns.append(ctn)
ip = ''
if not ip_addr == '':
ip = '--ip {0}'.format(ip_addr)
if self.subnet.version == 6:
ip = '--ip6 {0}'.format(ip_addr)
local("docker network connect {0} {1} {2}".format(ip, self.name, ctn.docker_name()))
i = [x for x in list(Client(timeout=60, version='auto').inspect_network(self.id)['Containers'].values()) if x['Name'] == ctn.docker_name()][0]
if self.subnet.version == 4:
eth = 'eth{0}'.format(len(ctn.ip_addrs))
addr = i['IPv4Address']
ctn.ip_addrs.append((eth, addr, self.name))
else:
eth = 'eth{0}'.format(len(ctn.ip6_addrs))
addr = i['IPv6Address']
ctn.ip6_addrs.append((eth, addr, self.name))
def __init__(self, service_name):
self.name = service_name
self.dico = model.Dico(self.name)
self.tag = self.dico.tag
if self.dico.privileged:
self.privileged = self.dico.privileged
else:
self.privileged = None
if self.dico.network_mode:
self.network_mode = self.dico.network_mode
else:
self.network_mode = 'bridge'
self.dockerapi = docker.Client(base_url=CONF.docker_host,
version=CONF.docker_version,
timeout=60)
info = self.get_info()
self.id = info.get('id')
self.ip = info.get('ip')
self.hostname = info.get('hostname')
self.started = info.get('started')
self.created = info.get('created')
raise RuntimeError('docker-py required for docker operations')
# First try to auto detect docker parameters from environment
try:
args = docker.utils.kwargs_from_env(assert_hostname=False)
args.update(dict(version=version))
cli = docker.Client(**args)
cli.info()
return cli
except requests.exceptions.ConnectionError:
pass
for sock in docker_socks:
if os.path.exists(sock):
try:
cli = docker.Client(base_url='unix://{}'.format(sock), version=version)
cli.info()
return cli
except requests.exceptions.ConnectionError:
pass
raise RuntimeError('Could not locate a usable docker socket')
def _ensure_containers_up(project, service):
docker_client = Client(version='auto')
service_container = docker_client.containers(
filters={
'label': ["com.docker.compose.project={}".format(project),
"com.docker.compose.service={}".format(service)]
}
)[0]
container_id = service_container['Id']
timeout_in_seconds = 5
timed_out = time.time() + timeout_in_seconds
while time.time() < timed_out:
inspect_info = docker_client.inspect_container(container_id)
container_status = inspect_info['State']['Status']
if container_status == 'running':
return container_id
time.sleep(0.5)
def command_line_run(argv):
format = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.INFO, format=format)
image_name = first_parser(argv)
logger.info("starting image {}".format(image_name))
config = docker.utils.kwargs_from_env()
docker_client = docker.Client(**config)
raw_kliko_data = extract_params(docker_client, image_name)
kliko_data = validate_kliko(yaml.safe_load(raw_kliko_data))
parameters, input_path, output_path, work_path = second_parser(argv, kliko_data)
paths = {
'input': input_path,
'output': output_path,
'work': work_path,
}
kliko_runner(kliko_data=kliko_data, parameters=parameters,
docker_client=docker_client,
image_name=image_name, paths=paths)
import sh
import docker
import textwrap
import netaddr
import docker.errors
import re
from pycalico.ipam import IPAMClient
from netaddr.core import AddrFormatError
DOCKER_VERSION = "1.16"
ORCHESTRATOR_ID = "docker"
hostname = socket.gethostname()
client = IPAMClient()
docker_client = docker.Client(version=DOCKER_VERSION,
base_url=os.getenv("DOCKER_HOST",
"unix://var/run/docker.sock"))
try:
sysctl = sh.Command._create("sysctl")
except sh.CommandNotFound as e:
print "Missing command: %s" % e.message
def enforce_root():
"""
Check if the current process is running as the root user.
:return: Nothing. sys.exit if not running as root.
"""
if os.geteuid() != 0:
print >> sys.stderr, "This command must be run as root."
- docker.url: URL to the docker service
- docker.version: API version to use
'''
kwargs = {}
get = __salt__['config.get']
for k, p in (('base_url', 'docker.url'),
('version', 'docker.version')):
param = get(p, NOTSET)
if param is not NOTSET:
kwargs[k] = param
if timeout is not None:
# make sure we override default timeout of docker-py
# only if defined by user.
kwargs['timeout'] = timeout
client = docker.Client(**kwargs)
# force 1..5 API for registry login
if not version:
if client._version == '1.4':
client._version = '1.5'
if getattr(client, '_cfg', None) is None:
client._cfg = {
'Configs': {},
'rootPath': '/dev/null'
}
client._cfg.update(_merge_auth_bits())
return client
def setup(self):
docker_opts = self._get_config()
# Assign sane defaults.
if docker_opts['version'] is None:
docker_opts['version'] = '1.13'
if docker_opts['url'] is None:
docker_opts['url'] = 'unix://var/run/docker.sock'
self._version = docker_opts['version']
self._url = docker_opts['url']
self._timeout = 10
if docker_opts['timeout'] is not None:
self._timeout = docker_opts['timeout']
self._ps_opts = docker_opts['ps_options']
self._client = docker.Client(base_url=self._url,
version=self._version,
timeout=self._timeout)
self._running_containers = self._get_active_containers()
self._poll_interval = docker_opts.get('poll_interval', self._poll_interval)
def check_docker_image(service, tag):
"""Checks whether the given image for :service: with :tag: exists.
:raises: ValueError if more than one docker image with :tag: found.
:returns: True if there is exactly one matching image found.
"""
docker_client = docker.Client(timeout=60)
image_name = build_docker_image_name(service)
docker_tag = build_docker_tag(service, tag)
images = docker_client.images(name=image_name)
result = [image for image in images if docker_tag in image['RepoTags']]
if len(result) > 1:
raise ValueError('More than one docker image found with tag %s\n%s' % docker_tag, result)
return len(result) == 1