Debian Codegraph @

buildkit/cache/remotecache/v1/chains.go

raw
1 package cacheimport
2
3 import (
4 "context"
5 "encoding/binary"
6 "maps"
7 "slices"
8 "strings"
9 "unique"
10
11 "github.com/cespare/xxhash/v2"
12 "github.com/containerd/containerd/v2/core/content"
13 cerrdefs "github.com/containerd/errdefs"
14 "github.com/moby/buildkit/session"
15 "github.com/moby/buildkit/solver"
16 digest "github.com/opencontainers/go-digest"
17 ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
18 "github.com/pkg/errors"
19 )
20
21 func NewCacheChains() *CacheChains {
22 return &CacheChains{roots: map[digest.Digest]*item{}}
23 }
24
25 type CacheChains struct {
26 roots map[digest.Digest]*item
27 }
28
29 var _ solver.CacheExporterTarget = &CacheChains{}
30
31 func (c *CacheChains) computeIDs() {
32 for it := range c.leaves() {
33 it.computeID()
34 }
35 }
36
37 func (c *CacheChains) leaves() map[*item]struct{} {
38 leafs := map[*item]struct{}{}
39 visited := map[*item]struct{}{}
40 for _, it := range c.roots {
41 it.walkChildren(func(i *item) error {
42 if len(i.children) == 0 {
43 leafs[i] = struct{}{}
44 }
45 return nil
46 }, visited)
47 }
48 return leafs
49 }
50
51 func (c *CacheChains) Add(dgst digest.Digest, deps [][]solver.CacheLink, results []solver.CacheExportResult) (solver.CacheExporterRecord, bool, error) {
52 if strings.HasPrefix(dgst.String(), "random:") {
53 return nil, false, nil
54 }
55 r := &item{
56 dgst: dgst,
57 results: results,
58 cc: c,
59 }
60
61 if len(deps) == 0 {
62 if prev, ok := c.roots[dgst]; ok {
63 r = prev
64 }
65 for _, rr := range results {
66 r.addResult(rr)
67 }
68 c.roots[dgst] = r
69 return r, true, nil
70 }
71
72 matchDeps := make([]func() map[*item]struct{}, len(deps))
73 for i, dd := range deps {
74 if len(dd) == 0 {
75 return nil, false, errors.Errorf("empty dependency for %s", dgst)
76 }
77 type itemWithSelector struct {
78 Src *item
79 Selector string
80 }
81 items := make([]itemWithSelector, len(dd))
82 for ii, d := range dd {
83 it, ok := d.Src.(*item)
84 if !ok {
85 return nil, false, errors.Errorf("invalid dependency type %T for %s", d.Src, dgst)
86 }
87 if it.cc != c {
88 return nil, false, errors.Errorf("dependency %s is not part of the same cache chain", it.dgst)
89 }
90 items[ii] = itemWithSelector{
91 Src: it,
92 Selector: d.Selector,
93 }
94 }
95 matchDeps[i] = func() map[*item]struct{} {
96 candidates := map[*item]struct{}{}
97 for _, it := range items {
98 maps.Copy(candidates, it.Src.children[unique.Make(linkv2{
99 selector: it.Selector,
100 index: i,
101 digest: dgst,
102 })])
103 }
104 return candidates
105 }
106 }
107 items := IntersectAll(matchDeps)
108
109 if len(items) > 1 {
110 var main *item
111 for it := range items {
112 main = it
113 break
114 }
115 for it := range items {
116 if it == main {
117 continue
118 }
119 for l, m := range it.children {
120 if main.children == nil {
121 main.children = map[unique.Handle[linkv2]]map[*item]struct{}{}
122 }
123 if _, ok := main.children[l]; !ok {
124 main.children[l] = map[*item]struct{}{}
125 }
126 for ch := range m {
127 main.children[l][ch] = struct{}{}
128 for i, links := range ch.parents {
129 newlinks := map[link]struct{}{}
130 for l := range links {
131 if l.src == it {
132 l.src = main
133 }
134 newlinks[l] = struct{}{}
135 }
136 ch.parents[i] = newlinks
137 }
138 }
139 }
140 for _, rr := range it.results {
141 main.addResult(rr)
142 }
143 }
144 items = map[*item]struct{}{main: {}}
145 }
146
147 for it := range items {
148 r = it
149 for _, rr := range results {
150 r.addResult(rr)
151 }
152
153 // make sure that none of the deps are children of r
154 allChildren := map[*item]struct{}{}
155 if err := r.walkChildren(func(i *item) error {
156 allChildren[i] = struct{}{}
157 return nil
158 }, map[*item]struct{}{}); err != nil {
159 return nil, false, errors.Wrapf(err, "failed to walk children of %s", dgst)
160 }
161 for i, dd := range deps {
162 for j, d := range dd {
163 if _, ok := allChildren[d.Src.(*item)]; ok {
164 deps[i][j].Src = nil
165 }
166 }
167 }
168 break
169 }
170 for i, dd := range deps {
171 for _, d := range dd {
172 if d.Src == nil {
173 continue
174 }
175 d.Src.(*item).addChild(r, i, d.Selector)
176 }
177 }
178 return r, true, nil
179 }
180
181 func IntersectAll[T comparable](
182 funcs []func() map[T]struct{},
183 ) map[T]struct{} {
184 if len(funcs) == 0 {
185 return nil
186 }
187
188 intersection := funcs[0]()
189
190 for _, f := range funcs[1:] {
191 next := f()
192 for k := range intersection {
193 if _, ok := next[k]; !ok {
194 delete(intersection, k)
195 }
196 }
197 if len(intersection) == 0 {
198 return nil
199 }
200 }
201
202 return intersection
203 }
204
205 // Marshal converts the cache chains structure into a cache config and a
206 // collection of providers for reading the results from.
207 //
208 // Marshal aims to validate, normalize and sort the output to ensure a
209 // consistent digest (since cache configs are typically uploaded and stored in
210 // content-addressable OCI registries).
211 func (c *CacheChains) Marshal(ctx context.Context) (*CacheConfig, DescriptorProvider, error) {
212 st := &marshalState{
213 chainsByID: map[string]int{},
214 descriptors: DescriptorProvider{},
215 recordsByItem: map[*item]int{},
216 }
217
218 for it := range c.leaves() {
219 if err := marshalItem(ctx, it, st); err != nil {
220 return nil, nil, err
221 }
222 }
223
224 cc := CacheConfig{
225 Layers: st.layers,
226 Records: st.records,
227 }
228 sortConfig(&cc)
229
230 return &cc, st.descriptors, nil
231 }
232
233 type DescriptorProvider map[digest.Digest]DescriptorProviderPair
234
235 type DescriptorProviderPair struct {
236 Descriptor ocispecs.Descriptor
237 Provider content.Provider
238 InfoProvider content.InfoProvider
239 }
240
241 func (p DescriptorProviderPair) ReaderAt(ctx context.Context, desc ocispecs.Descriptor) (content.ReaderAt, error) {
242 return p.Provider.ReaderAt(ctx, desc)
243 }
244
245 func (p DescriptorProviderPair) Info(ctx context.Context, dgst digest.Digest) (content.Info, error) {
246 if p.InfoProvider != nil {
247 return p.InfoProvider.Info(ctx, dgst)
248 }
249 if dgst != p.Descriptor.Digest {
250 return content.Info{}, errors.Wrapf(cerrdefs.ErrNotFound, "blob %s", dgst)
251 }
252 return content.Info{
253 Digest: p.Descriptor.Digest,
254 Size: p.Descriptor.Size,
255 }, nil
256 }
257
258 func (p DescriptorProviderPair) UnlazySession(desc ocispecs.Descriptor) session.Group {
259 type unlazySession interface {
260 UnlazySession(ocispecs.Descriptor) session.Group
261 }
262 if cd, ok := p.Provider.(unlazySession); ok {
263 return cd.UnlazySession(desc)
264 }
265 return nil
266 }
267
268 func (p DescriptorProviderPair) SnapshotLabels(descs []ocispecs.Descriptor, index int) map[string]string {
269 type snapshotLabels interface {
270 SnapshotLabels([]ocispecs.Descriptor, int) map[string]string
271 }
272 if cd, ok := p.Provider.(snapshotLabels); ok {
273 return cd.SnapshotLabels(descs, index)
274 }
275 return nil
276 }
277
278 type linkv2 struct {
279 selector string
280 index int
281 digest digest.Digest
282 }
283
284 // item is an implementation of a record in the cache chain. After validation,
285 // normalization and marshalling into the cache config, the item results form
286 // into the "layers", while the digests and the links form into the "records".
287 type item struct {
288 solver.CacheExporterRecordBase
289
290 id string
291
292 // dgst is the unique identifier for each record.
293 // This *roughly* corresponds to an edge (vertex cachekey + index) in the
294 // solver - however, a single vertex can produce multiple unique cache keys
295 // (e.g. fast/slow), so it's a one-to-many relation.
296 dgst digest.Digest
297
298 children map[unique.Handle[linkv2]]map[*item]struct{}
299
300 parents []map[link]struct{}
301
302 results []solver.CacheExportResult
303
304 cc *CacheChains
305 }
306
307 // link is a pointer to an item, with an optional selector.
308 type link struct {
309 src *item
310 selector string
311 }
312
313 func (c *item) addChild(src *item, index int, selector string) {
314 if c.children == nil {
315 c.children = map[unique.Handle[linkv2]]map[*item]struct{}{}
316 }
317 h := unique.Make(linkv2{
318 selector: selector,
319 index: index,
320 digest: src.dgst,
321 })
322 m, ok := c.children[h]
323 if !ok {
324 m = map[*item]struct{}{}
325 c.children[h] = m
326 }
327 if _, ok := m[src]; ok {
328 return
329 }
330 m[src] = struct{}{}
331
332 for index >= len(src.parents) {
333 src.parents = append(src.parents, map[link]struct{}{})
334 }
335 src.parents[index][link{src: c, selector: selector}] = struct{}{}
336 }
337
338 func (c *item) addResult(r solver.CacheExportResult) {
339 var exists bool
340 for _, rr := range c.results {
341 if !rr.CreatedAt.Equal(r.CreatedAt) {
342 continue
343 }
344 if len(rr.Result.Descriptors) != len(r.Result.Descriptors) {
345 continue
346 }
347 for i, d := range rr.Result.Descriptors {
348 if d.Digest != r.Result.Descriptors[i].Digest {
349 continue
350 }
351 }
352 exists = true
353 break
354 }
355 if !exists {
356 c.results = append(c.results, r)
357 }
358 }
359
360 func (c *item) computeID() {
361 if c.id != "" {
362 return
363 }
364
365 if len(c.parents) == 0 {
366 c.id = c.dgst.String()
367 return
368 }
369
370 // deterministic ID
371 h := xxhash.New()
372 h.Write([]byte(c.dgst.String()))
373 h.Write([]byte{0})
374
375 for idx, m := range c.parents {
376 binary.Write(h, binary.LittleEndian, uint32(idx))
377 h.Write([]byte{0})
378 for l := range m {
379 if l.src.id == "" {
380 l.src.computeID()
381 }
382 h.Write([]byte(l.src.id))
383 h.Write([]byte{0})
384 h.Write([]byte(l.selector))
385 h.Write([]byte{0})
386 }
387 }
388 c.id = string(h.Sum(nil))
389 }
390
391 func (c *item) bestResult() *solver.CacheExportResult {
392 if len(c.results) == 0 {
393 return nil
394 }
395 slices.SortFunc(c.results, func(a, b solver.CacheExportResult) int {
396 return b.CreatedAt.Compare(a.CreatedAt)
397 })
398 return &c.results[0]
399 }
400
401 func (c *item) walkChildren(fn func(i *item) error, visited map[*item]struct{}) error {
402 if _, ok := visited[c]; ok {
403 return nil
404 }
405 visited[c] = struct{}{}
406 if err := fn(c); err != nil {
407 return err
408 }
409 for _, ch := range c.children {
410 for it := range ch {
411 if err := it.walkChildren(fn, visited); err != nil {
412 return err
413 }
414 }
415 }
416 return nil
417 }
418
419 func (c *item) walkAllResults(fn func(i *item) error, visited map[*item]struct{}) error {
420 if _, ok := visited[c]; ok {
421 return nil
422 }
423 visited[c] = struct{}{}
424 if err := fn(c); err != nil {
425 return err
426 }
427 for _, links := range c.parents {
428 for l := range links {
429 if err := l.src.walkAllResults(fn, visited); err != nil {
430 return err
431 }
432 }
433 }
434 return nil
435 }