client/image_pull.go
7c36a1af
 package client
 
 import (
 	"io"
 	"net/http"
 	"net/url"
d98ecf2d
 	"strings"
7c36a1af
 
 	"golang.org/x/net/context"
 
3a127939
 	"github.com/docker/distribution/reference"
7c36a1af
 	"github.com/docker/docker/api/types"
 )
 
 // ImagePull requests the docker host to pull an image from a remote registry.
 // It executes the privileged function if the operation is unauthorized
 // and it tries one more time.
 // It's up to the caller to handle the io.ReadCloser and close it properly.
 //
 // FIXME(vdemeester): there is currently used in a few way in docker/docker
 // - if not in trusted content, ref is used to pass the whole reference, and tag is empty
 // - if in trusted content, ref is used to pass the reference name, and tag for the digest
3a127939
 func (cli *Client) ImagePull(ctx context.Context, refStr string, options types.ImagePullOptions) (io.ReadCloser, error) {
 	ref, err := reference.ParseNormalizedNamed(refStr)
7c36a1af
 	if err != nil {
 		return nil, err
 	}
 
 	query := url.Values{}
3a127939
 	query.Set("fromImage", reference.FamiliarName(ref))
 	if !options.All {
 		query.Set("tag", getAPITagFromNamedRef(ref))
7c36a1af
 	}
d98ecf2d
 	if options.Platform != "" {
 		query.Set("platform", strings.ToLower(options.Platform))
0380fbff
 	}
 
d98ecf2d
 	resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth)
7c36a1af
 	if resp.statusCode == http.StatusUnauthorized && options.PrivilegeFunc != nil {
 		newAuthHeader, privilegeErr := options.PrivilegeFunc()
 		if privilegeErr != nil {
 			return nil, privilegeErr
 		}
d98ecf2d
 		resp, err = cli.tryImageCreate(ctx, query, newAuthHeader)
7c36a1af
 	}
 	if err != nil {
 		return nil, err
 	}
 	return resp.body, nil
 }
3a127939
 
 // getAPITagFromNamedRef returns a tag from the specified reference.
 // This function is necessary as long as the docker "server" api expects
 // digests to be sent as tags and makes a distinction between the name
 // and tag/digest part of a reference.
 func getAPITagFromNamedRef(ref reference.Named) string {
 	if digested, ok := ref.(reference.Digested); ok {
 		return digested.Digest().String()
 	}
 	ref = reference.TagNameOnly(ref)
 	if tagged, ok := ref.(reference.Tagged); ok {
 		return tagged.Tag()
 	}
 	return ""
 }