pull.go 2.3 KB

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