// DownloadImage download the image, duh. It expects to actually
// receive the file, instead of being asked to use the cached version.
489426
func (o *httpOps) DownloadImage(u *url.URL) (readSeekCloser, *cacheData, error) {
	ensureLogger(o.Debug)
	image, cd, err := o.DownloadImageWithETag(u, "")
	if err != nil {
		return nil, nil, err
	}
	if cd.UseCached {
		return nil, nil, fmt.Errorf("asked to use cached image even if not asked for that")
	}
	return image, cd, nil
}
1264567
func (d *downloader) DownloadFile(url string) (int64, string, error) {
	c := http.Client{
		CheckRedirect: func(r *http.Request, via []*http.Request) error {
			r.URL.Opaque = r.URL.Path

			//some redirect return '/' as url
			if strings.Trim(r.URL.Opaque, "/") != "" {
				url = r.URL.Opaque
			}

			return nil
		},
	}

	r, err := c.Get(url)

	if err != nil {
		return 0, "", err
	}
	defer r.Body.Close()

	if r.StatusCode == 200 {
		d.filename = getFilenameFromHeader(r.Header.Get("Content-Disposition"))

		if d.filename == "" {
			d.filename = getFilenameFromURL(url)
		}

		f, err := os.Create(filepath.Join(d.saveDir, d.filename))
		if err != nil {
			return 0, "", err
		}
		defer f.Close()

		size, err := io.Copy(f, r.Body)
		if err != nil {
			return 0, "", err
		}

		d.downloaded = true
		return size, d.filename, nil

	}
	return 0, "", fmt.Errorf("Error downloading file from %s", url)
}
312994
func (c *Calcium) CacheImage(ctx context.Context, podname, nodename string, images []string, step int) (chan *types.CacheImageMessage, error) {
	ch := make(chan *types.CacheImageMessage)

	var err error
	nodes := []*types.Node{}
	if nodename != "" {
		n, err := c.GetNode(ctx, podname, nodename)
		if err != nil {
			return ch, err
		}
		nodes = append(nodes, n)
	} else {
		nodes, err = c.store.GetNodesByPod(ctx, podname)
		if err != nil {
			return ch, err
		}
	}

	if len(nodes) == 0 {
		return nil, types.ErrPodNoNodes
	}

	go func() {
		defer close(ch)
		wg := sync.WaitGroup{}
		defer wg.Wait()
		for i, node := range nodes {
			wg.Add(1)
			go func(node *types.Node) {
				defer wg.Done()
				for _, image := range images {
					m := &types.CacheImageMessage{
						Image:    image,
						Success:  true,
						Nodename: node.Name,
						Message:  "",
					}
					if err := pullImage(ctx, node, image); err != nil {
						m.Success = false
						m.Message = err.Error()
					}
					ch <- m
				}
			}(node)
			if (i+1)%step == 0 {
				log.Info("[CacheImage] Wait for puller cleaner done")
				wg.Wait()
			}
		}
	}()

	return ch, nil
}
901917
func (at *DownloadableAsset) Download(out io.Writer) (int64, error) {
	return DownloadAsset(at, out)
}
331938
func (f *Facade) GetRegistryImage(ctx datastore.Context, image string) (*registry.Image, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.GetRegistryImage"))
	rImage, err := f.registryStore.Get(ctx, image)
	if err != nil {
		return nil, err
	}
	return rImage, nil
}
908013
func (s *Server) CopyRemoteImage(
	sourced SourcedImage, aliases []string, callback environs.StatusCallbackFunc,
) error {
	logger.Debugf("Copying image from remote server")

	newAliases := make([]api.ImageAlias, len(aliases))
	for i, a := range aliases {
		newAliases[i] = api.ImageAlias{Name: a}
	}

	req := &lxd.ImageCopyArgs{Aliases: newAliases}
	op, err := s.CopyImage(sourced.LXDServer, *sourced.Image, req)
	if err != nil {
		return errors.Trace(err)
	}

	// Report progress via callback if supplied.
	if callback != nil {
		progress := func(op api.Operation) {
			if op.Metadata == nil {
				return
			}
			for _, key := range []string{"fs_progress", "download_progress"} {
				if value, ok := op.Metadata[key]; ok {
					callback(status.Provisioning, fmt.Sprintf("Retrieving image: %s", value.(string)), nil)
					return
				}
			}
		}
		_, err = op.AddHandler(progress)
		if err != nil {
			return errors.Trace(err)
		}
	}

	if err := op.Wait(); err != nil {
		return errors.Trace(err)
	}
	opInfo, err := op.GetTarget()
	if err != nil {
		return errors.Trace(err)
	}
	if opInfo.StatusCode != api.Success {
		return fmt.Errorf("image copy failed: %s", opInfo.Err)
	}
	return nil
}
493515
func (c *Conn) DeleteImage(image *Image) error {
	return c.do("smugmug.images.delete", nil, "ImageID", itoa64(image.ID))
}
1297743
func (dfs *DistributedFilesystem) pullImage(image string) (*dockerclient.Image, error) {
	// Find (or download) the image
	img, err := dfs.docker.FindImage(image)
	if docker.IsImageNotFound(err) {
		glog.Infof("Image %s not found locally, pulling", image)
		if err := dfs.docker.PullImage(image); err != nil {
			glog.Errorf("Could not pull image %s: %s", image, err)
			return nil, err
		} else if img, err = dfs.docker.FindImage(image); err != nil {
			glog.Errorf("Could not find image %s: %s", image, err)
			return nil, err
		}
	} else if err != nil {
		glog.Errorf("Could not find image %s: %s", image, err)
		return nil, err
	}
	return img, nil
}
169368
func (c *CloudAPI) GetImage(imageID string) (*cloudapi.Image, error) {
	if err := c.ProcessFunctionHook(c, imageID); err != nil {
		return nil, err
	}

	for _, image := range c.images {
		if image.Id == imageID {
			return &image, nil
		}
	}

	return nil, fmt.Errorf("Image %s not found", imageID)
}
853199
func (dh *Client) TagImage(imageId, repository, tag string) (e error) {
	if repository == "" {
		return fmt.Errorf("empty repository given")
	}
	url := dh.Address + "/images/" + imageId + "/tag?repo=" + repository

	if tag != "" {
		url += "&tag=" + tag
	}
	rsp, e := dh.post(url)
	if e != nil {
		return e
	}
	return rsp.Body.Close()
}
1333188
func (o *httpOps) DownloadImageWithETag(u *url.URL, etag string) (readSeekCloser, *cacheData, error) {
	var aciFile *removeOnClose // closed on error
	var errClose error         // error signaling to close aciFile

	ensureLogger(o.Debug)
	aciFile, err := getTmpROC(o.S, u.String())
	if err != nil {
		return nil, nil, err
	}

	defer func() {
		if errClose != nil {
			aciFile.Close()
		}
	}()

	session := o.getSession(u, aciFile.File, "ACI", etag)
	dl := o.getDownloader(session)
	errClose = dl.Download(u, aciFile.File)
	if errClose != nil {
		return nil, nil, errwrap.Wrap(errors.New("error downloading ACI"), errClose)
	}

	if session.Cd.UseCached {
		aciFile.Close()
		return NopReadSeekCloser(nil), session.Cd, nil
	}

	return aciFile, session.Cd, nil
}
611406
func copyImage(img *v1alpha.Image) *v1alpha.Image {
	return &v1alpha.Image{
		BaseFormat:      img.BaseFormat,
		Id:              img.Id,
		Name:            img.Name,
		Version:         img.Version,
		ImportTimestamp: img.ImportTimestamp,
		Manifest:        img.Manifest,
		Size:            img.Size,
		Annotations:     img.Annotations,
		Labels:          img.Labels,
	}
}
794197
func DownloadAssetAsync(asset Downloadable, out io.Writer, c AsyncDownloadChannel) {
	go func() {
		results := &AsyncDownloadResult{Asset: asset, Writer: out}
		size, err := DownloadAsset(asset, out)
		if err != nil {
			results.Error = err
		} else {
			results.Size = size
		}
		c <- results
	}()
}
1348824
func (f *FakeDockerClient) PullImage(image string, auth dockertypes.AuthConfig, opts dockertypes.ImagePullOptions) error {
	f.Lock()
	defer f.Unlock()
	f.appendCalled(CalledDetail{name: "pull"})
	err := f.popError("pull")
	if err == nil {
		if !f.isAuthorizedForImage(image, auth) {
			return ImageNotFoundError{ID: image}
		}

		authJson, _ := json.Marshal(auth)
		inspect := createImageInspectFromRef(image)
		f.ImageInspects[image] = inspect
		f.appendPulled(fmt.Sprintf("%s using %s", image, string(authJson)))
		f.Images = append(f.Images, *createImageFromImageInspect(*inspect))
		f.ImagesPulled = append(f.ImagesPulled, image)
	}
	return err
}
676263
func waitCacheImages(g *errgroup.Group) {
	if !viper.GetBool(cacheImages) {
		return
	}
	console.OutStyle("waiting", "Waiting for image downloads to complete ...")
	if err := g.Wait(); err != nil {
		glog.Errorln("Error caching images: ", err)
	}
}
309131
func (client *Client) DownloadRichMenuImage(richMenuID string) *DownloadRichMenuImageCall {
	return &DownloadRichMenuImageCall{
		c:          client,
		richMenuID: richMenuID,
	}
}
1329868
func NewImageAsset(url *url.URL, id, alt, title string) *Image {
	return &Image{
		DownloadableAsset: DownloadableAsset{
			Asset: Asset{
				URL:  url,
				ID:   id,
				Type: ImageAsset,
			},
		},
		Alt:   alt,
		Title: title,
	}
}