image_push.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package client // import "github.com/docker/docker/client"
  2. import (
  3. "context"
  4. "errors"
  5. "io"
  6. "net/url"
  7. "github.com/docker/distribution/reference"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/errdefs"
  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. name := reference.FamiliarName(ref)
  24. query := url.Values{}
  25. if !options.All {
  26. ref = reference.TagNameOnly(ref)
  27. if tagged, ok := ref.(reference.Tagged); ok {
  28. query.Set("tag", tagged.Tag())
  29. }
  30. }
  31. resp, err := cli.tryImagePush(ctx, name, query, options.RegistryAuth)
  32. if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil {
  33. newAuthHeader, privilegeErr := options.PrivilegeFunc()
  34. if privilegeErr != nil {
  35. return nil, privilegeErr
  36. }
  37. resp, err = cli.tryImagePush(ctx, name, query, newAuthHeader)
  38. }
  39. if err != nil {
  40. return nil, err
  41. }
  42. return resp.body, nil
  43. }
  44. func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.Values, registryAuth string) (serverResponse, error) {
  45. headers := map[string][]string{"X-Registry-Auth": {registryAuth}}
  46. return cli.post(ctx, "/images/"+imageID+"/push", query, nil, headers)
  47. }