This repository was archived by the owner on Aug 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathfind_cache.go
428 lines (387 loc) · 11.1 KB
/
find_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
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package memory
import (
"strings"
"sync"
"time"
"github.com/grafana/metrictank/schema"
"github.com/grafana/metrictank/stats"
lru "github.com/hashicorp/golang-lru"
log "github.com/sirupsen/logrus"
)
var (
// metric idx.memory.find-cache.ops.hit is a counter of findCache hits
findCacheHit = stats.NewCounterRate32("idx.memory.find-cache.ops.hit")
// metric idx.memory.find-cache.ops.miss is a counter of findCache misses
findCacheMiss = stats.NewCounterRate32("idx.memory.find-cache.ops.miss")
// metric idx.memory.find-cache.backoff is the number of find caches in backoff mode
findCacheBackoff = stats.NewGauge32("idx.memory.find-cache.backoff")
// metric idx.memory.find-cache.entries is the number of entries in the cache
findCacheEntries = stats.NewGauge32("idx.memory.find-cache.entries")
// metric idx.memory.find-cache.invalidation.recv is the number of received invalidation requests
findCacheInvalidationsReceived = stats.NewCounterRate32("idx.memory.find-cache.invalidation.recv")
// metric idx.memory.find-cache.invalidation.exec is the number of executed invalidation requests
findCacheInvalidationsExecuted = stats.NewCounterRate32("idx.memory.find-cache.invalidation.exec")
// metric idx.memory.find-cache.invalidation.drop is the number of dropped invalidation requests
findCacheInvalidationsDropped = stats.NewCounterRate32("idx.memory.find-cache.invalidation.drop")
)
type invalidateRequest struct {
orgId uint32
path string
}
// FindCache is a caching layer for the in-memory index. The cache provides
// per org LRU caches of patterns and the resulting []*Nodes from searches
// on the index. Users should call `InvalidateFor(orgId, path)` when new
// entries are added to, or removed from the index to invalidate any cached
// patterns that match the path.
// `invalidateQueueSize` sets the maximum number of invalidations for
// a specific orgId that can be running at any time. If this number is exceeded
// then the cache for that orgId will be immediately purged and disabled for
// `backoffTime`. This mechanism protects the instance from excessive resource
// usage when a large number of new series are added at once.
type FindCache struct {
size int
invalidateQueueSize int
invalidateMaxSize int
invalidateMaxWait time.Duration
backoffTime time.Duration
shutdown chan struct{}
invalidateReqs chan invalidateRequest
forceInvalidationReq chan struct{}
forceInvalidationResp chan struct{}
cache map[uint32]*lru.Cache
backoff bool
sync.RWMutex
}
func NewFindCache(size, invalidateQueueSize, invalidateMaxSize int, invalidateMaxWait, backoffTime time.Duration) *FindCache {
fc := &FindCache{
size: size,
invalidateQueueSize: invalidateQueueSize,
invalidateMaxSize: invalidateMaxSize,
invalidateMaxWait: invalidateMaxWait,
backoffTime: backoffTime,
shutdown: make(chan struct{}),
invalidateReqs: make(chan invalidateRequest, invalidateQueueSize),
forceInvalidationReq: make(chan struct{}),
forceInvalidationResp: make(chan struct{}),
cache: make(map[uint32]*lru.Cache),
}
go fc.processInvalidateQueue()
go fc.stats()
return fc
}
func (c *FindCache) Get(orgId uint32, pattern string) ([]*Node, bool) {
c.RLock()
cache, ok := c.cache[orgId]
c.RUnlock()
if !ok {
findCacheMiss.Inc()
return nil, ok
}
nodes, ok := cache.Get(pattern)
if !ok {
findCacheMiss.Inc()
return nil, ok
}
findCacheHit.Inc()
return nodes.([]*Node), ok
}
func (c *FindCache) Add(orgId uint32, pattern string, nodes []*Node) {
c.RLock()
cache, ok := c.cache[orgId]
backoff := c.backoff
c.RUnlock()
var err error
if !ok {
// don't init the cache if we are in backoff mode.
if backoff {
return
}
c.Lock()
// re-check. someone else may have added a cache in the meantime.
cache, ok = c.cache[orgId]
if !ok {
cache, err = lru.New(c.size)
if err != nil {
log.Errorf("memory-idx: findCache failed to create lru. err=%s", err)
c.Unlock()
return
}
c.cache[orgId] = cache
}
c.Unlock()
}
cache.Add(pattern, nodes)
}
// Purge clears the cache for the specified orgId
func (c *FindCache) Purge(orgId uint32) {
c.RLock()
cache, ok := c.cache[orgId]
c.RUnlock()
if !ok {
return
}
cache.Purge()
}
// PurgeAll clears the caches for all orgIds
func (c *FindCache) PurgeAll() {
c.RLock()
orgs := make([]uint32, len(c.cache))
i := 0
for k := range c.cache {
orgs[i] = k
i++
}
c.RUnlock()
for _, org := range orgs {
c.Purge(org)
}
}
// InvalidateFor removes entries from the cache for 'orgId'
// that match the provided path. If lots of InvalidateFor calls
// are made at once and we end up with `invalidateQueueSize` concurrent
// goroutines processing the invalidations, we purge the cache and
// disable it for `backoffTime`. Future InvalidateFor calls made during
// the backoff time will then return immediately.
func (c *FindCache) InvalidateFor(orgId uint32, path string) {
c.Lock()
findCacheInvalidationsReceived.Inc()
defer c.Unlock()
if c.backoff {
findCacheInvalidationsDropped.Inc()
return
}
cache, ok := c.cache[orgId]
if !ok || cache.Len() < 1 {
findCacheInvalidationsDropped.Inc()
return
}
req := invalidateRequest{
orgId: orgId,
path: path,
}
select {
case c.invalidateReqs <- req:
default:
c.triggerBackoff()
}
}
// caller must hold lock!
func (c *FindCache) triggerBackoff() {
log.Infof("memory-idx: findCache invalidate-queue full. Disabling cache for %s", c.backoffTime.String())
findCacheBackoff.Inc()
c.backoff = true
time.AfterFunc(c.backoffTime, func() {
findCacheBackoff.Dec()
c.Lock()
c.backoff = false
c.Unlock()
})
c.cache = make(map[uint32]*lru.Cache)
// drain queue
L:
for {
select {
case <-c.invalidateReqs:
default:
break L
}
}
}
func (c *FindCache) forceInvalidation() {
c.forceInvalidationReq <- struct{}{}
<-c.forceInvalidationResp
}
func (c *FindCache) Shutdown() {
close(c.shutdown)
}
func (c *FindCache) stats() {
var prev int
tick := time.NewTicker(2 * time.Second)
for {
select {
case <-tick.C:
size := 0
c.RLock()
for _, cache := range c.cache {
size += cache.Len()
}
c.RUnlock()
// we track and subtract our previous entry, so that this works for
// partitioned index, which has multiple findcaches. want to see
// total entries across them all.
if size > prev {
findCacheEntries.AddUint32(uint32(size - prev))
} else {
findCacheEntries.DecUint32(uint32(prev - size))
}
prev = size
case <-c.shutdown:
tick.Stop()
return
}
}
}
func (c *FindCache) processInvalidateQueue() {
type invalidateBuffer struct {
buffer map[uint32][]invalidateRequest
count uint32
}
timer := time.NewTimer(c.invalidateMaxWait)
buf := invalidateBuffer{
buffer: make(map[uint32][]invalidateRequest),
}
processQueue := func() {
for orgid, reqs := range buf.buffer {
c.RLock()
cache := c.cache[orgid]
c.RUnlock()
// nothing cached for this org. nothing to do
if cache == nil {
findCacheInvalidationsDropped.Inc()
continue
}
// construct a tree including all of the now-invalid paths
// we can then call `find(tree, pattern)` for each pattern in the cache and purge it if it matches the tree
// we can't simply prune all cache keys that equal path or a subtree of it, because
// what's cached are search patterns which may contain wildcards and other expressions
tree := newBareTree()
for _, req := range reqs {
tree.add(req.path)
}
for _, k := range cache.Keys() {
matches, err := find((*Tree)(tree), k.(string))
if err != nil {
log.Errorf("memory-idx: checking if cache key %q matches any of the %d invalid patterns resulted in error: %s", k, len(reqs), err)
}
if err != nil || len(matches) > 0 {
cache.Remove(k)
}
}
findCacheInvalidationsExecuted.Add(len(reqs))
}
// all done, reset the buffer
buf.buffer = make(map[uint32][]invalidateRequest)
buf.count = 0
}
for {
select {
case <-timer.C:
timer.Reset(c.invalidateMaxWait)
if buf.count > 0 {
processQueue()
}
case <-c.forceInvalidationReq:
if !timer.Stop() {
<-timer.C
}
timer.Reset(c.invalidateMaxWait)
if buf.count > 0 {
processQueue()
}
c.forceInvalidationResp <- struct{}{}
case req := <-c.invalidateReqs:
if len(c.invalidateReqs) == c.invalidateQueueSize-1 {
log.Info("memory-idx: findCache invalidation channel was full, clearing findCache") // note: responsibility of InvalidateFor to set up backoff
c.Lock()
c.cache = make(map[uint32]*lru.Cache)
c.Unlock()
buf.buffer = make(map[uint32][]invalidateRequest)
buf.count = 0
continue
}
buf.buffer[req.orgId] = append(buf.buffer[req.orgId], req)
buf.count++
if int(buf.count) >= c.invalidateMaxSize {
if !timer.Stop() {
<-timer.C
}
timer.Reset(c.invalidateMaxWait)
processQueue()
}
case <-c.shutdown:
return
}
}
}
// PurgeFindCache purges the findCaches for all orgIds
func (m *UnpartitionedMemoryIdx) PurgeFindCache() {
if m.findCache != nil {
m.findCache.PurgeAll()
}
}
// ForceInvalidationFindCache forces a full invalidation cycle of the find cache
func (m *UnpartitionedMemoryIdx) ForceInvalidationFindCache() {
if m.findCache != nil {
m.findCache.forceInvalidation()
}
}
// PurgeFindCache purges the findCaches for all orgIds
// across all partitions
func (p *PartitionedMemoryIdx) PurgeFindCache() {
for _, m := range p.Partition {
if m.findCache != nil {
m.findCache.PurgeAll()
}
}
}
// ForceInvalidationFindCache forces a full invalidation cycle of the find cache
func (p *PartitionedMemoryIdx) ForceInvalidationFindCache() {
for _, m := range p.Partition {
if m.findCache != nil {
m.findCache.forceInvalidation()
}
}
}
// BareTree is a Tree that can be used for finds,
// but is incomplete
// (it does not track actual MKey's or multiple Defs with same path)
// so should not be used as an actual index
type bareTree Tree
func newBareTree() *bareTree {
tree := Tree{
Items: map[string]*Node{
"": {},
},
}
return (*bareTree)(&tree)
}
// Add adds the series path,
// creating the nodes for each branch and the leaf node
// based on UnpartitionedMemoryIdx.add() but without all the stuff
// we don't need
func (tree *bareTree) add(path string) {
// if a node already exists under the same path, nothing left to do
if _, ok := tree.Items[path]; ok {
return
}
pos := strings.LastIndex(path, ".")
// now walk backwards through the node path to find the first branch which exists that
// this path extends and add us as a child
// until then, keep adding new intermediate branches
prevPos := len(path)
for pos != -1 {
branch := path[:pos]
prevNode := path[pos+1 : prevPos]
if n, ok := tree.Items[branch]; ok {
n.Children = append(n.Children, prevNode)
break
}
tree.Items[branch] = &Node{
Path: branch,
Children: []string{prevNode},
}
prevPos = pos
pos = strings.LastIndex(branch, ".")
}
if pos == -1 {
// no existing branches found that match. need to add to the root node.
branch := path[:prevPos]
n := tree.Items[""]
n.Children = append(n.Children, branch)
}
// Add leaf node
tree.Items[path] = &Node{
Path: path,
Defs: []schema.MKey{},
}
}