/
workcache.go
102 lines (84 loc) · 1.94 KB
/
workcache.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
95
96
97
98
99
100
101
102
package workapplier
import (
"crypto/md5"
"encoding/json"
"fmt"
"io"
"sync"
"k8s.io/klog/v2"
workapiv1 "open-cluster-management.io/api/work/v1"
)
type workKey struct {
cluster string
name string
}
type cachedResource struct {
resourceHash string
generation int64
}
type workCache struct {
mutex sync.RWMutex
cache map[workKey]cachedResource
}
func newWorkCache() *workCache {
return &workCache{
cache: map[workKey]cachedResource{},
}
}
func (w *workCache) updateCache(required, existing *workapiv1.ManifestWork) {
if required == nil || existing == nil {
return
}
w.mutex.Lock()
defer w.mutex.Unlock()
key := workKey{
cluster: required.Namespace,
name: required.Name,
}
value := cachedResource{
resourceHash: hashOfResourceStruct(required),
generation: existing.Generation,
}
w.cache[key] = value
}
func (w *workCache) removeCache(name, cluster string) {
key := workKey{
cluster: cluster,
name: name,
}
w.mutex.Lock()
defer w.mutex.Unlock()
delete(w.cache, key)
}
func (w *workCache) safeToSkipApply(required, existing *workapiv1.ManifestWork) bool {
if required == nil || existing == nil {
return false
}
cacheKey := workKey{
cluster: required.Namespace,
name: required.Name,
}
resourceHash := hashOfResourceStruct(required)
generation := existing.Generation
w.mutex.RLock()
defer w.mutex.RUnlock()
var generationMatch, hashMatch bool
if cached, exists := w.cache[cacheKey]; exists {
generationMatch = cached.generation == generation
hashMatch = cached.resourceHash == resourceHash
if generationMatch && hashMatch {
klog.V(4).Infof("found matching generation & manifest hash")
return true
}
}
return false
}
func hashOfResourceStruct(o interface{}) string {
oString, _ := json.Marshal(o)
h := md5.New()
if _, err := io.WriteString(h, string(oString)); err != nil {
klog.Errorf("failed to hash object: %v", err)
}
rval := fmt.Sprintf("%x", h.Sum(nil))
return rval
}