/
hobscache.go
223 lines (199 loc) · 5.64 KB
/
hobscache.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package hob
import (
"encoding/json"
"math/rand"
"sync"
"time"
log "github.com/cihub/seelog"
"github.com/jpillora/backoff"
"github.com/stretchr/testify/mock"
"github.com/hailo-platform/H2O/platform/multiclient"
"github.com/hailo-platform/H2O/platform/server"
"github.com/hailo-platform/H2O/go-service-layer/config"
)
var (
memoryCacheImpl map[string]*HobData = make(map[string]*HobData) // map[LON] to *HobData of London
)
type HobsCache interface {
ReadHob(hob string) *Hob
ReadServiceTypes(hob string) ServiceTypes
}
type HobData struct {
Hob *Hob `json:"hob"`
HobHash string `json:"hobHash"`
ServiceTypes ServiceTypes `json:"serviceTypes"`
ServiceTypesHash string `json:"serviceTypesHash"`
}
type MockHobsCache struct {
mock.Mock
}
func (c *MockHobsCache) ReadHob(hob string) *Hob {
ret := c.Mock.Called(hob)
return ret.Get(0).(*Hob)
}
func (c *MockHobsCache) ReadServiceTypes(hob string) ServiceTypes {
ret := c.Mock.Called(hob)
return ret.Get(0).(ServiceTypes)
}
type cache struct {
initRefresher sync.Once
mtx sync.RWMutex
rnd *rand.Rand
scopeFrom multiclient.Scoper
refresh chan string
backoff *backoff.Backoff
}
func MemoryHobsCache() HobsCache {
return &cache{
rnd: rand.New(rand.NewSource(time.Now().UTC().UnixNano())),
scopeFrom: server.Scoper(),
refresh: make(chan string, 10),
backoff: &backoff.Backoff{
Min: failedMinLoadRetry,
Max: failedMaxLoadRetry,
Factor: failedLoadRetryFactor,
Jitter: true,
},
}
}
func (c *cache) ReadHob(hob string) *Hob {
log.Debugf("cache.ReadHob for hob:%v", hob)
hobData := c.readHobDataFromCache(hob)
if hobData != nil {
return hobData.Hob
} // else
return nil
}
func (c *cache) ReadServiceTypes(hob string) ServiceTypes {
log.Debugf("cache.ReadServiceTypes for hob:%v", hob)
hobData := c.readHobDataFromCache(hob)
if hobData != nil {
return hobData.ServiceTypes
} // else
return nil
}
func (c *cache) readHobDataFromCache(hob string) *HobData {
// Read the hobData from memcache
c.mtx.RLock()
readHob, ok := memoryCacheImpl[hob]
c.mtx.RUnlock()
if ok && readHob != nil {
return readHob
} // else
c.mtx.Lock()
readHob, ok = memoryCacheImpl[hob] // double check the values after acquiring the lock
if !ok {
memoryCacheImpl[hob] = nil
}
c.mtx.Unlock()
if ok && readHob != nil {
return readHob
}
// we added a new hob that is not cached, run the multiconfig load of all the known the hobs
c.initRefresher.Do(c.scheduleReloadPeriodically)
go func() {
if len(c.refresh) == 0 {
c.refresh <- hob
}
}()
return nil
}
func (c *cache) scheduleReloadPeriodically() {
go c.reloadPeriodically()
}
func (c *cache) reloadPeriodically() {
ch := config.SubscribeChanges()
log.Infof("Scheduling reload")
tick := time.NewTicker(time.Duration(int64(forceReloadPeriod) + int64(c.jitter(forceReloadJitter))))
for {
select {
case <-tick.C:
log.Debugf("Config reload triggered by timer")
case <-ch:
log.Debugf("Config reload triggered by config notification")
// add some jitter
time.Sleep(c.jitter(triggerReloadJitter))
case hob, ok := <-c.refresh:
log.Debugf("Config reload triggered by query for new hob:%s ok:%v", hob, ok)
}
knownHobs, hobHashes, serviceTypesHashes := c.createMultiConfigParams()
if len(knownHobs) == 0 {
log.Warnf("got no hobs in knownHobs list")
continue
}
// block until we have loaded
for {
if err := c.readMulticonfig(knownHobs, hobHashes, serviceTypesHashes); err != nil {
if c.backoff.Attempt() > reloadMaxRetryAttempts {
break
}
time.Sleep(c.backoff.Duration())
continue
}
break
}
c.backoff.Reset()
}
}
func (c *cache) createMultiConfigParams() ([]string, []string, []string) {
c.mtx.RLock()
defer c.mtx.RUnlock()
knownHobsCount := len(memoryCacheImpl)
hobs := make([]string, knownHobsCount)
hobHashes := make([]string, knownHobsCount)
serviceTypesHashes := make([]string, knownHobsCount)
i := 0
for hob, hobData := range memoryCacheImpl {
hobHash := ""
serviceTypesHash := ""
if hobData != nil {
hobHash = hobData.HobHash
serviceTypesHash = hobData.ServiceTypesHash
}
hobs[i] = hob
hobHashes[i] = hobHash
serviceTypesHashes[i] = serviceTypesHash
i++
}
return hobs, hobHashes, serviceTypesHashes
}
func (c *cache) jitter(j time.Duration) time.Duration {
return time.Duration(int64(c.rnd.Float64() * float64(j)))
}
func (c *cache) readMulticonfig(hobs, hobHashes, serviceTypesHashes []string) error {
log.Debugf("running hobservice.multiconfig with hobs:%v, hobHashes:%v, serviceTypeHashes:%v", hobs, hobHashes, serviceTypesHashes)
newHobs, newHobsConfigs, newHobsHashes, newServiceTypesConfigs, newServiceTypesHashes, err := h2HobService.Multiconfig(hobs, hobHashes, serviceTypesHashes)
if err != nil {
return err
}
c.mtx.Lock()
defer c.mtx.Unlock()
for i, hob := range newHobs {
hData := memoryCacheImpl[hob]
if hData == nil {
hData = &HobData{}
}
if len(newHobsConfigs[i]) > 0 {
h := &Hob{}
err := json.Unmarshal([]byte(newHobsConfigs[i]), h)
if err != nil {
log.Errorf("error unmarshalling hob:%v err:%v", hob, err)
return err
}
hData.Hob = h
hData.HobHash = newHobsHashes[i]
}
if len(newServiceTypesConfigs[i]) > 0 {
serviceTypes := make(ServiceTypes)
err := json.Unmarshal([]byte(newServiceTypesConfigs[i]), &serviceTypes)
if err != nil {
log.Errorf("error unmarshalling serviceTypes:%v serviceTypes:%v\n trying to unmarshal:%v", hob, err, newServiceTypesConfigs[i])
return err
}
hData.ServiceTypes = serviceTypes
hData.ServiceTypesHash = newServiceTypesHashes[i]
}
memoryCacheImpl[hob] = hData
}
return nil
}