How to use the docker.errors.ImageNotFound 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 se7entyse7en / pydockenv / pydockenv / commands / environment.py View on Github external
def delete_network(env_name):
    network_name = definitions.CONTAINERS_PREFIX + env_name + '_network'
    try:
        network = Client.get_instance().networks.get(network_name)
    except docker.errors.ImageNotFound:
        click.echo(f'Network {network_name} not found, exiting...')
        raise

    for c in network.containers:
        network.disconnect(c)

    network.remove()
github zyfra / ebonite / src / ebonite / build / builder / docker_builder.py View on Github external
def _build_image(self, context_dir):
        tag = '{}:{}'.format(self.name, self.tag)
        logger.debug('Building docker image %s from %s...', tag, context_dir)
        with create_docker_client() as client:
            if not self.force_overwrite:
                try:
                    client.images.get(tag)
                    raise ValueError(f'Image {tag} already exists. Change name or set force_overwrite=True.')
                except errors.ImageNotFound:
                    pass
            else:
                try:
                    client.images.remove(tag)  # to avoid spawning dangling images
                except errors.ImageNotFound:
                    pass
            try:
                _, logs = client.images.build(path=context_dir, tag=tag)
                logger.info('Build successful')
                _print_docker_logs(logs)
            except errors.BuildError as e:
                _print_docker_logs(e.build_log)
                raise
github mushorg / tanner / tanner / utils / docker_helper.py View on Github external
async def create_container(self, container_name):
        await self.setup_host_image()
        container = await self.get_container(container_name)
        if not container:
            try:
                container = self.docker_client.containers.create(image=self.host_image,
                                                                 stdin_open=True,
                                                                 name=container_name
                                                                 )
            except (docker.errors.APIError, docker.errors.ImageNotFound) as docker_error:
                self.logger.exception('Error while creating a container %s', docker_error)
        return container
github supervisely / supervisely / agent / src / worker / task_dockerized.py View on Github external
def _docker_image_exists(self):
        try:
            _ = self._docker_api.images.get(self.docker_image_name)
        except DockerImageNotFound:
            return False
        return True
github DistributedSystemsGroup / zoe / zoe_master / backends / docker / api_client.py View on Github external
if service_instance.shm_size > 0:
            run_args['shm_size'] = service_instance.shm_size

        if get_conf().gelf_address != '':
            run_args['log_config'] = {
                "type": "gelf",
                "config": {
                    'gelf-address': get_conf().gelf_address,
                    'labels': ",".join(service_instance.labels)
                }
            }

        cont = None
        try:
            cont = self.cli.containers.run(**run_args)
        except docker.errors.ImageNotFound:
            raise ZoeException(message='Image not found')
        except docker.errors.APIError as e:
            if cont is not None:
                cont.remove(force=True)
            if e.explanation == b'no resources available to schedule container':
                raise ZoeNotEnoughResourcesException(message=str(e))
            else:
                raise ZoeException(message=str(e))
        except Exception as e:
            if cont is not None:
                cont.remove(force=True)
            raise ZoeException(str(e))

        cont = self.cli.containers.get(cont.id)
        return self._container_summary(cont)
github di-unipi-socc / DockerFinder / analysis / pyFinder / pyfinder / scanner.py View on Github external
"[{}] creating container with entrypoint ={}".format(name, entrypoint))

        try:
            container = self.client_daemon.containers.create(
                image=name,
                entrypoint=entrypoint
            )

            # start the container with sleep
            container.start()
            image.softwares = self._extract_softwares(container)
            image.distro = self._extract_distribution(container)
            container.stop(timeout=1)

            container.remove(v=True)
        except (docker.errors.ImageNotFound, docker.errors.APIError) as e:
            container.remove(v=True, force=True)
            self.logger.error(str(e))
            raise
        # # remove the contatiner
github DataBiosphere / toil / src / toil / __init__.py View on Github external
return registryName, imageName, tag


def checkDockerSchema(appliance):
    if not appliance:
        raise ImageNotFound("No docker image specified.")
    elif '://' in appliance:
        raise ImageNotFound("Docker images cannot contain a schema (such as '://'): %s"
                            "" % appliance)
    elif len(appliance) > 256:
        raise ImageNotFound("Docker image must be less than 256 chars: %s"
                            "" % appliance)


class ApplianceImageNotFound(ImageNotFound):
    """
    Compose an ApplianceImageNotFound error complaining that the given name and
    tag for TOIL_APPLIANCE_SELF specify an image manifest which could not be
    retrieved from the given URL, because it produced the given HTTP error
    code.

    :param str origAppliance: The full url of the docker image originally
                              specified by the user (or the default).
                              e.g. "quay.io/ucsc_cgl/toil:latest"
    :param str url: The URL at which the image's manifest is supposed to appear
    :param int statusCode: the failing HTTP status code returned by the URL
    """
    def __init__(self, origAppliance, url, statusCode):
        msg = ("The docker image that TOIL_APPLIANCE_SELF specifies (%s) produced "
               "a nonfunctional manifest URL (%s). The HTTP status returned was %s. "
               "The specifier is most likely unsupported or malformed.  "
github docker / compose / compose / cli / main.py View on Github external
timeout=timeout,
                    detached=detached,
                    remove_orphans=remove_orphans,
                    ignore_orphans=ignore_orphans,
                    scale_override=parse_scale_args(options['--scale']),
                    start=not no_start,
                    always_recreate_deps=always_recreate_deps,
                    reset_container_image=rebuild,
                    renew_anonymous_volumes=options.get('--renew-anon-volumes'),
                    silent=options.get('--quiet-pull'),
                    cli=native_builder,
                )

            try:
                to_attach = up(False)
            except docker.errors.ImageNotFound as e:
                log.error(
                    "The image for the service you're trying to recreate has been removed. "
                    "If you continue, volume data could be lost. Consider backing up your data "
                    "before continuing.\n".format(e.explanation)
                )
                res = yesno("Continue with the new image? [yN]", False)
                if res is None or not res:
                    raise e

                to_attach = up(True)

            if detached or no_start:
                return

            attached_containers = filter_containers_to_service_names(to_attach, service_names)
github dephell / dephell / dephell / controllers / _docker.py View on Github external
def create(self, *, pull=True) -> None:
        if 'container' in self.__dict__:
            del self.__dict__['container']
        # get image
        try:
            image = self.client.images.get(self.image_name)
        except docker.errors.ImageNotFound:
            if not pull:
                raise
            self.logger.info('image not found, pulling...', extra=dict(
                repository=self.repository,
                tag=self.tag,
            ))
            image = self.client.images.pull(repository=self.repository, tag=self.tag)
            self.logger.info('pulled')

        # create network
        self.client.networks.create(self.network_name, check_duplicate=True)

        # mount the project
        # (but do not mount if it's obviously not a project)
        mounts = []
        if self.path not in (Path.home(), Path('/')):
github kyocum / disdat / disdat / run.py View on Github external
_logger.info("VOLUMES: {}".format(volumes))
        else:
            pipeline_image_name = common.make_project_image_name(pipeline_setup_file)

        _logger.debug('Running image {} with arguments {}'.format(pipeline_image_name, arglist))

        stdout = client.containers.run(pipeline_image_name, arglist, detach=False,
                                       environment=environment, init=True, stderr=True, volumes=volumes)
        stdout = six.ensure_str(stdout)
        if cli: print(stdout)
        return stdout
    except docker.errors.ContainerError as ce:
        _logger.error("Internal error running image {}".format(pipeline_image_name))
        _logger.error("Error: {}".format(six.ensure_str(ce.stderr)))
        return six.ensure_str(ce)
    except docker.errors.ImageNotFound:
        _logger.error("Unable to find the docker image {}".format(pipeline_image_name))
        return None