// Returns the most recent AMI out of a slice of images.
481830
func mostRecentAmi(images []*ec2.Image) *ec2.Image {
	sortedImages := images
	sort.Sort(imageSort(sortedImages))
	return sortedImages[len(sortedImages)-1]
}
1176419
func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io.ReadCloser, error) {
	var (
		statusCode = 0
		res        *http.Response
		err        error
		imageURL   = fmt.Sprintf("%simages/%s/layer", registry, imgID)
	)

	req, err := http.NewRequest("GET", imageURL, nil)
	if err != nil {
		return nil, fmt.Errorf("Error while getting from the server: %v", err)
	}

	res, err = r.client.Do(req)
	if err != nil {
		logrus.Debugf("Error contacting registry %s: %v", registry, err)
		// the only case err != nil && res != nil is https://golang.org/src/net/http/client.go#L515
		if res != nil {
			if res.Body != nil {
				res.Body.Close()
			}
			statusCode = res.StatusCode
		}
		return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
			statusCode, imgID)
	}

	if res.StatusCode != 200 {
		res.Body.Close()
		return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)",
			res.StatusCode, imgID)
	}

	if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 {
		logrus.Debug("server supports resume")
		return resumable.NewRequestReaderWithInitialResponse(r.client, req, 5, imgSize, res), nil
	}
	logrus.Debug("server doesn't support resume")
	return res.Body, nil
}
951708
func (r *RemoteImageService) ImageStatus(image *runtimeapi.ImageSpec) (*runtimeapi.Image, error) {
	ctx, cancel := getContextWithTimeout(r.timeout)
	defer cancel()

	resp, err := r.imageClient.ImageStatus(ctx, &runtimeapi.ImageStatusRequest{
		Image: image,
	})
	if err != nil {
		klog.Errorf("ImageStatus %q from image service failed: %v", image.Image, err)
		return nil, err
	}

	if resp.Image != nil {
		if resp.Image.Id == "" || resp.Image.Size_ == 0 {
			errorMessage := fmt.Sprintf("Id or size of image %q is not set", image.Image)
			klog.Errorf("ImageStatus failed: %s", errorMessage)
			return nil, errors.New(errorMessage)
		}
	}

	return resp.Image, nil
}
105473
func (api *ImagesAPI) Get(imageID string) (image *Image, err error) {
	res, err := api.client.restClient.Get(api.client.Endpoint+imageUrl+"/"+imageID, api.client.options.TokenOptions)
	if err != nil {
		return
	}
	defer res.Body.Close()
	res, err = getError(res)
	if err != nil {
		return
	}
	var result Image
	err = json.NewDecoder(res.Body).Decode(&result)
	return &result, err
}
231612
func (cli *Client) ImageList(ctx context.Context, options types.ImageListOptions) ([]types.ImageSummary, error) {
	var images []types.ImageSummary
	query := url.Values{}

	optionFilters := options.Filters
	referenceFilters := optionFilters.Get("reference")
	if versions.LessThan(cli.version, "1.25") && len(referenceFilters) > 0 {
		query.Set("filter", referenceFilters[0])
		for _, filterValue := range referenceFilters {
			optionFilters.Del("reference", filterValue)
		}
	}
	if optionFilters.Len() > 0 {
		filterJSON, err := filters.ToParamWithVersion(cli.version, optionFilters)
		if err != nil {
			return images, err
		}
		query.Set("filters", filterJSON)
	}
	if options.All {
		query.Set("all", "1")
	}

	serverResp, err := cli.get(ctx, "/images/json", query, nil)
	defer ensureReaderClosed(serverResp)
	if err != nil {
		return images, err
	}

	err = json.NewDecoder(serverResp.body).Decode(&images)
	return images, err
}
637622
func (s *storeImpl) GetImages(ctx datastore.Context) ([]Image, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("ImageRegistryStore.GetImages"))
	query := search.Query().Search("_exists_:Library")
	search := search.Search("controlplane").Type(kind).Size("50000").Query(query)
	q := datastore.NewQuery(ctx)
	results, err := q.Execute(search)
	if err != nil {
		return nil, err
	}
	return convert(results)
}
1153088
func (api *IconAPI) GetImage(id int64, size string) (*sacloud.Image, error) {

	res := &sacloud.Response{}
	err := api.read(id, map[string]string{"Size": size}, res)
	if err != nil {
		return nil, err
	}
	return res.Image, nil
}
498842
func (cli *Client) ImageHistory(ctx context.Context, imageID string) ([]image.HistoryResponseItem, error) {
	var history []image.HistoryResponseItem
	serverResp, err := cli.get(ctx, "/images/"+imageID+"/history", url.Values{}, nil)
	defer ensureReaderClosed(serverResp)
	if err != nil {
		return history, err
	}

	err = json.NewDecoder(serverResp.body).Decode(&history)
	return history, err
}
181452
func (r *REST) imageFor(ctx context.Context, tag string, imageStream *imageapi.ImageStream) (*imageapi.Image, error) {
	event := imageapi.LatestTaggedImage(imageStream, tag)
	if event == nil || len(event.Image) == 0 {
		return nil, kapierrors.NewNotFound(imagegroup.Resource("imagestreamtags"), imageapi.JoinImageStreamTag(imageStream.Name, tag))
	}

	return r.imageRegistry.GetImage(ctx, event.Image, &metav1.GetOptions{})
}
889388
func (c *repoCacheManager) fetchImages(tags []string) (fetchImagesResult, error) {
	images := map[string]image.Info{}

	// Create a list of images that need updating
	var toUpdate []imageToUpdate

	// Counters for reporting what happened
	var missing, refresh int
	for _, tag := range tags {
		if tag == "" {
			return fetchImagesResult{}, fmt.Errorf("empty tag in fetched tags")
		}

		// See if we have the manifest already cached
		newID := c.repoID.ToRef(tag)
		key := NewManifestKey(newID.CanonicalRef())
		bytes, deadline, err := c.cacheClient.GetKey(key)
		// If err, then we don't have it yet. Update.
		switch {
		case err != nil: // by and large these are cache misses, but any error shall count as "not found"
			if err != ErrNotCached {
				c.logger.Log("warning", "error from cache", "err", err, "ref", newID)
			}
			missing++
			toUpdate = append(toUpdate, imageToUpdate{ref: newID, previousRefresh: initialRefresh})
		case len(bytes) == 0:
			c.logger.Log("warning", "empty result from cache", "ref", newID)
			missing++
			toUpdate = append(toUpdate, imageToUpdate{ref: newID, previousRefresh: initialRefresh})
		default:
			var entry registry.ImageEntry
			if err := json.Unmarshal(bytes, &entry); err == nil {
				if c.trace {
					c.logger.Log("trace", "found cached manifest", "ref", newID, "last_fetched", entry.LastFetched.Format(time.RFC3339), "deadline", deadline.Format(time.RFC3339))
				}

				if entry.ExcludedReason == "" {
					images[tag] = entry.Info
					if c.now.After(deadline) {
						previousRefresh := minRefresh
						lastFetched := entry.Info.LastFetched
						if !lastFetched.IsZero() {
							previousRefresh = deadline.Sub(lastFetched)
						}
						toUpdate = append(toUpdate, imageToUpdate{ref: newID, previousRefresh: previousRefresh, previousDigest: entry.Info.Digest})
						refresh++
					}
				} else {
					if c.trace {
						c.logger.Log("trace", "excluded in cache", "ref", newID, "reason", entry.ExcludedReason)
					}
					if c.now.After(deadline) {
						toUpdate = append(toUpdate, imageToUpdate{ref: newID, previousRefresh: excludedRefresh})
						refresh++
					}
				}
			}
		}
	}

	result := fetchImagesResult{
		imagesFound:                images,
		imagesToUpdate:             toUpdate,
		imagesToUpdateRefreshCount: refresh,
		imagesToUpdateMissingCount: missing,
	}

	return result, nil
}
986050
func (api *ImagesAPI) GetAll(options *ImageGetOptions) (images *Images, err error) {
	uri := api.client.Endpoint + imageUrl
	if options != nil {
		uri += getQueryString(options)
	}
	res, err := api.client.restClient.GetList(api.client.Endpoint, uri, api.client.options.TokenOptions)
	if err != nil {
		return
	}

	images = &Images{}
	err = json.Unmarshal(res, images)
	return
}
1144486
func lastRuneStart(fd *formInfo, buf []byte) (Properties, int) {
	p := len(buf) - 1
	for ; p >= 0 && !utf8.RuneStart(buf[p]); p-- {
	}
	if p < 0 {
		return Properties{}, -1
	}
	return fd.info(inputBytes(buf), p), p
}
273343
func Alpha(dest *Image, alpha int) {
	r := dest.Bounds()

	var a, x, y, i int
	for x = r.Min.X; x < r.Max.X; x++ {
		for y = r.Min.Y; y < r.Max.Y; y++ {
			i = dest.PixOffset(x, y)
			a = int(dest.Pix[i+3])
			dest.Pix[i+3] = uint8((a * alpha) / 100)
		}
	}
}
1254767
func getImageNodes(nodes []gonum.Node) map[string]*imagegraph.ImageNode {
	ret := make(map[string]*imagegraph.ImageNode)
	for i := range nodes {
		if node, ok := nodes[i].(*imagegraph.ImageNode); ok {
			ret[node.Image.Name] = node
		}
	}
	return ret
}
196048
func (c *Client) ListImages(filter *Filter) ([]Image, error) {
	var resp []Image
	req := request{
		method: client.GET,
		url:    apiImages,
		filter: filter,
		resp:   &resp,
	}
	if _, err := c.sendRequest(req); err != nil {
		return nil, errors.Newf(err, "failed to get list of images")
	}
	return resp, nil
}
897234
func (ic *ImageCache) GetCache(parentID string, cfg *containertypes.Config) (string, error) {
	imgID, err := ic.localImageCache.GetCache(parentID, cfg)
	if err != nil {
		return "", err
	}
	if imgID != "" {
		for _, s := range ic.sources {
			if ic.isParent(s.ID(), image.ID(imgID)) {
				return imgID, nil
			}
		}
	}

	var parent *image.Image
	lenHistory := 0
	if parentID != "" {
		parent, err = ic.store.Get(image.ID(parentID))
		if err != nil {
			return "", errors.Wrapf(err, "unable to find image %v", parentID)
		}
		lenHistory = len(parent.History)
	}

	for _, target := range ic.sources {
		if !isValidParent(target, parent) || !isValidConfig(cfg, target.History[lenHistory]) {
			continue
		}

		if len(target.History)-1 == lenHistory { // last
			if parent != nil {
				if err := ic.store.SetParent(target.ID(), parent.ID()); err != nil {
					return "", errors.Wrapf(err, "failed to set parent for %v to %v", target.ID(), parent.ID())
				}
			}
			return target.ID().String(), nil
		}

		imgID, err := ic.restoreCachedImage(parent, target, cfg)
		if err != nil {
			return "", errors.Wrapf(err, "failed to restore cached image from %q to %v", parentID, target.ID())
		}

		ic.sources = []*image.Image{target} // avoid jumping to different target, tuned for safety atm
		return imgID.String(), nil
	}

	return "", nil
}
10267
func (i *imageCache) get() []container.Image {
	i.Lock()
	defer i.Unlock()
	sort.Sort(sliceutils.ByImageSize(i.images))
	return i.images
}