How to use the docker.APIClient 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 jupyter / repo2docker / tests / unit / test_cache_from.py View on Github external
def test_cache_from_base(tmpdir):
    cache_from = ["image-1:latest"]
    fake_log_value = {"stream": "fake"}
    fake_client = MagicMock(spec=docker.APIClient)
    fake_client.build.return_value = iter([fake_log_value])
    extra_build_kwargs = {"somekey": "somevalue"}

    # Test base image build pack
    tmpdir.chdir()
    for line in BaseImage().build(
        fake_client, "image-2", 100, {}, cache_from, extra_build_kwargs
    ):
        assert line == fake_log_value
    called_args, called_kwargs = fake_client.build.call_args
    assert "cache_from" in called_kwargs
    assert called_kwargs["cache_from"] == cache_from
github codalab / codalab-worksheets / worker / codalabworker / docker_client.py View on Github external
def __init__(self):
        docker_host = os.environ.get('DOCKER_HOST') or 'unix://var/run/docker.sock'
        cert_path = os.environ.get('DOCKER_CERT_PATH') or None
        if cert_path:
            tls_config = docker.tls.TLSConfig(
                client_cert=(
                    os.path.join(cert_path, 'cert.pem'),
                    os.path.join(cert_path, 'key.pem'),
                ),
                ca_cert=os.path.join(cert_path, 'ca.pem'),
                assert_hostname=False,
            )
            self._client = docker.APIClient(base_url=docker_host, version='auto', tls=tls_config)
        else:
            self._client = docker.APIClient(base_url=docker_host, version='auto')

        # Test to make sure that a connection can be established.
        try:
            self.test()
        except DockerException:
            print >>sys.stderr, """
On Linux, a valid Docker installation should create a Unix socket at
/var/run/docker.sock.

On Mac, DOCKER_HOST and optionally DOCKER_CERT_PATH should be defined. You need
to run the worker from the Docker shell.
"""
            raise

        # Check if nvidia-docker-plugin is available
        try:
github 6si / shipwright / shipwright / _lib / cli.py View on Github external
if config['namespace'] is None:
        exit(
            'Please specify your docker hub account in\n'
            'the .shipwright.json config file,\n '
            'the command line or set SW_NAMESPACE.\n'
            'Run shipwright --help for more information.',
        )
    assert_hostname = config.get('assert_hostname')
    if arguments['--x-assert-hostname']:
        assert_hostname = not arguments['--x-assert-hostname']

    tls_config = client_cfg.get('tls')
    if tls_config is not None:
        tls_config.assert_hostname = assert_hostname

    client = docker.APIClient(version='1.18', **client_cfg)
    commands = ['build', 'push', 'images']
    command_names = [c for c in commands if arguments.get(c)]
    command_name = command_names[0] if command_names else 'build'

    build_targets = {
        'exact': arguments['--exact'],
        'dependents': arguments['--dependents'],
        'exclude': arguments['--exclude'],
        'upto': arguments['--upto'],
    }

    no_build = False
    if command_name == 'push':
        no_build = arguments['--no-build']
    dump_file = None
    if arguments['--dump-file']:
github jupyter / repo2docker / repo2docker / app.py View on Github external
def build(self):
        """
        Build docker image
        """
        # Check if r2d can connect to docker daemon
        if not self.dry_run:
            try:
                docker_client = docker.APIClient(version="auto", **kwargs_from_env())
            except DockerException as e:
                self.log.exception(e)
                raise
        # If the source to be executed is a directory, continue using the
        # directory. In the case of a local directory, it is used as both the
        # source and target. Reusing a local directory seems better than
        # making a copy of it as it might contain large files that would be
        # expensive to copy.
        if os.path.isdir(self.repo):
            checkout_path = self.repo
        else:
            if self.git_workdir is None:
                checkout_path = tempfile.mkdtemp(prefix="repo2docker")
            else:
                checkout_path = self.git_workdir
github usmannasir / cyberpanel / dockerManager / container.py View on Github external
def listContainers(self, request=None, userID=None, data=None):
        try:
            client = docker.from_env()
            dockerAPI = docker.APIClient()

            currentACL = ACLManager.loadedACL(userID)
            containers = ACLManager.findAllContainers(currentACL, userID)

            allContainers = client.containers.list()
            containersList = []
            showUnlistedContainer = True

            # TODO: Add condition to show unlisted Containers only if user has admin level access

            unlistedContainers = []
            for container in allContainers:
                if container.name not in containers:
                    unlistedContainers.append(container)

            if not unlistedContainers:
github ros-tooling / cross_compile / ros_cross_compile / docker_client.py View on Github external
dockerfile_dir: Optional[Path] = None,
        buildargs: Optional[Dict[str, str]] = None,
    ) -> None:
        """
        Build a Docker image from a Dockerfile.

        :param dockerfile_dir: Absolute path to directory where Dockerfile can be found,
            defaults to the 'docker' directory in this package.
        :param dockerfile_name: The name of the Dockerfile to build.
        :param tag: What tag to give the created image.
        :param buildargs: Optional dictionary of str->str to set arguments for the build.
        :return None
        :raises docker.errors.BuildError: on build error
        """
        # Use low-level API to expose logs for image building
        docker_api = docker.APIClient(base_url='unix://var/run/docker.sock')
        log_generator = docker_api.build(
            path=str(dockerfile_dir) if dockerfile_dir else self._default_docker_dir,
            dockerfile=dockerfile_name,
            tag=tag,
            buildargs=buildargs,
            quiet=False,
            nocache=self._disable_cache,
            decode=True,
        )
        self._process_build_log(log_generator)
github openstack / kolla-ansible / ansible / library / kolla_toolbox.py View on Github external
def get_docker_client():
    try:
        return docker.Client
    except AttributeError:
        return docker.APIClient
github instacart / ahab / ahab / __init__.py View on Github external
def listen(self):
        client = docker.APIClient(base_url=self.url, version=docker_client_version)
        for event in client.events(decode=True):
            for k in ['time', 'Time']:
                if k in event:
                    event[k] = datetime.fromtimestamp(event[k])
            log.debug('Event: %s', event)
            data = {}
            i = get_id(event)
            if i is not None:
                try:
                    if 'from' in event or 'From' in event:
                        data = client.inspect_container(i)
                    else:
                        data = client.inspect_image(i)
                    self.data[i] = data
                except docker.errors.NotFound:
                    data = self.data[i]
github openstack / zun / zun / websocket / websocketproxy.py View on Github external
def _new_exec_client(self, container, token, uuid, exec_id):
        exec_instance = None
        for e in container.exec_instances:
            if token == e.token and exec_id == e.exec_id:
                exec_instance = e

        if not exec_instance:
            raise exception.InvalidWebsocketToken(token)

        access_url = '%s?token=%s&uuid=%s' % (CONF.websocket_proxy.base_url,
                                              token, uuid)

        self._verify_origin(access_url)

        client = docker.APIClient(base_url=exec_instance.url)
        tsock = client.exec_start(exec_id, socket=True, tty=True)
        if hasattr(tsock, "_sock"):
            # NOTE(hongbin): dockerpy returns different socket class depending
            # on python version and base_url (see _get_raw_response_socket) so
            # we need to handle it in here.
            tsock = tsock._sock

        try:
            self.do_proxy(tsock)
        finally:
            if tsock:
                tsock.shutdown(socket.SHUT_RDWR)
                tsock.close()
                self.vmsg(_("%s: Closed target") % exec_instance.url)
github google / android-emulator-container-scripts / emu / docker_device.py View on Github external
def get_api_client(self):
        try:
            api_client = docker.APIClient()
            logging.info(api_client.version())
            return api_client
        except:
            logging.exception("Failed to create default client, trying domain socket.", exc_info=True)

        api_client = docker.APIClient(base_url="unix://var/run/docker.sock")
        logging.info(api_client.version())
        return api_client