pull.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package image
  2. import (
  3. "errors"
  4. "fmt"
  5. "golang.org/x/net/context"
  6. "github.com/docker/docker/api/client"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/reference"
  9. "github.com/docker/docker/registry"
  10. "github.com/spf13/cobra"
  11. )
  12. type pullOptions struct {
  13. remote string
  14. all bool
  15. }
  16. // NewPullCommand creates a new `docker pull` command
  17. func NewPullCommand(dockerCli *client.DockerCli) *cobra.Command {
  18. var opts pullOptions
  19. cmd := &cobra.Command{
  20. Use: "pull [OPTIONS] NAME[:TAG|@DIGEST]",
  21. Short: "Pull an image or a repository from a registry",
  22. Args: cli.ExactArgs(1),
  23. RunE: func(cmd *cobra.Command, args []string) error {
  24. opts.remote = args[0]
  25. return runPull(dockerCli, opts)
  26. },
  27. }
  28. flags := cmd.Flags()
  29. flags.BoolVarP(&opts.all, "all-tags", "a", false, "Download all tagged images in the repository")
  30. client.AddTrustedFlags(flags, true)
  31. return cmd
  32. }
  33. func runPull(dockerCli *client.DockerCli, opts pullOptions) error {
  34. distributionRef, err := reference.ParseNamed(opts.remote)
  35. if err != nil {
  36. return err
  37. }
  38. if opts.all && !reference.IsNameOnly(distributionRef) {
  39. return errors.New("tag can't be used with --all-tags/-a")
  40. }
  41. if !opts.all && reference.IsNameOnly(distributionRef) {
  42. distributionRef = reference.WithDefaultTag(distributionRef)
  43. fmt.Fprintf(dockerCli.Out(), "Using default tag: %s\n", reference.DefaultTag)
  44. }
  45. var tag string
  46. switch x := distributionRef.(type) {
  47. case reference.Canonical:
  48. tag = x.Digest().String()
  49. case reference.NamedTagged:
  50. tag = x.Tag()
  51. }
  52. registryRef := registry.ParseReference(tag)
  53. // Resolve the Repository name from fqn to RepositoryInfo
  54. repoInfo, err := registry.ParseRepositoryInfo(distributionRef)
  55. if err != nil {
  56. return err
  57. }
  58. ctx := context.Background()
  59. authConfig := dockerCli.ResolveAuthConfig(ctx, repoInfo.Index)
  60. requestPrivilege := dockerCli.RegistryAuthenticationPrivilegedFunc(repoInfo.Index, "pull")
  61. if client.IsTrusted() && !registryRef.HasDigest() {
  62. // Check if tag is digest
  63. return dockerCli.TrustedPull(ctx, repoInfo, registryRef, authConfig, requestPrivilege)
  64. }
  65. return dockerCli.ImagePullPrivileged(ctx, authConfig, distributionRef.String(), requestPrivilege, opts.all)
  66. }