-
Notifications
You must be signed in to change notification settings - Fork 386
/
local_state_cache.go
94 lines (78 loc) · 2.07 KB
/
local_state_cache.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
90
91
92
93
94
package earthfile2llb
import (
"crypto/sha1"
"encoding/binary"
"encoding/hex"
"strings"
"sync"
"github.com/earthly/earthly/util/inodeutil"
"github.com/earthly/earthly/util/llbutil/llbfactory"
"github.com/earthly/earthly/util/llbutil/pllb"
)
// LocalStateCache provides caching of local States
type LocalStateCache struct {
mu sync.Mutex
cache map[string]pllb.State
}
// NewSharedLocalStateCache creates a new local state cache
func NewSharedLocalStateCache() *LocalStateCache {
return &LocalStateCache{
cache: map[string]pllb.State{},
}
}
// getOrConstruct returns a cached pllb.State with the same shared key, or creates a new one
// if it doesn't exist.
func (lsc *LocalStateCache) getOrConstruct(factory llbfactory.Factory) pllb.State {
localFactory, ok := factory.(*llbfactory.LocalFactory)
if !ok {
return factory.Construct()
}
lsc.mu.Lock()
defer lsc.mu.Unlock()
key := localFactory.GetSharedKey()
if st, ok := lsc.cache[key]; ok {
return st
}
st := factory.Construct()
lsc.cache[key] = st
return st
}
func getSharedKeyHintFromInclude(name string, incl []string) string {
h := sha1.New()
b := make([]byte, 8)
addToHash := func(path string) {
h.Write([]byte(path))
inode := inodeutil.GetInodeBestEffort(path)
binary.LittleEndian.PutUint64(b, inode)
h.Write(b)
}
addToHash(name)
for _, path := range incl {
addToHash(path)
}
return hex.EncodeToString(h.Sum(nil))
}
func createIncludePatterns(incl []string) []string {
incl2 := []string{}
for _, inc := range incl {
if inc == "." {
inc = "./*"
} else if strings.HasSuffix(inc, "/.") {
inc = inc[:len(inc)-1] + "*"
}
inc = quoteMeta(inc)
incl2 = append(incl2, inc)
}
return incl2
}
func addIncludePathAndSharedKeyHint(factory llbfactory.Factory, src []string) llbfactory.Factory {
localFactory, ok := factory.(*llbfactory.LocalFactory)
if !ok {
return factory
}
includePatterns := createIncludePatterns(src)
sharedKey := getSharedKeyHintFromInclude(localFactory.GetName(), includePatterns)
return localFactory.
WithInclude(includePatterns).
WithSharedKeyHint(sharedKey)
}