Check if `local_image` is present locally. If it is not, pull parent images and build.
    This includes pulling starcraft binary.

    :raises docker.errors.ImageNotFound
    :raises docker.errors.APIError
779556
def ensure_local_image(
        local_image: str,
        parent_image: str = SC_PARENT_IMAGE,
        java_image: str = SC_JAVA_IMAGE,
        starcraft_base_dir: str = SCBW_BASE_DIR,
        starcraft_binary_link: str = SC_BINARY_LINK,
) -> None:
    
    logger.info(f"checking if there is local image {local_image}")
    docker_images = docker_client.images.list(local_image)
    if len(docker_images) and docker_images[0].short_id is not None:
        logger.info(f"image {local_image} found locally.")
        return

    logger.info("image not found locally, creating...")
    pkg_docker_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), "local_docker")
    base_dir = os.path.join(starcraft_base_dir, "docker")
    logger.info(f"copying files from {pkg_docker_dir} to {base_dir}.")
    distutils.dir_util.copy_tree(pkg_docker_dir, base_dir)

    starcraft_zip_file = f"{base_dir}/starcraft.zip"
    if not os.path.exists(starcraft_zip_file):
        logger.info(f"downloading starcraft.zip to {starcraft_zip_file}")
        download_file(starcraft_binary_link, starcraft_zip_file)

    logger.info(f"pulling image {parent_image}, this may take a while...")
    pulled_image = docker_client.images.pull(parent_image)
    pulled_image.tag(java_image)

    logger.info(f"building local image {local_image}, this may take a while...")
    docker_client.images.build(path=base_dir, dockerfile="game.dockerfile", tag=local_image)
    logger.info(f"successfully built image {local_image}")
410565
def fetch_image(client, name):
    
    try:
        image = client.images.get(name)
    except docker.errors.ImageNotFound:
        name, tag = _parse_image_tag(name)
        tag = 'latest' if tag is None else tag

        log.info("Pulling tag '{}' for image '{}'...".format(tag, name))
        image = client.images.pull(name, tag=tag)

    log.debug("Found image '{}' for tag '{}'".format(image.id, name))
    return image
942918
def is_local(self):
        """"""
        from ambry.orm.exc import NotFoundError
        try:
            if self.local_datafile.exists:
                return True
        except NotFoundError:
            pass

        return False
21618
def fetch_local
      if File.file?(@local)
        # Check for bad user input in the local config.yml file.
        local = YAML.load_file(@local)
        raise FormatError unless local.is_a?(::Hash)

        local
      else
        {}
      end
    end
152115
def run(self):
        
        build_json = get_build_json()
        current_platform = platform.processor() or 'x86_64'
        self.manifest_list_cache = {}
        organization = get_registries_organization(self.workflow)

        for nonce, parent in enumerate(sorted(self.workflow.builder.parent_images.keys(),
                                              key=str)):
            if base_image_is_custom(parent.to_str()):
                continue

            image = parent
            is_base_image = False
            # original_base_image is an ImageName, so compare parent as an ImageName also
            if image == self.workflow.builder.original_base_image:
                is_base_image = True
                image = self._resolve_base_image(build_json)

            image = self._ensure_image_registry(image)

            if organization:
                image.enclose(organization)
                parent.enclose(organization)

            if self.check_platforms:
                # run only at orchestrator
                self._validate_platforms_in_image(image)
                self._collect_image_digests(image)

            # try to stay with digests
            image_with_digest = self._get_image_with_digest(image, current_platform)
            if image_with_digest is None:
                self.log.warning("Cannot resolve platform '%s' specific digest for image '%s'",
                                 current_platform, image)
            else:
                self.log.info("Replacing image '%s' with '%s'", image, image_with_digest)
                image = image_with_digest

            if self.check_platforms:
                new_arch_image = self._get_image_for_different_arch(image, current_platform)
                if new_arch_image:
                    image = new_arch_image

            if self.inspect_only:
                new_image = image
            else:
                new_image = self._pull_and_tag_image(image, build_json, str(nonce))
            self.workflow.builder.recreate_parent_images()
            self.workflow.builder.parent_images[parent] = new_image

            if is_base_image:
                if organization:
                    # we want to be sure we have original_base_image enclosed as well
                    self.workflow.builder.original_base_image.enclose(organization)
                self.workflow.builder.set_base_image(
                    str(new_image), insecure=self.parent_registry_insecure,
                    dockercfg_path=self.parent_registry_dockercfg_path
                )
        self.workflow.builder.parents_pulled = not self.inspect_only
        self.workflow.builder.base_image_insecure = self.parent_registry_insecure
357214
def build_main_image_cmd(self, srcdir, force):
        
        check_permissions()

        basetag = self.conf.basetag
        basedir = self.conf.basedir
        maintag = self.conf.maintag

        if not self.image_exists(tag=basetag):
            if not force:
                exit("Base image with tag {0} does not exist".format(basetag))
            else:
                echo("FORCE given. Forcefully building the base image.")
                self.build_base_image_cmd(force)

        if self.image_exists(tag=maintag):
            self.remove_image(tag=maintag)

        build_command = "/build/make-install-gluster.sh"
        container = self.create_container(image=basetag, command=build_command,
                                          volumes=["/build", "/src"])

        self.start(container, binds={basedir: "/build", srcdir: "/src"})
        echo('Building main image')
        while self.inspect_container(container)["State"]["Running"]:
            time.sleep(5)

        if not self.inspect_container(container)["State"]["ExitCode"] == 0:
            echo("Build failed")
            echo("Dumping logs")
            echo(self.logs(container))
            exit()

        # The docker remote api expects the repository and tag to be seperate
        # items for commit
        repo = maintag.split(':')[0]
        tag = maintag.split(':')[1]
        image = self.commit(container['Id'], repository=repo, tag=tag)
        echo("Built main image {0} (Id: {1})".format(maintag, image['Id']))
486364
def local_build(native, *args, **kwargs):
    
    method = 'native_build' if native else 'build'
    logging.debug(_('build type: %s'), method)
    return getattr(Builder(), method)(*args, **kwargs)
435508
def update_image(self, container_name, image_name):
        
        code, container = self.get_container(container_name)
        if code != httplib.OK:
            self.logger.error("Container %s is not exists. error code %s, error message %s", container_name, code,
                              container)
            return False

        _, old_image_name, _ = utils.parse_image_name(container.image)
        repository, name, version = utils.parse_image_name(image_name)
        if not repository or repository.lower() != DOCKER_NEG:
            self.logger.error("You image %s must have a 'docker.neg/' prefix string", image_name)
            return False

        if not repo.image_exists(name, tag=version):
            self.logger.error("You image %s must be location in docker.neg repository.", image_name)
            return False

        if old_image_name.lower() != name.lower():
            self.logger.error("You image %s must be same with container's Image.", image_name, container.image)
            return False

        code, result = self.update(container_name, tag=version)
        if code != httplib.OK:
            self.logger.error("Update container %s with image failure, code %s, result %s", container_name, code,
                              result)
            return False

        return True
1087804
def _has_local_storage(self, pod=None):
        

        for vol in pod.volumes:
            if vol.emptyDir is not None:
                return True
        return False
103192
def collect_local(self, path):
        
        for f in os.listdir(path):
            lpath = os.path.join(path, f)
            if not os.path.isfile(lpath):
                continue
            Artifact(self, lpath)
943251
def _format_local_file(self):
        

        if self.type != 'file':
            return

        if not self.entity:
            return

        if not is_win:
            return

        if self._file_exists():
            return

        self.args.local_file = self._to_unc_path(self.entity)
311830
def import_image(self, image=None, tag='latest', **kwargs):
        
        self.push_log("Fetching image '{0}' from registry.".format(image))
        return super(DockerFabricClient, self).import_image(image=image, tag=tag, **kwargs)
16099
def has_image(self, name: str) -> bool:
        
        path = "docker/images/{}".format(name)
        r = self.__api.head(path)
        if r.status_code == 204:
            return True
        elif r.status_code == 404:
            return False
        self.__api.handle_erroneous_response(r)
58632
def _populate_local(self):
        
        archives = glob(os.path.join(self.path, '*.zip'))
        for archive in archives:
            try:
                version = self._read_zip(archive)
                self.versions[version.vtuple] = self.meta_class(self, version, filepath=archive)
            except BadZipfile as e:
                self.log.warn('Unreadable zip archive in versions directory (%s): %s', e.message, archive)

        if self.dev_path:
            dev_archives = glob(os.path.join(self.dev_path, '*.zip'))
            dev_versions = []
            for dev_archive in dev_archives:
                try:
                    dev_versions.append((self._read_zip(dev_archive), dev_archive))
                except BadZipfile as e:
                    self.log.warn('Unreadable zip archive in versions directory (%s): %s', e.message, dev_archive)

            if not dev_versions:
                self.log.debug('No development releases found')
                return

            dev_version = sorted(dev_versions, key=lambda v: v[0].vtuple).pop()
            self.dev_version = self.meta_class(self, dev_version[0], filepath=dev_version[1])
459555
def image_needs_pushing(image):
    
    d = docker_client()
    try:
        d.images.get_registry_data(image)
    except docker.errors.APIError:
        # image not found on registry, needs pushing
        return True
    else:
        return False
1373831
function pullImage(docker, image, options) {
  return new Promise(function(accept, reject) {
    docker.pull(image).then(function(stream) {
      var pullStatusStream = new PullStatusStream();
      stream.pipe(pullStatusStream);

      pullStatusStream.on('data', function(value) {
        debug('pull image', value.toString());
      });

      pullStatusStream.once('error', reject);
      pullStatusStream.once('end', accept);
    });
  });
}
1118757
def _check_img_lib():
    """"""
    # Import imageio or PIL
    imageio = PIL = None
    try:
        import imageio
    except ImportError:
        try:
            import PIL.Image
        except ImportError:
            pass
    return imageio, PIL