github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/client/image_push.go (about)

     1  package client // import "github.com/docker/docker/client"
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"io"
     7  	"net/http"
     8  	"net/url"
     9  
    10  	"github.com/docker/distribution/reference"
    11  	"github.com/docker/docker/api/types"
    12  )
    13  
    14  // ImagePush requests the docker host to push an image to a remote registry.
    15  // It executes the privileged function if the operation is unauthorized
    16  // and it tries one more time.
    17  // It's up to the caller to handle the io.ReadCloser and close it properly.
    18  func (cli *Client) ImagePush(ctx context.Context, image string, options types.ImagePushOptions) (io.ReadCloser, error) {
    19  	ref, err := reference.ParseNormalizedNamed(image)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  
    24  	if _, isCanonical := ref.(reference.Canonical); isCanonical {
    25  		return nil, errors.New("cannot push a digest reference")
    26  	}
    27  
    28  	tag := ""
    29  	name := reference.FamiliarName(ref)
    30  
    31  	if nameTaggedRef, isNamedTagged := ref.(reference.NamedTagged); isNamedTagged {
    32  		tag = nameTaggedRef.Tag()
    33  	}
    34  
    35  	query := url.Values{}
    36  	query.Set("tag", tag)
    37  
    38  	resp, err := cli.tryImagePush(ctx, name, query, options.RegistryAuth)
    39  	if resp.statusCode == http.StatusUnauthorized && options.PrivilegeFunc != nil {
    40  		newAuthHeader, privilegeErr := options.PrivilegeFunc()
    41  		if privilegeErr != nil {
    42  			return nil, privilegeErr
    43  		}
    44  		resp, err = cli.tryImagePush(ctx, name, query, newAuthHeader)
    45  	}
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	return resp.body, nil
    50  }
    51  
    52  func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.Values, registryAuth string) (serverResponse, error) {
    53  	headers := map[string][]string{"X-Registry-Auth": {registryAuth}}
    54  	return cli.post(ctx, "/images/"+imageID+"/push", query, nil, headers)
    55  }