This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 104
/
memory.go
executable file
·1903 lines (1646 loc) · 54.7 KB
/
memory.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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package memory
import (
"flag"
"fmt"
"os"
"regexp"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/grafana/globalconf"
"github.com/grafana/metrictank/conf"
"github.com/grafana/metrictank/errors"
"github.com/grafana/metrictank/expr/tagquery"
"github.com/grafana/metrictank/idx"
"github.com/grafana/metrictank/mdata"
"github.com/grafana/metrictank/schema"
"github.com/grafana/metrictank/stats"
"github.com/grafana/metrictank/util"
log "github.com/sirupsen/logrus"
)
var (
// metric idx.memory.ops.update is the number of updates to the memory idx
statUpdate = stats.NewCounter32("idx.memory.ops.update")
// metric idx.memory.ops.add is the number of additions to the memory idx
statAdd = stats.NewCounter32("idx.memory.ops.add")
// metric idx.memory.add is the duration of a (successful) add of a metric to the memory idx
statAddDuration = stats.NewLatencyHistogram15s32("idx.memory.add")
// metric idx.memory.update is the duration of (successful) update of a metric to the memory idx
statUpdateDuration = stats.NewLatencyHistogram15s32("idx.memory.update")
// metric idx.memory.get is the duration of a get of one metric in the memory idx
statGetDuration = stats.NewLatencyHistogram15s32("idx.memory.get")
// metric idx.memory.list is the duration of memory idx listings
statListDuration = stats.NewLatencyHistogram15s32("idx.memory.list")
// metric idx.memory.find is the duration of memory idx find
statFindDuration = stats.NewLatencyHistogram15s32("idx.memory.find")
// metric idx.memory.delete is the duration of a delete of one or more metrics from the memory idx
statDeleteDuration = stats.NewLatencyHistogram15s32("idx.memory.delete")
// metric idx.memory.prune is the duration of successful memory idx prunes
statPruneDuration = stats.NewLatencyHistogram15s32("idx.memory.prune")
// metric idx.memory.filtered is number of series that have been excluded from responses due to their lastUpdate property
statFiltered = stats.NewCounter32("idx.memory.filtered")
// metric idx.metrics_active is the number of currently known metrics in the index
statMetricsActive = stats.NewGauge32("idx.metrics_active")
Enabled bool
maxPruneLockTime = time.Millisecond * 100
maxPruneLockTimeStr string
TagSupport bool
TagQueryWorkers int // number of workers to spin up when evaluation tag expressions
metaTagEnricherQueueSize = 100
metaTagEnricherBufferSize = 10000
metaTagEnricherBufferTime = 5 * time.Second
indexRulesFile string
IndexRules conf.IndexRules
Partitioned bool
findCacheSize = 1000
findCacheInvalidateQueueSize = 200
findCacheInvalidateMaxSize = 100
findCacheInvalidateMaxWait = 5 * time.Second
findCacheBackoffTime = time.Minute
writeQueueEnabled = false
writeQueueDelay = 30 * time.Second
writeMaxBatchSize = 5000
matchCacheSize = 1000
MetaTagSupport = false
)
func ConfigSetup() *flag.FlagSet {
memoryIdx := flag.NewFlagSet("memory-idx", flag.ExitOnError)
memoryIdx.BoolVar(&Enabled, "enabled", false, "")
memoryIdx.BoolVar(&TagSupport, "tag-support", true, "enables/disables querying based on tags")
memoryIdx.BoolVar(&Partitioned, "partitioned", false, "use separate indexes per partition. experimental feature")
memoryIdx.IntVar(&TagQueryWorkers, "tag-query-workers", 5, "number of workers to spin up to evaluate tag queries")
memoryIdx.IntVar(&metaTagEnricherQueueSize, "meta-tag-enricher-queue-size", 100, "size of event queue in the meta tag enricher")
memoryIdx.IntVar(&metaTagEnricherBufferSize, "meta-tag-enricher-buffer-size", 10000, "size of add metric event buffer in enricher")
memoryIdx.DurationVar(&metaTagEnricherBufferTime, "meta-tag-enricher-buffer-time", time.Second*5, "how long to buffer enricher events before they must be processed")
memoryIdx.IntVar(&findCacheSize, "find-cache-size", 1000, "number of find expressions to cache (per org). 0 disables cache")
memoryIdx.IntVar(&findCacheInvalidateQueueSize, "find-cache-invalidate-queue-size", 200, "size of queue for invalidating findCache entries")
memoryIdx.IntVar(&findCacheInvalidateMaxSize, "find-cache-invalidate-max-size", 100, "max amount of invalidations to queue up in one batch")
memoryIdx.BoolVar(&writeQueueEnabled, "write-queue-enabled", false, "enable buffering new metricDefinitions and writing them to the index in batches")
memoryIdx.DurationVar(&writeQueueDelay, "write-queue-delay", 30*time.Second, "maximum delay between flushing buffered metric writes to the index")
memoryIdx.IntVar(&writeMaxBatchSize, "write-max-batch-size", 5000, "maximum number of metricDefinitions that can be added to the index in a single batch")
memoryIdx.DurationVar(&findCacheInvalidateMaxWait, "find-cache-invalidate-max-wait", 5*time.Second, "max duration to wait building up a batch to invalidate")
memoryIdx.DurationVar(&findCacheBackoffTime, "find-cache-backoff-time", time.Minute, "amount of time to disable the findCache when the invalidate queue fills up.")
memoryIdx.StringVar(&indexRulesFile, "rules-file", "/etc/metrictank/index-rules.conf", "path to index-rules.conf file")
memoryIdx.StringVar(&maxPruneLockTimeStr, "max-prune-lock-time", "100ms", "Maximum duration each second a prune job can lock the index.")
memoryIdx.IntVar(&matchCacheSize, "match-cache-size", 1000, "size of regular expression cache in tag query evaluation")
memoryIdx.BoolVar(&MetaTagSupport, "meta-tag-support", false, "enables/disables querying based on meta tags which get defined via meta tag rules")
globalconf.Register("memory-idx", memoryIdx, flag.ExitOnError)
return memoryIdx
}
func ConfigProcess() {
var err error
maxPruneLockTime, err = time.ParseDuration(maxPruneLockTimeStr)
if err != nil {
log.Fatalf("could not parse max-prune-lock-time %q: %s", maxPruneLockTimeStr, err)
}
if maxPruneLockTime > time.Second {
log.Fatalf("invalid max-prune-lock-time of %s. Must be <= 1 second", maxPruneLockTimeStr)
}
// read index-rules.conf
IndexRules, err = conf.ReadIndexRules(indexRulesFile)
if os.IsNotExist(err) {
log.Infof("Index-rules.conf file %s does not exist; using defaults", indexRulesFile)
IndexRules = conf.NewIndexRules()
} else if err != nil {
log.Fatalf("can't read index-rules file %q: %s", indexRulesFile, err.Error())
}
if findCacheInvalidateMaxSize >= findCacheInvalidateQueueSize {
log.Fatal("find-cache-invalidate-max-size should be smaller than find-cache-invalidate-queue-size")
}
if MetaTagSupport && !TagSupport {
log.Fatal("To enable meta tag support it is required to also enable tag support")
}
tagquery.MetaTagSupport = MetaTagSupport
tagquery.MatchCacheSize = matchCacheSize
}
// interface implemented by both UnpartitionedMemoryIdx and PartitionedMemoryIdx
// this is needed to support unit tests.
type MemoryIndex interface {
idx.MetricIndex
idx.MetaRecordIdx
LoadPartition(int32, []schema.MetricDefinition) int
UpdateArchiveLastSave(schema.MKey, int32, uint32)
add(*idx.Archive)
PurgeFindCache()
ForceInvalidationFindCache()
}
func New() MemoryIndex {
if Partitioned {
return NewPartitionedMemoryIdx()
}
return NewUnpartitionedMemoryIdx()
}
type Tree struct {
Items map[string]*Node // key is the full path of the node.
}
type IdSet map[schema.MKey]struct{} // set of ids
func (ids IdSet) String() string {
var res string
for id := range ids {
if len(res) > 0 {
res += " "
}
res += id.String()
}
return res
}
type TagValues map[string]IdSet // value -> set of ids
type TagIndex map[string]TagValues // key -> list of values
func (t *TagIndex) addTagId(name, value string, id schema.MKey) {
ti := *t
if _, ok := ti[name]; !ok {
ti[name] = make(TagValues)
}
if _, ok := ti[name][value]; !ok {
ti[name][value] = make(IdSet)
}
ti[name][value][id] = struct{}{}
}
func (t *TagIndex) delTagId(name, value string, id schema.MKey) {
ti := *t
delete(ti[name][value], id)
if len(ti[name][value]) == 0 {
delete(ti[name], value)
if len(ti[name]) == 0 {
delete(ti, name)
}
}
}
// org id -> nameWithTags -> Set of references to schema.MetricDefinition
// nameWithTags is the name plus all tags in the <name>;<tag>=<value>... format.
type defByTagSet map[uint32]map[string]map[*schema.MetricDefinition]struct{}
func (t TagIndex) idHasTag(id schema.MKey, tag, value string) bool {
_, ok := t[tag][value][id]
return ok
}
func (defs defByTagSet) add(def *schema.MetricDefinition) {
var orgDefs map[string]map[*schema.MetricDefinition]struct{}
var ok bool
if orgDefs, ok = defs[def.OrgId]; !ok {
orgDefs = make(map[string]map[*schema.MetricDefinition]struct{})
defs[def.OrgId] = orgDefs
}
fullName := def.NameWithTags()
if _, ok = orgDefs[fullName]; !ok {
orgDefs[fullName] = make(map[*schema.MetricDefinition]struct{}, 1)
}
orgDefs[fullName][def] = struct{}{}
}
func (defs defByTagSet) del(def *schema.MetricDefinition) {
var orgDefs map[string]map[*schema.MetricDefinition]struct{}
var ok bool
if orgDefs, ok = defs[def.OrgId]; !ok {
return
}
fullName := def.NameWithTags()
delete(orgDefs[fullName], def)
if len(orgDefs[fullName]) == 0 {
delete(orgDefs, fullName)
}
if len(orgDefs) == 0 {
delete(defs, def.OrgId)
}
}
func (defs defByTagSet) defs(id uint32, fullName string) map[*schema.MetricDefinition]struct{} {
var orgDefs map[string]map[*schema.MetricDefinition]struct{}
var ok bool
if orgDefs, ok = defs[id]; !ok {
return nil
}
return orgDefs[fullName]
}
type Node struct {
Path string // branch or NameWithTags for leafs
Children []string
Defs []schema.MKey
}
func (n *Node) HasChildren() bool {
return len(n.Children) > 0
}
func (n *Node) Leaf() bool {
return len(n.Defs) > 0
}
func (n *Node) String() string {
if n.Leaf() {
return fmt.Sprintf("leaf - %s", n.Path)
}
return fmt.Sprintf("branch - %s", n.Path)
}
type UnpartitionedMemoryIdx struct {
sync.RWMutex
*metaTagIdx
// used for both hierarchy and tag index, so includes all MDs, with
// and without tags. It also mixes all orgs into one flat map.
defById map[schema.MKey]*idx.Archive
// used by hierarchy index only
tree map[uint32]*Tree // by orgId
// used by tag index
defByTagSet defByTagSet
tags map[uint32]TagIndex // by orgId
findCache *FindCache
writeQueue *WriteQueue
}
func NewUnpartitionedMemoryIdx() *UnpartitionedMemoryIdx {
m := &UnpartitionedMemoryIdx{
defById: make(map[schema.MKey]*idx.Archive),
defByTagSet: make(defByTagSet),
tree: make(map[uint32]*Tree),
tags: make(map[uint32]TagIndex),
}
if MetaTagSupport {
m.metaTagIdx = newMetaTagIndex(m.idsByTagQueryIntoCallback)
}
return m
}
func (m *UnpartitionedMemoryIdx) Init() error {
if findCacheSize > 0 {
log.Infof("memoryIdx: enabling findCache with with a size of %d items", findCacheSize)
m.findCache = NewFindCache(findCacheSize, findCacheInvalidateQueueSize, findCacheInvalidateMaxSize, findCacheInvalidateMaxWait, findCacheBackoffTime)
}
if writeQueueEnabled {
m.writeQueue = NewWriteQueue(m, writeQueueDelay, writeMaxBatchSize)
}
return nil
}
func (m *UnpartitionedMemoryIdx) Stop() {
if m.findCache != nil {
m.findCache.Shutdown()
m.findCache = nil
}
if m.writeQueue != nil {
m.writeQueue.Stop()
m.writeQueue = nil
}
if MetaTagSupport && m.metaTagIdx != nil {
m.Lock()
m.metaTagIdx.stop()
m.metaTagIdx = nil
m.Unlock()
}
return
}
// bumpLastUpdate increases lastUpdate.
// note:
// * received point may be older than a previously received point, in which case the previous value was correct
// * someone else may have just concurrently updated lastUpdate to a higher value than what we have, which we should restore
// * by the time we look at the previous value and try to restore it, someone else may have updated it to a higher value
// all these scenarios are unlikely but we should accommodate them anyway.
func bumpLastUpdate(loc *int64, newVal int64) {
util.AtomicBumpInt64(loc, newVal)
}
// updates the partition and lastUpdate ts in an archive. Returns the previously set partition
func updateExisting(existing *idx.Archive, partition int32, lastUpdate int64, pre time.Time) int32 {
bumpLastUpdate(&existing.LastUpdate, lastUpdate)
oldPart := atomic.SwapInt32(&existing.Partition, partition)
statUpdate.Inc()
statUpdateDuration.Value(time.Since(pre))
return oldPart
}
// Update updates an existing archive, if found.
// It returns whether it was found, and - if so - the (updated) existing archive and its old partition
func (m *UnpartitionedMemoryIdx) Update(point schema.MetricPoint, partition int32) (idx.Archive, int32, bool) {
pre := time.Now()
m.RLock()
existing, ok := m.defById[point.MKey]
m.RUnlock()
if ok {
if log.IsLevelEnabled(log.DebugLevel) {
log.Debugf("memory-idx: metricDef with id %v already in index", point.MKey)
}
oldPart := updateExisting(existing, partition, int64(point.Time), pre)
return CloneArchive(existing), oldPart, true
}
if m.writeQueue != nil {
// if we are using the writeQueue, then the archive for this MKey might be queued
// and not yet flushed to the index yet.
existing, ok := m.writeQueue.Get(point.MKey)
if ok {
if log.IsLevelEnabled(log.DebugLevel) {
log.Debugf("memory-idx: metricDef with id %v is in the writeQueue", point.MKey)
}
oldPart := updateExisting(existing, partition, int64(point.Time), pre)
return CloneArchive(existing), oldPart, true
}
// we need to do one final check of m.defById, as the writeQueue may have been flushed between
// when we released m.RLock() and when the call to m.writeQueue.Get() was able to obtain its own lock.
m.RLock()
existing, ok = m.defById[point.MKey]
m.RUnlock()
if ok {
if log.IsLevelEnabled(log.DebugLevel) {
log.Debugf("memory-idx: metricDef with id %v already in index", point.MKey)
}
oldPart := updateExisting(existing, partition, int64(point.Time), pre)
return CloneArchive(existing), oldPart, true
}
}
return idx.Archive{}, 0, false
}
// AddOrUpdate returns the corresponding Archive for the MetricData.
// if it is existing -> updates lastUpdate based on .Time, and partition
// if was new -> adds new MetricDefinition to index
func (m *UnpartitionedMemoryIdx) AddOrUpdate(mkey schema.MKey, data *schema.MetricData, partition int32) (idx.Archive, int32, bool) {
pre := time.Now()
// we only need a lock while reading the m.defById map. All future operations on the archive
// use sync/atomic to allow concurrent read/writes
m.RLock()
existing, ok := m.defById[mkey]
m.RUnlock()
if ok {
if log.IsLevelEnabled(log.DebugLevel) {
log.Debugf("memory-idx: metricDef with id %s already in the index", mkey)
}
oldPart := updateExisting(existing, partition, data.Time, pre)
return CloneArchive(existing), oldPart, ok
}
def := schema.MetricDefinitionFromMetricData(data)
def.Partition = partition
archive := createArchive(def)
if m.writeQueue == nil {
// writeQueue not enabled, so acquire a wlock and immediately add to the index.
m.Lock()
m.add(archive)
m.Unlock()
statAddDuration.Value(time.Since(pre))
} else {
// push the new archive into the writeQueue. If there is already an archive in the
// writeQueue with the same mkey, it will be replaced.
m.writeQueue.Queue(archive)
}
return CloneArchive(archive), 0, false
}
// UpdateArchiveLastSave updates the LastSave timestamp of the archive
func (m *UnpartitionedMemoryIdx) UpdateArchiveLastSave(id schema.MKey, partition int32, lastSave uint32) {
m.RLock()
existing, ok := m.defById[id]
m.RUnlock()
if ok {
atomic.StoreUint32(&existing.LastSave, lastSave)
return
}
// The index may not have an entry for the id for the following reasons
// - the MetricDef has just been deleted from the index
// - the metricDef is waiting in the writeQueue and hasnt been added yet
if m.writeQueue != nil {
// if we are using the writeQueue, then the archive for this MKey might be queued
// and not yet flushed to the index yet.
existing, ok = m.writeQueue.Get(id)
if ok {
atomic.StoreUint32(&existing.LastSave, lastSave)
return
}
// we need to do one final check of m.defById, as the writeQueue may have been flushed between
// when we released m.RLock() and when the call to m.writeQueue.Get() was able to obtain its own lock.
m.RLock()
existing, ok = m.defById[id]
m.RUnlock()
if ok {
atomic.StoreUint32(&existing.LastSave, lastSave)
return
}
}
}
// indexTags reads the tags of a given metric definition and creates the
// corresponding tag index entries to refer to it. It assumes a lock is
// already held.
func (m *UnpartitionedMemoryIdx) indexTags(def *schema.MetricDefinition) {
tags, ok := m.tags[def.OrgId]
if !ok {
tags = make(TagIndex)
m.tags[def.OrgId] = tags
}
for _, tag := range def.Tags {
tagSplits := strings.SplitN(tag, "=", 2)
if len(tagSplits) < 2 {
// should never happen because every tag in the index
// must have a valid format
invalidTag.Inc()
log.Errorf("memory-idx: Tag %q of id %q has an invalid format", tag, def.Id)
continue
}
tagName := tagSplits[0]
tagValue := tagSplits[1]
tags.addTagId(tagName, tagValue, def.Id)
}
tags.addTagId("name", def.NameSanitizedAsTagValue(), def.Id)
m.defByTagSet.add(def)
if MetaTagSupport {
m.Unlock()
m.getOrgMetaTagIndex(def.OrgId).enricher.addMetric(*def)
m.Lock()
}
}
// deindexTags takes a given metric definition and removes all references
// to it from the tag index. It assumes a lock is already held.
// a return value of "false" means there was an error and the deindexing was
// unsuccessful, "true" means the indexing was at least partially or completely
// successful
func (m *UnpartitionedMemoryIdx) deindexTags(tags TagIndex, def *schema.MetricDefinition) bool {
for _, tag := range def.Tags {
tagSplits := strings.SplitN(tag, "=", 2)
if len(tagSplits) < 2 {
// should never happen because every tag in the index
// must have a valid format
invalidTag.Inc()
log.Errorf("memory-idx: Tag %q of id %q has an invalid format", tag, def.Id)
continue
}
tagName := tagSplits[0]
tagValue := tagSplits[1]
tags.delTagId(tagName, tagValue, def.Id)
}
tags.delTagId("name", def.NameSanitizedAsTagValue(), def.Id)
m.defByTagSet.del(def)
if MetaTagSupport {
m.Unlock()
m.getOrgMetaTagIndex(def.OrgId).enricher.delMetric(def)
m.Lock()
}
return true
}
// Used to rebuild the index from an existing set of metricDefinitions for a specific paritition.
func (m *UnpartitionedMemoryIdx) LoadPartition(partition int32, defs []schema.MetricDefinition) int {
// UnpartitionedMemoryIdx isnt partitioned, so just ignore the partition passed and call Load()
return m.Load(defs)
}
// Used to rebuild the index from an existing set of metricDefinitions.
func (m *UnpartitionedMemoryIdx) Load(defs []schema.MetricDefinition) int {
m.Lock()
defer m.Unlock()
var pre time.Time
var num int
for i := range defs {
def := &defs[i]
pre = time.Now()
if _, ok := m.defById[def.Id]; ok {
continue
}
m.add(createArchive(def))
// as we are loading the metricDefs from a persistent store, set the lastSave
// to the lastUpdate timestamp. This won't exactly match the true lastSave Timstamp,
// but it will be close enough and it will always be true that the lastSave was at
// or after this time. For metrics that are sent at or close to real time (the typical
// use case), then the value will be within a couple of seconds of the true lastSave.
m.defById[def.Id].LastSave = uint32(def.LastUpdate)
num++
statAddDuration.Value(time.Since(pre))
}
return num
}
func createArchive(def *schema.MetricDefinition) *idx.Archive {
path := def.NameWithTags()
schemaId, _ := mdata.MatchSchema(path, def.Interval)
aggId, _ := mdata.MatchAgg(path)
irId, _ := IndexRules.Match(path)
return &idx.Archive{
MetricDefinition: *def,
SchemaId: schemaId,
AggId: aggId,
IrId: irId,
}
}
func (m *UnpartitionedMemoryIdx) add(archive *idx.Archive) {
// there is a race condition that can lead to an archive being added
// to the writeQueue just after a queued copy of the archive was flushed.
// If that happens, we just do an update lastUpdate instead
if existing, ok := m.defById[archive.Id]; ok {
// We deliberately dont update existing.Partition as any change
// cant be passed back to the caller (cassandraIdx,BigtableIdx).
// If the partition has changed, then the next datapoint will update
// the partition and notify the caller of the change.
bumpLastUpdate(&existing.LastUpdate, archive.LastUpdate)
return
}
statMetricsActive.Inc()
def := &archive.MetricDefinition
path := def.NameWithTags()
if TagSupport {
sort.Strings(def.Tags)
// Even if there are no tags, index at least "name". It's important to use the definition
// in the archive pointer that we add to defById, because the pointers must reference the
// same underlying object in m.defById and m.defByTagSet
m.indexTags(def)
if len(def.Tags) > 0 {
if _, ok := m.defById[def.Id]; !ok {
m.defById[def.Id] = archive
statAdd.Inc()
log.Debugf("memory-idx: adding %s to DefById", path)
}
return
}
}
if m.findCache != nil {
defer func() {
go m.findCache.InvalidateFor(def.OrgId, path)
}()
}
//first check to see if a tree has been created for this OrgId
tree, ok := m.tree[def.OrgId]
if !ok || len(tree.Items) == 0 {
log.Debugf("memory-idx: first metricDef seen for orgId %d", def.OrgId)
root := &Node{
Path: "",
Children: make([]string, 0),
Defs: make([]schema.MKey, 0),
}
m.tree[def.OrgId] = &Tree{
Items: map[string]*Node{"": root},
}
tree = m.tree[def.OrgId]
} else {
// now see if there is an existing branch or leaf with the same path.
// An existing leaf is possible if there are multiple metricDefs for the same path due
// to different tags or interval
if node, ok := tree.Items[path]; ok {
log.Debugf("memory-idx: existing index entry for %s. Adding %s to Defs list", path, def.Id)
node.Defs = append(node.Defs, def.Id)
m.defById[def.Id] = archive
statAdd.Inc()
return
}
}
pos := strings.LastIndex(path, ".")
// now walk backwards through the node path to find the first branch which exists that
// this path extends.
prevPos := len(path)
for pos != -1 {
branch := path[:pos]
prevNode := path[pos+1 : prevPos]
if n, ok := tree.Items[branch]; ok {
log.Debugf("memory-idx: adding %s as child of %s", prevNode, n.Path)
n.Children = append(n.Children, prevNode)
break
}
log.Debugf("memory-idx: creating branch %s with child %s", branch, prevNode)
tree.Items[branch] = &Node{
Path: branch,
Children: []string{prevNode},
Defs: make([]schema.MKey, 0),
}
prevPos = pos
pos = strings.LastIndex(branch, ".")
}
if pos == -1 {
// need to add to the root node.
branch := path[:prevPos]
log.Debugf("memory-idx: no existing branches found for %s. Adding to the root node.", branch)
n := tree.Items[""]
n.Children = append(n.Children, branch)
}
// Add leaf node
log.Debugf("memory-idx: creating leaf %s", path)
tree.Items[path] = &Node{
Path: path,
Children: []string{},
Defs: []schema.MKey{def.Id},
}
m.defById[def.Id] = archive
statAdd.Inc()
return
}
func (m *UnpartitionedMemoryIdx) Get(id schema.MKey) (idx.Archive, bool) {
pre := time.Now()
m.RLock()
defer m.RUnlock()
def, ok := m.defById[id]
statGetDuration.Value(time.Since(pre))
if ok {
return CloneArchive(def), ok
}
return idx.Archive{}, ok
}
// GetPath returns the node under the given org and path.
// this is an alternative to Find for when you have a path, not a pattern, and want to lookup in a specific org tree only.
func (m *UnpartitionedMemoryIdx) GetPath(orgId uint32, path string) []idx.Archive {
m.RLock()
defer m.RUnlock()
tree, ok := m.tree[orgId]
if !ok {
return nil
}
node := tree.Items[path]
if node == nil {
return nil
}
archives := make([]idx.Archive, len(node.Defs))
for i, def := range node.Defs {
archive := m.defById[def]
archives[i] = CloneArchive(archive)
}
return archives
}
func (m *UnpartitionedMemoryIdx) FindByTag(orgId uint32, query tagquery.Query) []idx.Node {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil
}
var metaTagIdx *orgMetaTagIdx
if MetaTagSupport {
metaTagIdx = m.getOrgMetaTagIndex(orgId)
if metaTagIdx.enricher.countMetricsWithMetaTags() == 0 {
metaTagIdx = nil
}
}
resCh := make(chan schema.MKey, 100)
m.RLock()
// construct the output slice of idx.Node's such that there is only 1 idx.Node for each path
m.idsByTagQuery(orgId, query, resCh, true)
byPath := make(map[string]*idx.Node)
for id := range resCh {
def, ok := m.defById[id]
if !ok {
corruptIndex.Inc()
log.Errorf("memory-idx: corrupt. ID %q has been given, but it is not in the byId lookup table", id)
continue
}
nameWithTags := def.NameWithTags()
if existing, ok := byPath[nameWithTags]; !ok {
byPath[nameWithTags] = &idx.Node{
Path: nameWithTags,
Leaf: true,
HasChildren: false,
Defs: []idx.Archive{CloneArchive(def)},
}
if metaTagIdx != nil {
byPath[nameWithTags].MetaTags = metaTagIdx.getMetaTagsById(def.Id.Key)
}
} else {
existing.Defs = append(existing.Defs, CloneArchive(def))
}
}
m.RUnlock()
results := make([]idx.Node, len(byPath))
i := 0
for _, v := range byPath {
results[i] = *v
i++
}
return results
}
func (m *UnpartitionedMemoryIdx) FindTerms(orgID uint32, tags []string, query tagquery.Query) (uint32, map[string]map[string]uint32) {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return 0, nil
}
needsName := false
terms := make(map[string]map[string]uint32)
for _, tag := range tags {
if tag == "name" {
needsName = true
}
terms[tag] = make(map[string]uint32)
}
resCh := make(chan schema.MKey, 100)
m.RLock()
// construct the output slice of idx.Node's such that there is only 1 idx.Node for each path
m.idsByTagQuery(orgID, query, resCh, true)
var totalResults uint32
for id := range resCh {
def, ok := m.defById[id]
if !ok {
corruptIndex.Inc()
log.Errorf("memory-idx: corrupt. ID %q has been given, but it is not in the byId lookup table", id)
continue
}
totalResults++
for _, tag := range def.Tags {
tagValue := strings.SplitN(tag, "=", 2)
if len(tagValue) < 2 {
// should never happen because invalid tags should get rejected at ingestion
corruptIndex.Inc()
log.Errorf("memory-idx: tag \"%s\" is invalid because it has no \"=\"", tag)
continue
}
if tagTerm, ok := terms[tagValue[0]]; ok {
tagTerm[tagValue[1]]++
}
}
if needsName {
terms["name"][def.Name]++
}
}
m.RUnlock()
return totalResults, terms
}
// Tags returns a list of all tag keys associated with the metrics of a given
// organization. The return values are filtered by the regex in the second parameter.
func (m *UnpartitionedMemoryIdx) Tags(orgId uint32, filter *regexp.Regexp) []string {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil
}
m.RLock()
tags, ok := m.tags[orgId]
if !ok {
m.RUnlock()
return nil
}
var res []string
res = make([]string, 0, len(tags))
for tag := range tags {
// filter by pattern if one was given
if filter != nil && !filter.MatchString(tag) {
continue
}
res = append(res, tag)
}
m.RUnlock()
if !MetaTagSupport {
sort.Strings(res)
return res
}
res = append(res, m.getOrgMetaTagIndex(orgId).hierarchy.getTagsByFilter(filter)...)
sort.Strings(res)
return res
}
func (m *UnpartitionedMemoryIdx) TagDetails(orgId uint32, key string, filter *regexp.Regexp) map[string]uint64 {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil
}
m.RLock()
tags, ok := m.tags[orgId]
if !ok {
m.RUnlock()
return nil
}
res := make(map[string]uint64)
for value, ids := range tags[key] {
if filter != nil && !filter.MatchString(value) {
continue
}
res[value] += uint64(len(ids))
}
if !MetaTagSupport {
m.RUnlock()
return res
}
metaTagIdx := m.getOrgMetaTagIndex(orgId)
for value, recordIds := range metaTagIdx.hierarchy.getTagValuesByRegex(key, filter) {
for _, recordId := range recordIds {
record, ok := metaTagIdx.records.getMetaRecordById(recordId)
if !ok {
continue
}
query, err := tagquery.NewQuery(record.Expressions, 0)
if err != nil {
corruptIndex.Inc()
log.Errorf("memory-idx: corrupt. record expressions cannot instantiate query: %+v results in %s", record.Expressions, err)
continue
}
resCh := make(chan schema.MKey, 100)
m.idsByTagQuery(orgId, query, resCh, false)
for range resCh {
res[value]++
}
}
}
m.RUnlock()
return res
}
// FindTags returns tags matching the specified conditions
// prefix: prefix match
// limit: the maximum number of results to return
//
// the results will always be sorted alphabetically for consistency
func (m *UnpartitionedMemoryIdx) FindTags(orgId uint32, prefix string, limit uint) []string {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil
}
m.RLock()
tags, ok := m.tags[orgId]
if !ok {
m.RUnlock()
return nil
}
// probably allocating more than necessary, still better than growing
res := make([]string, 0, len(tags))
for tag := range tags {
// a tag gets appended to the result set if either the given prefix is
// empty or the tag has the given prefix
if len(prefix) == 0 || strings.HasPrefix(tag, prefix) {
res = append(res, tag)
}
}
m.RUnlock()
if !MetaTagSupport {
return m.finalizeResult(res, limit, false)
}
metaTags := m.getOrgMetaTagIndex(orgId).hierarchy.getTagsByPrefix(prefix)
if len(metaTags) == 0 {
return m.finalizeResult(res, limit, false)
}
return m.finalizeResult(append(res, metaTags...), limit, true)
}
// FindTagsWithQuery returns tags matching the specified conditions
// query: tagdb query to run on the index
// limit: the maximum number of results to return
//
// the results will always be sorted alphabetically for consistency
func (m *UnpartitionedMemoryIdx) FindTagsWithQuery(orgId uint32, prefix string, query tagquery.Query, limit uint) []string {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil
}
var metaTagIdx *orgMetaTagIdx
if MetaTagSupport {
metaTagIdx = m.getOrgMetaTagIndex(orgId)
if metaTagIdx.enricher.countMetricsWithMetaTags() == 0 {
// if the enricher is empty we set the index back to nil so it doesn't even get called
metaTagIdx = nil