Debian Codegraph @

buildkit/cache/remotecache/azblob/importer.go

raw
1 package azblob
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "sync"
9
10 "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
11 "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
12 "github.com/containerd/containerd/v2/core/content"
13 "github.com/containerd/containerd/v2/pkg/labels"
14 cerrdefs "github.com/containerd/errdefs"
15 "github.com/moby/buildkit/cache/remotecache"
16 v1 "github.com/moby/buildkit/cache/remotecache/v1"
17 "github.com/moby/buildkit/session"
18 "github.com/moby/buildkit/solver"
19 "github.com/moby/buildkit/util/bklog"
20 "github.com/moby/buildkit/util/contentutil"
21 "github.com/moby/buildkit/util/progress"
22 "github.com/moby/buildkit/worker"
23 digest "github.com/opencontainers/go-digest"
24 ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
25 "github.com/pkg/errors"
26 "golang.org/x/sync/errgroup"
27 )
28
29 // ResolveCacheImporterFunc for "azblob" cache importer.
30 func ResolveCacheImporterFunc() remotecache.ResolveCacheImporterFunc {
31 return func(ctx context.Context, g session.Group, attrs map[string]string) (remotecache.Importer, ocispecs.Descriptor, error) {
32 config, err := getConfig(attrs)
33 if err != nil {
34 return nil, ocispecs.Descriptor{}, errors.Wrap(err, "failed to create azblob config")
35 }
36
37 containerClient, err := createContainerClient(ctx, config)
38 if err != nil {
39 return nil, ocispecs.Descriptor{}, errors.Wrap(err, "failed to create container client")
40 }
41
42 importer := &importer{
43 config: config,
44 containerClient: containerClient,
45 }
46
47 return importer, ocispecs.Descriptor{}, nil
48 }
49 }
50
51 var _ remotecache.Importer = &importer{}
52
53 type importer struct {
54 config *Config
55 containerClient *container.Client
56 }
57
58 func (ci *importer) Resolve(ctx context.Context, _ ocispecs.Descriptor, id string, w worker.Worker) (solver.CacheManager, error) {
59 eg, ctx := errgroup.WithContext(ctx)
60 ccs := make([]*v1.CacheChains, len(ci.config.Names))
61
62 for i, name := range ci.config.Names {
63 func(i int, name string) {
64 eg.Go(func() error {
65 cc, err := ci.loadManifest(ctx, name)
66 if err != nil {
67 return errors.Wrapf(err, "failed to load cache manifest %s", name)
68 }
69 ccs[i] = cc
70 return nil
71 })
72 }(i, name)
73 }
74
75 if err := eg.Wait(); err != nil {
76 return nil, err
77 }
78
79 cms := make([]solver.CacheManager, 0, len(ccs))
80
81 for _, cc := range ccs {
82 keysStorage, resultStorage, err := v1.NewCacheKeyStorage(cc, w)
83 if err != nil {
84 return nil, err
85 }
86 cms = append(cms, solver.NewCacheManager(ctx, id, keysStorage, resultStorage))
87 }
88
89 return solver.NewCombinedCacheManager(cms, nil), nil
90 }
91
92 func (ci *importer) loadManifest(ctx context.Context, name string) (*v1.CacheChains, error) {
93 key := manifestKey(ci.config, name)
94 exists, err := blobExists(ctx, ci.containerClient, key)
95 if err != nil {
96 return nil, err
97 }
98
99 bklog.G(ctx).Debugf("name %s cache with key %s exists = %v", name, key, exists)
100
101 if !exists {
102 return v1.NewCacheChains(), nil
103 }
104
105 blobClient := ci.containerClient.NewBlockBlobClient(key)
106
107 res, err := blobClient.DownloadStream(ctx, &blob.DownloadStreamOptions{})
108 if err != nil {
109 return nil, errors.WithStack(err)
110 }
111
112 reader := res.Body
113 defer reader.Close()
114 bytes, err := io.ReadAll(reader)
115 if err != nil {
116 return nil, errors.WithStack(err)
117 }
118
119 bklog.G(ctx).Debugf("imported config: %s", string(bytes))
120
121 var config v1.CacheConfig
122 if err := json.Unmarshal(bytes, &config); err != nil {
123 return nil, errors.WithStack(err)
124 }
125
126 allLayers := v1.DescriptorProvider{}
127 for _, l := range config.Layers {
128 dpp, err := ci.makeDescriptorProviderPair(l)
129 if err != nil {
130 return nil, err
131 }
132 allLayers[l.Blob] = *dpp
133 }
134
135 progress.OneOff(ctx, fmt.Sprintf("found %d layers in cache", len(allLayers)))(nil)
136
137 cc := v1.NewCacheChains()
138 if err := v1.ParseConfig(config, allLayers, cc); err != nil {
139 return nil, err
140 }
141
142 return cc, nil
143 }
144
145 func (ci *importer) makeDescriptorProviderPair(l v1.CacheLayer) (*v1.DescriptorProviderPair, error) {
146 if l.Annotations == nil {
147 return nil, errors.Errorf("cache layer with missing annotations")
148 }
149 annotations := map[string]string{}
150 if l.Annotations.DiffID == "" {
151 return nil, errors.Errorf("cache layer with missing diffid")
152 }
153 annotations[labels.LabelUncompressed] = l.Annotations.DiffID.String()
154 if !l.Annotations.CreatedAt.IsZero() {
155 txt, err := l.Annotations.CreatedAt.MarshalText()
156 if err != nil {
157 return nil, errors.WithStack(err)
158 }
159 annotations["buildkit/createdat"] = string(txt)
160 }
161 desc := ocispecs.Descriptor{
162 MediaType: l.Annotations.MediaType,
163 Digest: l.Blob,
164 Size: l.Annotations.Size,
165 Annotations: annotations,
166 }
167 p := &ciProvider{
168 desc: desc,
169 containerClient: ci.containerClient,
170 Provider: contentutil.FromFetcher(&fetcher{containerClient: ci.containerClient, config: ci.config}),
171 config: ci.config,
172 }
173 return &v1.DescriptorProviderPair{
174 Descriptor: desc,
175 Provider: p,
176 InfoProvider: p,
177 }, nil
178 }
179
180 type fetcher struct {
181 containerClient *container.Client
182 config *Config
183 }
184
185 func (f *fetcher) Fetch(ctx context.Context, desc ocispecs.Descriptor) (io.ReadCloser, error) {
186 key := blobKey(f.config, desc.Digest)
187 exists, err := blobExists(ctx, f.containerClient, key)
188 if err != nil {
189 return nil, err
190 }
191
192 if !exists {
193 return nil, errors.Errorf("blob %s not found", desc.Digest)
194 }
195
196 bklog.G(ctx).Debugf("reading layer from cache: %s", key)
197
198 blobClient := f.containerClient.NewBlockBlobClient(key)
199 res, err := blobClient.DownloadStream(ctx, &blob.DownloadStreamOptions{})
200 if err != nil {
201 return nil, err
202 }
203
204 return res.Body, nil
205 }
206
207 type ciProvider struct {
208 content.Provider
209 desc ocispecs.Descriptor
210 containerClient *container.Client
211 config *Config
212 checkMutex sync.Mutex
213 checked bool
214 }
215
216 func (p *ciProvider) Info(ctx context.Context, dgst digest.Digest) (content.Info, error) {
217 if dgst != p.desc.Digest {
218 return content.Info{}, errors.Wrapf(cerrdefs.ErrNotFound, "blob %s", dgst)
219 }
220
221 if p.checked {
222 return content.Info{
223 Digest: p.desc.Digest,
224 Size: p.desc.Size,
225 }, nil
226 }
227
228 p.checkMutex.Lock()
229 defer p.checkMutex.Unlock()
230
231 key := blobKey(p.config, dgst)
232 exists, err := blobExists(ctx, p.containerClient, key)
233 if err != nil {
234 return content.Info{}, err
235 }
236
237 if !exists {
238 return content.Info{}, errors.Wrapf(cerrdefs.ErrNotFound, "blob %s", dgst)
239 }
240
241 p.checked = true
242 return content.Info{
243 Digest: p.desc.Digest,
244 Size: p.desc.Size,
245 }, nil
246 }