diffid.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Copyright The containerd Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package images
  14. import (
  15. "compress/gzip"
  16. "context"
  17. "io"
  18. "github.com/containerd/containerd/content"
  19. "github.com/containerd/containerd/labels"
  20. "github.com/opencontainers/go-digest"
  21. ocispec "github.com/opencontainers/image-spec/specs-go/v1"
  22. "github.com/sirupsen/logrus"
  23. )
  24. // GetDiffID gets the diff ID of the layer blob descriptor.
  25. func GetDiffID(ctx context.Context, cs content.Store, desc ocispec.Descriptor) (digest.Digest, error) {
  26. switch desc.MediaType {
  27. case
  28. // If the layer is already uncompressed, we can just return its digest
  29. MediaTypeDockerSchema2Layer,
  30. ocispec.MediaTypeImageLayer,
  31. MediaTypeDockerSchema2LayerForeign,
  32. ocispec.MediaTypeImageLayerNonDistributable:
  33. return desc.Digest, nil
  34. }
  35. info, err := cs.Info(ctx, desc.Digest)
  36. if err != nil {
  37. return "", err
  38. }
  39. v, ok := info.Labels[labels.LabelUncompressed]
  40. if ok {
  41. // Fast path: if the image is already unpacked, we can use the label value
  42. return digest.Parse(v)
  43. }
  44. // if the image is not unpacked, we may not have the label
  45. ra, err := cs.ReaderAt(ctx, desc)
  46. if err != nil {
  47. return "", err
  48. }
  49. defer ra.Close()
  50. r := content.NewReader(ra)
  51. gzR, err := gzip.NewReader(r)
  52. if err != nil {
  53. return "", err
  54. }
  55. digester := digest.Canonical.Digester()
  56. hashW := digester.Hash()
  57. if _, err := io.Copy(hashW, gzR); err != nil {
  58. return "", err
  59. }
  60. if err := ra.Close(); err != nil {
  61. return "", err
  62. }
  63. digest := digester.Digest()
  64. // memorize the computed value
  65. if info.Labels == nil {
  66. info.Labels = make(map[string]string)
  67. }
  68. info.Labels[labels.LabelUncompressed] = digest.String()
  69. if _, err := cs.Update(ctx, info, "labels"); err != nil {
  70. logrus.WithError(err).Warnf("failed to set %s label for %s", labels.LabelUncompressed, desc.Digest)
  71. }
  72. return digest, nil
  73. }