image_pull.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. package containerd
  2. import (
  3. "context"
  4. "io"
  5. "github.com/containerd/containerd"
  6. cerrdefs "github.com/containerd/containerd/errdefs"
  7. "github.com/containerd/containerd/images"
  8. "github.com/containerd/containerd/log"
  9. "github.com/containerd/containerd/pkg/snapshotters"
  10. "github.com/containerd/containerd/platforms"
  11. "github.com/distribution/reference"
  12. "github.com/docker/docker/api/types/events"
  13. "github.com/docker/docker/api/types/registry"
  14. "github.com/docker/docker/errdefs"
  15. "github.com/docker/docker/pkg/progress"
  16. "github.com/docker/docker/pkg/streamformatter"
  17. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  18. )
  19. // PullImage initiates a pull operation. ref is the image to pull.
  20. func (i *ImageService) PullImage(ctx context.Context, ref reference.Named, platform *ocispec.Platform, metaHeaders map[string][]string, authConfig *registry.AuthConfig, outStream io.Writer) error {
  21. var opts []containerd.RemoteOpt
  22. if platform != nil {
  23. opts = append(opts, containerd.WithPlatform(platforms.Format(*platform)))
  24. }
  25. resolver, _ := i.newResolverFromAuthConfig(ctx, authConfig)
  26. opts = append(opts, containerd.WithResolver(resolver))
  27. old, err := i.resolveDescriptor(ctx, ref.String())
  28. if err != nil && !errdefs.IsNotFound(err) {
  29. return err
  30. }
  31. p := platforms.Default()
  32. if platform != nil {
  33. p = platforms.Only(*platform)
  34. }
  35. jobs := newJobs()
  36. h := images.HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
  37. if images.IsLayerType(desc.MediaType) {
  38. jobs.Add(desc)
  39. }
  40. return nil, nil
  41. })
  42. opts = append(opts, containerd.WithImageHandler(h))
  43. out := streamformatter.NewJSONProgressOutput(outStream, false)
  44. pp := pullProgress{store: i.client.ContentStore(), showExists: true}
  45. finishProgress := jobs.showProgress(ctx, out, pp)
  46. defer finishProgress()
  47. var sentPullingFrom bool
  48. ah := images.HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
  49. if images.IsManifestType(desc.MediaType) {
  50. if !sentPullingFrom {
  51. var tagOrDigest string
  52. if tagged, ok := ref.(reference.Tagged); ok {
  53. tagOrDigest = tagged.Tag()
  54. } else {
  55. tagOrDigest = ref.String()
  56. }
  57. progress.Message(out, tagOrDigest, "Pulling from "+reference.Path(ref))
  58. sentPullingFrom = true
  59. }
  60. available, _, _, missing, err := images.Check(ctx, i.client.ContentStore(), desc, p)
  61. if err != nil {
  62. return nil, err
  63. }
  64. // If we already have all the contents pull shouldn't show any layer
  65. // download progress, not even a "Already present" message.
  66. if available && len(missing) == 0 {
  67. pp.hideLayers = true
  68. }
  69. }
  70. return nil, nil
  71. })
  72. opts = append(opts, containerd.WithImageHandler(ah))
  73. opts = append(opts, containerd.WithPullUnpack)
  74. // TODO(thaJeztah): we may have to pass the snapshotter to use if the pull is part of a "docker run" (container create -> pull image if missing). See https://github.com/moby/moby/issues/45273
  75. opts = append(opts, containerd.WithPullSnapshotter(i.snapshotter))
  76. // AppendInfoHandlerWrapper will annotate the image with basic information like manifest and layer digests as labels;
  77. // this information is used to enable remote snapshotters like nydus and stargz to query a registry.
  78. infoHandler := snapshotters.AppendInfoHandlerWrapper(ref.String())
  79. opts = append(opts, containerd.WithImageHandlerWrapper(infoHandler))
  80. img, err := i.client.Pull(ctx, ref.String(), opts...)
  81. if err != nil {
  82. return err
  83. }
  84. logger := log.G(ctx).WithFields(log.Fields{
  85. "digest": img.Target().Digest,
  86. "remote": ref.String(),
  87. })
  88. logger.Info("image pulled")
  89. progress.Message(out, "", "Digest: "+img.Target().Digest.String())
  90. writeStatus(out, reference.FamiliarString(ref), old.Digest != img.Target().Digest)
  91. // The pull succeeded, so try to remove any dangling image we have for this target
  92. err = i.client.ImageService().Delete(context.Background(), danglingImageName(img.Target().Digest))
  93. if err != nil && !cerrdefs.IsNotFound(err) {
  94. // Image pull succeeded, but cleaning up the dangling image failed. Ignore the
  95. // error to not mark the pull as failed.
  96. logger.WithError(err).Warn("unexpected error while removing outdated dangling image reference")
  97. }
  98. i.LogImageEvent(reference.FamiliarString(ref), reference.FamiliarName(ref), events.ActionPull)
  99. return nil
  100. }
  101. // writeStatus writes a status message to out. If newerDownloaded is true, the
  102. // status message indicates that a newer image was downloaded. Otherwise, it
  103. // indicates that the image is up to date. requestedTag is the tag the message
  104. // will refer to.
  105. func writeStatus(out progress.Output, requestedTag string, newerDownloaded bool) {
  106. if newerDownloaded {
  107. progress.Message(out, "", "Status: Downloaded newer image for "+requestedTag)
  108. } else {
  109. progress.Message(out, "", "Status: Image is up to date for "+requestedTag)
  110. }
  111. }