image_push.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package client
  2. import (
  3. "errors"
  4. "io"
  5. "net/http"
  6. "net/url"
  7. "golang.org/x/net/context"
  8. distreference "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, ref string, options types.ImagePushOptions) (io.ReadCloser, error) {
  16. distributionRef, err := distreference.ParseNamed(ref)
  17. if err != nil {
  18. return nil, err
  19. }
  20. if _, isCanonical := distributionRef.(distreference.Canonical); isCanonical {
  21. return nil, errors.New("cannot push a digest reference")
  22. }
  23. var tag = ""
  24. if nameTaggedRef, isNamedTagged := distributionRef.(distreference.NamedTagged); isNamedTagged {
  25. tag = nameTaggedRef.Tag()
  26. }
  27. query := url.Values{}
  28. query.Set("tag", tag)
  29. resp, err := cli.tryImagePush(ctx, distributionRef.Name(), query, options.RegistryAuth)
  30. if resp.statusCode == http.StatusUnauthorized && options.PrivilegeFunc != nil {
  31. newAuthHeader, privilegeErr := options.PrivilegeFunc()
  32. if privilegeErr != nil {
  33. return nil, privilegeErr
  34. }
  35. resp, err = cli.tryImagePush(ctx, distributionRef.Name(), query, newAuthHeader)
  36. }
  37. if err != nil {
  38. return nil, err
  39. }
  40. return resp.body, nil
  41. }
  42. func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.Values, registryAuth string) (serverResponse, error) {
  43. headers := map[string][]string{"X-Registry-Auth": {registryAuth}}
  44. return cli.post(ctx, "/images/"+imageID+"/push", query, nil, headers)
  45. }