image_push.go 1.6 KB

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