// GetImage fetches Docker repository information from the specified Docker
// registry. If the registry is an empty string it defaults to the DockerHub.
// The integer return value is the status code of the HTTP response.
492355
func GetImage(name, registryURL string) (*Image, int, error) {
	if name == "" {
		return nil, -1, errors.New("image name is empty")
	}

	var ru *url.URL
	var err error
	if len(registryURL) != 0 {
		ru, err = url.Parse(registryURL)
	} else {
		ru, err = url.Parse(DockerHubRegistryURL)
		registryURL = DockerHubRegistryURL
	}
	if err != nil {
		return nil, -1, err
	}

	// In order to get layers from Docker CDN we need to hit 'images' endpoint
	// and request the token. Client should also accept and store cookies, as
	// they are needed to fetch the layer data later.
	imagesURL := fmt.Sprintf("%s/v1/repositories/%s/images", registryURL, name)

	req, err := http.NewRequest("GET", imagesURL, nil)
	if err != nil {
		return nil, -1, err
	}

	// FIXME: Send 'Connection: close' header on HTTP requests
	// as reusing the connection is still prone to EOF/Connection reset errors
	// in certain network environments...
	// See: ENGT-9670
	// https://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors
	req.Close = true

	req.Header.Set("X-Docker-Token", "true")

	client := &http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyFromEnvironment,
		},
	}
	client.Jar, err = cookiejar.New(nil) // Docker repo API sets and uses cookies for CDN.
	if err != nil {
		return nil, -1, err
	}

	res, err := client.Do(req)
	if err != nil {
		return nil, -1, err
	}
	defer res.Body.Close()
	switch res.StatusCode {
	case http.StatusOK:
		// Fall through.
	case http.StatusNotFound:
		return nil, res.StatusCode, fmt.Errorf("image %q not found", name)
	default:
		return nil, res.StatusCode, fmt.Errorf("HTTP %d ", res.StatusCode)
	}

	token := res.Header.Get("X-Docker-Token")
	endpoints := strings.Split(res.Header.Get("X-Docker-Endpoints"), ",")

	if len(endpoints) == 0 {
		return nil, res.StatusCode, errors.New("Docker index response didn't contain any endpoints")
	}
	for i := range endpoints {
		endpoints[i] = strings.Trim(endpoints[i], " ")
	}

	img := &Image{
		Name:      name,
		client:    client,
		endpoints: endpoints,
		token:     token,
		scheme:    ru.Scheme,
	}

	img.tags, err = img.fetchTags()
	if err != nil {
		return nil, res.StatusCode, err
	}

	return img, res.StatusCode, nil
}
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
}
705634
func (f *Facade) getImageUUID(ctx datastore.Context, imageName string) (string, error) {
	logger := plog.WithField("imagename", imageName)

	if imageName == "" {
		logger.Debug("Image name not specified")
		return "", nil
	}

	imageID, err := commons.ParseImageID(imageName)
	if err != nil {
		logger.WithError(err).Debug("Could not parse service image")
		return "", err
	}
	imageID.Tag = docker.Latest
	logger = logger.WithField("imagename", imageID.String())
	logger.Debug("Parsed service image")

	imageData, err := f.registryStore.Get(ctx, imageID.String())
	if err != nil {
		logger.WithError(err).Debug("Could not look up service image in image registry")
		return "", err
	}

	logger.WithField("imageuuid", imageData.UUID).Debug("Loaded image uuid")
	return imageData.UUID, nil
}
1055954
func (a *AgentServer) PullImage(req PullImageRequest, image *string) error {

	logger := plog.WithFields(logrus.Fields{
		"image": req.Image,
		"registry": req.Registry})

	// set up the connections
	docker, err := docker.NewDockerClient()
	if err != nil {
		logger.WithError(err).Error("Could not connect to docker client")
		return err
	}
	conn, err := zzk.GetLocalConnection("/")
	if err != nil {
		logger.WithError(err).Error("Could not acquire coordinator connection")
		return err
	}

	// pull the image from the registry
	reg := registry.NewRegistryListener(docker, req.Registry, "")
	reg.SetConnection(conn)
	timer := time.NewTimer(req.Timeout)
	defer timer.Stop()
	if err := reg.PullImage(timer.C, req.Image); err != nil {
		logger.WithError(err).Error("Could not pull image from registry")
		return err
	}

	// get the tag of the image pulled
	*image, err = reg.ImagePath(req.Image)
	if err != nil {
		logger.WithError(err).Error("Could not get image id for image from registry")
		return err
	}

	return nil
}
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()
}
309980
func (c Client) GetImageStream(ctx context.Context, name string, options *metav1.GetOptions) (*imagev1.ImageStream, error) {
	return c.ImageStreams.ImageStreams(apirequest.NamespaceValue(ctx)).Get(name, *options)
}
666276
func (srv *Server) Get(params imageserver.Params) (*imageserver.Image, error) {
	pth, err := srv.getPath(params)
	if err != nil {
		return nil, err
	}
	data, err := loadFile(pth)
	if err != nil {
		return nil, err
	}
	format, err := srv.identify(pth, data)
	if err != nil {
		return nil, err
	}
	return &imageserver.Image{
		Format: format,
		Data:   data,
	}, nil
}
229604
func (cache *Cache) Get(key string, params imageserver.Params) (*imageserver.Image, error) {
	data, err := cache.getData(key)
	if err != nil {
		return nil, err
	}
	if data == nil {
		return nil, nil
	}
	im := new(imageserver.Image)
	err = im.UnmarshalBinaryNoCopy(data)
	if err != nil {
		return nil, err
	}
	return im, nil
}
296759
func (f *Facade) GetRegistryImages(ctx datastore.Context) ([]registry.Image, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.GetRegistryImages"))
	rImages, err := f.registryStore.GetImages(ctx)
	if err != nil {
		return nil, err
	}
	return rImages, nil
}
764436
func (c *Cache) GetImageRepositoryMetadata(id image.Name) (image.RepositoryMetadata, error) {
	repoKey := NewRepositoryKey(id.CanonicalName())
	bytes, _, err := c.Reader.GetKey(repoKey)
	if err != nil {
		return image.RepositoryMetadata{}, err
	}
	var repo ImageRepository
	if err = json.Unmarshal(bytes, &repo); err != nil {
		return image.RepositoryMetadata{}, err
	}

	// We only care about the error if we've never successfully
	// updated the result.
	if repo.LastUpdate.IsZero() {
		if repo.LastError != "" {
			return image.RepositoryMetadata{}, errors.New(repo.LastError)
		}
		return image.RepositoryMetadata{}, ErrNotCached
	}

	return repo.RepositoryMetadata, nil
}
1208345
func (dh *Client) PullImage(name string) error {
	if name == "" {
		return fmt.Errorf("no image name given")
	}

	registry, repository, tag := splitImageName(name)

	reqURL := dh.Address + "/images/create"
	values := &url.Values{}
	values.Add("fromImage", registry+"/"+repository)
	values.Add("repo", repository)
	if registry != "" {
		values.Add("registry", registry)
	}
	if tag != "" {
		values.Add("tag", tag)
	}

	rsp, e := dh.post(reqURL + "?" + values.Encode())
	if e != nil {
		return e
	}
	defer rsp.Body.Close()
	if rsp.Status[0] != '2' {
		return fmt.Errorf("expected status 2xx, was %d", rsp.StatusCode)
	}
	return handleJSONStream(rsp.Body, HandlePullImageMessage)
}
606329
func getImageVisibility(visibility string) (*images.ImageVisibility, error) {
	visibilities := [...]images.ImageVisibility{
		images.ImageVisibilityPublic,
		images.ImageVisibilityPrivate,
		images.ImageVisibilityCommunity,
		images.ImageVisibilityShared,
	}

	for _, v := range visibilities {
		if string(v) == visibility {
			return &v, nil
		}
	}

	return nil, fmt.Errorf("Not a valid visibility: %s", visibility)
}
930345
func GetRuntimeImage(docker Docker, config *api.Config) error {
	_, err := pullAndCheck(config.RuntimeImage, docker, config.RuntimeImagePullPolicy, config)
	return err
}
1227010
func (d Docker) GetCachedImage(imgID string, cfg *container.Config) (string, error) {
	cache, err := d.Daemon.ImageGetCached(image.ID(imgID), cfg)
	if cache == nil || err != nil {
		return "", err
	}
	return cache.ID().String(), nil
}
644793
func (c *CheckRunImage) GetImageURL() string {
	if c == nil || c.ImageURL == nil {
		return ""
	}
	return *c.ImageURL
}
512254
func (c *images) Get(name string, options v1.GetOptions) (result *image.Image, err error) {
	result = &image.Image{}
	err = c.client.Get().
		Resource("images").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}
780498
func (c *Client) PullImage(opts PullImageOptions, auth AuthConfiguration) error {
	if opts.Repository == "" {
		return ErrNoSuchImage
	}

	headers, err := headersWithAuth(auth)
	if err != nil {
		return err
	}
	if opts.Tag == "" && strings.Contains(opts.Repository, "@") {
		parts := strings.SplitN(opts.Repository, "@", 2)
		opts.Repository = parts[0]
		opts.Tag = parts[1]
	}
	return c.createImage(queryString(&opts), headers, nil, opts.OutputStream, opts.RawJSONStream, opts.InactivityTimeout, opts.Context)
}