github.com/GoogleContainerTools/kpt@v1.0.0-beta.50.0.20240520170205-c25345ffcbee/pkg/oci/cache.go (about) 1 // Copyright 2022 The kpt Authors 2 // 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package oci 16 17 import ( 18 "bytes" 19 "context" 20 "fmt" 21 "io" 22 "path/filepath" 23 24 v1 "github.com/google/go-containerregistry/pkg/v1" 25 ) 26 27 // CachedConfigFile fetches ConfigFile making use of the cache 28 // TODO: This should be incorporated into the go-containerregistry, along with replacing a fetcher 29 func (r *Storage) CachedConfigFile(ctx context.Context, imageName imageName) (*v1.ConfigFile, error) { 30 ociImage, err := r.ToRemoteImage(ctx, imageName) 31 if err != nil { 32 return nil, err 33 } 34 35 manifest, err := r.CachedManifest(ctx, ociImage) 36 if err != nil { 37 return nil, fmt.Errorf("error fetching manifest for image: %w", err) 38 } 39 40 digest := manifest.Config.Digest 41 42 fetcher := func() (io.ReadCloser, error) { 43 b, err := ociImage.RawConfigFile() 44 if err != nil { 45 return nil, err 46 } 47 r := bytes.NewReader(b) 48 return io.NopCloser(r), nil 49 } 50 51 f, err := WithCacheFile(filepath.Join(r.cacheDir, "config", digest.String()), fetcher) 52 if err != nil { 53 return nil, err 54 } 55 defer f.Close() 56 57 config, err := v1.ParseConfigFile(f) 58 if err != nil { 59 return nil, fmt.Errorf("error parsing config: %w", err) 60 } 61 return config, nil 62 } 63 64 // CachedManifest fetches Manifest making use of the cache 65 // TODO: This should be incorporated into the go-containerregistry, along with replacing a fetcher 66 func (r *Storage) CachedManifest(_ context.Context, image v1.Image) (*v1.Manifest, error) { 67 digest, err := image.Digest() 68 if err != nil { 69 return nil, fmt.Errorf("cannot get image manifest: %w", err) 70 } 71 72 fetcher := func() (io.ReadCloser, error) { 73 b, err := image.RawManifest() 74 if err != nil { 75 return nil, err 76 } 77 r := bytes.NewReader(b) 78 return io.NopCloser(r), nil 79 } 80 81 f, err := WithCacheFile(filepath.Join(r.cacheDir, "manifest", digest.String()), fetcher) 82 if err != nil { 83 return nil, err 84 } 85 defer f.Close() 86 87 manifest, err := v1.ParseManifest(f) 88 if err != nil { 89 return nil, fmt.Errorf("error parsing manifest: %w", err) 90 } 91 return manifest, nil 92 }