Skip to content

Commit

Permalink
Avoid a network call for digest based images (#396)
Browse files Browse the repository at this point in the history
Signed-off-by: Mikalai Radchuk <mradchuk@redhat.com>
  • Loading branch information
m1kola committed Sep 12, 2024
1 parent 1e962d2 commit 8e71e93
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions internal/source/image_registry_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,16 @@ func (i *ImageRegistry) Unpack(ctx context.Context, catalog *catalogdv1alpha1.Cl
}
remoteOpts = append(remoteOpts, remote.WithTransport(tlsTransport))

// always fetch the hash
imgDesc, err := remote.Head(imgRef, remoteOpts...)
digestHex, err := resolveDigest(imgRef, remoteOpts...)
if err != nil {
return nil, fmt.Errorf("error fetching image descriptor: %w", err)
}
l.V(1).Info("resolved image descriptor", "digest", imgDesc.Digest.String())
l.V(1).Info("resolved image descriptor", "digest", digestHex)

unpackPath := filepath.Join(i.BaseCachePath, catalog.Name, imgDesc.Digest.Hex)
resolvedRef := fmt.Sprintf("%s@sha256:%s", imgRef.Context().Name(), imgDesc.Digest.Hex)
unpackPath := filepath.Join(i.BaseCachePath, catalog.Name, digestHex)
resolvedRef := fmt.Sprintf("%s@sha256:%s", imgRef.Context().Name(), digestHex)
if stat, err := os.Stat(unpackPath); err == nil && stat.IsDir() {
l.V(1).Info("found image in filesystem cache", "digest", imgDesc.Digest.Hex)
l.V(1).Info("found image in filesystem cache", "digest", digestHex)
// TODO: https://github.com/operator-framework/catalogd/issues/389
return unpackedResult(os.DirFS(unpackPath), catalog, resolvedRef, metav1.Time{Time: time.Now()}), nil
}
Expand Down Expand Up @@ -137,6 +136,23 @@ func unpackedResult(fsys fs.FS, catalog *catalogdv1alpha1.ClusterCatalog, ref st
}
}

// resolveDigest returns hex value of the digest for image reference
func resolveDigest(imgRef name.Reference, remoteOpts ...remote.Option) (string, error) {
digest, isDigest := imgRef.(name.Digest)
if isDigest {
digestHex := strings.TrimPrefix(digest.DigestStr(), "sha256:")
// If the reference is already a digest - return without making a network call
return digestHex, nil
}

imgDesc, err := remote.Head(imgRef, remoteOpts...)
if err != nil {
return "", err
}

return imgDesc.Digest.Hex, nil
}

// unpackImage unpacks a catalog image reference to the provided unpackPath,
// returning an error if any errors are encountered along the way.
func unpackImage(ctx context.Context, imgRef name.Reference, unpackPath string, remoteOpts ...remote.Option) error {
Expand Down

0 comments on commit 8e71e93

Please sign in to comment.