image.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package images // import "github.com/docker/docker/daemon/images"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "github.com/containerd/containerd/content"
  8. cerrdefs "github.com/containerd/containerd/errdefs"
  9. "github.com/containerd/containerd/images"
  10. "github.com/containerd/containerd/leases"
  11. "github.com/containerd/containerd/platforms"
  12. "github.com/containerd/log"
  13. "github.com/distribution/reference"
  14. imagetypes "github.com/docker/docker/api/types/image"
  15. "github.com/docker/docker/errdefs"
  16. "github.com/docker/docker/image"
  17. "github.com/docker/docker/layer"
  18. "github.com/opencontainers/go-digest"
  19. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  20. "github.com/pkg/errors"
  21. )
  22. // ErrImageDoesNotExist is error returned when no image can be found for a reference.
  23. type ErrImageDoesNotExist struct {
  24. Ref reference.Reference
  25. }
  26. func (e ErrImageDoesNotExist) Error() string {
  27. ref := e.Ref
  28. if named, ok := ref.(reference.Named); ok {
  29. ref = reference.TagNameOnly(named)
  30. }
  31. return fmt.Sprintf("No such image: %s", reference.FamiliarString(ref))
  32. }
  33. // NotFound implements the NotFound interface
  34. func (e ErrImageDoesNotExist) NotFound() {}
  35. type manifestList struct {
  36. Manifests []ocispec.Descriptor `json:"manifests"`
  37. }
  38. type manifest struct {
  39. Config ocispec.Descriptor `json:"config"`
  40. }
  41. func (i *ImageService) PrepareSnapshot(ctx context.Context, id string, parentImage string, platform *ocispec.Platform, setupInit func(string) error) error {
  42. // Only makes sense when conatinerd image store is used
  43. panic("not implemented")
  44. }
  45. func (i *ImageService) manifestMatchesPlatform(ctx context.Context, img *image.Image, platform ocispec.Platform) (bool, error) {
  46. logger := log.G(ctx).WithField("image", img.ID).WithField("desiredPlatform", platforms.Format(platform))
  47. ls, err := i.leases.ListResources(ctx, leases.Lease{ID: imageKey(img.ID().String())})
  48. if err != nil {
  49. if cerrdefs.IsNotFound(err) {
  50. return false, nil
  51. }
  52. logger.WithError(err).Error("Error looking up image leases")
  53. return false, err
  54. }
  55. // Note we are comparing against manifest lists here, which we expect to always have a CPU variant set (where applicable).
  56. // So there is no need for the fallback matcher here.
  57. comparer := platforms.Only(platform)
  58. var (
  59. ml manifestList
  60. m manifest
  61. )
  62. makeRdr := func(ra content.ReaderAt) io.Reader {
  63. return io.LimitReader(io.NewSectionReader(ra, 0, ra.Size()), 1e6)
  64. }
  65. for _, r := range ls {
  66. logger := logger.WithField("resourceID", r.ID).WithField("resourceType", r.Type)
  67. logger.Debug("Checking lease resource for platform match")
  68. if r.Type != "content" {
  69. continue
  70. }
  71. ra, err := i.content.ReaderAt(ctx, ocispec.Descriptor{Digest: digest.Digest(r.ID)})
  72. if err != nil {
  73. if cerrdefs.IsNotFound(err) {
  74. continue
  75. }
  76. logger.WithError(err).Error("Error looking up referenced manifest list for image")
  77. continue
  78. }
  79. data, err := io.ReadAll(makeRdr(ra))
  80. ra.Close()
  81. if err != nil {
  82. logger.WithError(err).Error("Error reading manifest list for image")
  83. continue
  84. }
  85. ml.Manifests = nil
  86. if err := json.Unmarshal(data, &ml); err != nil {
  87. logger.WithError(err).Error("Error unmarshalling content")
  88. continue
  89. }
  90. for _, md := range ml.Manifests {
  91. switch md.MediaType {
  92. case ocispec.MediaTypeImageManifest, images.MediaTypeDockerSchema2Manifest:
  93. default:
  94. continue
  95. }
  96. p := ocispec.Platform{
  97. Architecture: md.Platform.Architecture,
  98. OS: md.Platform.OS,
  99. Variant: md.Platform.Variant,
  100. }
  101. if !comparer.Match(p) {
  102. logger.WithField("otherPlatform", platforms.Format(p)).Debug("Manifest is not a match")
  103. continue
  104. }
  105. // Here we have a platform match for the referenced manifest, let's make sure the manifest is actually for the image config we are using.
  106. ra, err := i.content.ReaderAt(ctx, ocispec.Descriptor{Digest: md.Digest})
  107. if err != nil {
  108. logger.WithField("otherDigest", md.Digest).WithError(err).Error("Could not get reader for manifest")
  109. continue
  110. }
  111. data, err := io.ReadAll(makeRdr(ra))
  112. ra.Close()
  113. if err != nil {
  114. logger.WithError(err).Error("Error reading manifest for image")
  115. continue
  116. }
  117. if err := json.Unmarshal(data, &m); err != nil {
  118. logger.WithError(err).Error("Error desserializing manifest")
  119. continue
  120. }
  121. if m.Config.Digest == img.ID().Digest() {
  122. logger.WithField("manifestDigest", md.Digest).Debug("Found matching manifest for image")
  123. return true, nil
  124. }
  125. logger.WithField("otherDigest", md.Digest).Debug("Skipping non-matching manifest")
  126. }
  127. }
  128. return false, nil
  129. }
  130. // GetImage returns an image corresponding to the image referred to by refOrID.
  131. func (i *ImageService) GetImage(ctx context.Context, refOrID string, options imagetypes.GetImageOpts) (*image.Image, error) {
  132. img, err := i.getImage(ctx, refOrID, options)
  133. if err != nil {
  134. return nil, err
  135. }
  136. if options.Details {
  137. var size int64
  138. var layerMetadata map[string]string
  139. layerID := img.RootFS.ChainID()
  140. if layerID != "" {
  141. l, err := i.layerStore.Get(layerID)
  142. if err != nil {
  143. return nil, err
  144. }
  145. defer layer.ReleaseAndLog(i.layerStore, l)
  146. size = l.Size()
  147. layerMetadata, err = l.Metadata()
  148. if err != nil {
  149. return nil, err
  150. }
  151. }
  152. lastUpdated, err := i.imageStore.GetLastUpdated(img.ID())
  153. if err != nil {
  154. return nil, err
  155. }
  156. img.Details = &image.Details{
  157. References: i.referenceStore.References(img.ID().Digest()),
  158. Size: size,
  159. Metadata: layerMetadata,
  160. Driver: i.layerStore.DriverName(),
  161. LastUpdated: lastUpdated,
  162. }
  163. }
  164. return img, nil
  165. }
  166. func (i *ImageService) GetImageManifest(ctx context.Context, refOrID string, options imagetypes.GetImageOpts) (*ocispec.Descriptor, error) {
  167. panic("not implemented")
  168. }
  169. func (i *ImageService) getImage(ctx context.Context, refOrID string, options imagetypes.GetImageOpts) (retImg *image.Image, retErr error) {
  170. defer func() {
  171. if retErr != nil || retImg == nil || options.Platform == nil {
  172. return
  173. }
  174. imgPlat := ocispec.Platform{
  175. OS: retImg.OS,
  176. Architecture: retImg.Architecture,
  177. Variant: retImg.Variant,
  178. }
  179. p := *options.Platform
  180. // Note that `platforms.Only` will fuzzy match this for us
  181. // For example: an armv6 image will run just fine on an armv7 CPU, without emulation or anything.
  182. if OnlyPlatformWithFallback(p).Match(imgPlat) {
  183. return
  184. }
  185. // In some cases the image config can actually be wrong (e.g. classic `docker build` may not handle `--platform` correctly)
  186. // So we'll look up the manifest list that corresponds to this image to check if at least the manifest list says it is the correct image.
  187. var matches bool
  188. matches, retErr = i.manifestMatchesPlatform(ctx, retImg, p)
  189. if matches || retErr != nil {
  190. return
  191. }
  192. // This allows us to tell clients that we don't have the image they asked for
  193. // Where this gets hairy is the image store does not currently support multi-arch images, e.g.:
  194. // An image `foo` may have a multi-arch manifest, but the image store only fetches the image for a specific platform
  195. // The image store does not store the manifest list and image tags are assigned to architecture specific images.
  196. // So we can have a `foo` image that is amd64 but the user requested armv7. If the user looks at the list of images.
  197. // This may be confusing.
  198. // The alternative to this is to return an errdefs.Conflict error with a helpful message, but clients will not be
  199. // able to automatically tell what causes the conflict.
  200. retErr = errdefs.NotFound(errors.Errorf("image with reference %s was found but does not match the specified platform: wanted %s, actual: %s", refOrID, platforms.Format(p), platforms.Format(imgPlat)))
  201. }()
  202. ref, err := reference.ParseAnyReference(refOrID)
  203. if err != nil {
  204. return nil, errdefs.InvalidParameter(err)
  205. }
  206. namedRef, ok := ref.(reference.Named)
  207. if !ok {
  208. digested, ok := ref.(reference.Digested)
  209. if !ok {
  210. return nil, ErrImageDoesNotExist{ref}
  211. }
  212. if img, err := i.imageStore.Get(image.ID(digested.Digest())); err == nil {
  213. return img, nil
  214. }
  215. return nil, ErrImageDoesNotExist{ref}
  216. }
  217. if dgst, err := i.referenceStore.Get(namedRef); err == nil {
  218. // Search the image stores to get the operating system, defaulting to host OS.
  219. if img, err := i.imageStore.Get(image.ID(dgst)); err == nil {
  220. return img, nil
  221. }
  222. }
  223. // Search based on ID
  224. if id, err := i.imageStore.Search(refOrID); err == nil {
  225. img, err := i.imageStore.Get(id)
  226. if err != nil {
  227. return nil, ErrImageDoesNotExist{ref}
  228. }
  229. return img, nil
  230. }
  231. return nil, ErrImageDoesNotExist{ref}
  232. }
  233. // OnlyPlatformWithFallback uses `platforms.Only` with a fallback to handle the case where the platform
  234. // being matched does not have a CPU variant.
  235. //
  236. // The reason for this is that CPU variant is not even if the official image config spec as of this writing.
  237. // See: https://github.com/opencontainers/image-spec/pull/809
  238. // Since Docker tends to compare platforms from the image config, we need to handle this case.
  239. func OnlyPlatformWithFallback(p ocispec.Platform) platforms.Matcher {
  240. return &onlyFallbackMatcher{only: platforms.Only(p), p: platforms.Normalize(p)}
  241. }
  242. type onlyFallbackMatcher struct {
  243. only platforms.Matcher
  244. p ocispec.Platform
  245. }
  246. func (m *onlyFallbackMatcher) Match(other ocispec.Platform) bool {
  247. if m.only.Match(other) {
  248. // It matches, no reason to fallback
  249. return true
  250. }
  251. if other.Variant != "" {
  252. // If there is a variant then this fallback does not apply, and there is no match
  253. return false
  254. }
  255. otherN := platforms.Normalize(other)
  256. otherN.Variant = "" // normalization adds a default variant... which is the whole problem with `platforms.Only`
  257. return m.p.OS == otherN.OS &&
  258. m.p.Architecture == otherN.Architecture
  259. }