How to use the docker.from_env function in docker

To help you get started, we’ve selected a few docker examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github status-im / status-react / test / desktop_sikuli / main.py View on Github external
def main(**kwargs):

    if not os.path.exists(kwargs['test_results_path']):
        os.makedirs(kwargs['test_results_path'])
    if kwargs['linux_app_url']:
        linux_app_url = kwargs['linux_app_url']
    else:
        linux_app_url = re.findall('https\S*AppImage', requests.get('https://status.im/nightly/').text)[0]
    app_version = ([i for i in [i for i in linux_app_url.split('/') if '.AppImage' in i]])[0]
    urlretrieve(linux_app_url, 'nightly.AppImage')
    client = docker.from_env()
    client.images.build(tag='status_desktop', path='.')
    pytest.main(['--collect-only', '-m %s' % kwargs['mark']])
    from tests import test_data
    if kwargs['testrail_report']:
        testrail_report = TestrailReportDesktop(kwargs['test_results_path'])
        testrail_report.add_run(app_version if app_version else '%s' % datetime.now().strftime("%Y-%m-%d %H:%M"))
    for test in test_data.tests_to_run:
        print(test)
        try:
            container = client.containers.run("status_desktop",
                                              detach=True, tty=True, ports={'5900/tcp': 5900},
                                              volumes={kwargs['test_results_path']: {'bind': TEST_REPORT_DIR_CONTAINER,
                                                                                     'mode': 'rw'}})
            outcome = container.exec_run(['/jython-2.7.1/bin/jython', '-m', 'pytest', '/home/tests/' + test],
                                         stdout=True, stderr=False, stdin=True)
        except Exception:
github confluentinc / cp-docker-images / tests / steps / steps.py View on Github external
def step_impl(context, image_name, basedir):
    client = docker.from_env(assert_hostname=False)
    full_image_path = os.path.join(IMAGE_DIR, basedir)
    output = client.build(full_image_path, rm=True, tag=image_name)
    response = ["     %s" % (line,) for line in output]
    print("Building image %s from %s" % (full_image_path, basedir))
    print(response)
    return True
github donovosoft / paas-utils / build.py View on Github external
def build_docker(self, user, passw):
    	client = docker.from_env()
    	dockerfile = self.app_name+'/'
    	tag = 'donovosoft/'+self.app_name
    	image = client.images.build(path=dockerfile, stream=False)
    	image.tag(tag, self.app_version)
    	client.login(username=user, password=passw)
    	client.images.push('docker.io/'+tag, self.app_version, stream=False)
    	print "Build OK"
github BciPy / BciPy / bcipy / oclm_language_model / language_model.py View on Github external
between the host (local machine) and its server
        (the docker machine)
        Establishing the connection and running the server
        are done in a single operartion
        Input:
          host (str) - host machine ip address
          port (str) - the port used in docker
          logfile (str) - a valid filename to function as a logger
        """

        # assert strings
        assert type(host) == str, "%r is not a string type" % host
        assert type(port) == str, "%r is not a string type" % port
        # assert docker is on
        try:
            client = docker.from_env()
        except BaseException:
            raise DockerDownError  # docker ps for instance

        self.host = host
        self.port = port
        logging.basicConfig(filename=logfile, level=logging.INFO)

        try:
            # remove existing containers
            self.__rm_cons__(client)
        except:
            pass

        # create a new contaienr from image
        self.container = client.containers.run(
            image='oclmimage',
github tox-dev / tox-docker / assert_containers_and_volumes_unchanged.py View on Github external
import os
import sys

import docker


client = docker.from_env(version="auto")
envdir = os.environ["TOX_ENV_DIR"]

container_ids = set([
    container.attrs["Id"].strip()
    for container in client.containers.list()
])
volume_ids = set([
    volume.attrs["Name"].strip()
    for volume in client.volumes.list()
])

with open(envdir + "/containers.list", "r") as fp:
    old_container_ids = set([l.strip() for l in fp if l.strip()])
with open(envdir + "/volumes.list", "r") as fp:
    old_volume_ids = set([l.strip() for l in fp if l.strip()])
github ansible / molecule / molecule / provisioners.py View on Github external
def __init__(self, molecule):
        super(DockerProvisioner, self).__init__(molecule)
        self._docker = docker.from_env(assert_hostname=False)
        self._containers = self.m._config.config['docker']['containers']
        self._provider = self._get_provider()
        self._platform = self._get_platform()
        self.status()

        self.image_tag = 'molecule_local/{}:{}'
github bn2302 / rl_torcs / src / a3c.py View on Github external
for worker in workers:
                t = threading.Thread(
                    target=(
                        lambda: worker.work(
                            self.max_episode_length, self.gamma, sess, coord,
                            saver)))
                t.start()
                sleep(0.5)
                worker_threads.append(t)
            coord.join(worker_threads)


if __name__ == "__main__":
    import docker

    docker_client = docker.from_env()

    a3c = A3C(docker_client)
    a3c.train(1)
github rackerlabs / fleece / fleece / cli / build / build.py View on Github external
def _build(service_name, python_version, src_dir, requirements_path,
           dependencies, rebuild, exclude, dist_dir, inject_build_info):
    print(f'Building {service_name} with {python_version}...')

    try:
        docker_api = docker.from_env(version='auto')
    except:  # noqa
        raise RuntimeError("Docker not found.")

    image, _logs = docker_api.images.build(
        path=build_dir, tag=service_name,
        buildargs={'python_version': python_version,
                   'deps': ' '.join(dependencies)})

    with open(requirements_path, 'rb') as fp:
        dependencies_sha1 = hashlib.sha1(fp.read()).hexdigest()  # nosec

    # Set up volumes
    src_name = f'{service_name}-src'
    req_name = f'{service_name}-requirements'
    dist_name = f'{service_name}-dist'
    create_volume(src_name)
github FNNDSC / pman / pman / pman.py View on Github external
def service_exists(str_serviceName):
            """
            Returns a bool:
                - True:      does exist
                - False:     does not exist
            """
            b_exists        = False
            client          = docker.from_env()
            try:
                service     = client.services.get(str_serviceName)
                b_exists    = True
            except:
                b_exists    = False
            return b_exists
github AnnieYingQian / CollaborativeOnlineJudgeSystem / week3 / executor / executor_utils.py View on Github external
import docker
import os
import shutil
import uuid

from docker.errors import APIError
from docker.errors import ContainerError
from docker.errors import ImageNotFound

# get current directory
CURRENT_DIR = os.path.dirname(os.path.relpath(__file__))
IMAGE_NAME = 'annie91/cs503_1801' # use the image name you created

client = docker.from_env()

# store the code in tmp folder
TEMP_BUILD_DIR = "%s/tmp/" % CURRENT_DIR
# latest is the latest version of docker image
CONTAINER_NAME = "%s:latest" % IMAGE_NAME

SOURCE_FILE_NAMES = {
    "java": "Example.java",
    "python": "example.py"
}

BINARY_NAMES = {
    "java": "Example",
    "python": "example.py"
}