-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
cacheopts.go
89 lines (81 loc) · 2.15 KB
/
cacheopts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package solver
import (
"context"
"github.com/moby/buildkit/util/bklog"
digest "github.com/opencontainers/go-digest"
)
type CacheOpts map[interface{}]interface{}
type cacheOptGetterKey struct{}
func CacheOptGetterOf(ctx context.Context) func(keys ...interface{}) map[interface{}]interface{} {
if v := ctx.Value(cacheOptGetterKey{}); v != nil {
if getter, ok := v.(func(keys ...interface{}) map[interface{}]interface{}); ok {
return getter
}
}
return nil
}
func withAncestorCacheOpts(ctx context.Context, start *state) context.Context {
return context.WithValue(ctx, cacheOptGetterKey{}, func(keys ...interface{}) map[interface{}]interface{} {
keySet := make(map[interface{}]struct{})
for _, k := range keys {
keySet[k] = struct{}{}
}
values := make(map[interface{}]interface{})
walkAncestors(ctx, start, func(st *state) bool {
if st.clientVertex.Error != "" {
// don't use values from cancelled or otherwise error'd vertexes
return false
}
for _, res := range st.op.cacheRes {
if res.Opts == nil {
continue
}
for k := range keySet {
if v, ok := res.Opts[k]; ok {
values[k] = v
delete(keySet, k)
if len(keySet) == 0 {
return true
}
}
}
}
return false
})
return values
})
}
func walkAncestors(ctx context.Context, start *state, f func(*state) bool) {
stack := [][]*state{{start}}
cache := make(map[digest.Digest]struct{})
for len(stack) > 0 {
sts := stack[len(stack)-1]
if len(sts) == 0 {
stack = stack[:len(stack)-1]
continue
}
st := sts[len(sts)-1]
stack[len(stack)-1] = sts[:len(sts)-1]
if st == nil {
continue
}
if _, ok := cache[st.origDigest]; ok {
continue
}
cache[st.origDigest] = struct{}{}
if shouldStop := f(st); shouldStop {
return
}
stack = append(stack, []*state{})
for _, parentDgst := range st.clientVertex.Inputs {
st.solver.mu.RLock()
parent := st.solver.actives[parentDgst]
st.solver.mu.RUnlock()
if parent == nil {
bklog.G(ctx).Warnf("parent %q not found in active job list during cache opt search", parentDgst)
continue
}
stack[len(stack)-1] = append(stack[len(stack)-1], parent)
}
}
}