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 pathmemory.go
executable file
·1424 lines (1228 loc) · 36.6 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"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/grafana/metrictank/errors"
"github.com/grafana/metrictank/idx"
"github.com/grafana/metrictank/mdata"
"github.com/grafana/metrictank/stats"
"github.com/raintank/worldping-api/pkg/log"
"github.com/rakyll/globalconf"
"gopkg.in/raintank/schema.v1"
)
var (
LogLevel int
// metric idx.memory.update is the number of updates to the memory idx
statUpdate = stats.NewCounter32("idx.memory.ops.update")
// metric idx.memory.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
matchCacheSize int
TagSupport bool
TagQueryWorkers int // number of workers to spin up when evaluation tag expressions
)
func ConfigSetup() {
memoryIdx := flag.NewFlagSet("memory-idx", flag.ExitOnError)
memoryIdx.BoolVar(&Enabled, "enabled", false, "")
memoryIdx.BoolVar(&TagSupport, "tag-support", false, "enables/disables querying based on tags")
memoryIdx.IntVar(&TagQueryWorkers, "tag-query-workers", 50, "number of workers to spin up to evaluate tag queries")
memoryIdx.IntVar(&matchCacheSize, "match-cache-size", 1000, "size of regular expression cache in tag query evaluation")
globalconf.Register("memory-idx", memoryIdx)
}
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 TagValue map[string]IdSet // value -> set of ids
type TagIndex map[string]TagValue // key -> list of values
func (t *TagIndex) addTagId(name, value string, id schema.MKey) {
ti := *t
if _, ok := ti[name]; !ok {
ti[name] = make(TagValue)
}
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 (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
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)
}
// Implements the the "MetricIndex" interface
type MemoryIdx struct {
sync.RWMutex
// 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
}
func New() *MemoryIdx {
return &MemoryIdx{
defById: make(map[schema.MKey]*idx.Archive),
defByTagSet: make(defByTagSet),
tree: make(map[uint32]*Tree),
tags: make(map[uint32]TagIndex),
}
}
func (m *MemoryIdx) Init() error {
return nil
}
func (m *MemoryIdx) Stop() {
return
}
// 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 *MemoryIdx) Update(point schema.MetricPoint, partition int32) (idx.Archive, int32, bool) {
pre := time.Now()
m.Lock()
defer m.Unlock()
existing, ok := m.defById[point.MKey]
if ok {
oldPart := existing.Partition
if LogLevel < 2 {
log.Debug("metricDef with id %v already in index", point.MKey)
}
existing.LastUpdate = int64(point.Time)
existing.Partition = partition
statUpdate.Inc()
statUpdateDuration.Value(time.Since(pre))
return *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 *MemoryIdx) AddOrUpdate(mkey schema.MKey, data *schema.MetricData, partition int32) (idx.Archive, int32, bool) {
pre := time.Now()
m.Lock()
defer m.Unlock()
existing, ok := m.defById[mkey]
if ok {
oldPart := existing.Partition
log.Debug("metricDef with id %s already in index.", mkey)
existing.LastUpdate = data.Time
existing.Partition = partition
statUpdate.Inc()
statUpdateDuration.Value(time.Since(pre))
return *existing, oldPart, ok
}
def := schema.MetricDefinitionFromMetricData(data)
def.Partition = partition
archive := m.add(def)
statMetricsActive.Inc()
statAddDuration.Value(time.Since(pre))
if TagSupport {
m.indexTags(def)
}
return archive, 0, false
}
// UpdateArchive updates the archive information
func (m *MemoryIdx) UpdateArchive(archive idx.Archive) {
m.Lock()
defer m.Unlock()
if _, ok := m.defById[archive.Id]; !ok {
return
}
*(m.defById[archive.Id]) = archive
}
// 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 *MemoryIdx) 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.Error(3, "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.Name, def.Id)
m.defByTagSet.add(def)
}
// 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 *MemoryIdx) 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.Error(3, "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.Name, def.Id)
m.defByTagSet.del(def)
return true
}
// Used to rebuild the index from an existing set of metricDefinitions.
func (m *MemoryIdx) 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(def)
if TagSupport {
m.indexTags(def)
}
// as we are loading the metricDefs from a persistent store, set the lastSave
// to the lastUpdate timestamp. This wont 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++
statMetricsActive.Inc()
statAddDuration.Value(time.Since(pre))
}
return num
}
func (m *MemoryIdx) add(def *schema.MetricDefinition) idx.Archive {
path := def.NameWithTags()
schemaId, _ := mdata.MatchSchema(path, def.Interval)
aggId, _ := mdata.MatchAgg(path)
sort.Strings(def.Tags)
archive := &idx.Archive{
MetricDefinition: *def,
SchemaId: schemaId,
AggId: aggId,
}
if TagSupport && len(def.Tags) > 0 {
if _, ok := m.defById[def.Id]; !ok {
m.defById[def.Id] = archive
statAdd.Inc()
log.Debug("memory-idx: adding %s to DefById", path)
}
return *archive
}
//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.Debug("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.Debug("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 *archive
}
}
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.Debug("memory-idx: adding %s as child of %s", prevNode, n.Path)
n.Children = append(n.Children, prevNode)
break
}
log.Debug("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.Debug("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.Debug("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 *archive
}
func (m *MemoryIdx) 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 *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 *MemoryIdx) 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] = *archive
}
return archives
}
func (m *MemoryIdx) TagDetails(orgId uint32, key, filter string, from int64) (map[string]uint64, error) {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil, nil
}
var re *regexp.Regexp
if len(filter) > 0 {
if filter[0] != byte('^') {
filter = "^(?:" + filter + ")"
}
var err error
re, err = regexp.Compile(filter)
if err != nil {
return nil, err
}
}
m.RLock()
defer m.RUnlock()
tags, ok := m.tags[orgId]
if !ok {
return nil, nil
}
values, ok := tags[key]
if !ok {
return nil, nil
}
res := make(map[string]uint64)
for value, ids := range values {
if re != nil && !re.MatchString(value) {
continue
}
count := uint64(0)
if from > 0 {
for id := range ids {
def, ok := m.defById[id]
if !ok {
corruptIndex.Inc()
log.Error(3, "memory-idx: corrupt. ID %q is in tag index but not in the byId lookup table", id)
continue
}
if def.LastUpdate < from {
continue
}
count++
}
} else {
count += uint64(len(ids))
}
if count > 0 {
res[value] = count
}
}
return res, nil
}
// FindTags returns tags matching the specified conditions
// prefix: prefix match
// expressions: tagdb expressions in the same format as graphite
// from: tags must have at least one metric with LastUpdate >= from
// limit: the maximum number of results to return
//
// the results will always be sorted alphabetically for consistency
func (m *MemoryIdx) FindTags(orgId uint32, prefix string, expressions []string, from int64, limit uint) ([]string, error) {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil, nil
}
var res []string
// only if expressions are specified we need to build a tag query.
// otherwise, the generation of the result set is much simpler
if len(expressions) > 0 {
// incorporate the tag prefix into the tag query expressions
if len(prefix) > 0 {
expressions = append(expressions, "__tag^="+prefix)
}
query, err := NewTagQuery(expressions, from)
if err != nil {
return nil, err
}
// only acquire lock after we're sure the query is valid
m.RLock()
defer m.RUnlock()
tags, ok := m.tags[orgId]
if !ok {
return nil, nil
}
resMap := query.RunGetTags(tags, m.defById)
for tag := range resMap {
res = append(res, tag)
}
sort.Strings(res)
if uint(len(res)) > limit {
res = res[:limit]
}
} else {
m.RLock()
defer m.RUnlock()
tags, ok := m.tags[orgId]
if !ok {
return nil, nil
}
tagsSorted := make([]string, 0, len(tags))
for tag := range tags {
if !strings.HasPrefix(tag, prefix) {
continue
}
tagsSorted = append(tagsSorted, tag)
}
sort.Strings(tagsSorted)
for _, tag := range tagsSorted {
// only if from is specified we need to find at least one
// metric with LastUpdate >= from
if (from > 0 && m.hasOneMetricFrom(tags, tag, from)) || from == 0 {
res = append(res, tag)
}
// the tags are processed in sorted order, so once we have have "limit" results we can break
if uint(len(res)) >= limit {
break
}
}
}
return res, nil
}
// FindTagValues returns tag values matching the specified conditions
// tag: tag key match
// prefix: value prefix match
// expressions: tagdb expressions in the same format as graphite
// from: tags must have at least one metric with LastUpdate >= from
// limit: the maximum number of results to return
//
// the results will always be sorted alphabetically for consistency
func (m *MemoryIdx) FindTagValues(orgId uint32, tag, prefix string, expressions []string, from int64, limit uint) ([]string, error) {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil, nil
}
var res []string
// only if expressions are specified we need to build a tag query.
// otherwise, the generation of the result set is much simpler
if len(expressions) > 0 {
// add the value prefix into the expressions as an additional condition
if len(prefix) > 0 {
expressions = append(expressions, tag+"^="+prefix)
} else {
// if no value prefix has been specified we still require that at
// least the given tag must be present
expressions = append(expressions, tag+"!=")
}
query, err := NewTagQuery(expressions, from)
if err != nil {
return nil, err
}
// only acquire lock after we're sure the query is valid
m.RLock()
defer m.RUnlock()
tags, ok := m.tags[orgId]
if !ok {
return nil, nil
}
ids := query.Run(tags, m.defById)
valueMap := make(map[string]struct{})
prefix := tag + "="
for id := range ids {
var ok bool
var def *idx.Archive
if def, ok = m.defById[id]; !ok {
// should never happen because every ID in the tag index
// must be present in the byId lookup table
corruptIndex.Inc()
log.Error(3, "memory-idx: ID %q is in tag index but not in the byId lookup table", id)
continue
}
// special case if the tag to complete values for is "name"
if tag == "name" {
valueMap[def.Name] = struct{}{}
} else {
for _, t := range def.Tags {
if !strings.HasPrefix(t, prefix) {
continue
}
// keep the value after "=", that's why "+1"
valueMap[t[len(prefix):]] = struct{}{}
}
}
}
res = make([]string, 0, len(valueMap))
for v := range valueMap {
res = append(res, v)
}
} else {
m.RLock()
defer m.RUnlock()
tags, ok := m.tags[orgId]
if !ok {
return nil, nil
}
vals, ok := tags[tag]
if !ok {
return nil, nil
}
res = make([]string, 0, len(vals))
for val := range vals {
if !strings.HasPrefix(val, prefix) {
continue
}
res = append(res, val)
}
}
sort.Strings(res)
if uint(len(res)) > limit {
res = res[:limit]
}
return res, nil
}
// 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.
// If the third parameter is >0 then only metrics will be accounted of which the
// LastUpdate time is >= the given value.
func (m *MemoryIdx) Tags(orgId uint32, filter string, from int64) ([]string, error) {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil, nil
}
var re *regexp.Regexp
if len(filter) > 0 {
if filter[0] != byte('^') {
filter = "^(?:" + filter + ")"
}
var err error
re, err = regexp.Compile(filter)
if err != nil {
return nil, err
}
}
m.RLock()
defer m.RUnlock()
tags, ok := m.tags[orgId]
if !ok {
return nil, nil
}
var res []string
// if there is no filter/from given we know how much space we'll need
// and can preallocate it
if re == nil && from == 0 {
res = make([]string, 0, len(tags))
}
for tag := range tags {
// filter by pattern if one was given
if re != nil && !re.MatchString(tag) {
continue
}
// if from is > 0 we need to find at least one metric definition where
// LastUpdate >= from before we add the tag to the result set
if (from > 0 && m.hasOneMetricFrom(tags, tag, from)) || from == 0 {
res = append(res, tag)
}
}
return res, nil
}
func (m *MemoryIdx) hasOneMetricFrom(tags TagIndex, tag string, from int64) bool {
for _, ids := range tags[tag] {
for id := range ids {
def, ok := m.defById[id]
if !ok {
corruptIndex.Inc()
log.Error(3, "memory-idx: corrupt. ID %q is in tag index but not in the byId lookup table", id)
continue
}
// as soon as we found one metric definition with LastUpdate >= from
// we can return true
if def.LastUpdate >= from {
return true
}
}
}
return false
}
func (m *MemoryIdx) FindByTag(orgId uint32, expressions []string, from int64) ([]idx.Node, error) {
if !TagSupport {
log.Warn("memory-idx: received tag query, but tag support is disabled")
return nil, nil
}
query, err := NewTagQuery(expressions, from)
if err != nil {
return nil, err
}
m.RLock()
defer m.RUnlock()
ids := m.idsByTagQuery(orgId, query)
res := make([]idx.Node, 0, len(ids))
for id := range ids {
def, ok := m.defById[id]
if !ok {
corruptIndex.Inc()
log.Error(3, "memory-idx: corrupt. ID %q has been given, but it is not in the byId lookup table", id)
continue
}
res = append(res, idx.Node{
Path: def.NameWithTags(),
Leaf: true,
HasChildren: false,
Defs: []idx.Archive{*def},
})
}
return res, nil
}
func (m *MemoryIdx) idsByTagQuery(orgId uint32, query TagQuery) IdSet {
tags, ok := m.tags[orgId]
if !ok {
return nil
}
return query.Run(tags, m.defById)
}
func (m *MemoryIdx) Find(orgId uint32, pattern string, from int64) ([]idx.Node, error) {
pre := time.Now()
m.RLock()
defer m.RUnlock()
matchedNodes, err := m.find(orgId, pattern)
if err != nil {
return nil, err
}
if orgId != idx.OrgIdPublic && idx.OrgIdPublic > 0 {
publicNodes, err := m.find(idx.OrgIdPublic, pattern)
if err != nil {
return nil, err
}
matchedNodes = append(matchedNodes, publicNodes...)
}
log.Debug("memory-idx: %d nodes matching pattern %s found", len(matchedNodes), pattern)
results := make([]idx.Node, 0)
seen := make(map[string]struct{})
// if there are public (orgId OrgIdPublic) and private leaf nodes with the same series
// path, then the public metricDefs will be excluded.
for _, n := range matchedNodes {
if _, ok := seen[n.Path]; !ok {
idxNode := idx.Node{
Path: n.Path,
Leaf: n.Leaf(),
HasChildren: n.HasChildren(),
}
if idxNode.Leaf {
idxNode.Defs = make([]idx.Archive, 0, len(n.Defs))
for _, id := range n.Defs {
def := m.defById[id]
if from != 0 && def.LastUpdate < from {
statFiltered.Inc()
log.Debug("memory-idx: from is %d, so skipping %s which has LastUpdate %d", from, def.Id, def.LastUpdate)
continue
}
log.Debug("memory-idx Find: adding to path %s archive id=%s name=%s int=%d schemaId=%d aggId=%d lastSave=%d", n.Path, def.Id, def.Name, def.Interval, def.SchemaId, def.AggId, def.LastSave)
idxNode.Defs = append(idxNode.Defs, *def)
}
if len(idxNode.Defs) == 0 {
continue
}
}
results = append(results, idxNode)
seen[n.Path] = struct{}{}
} else {
log.Debug("memory-idx: path %s already seen", n.Path)
}
}
log.Debug("memory-idx: %d nodes has %d unique paths.", len(matchedNodes), len(results))
statFindDuration.Value(time.Since(pre))
return results, nil
}
func (m *MemoryIdx) find(orgId uint32, pattern string) ([]*Node, error) {
tree, ok := m.tree[orgId]
if !ok {
log.Debug("memory-idx: orgId %d has no metrics indexed.", orgId)
return nil, nil
}
var nodes []string
if strings.Index(pattern, ";") == -1 {
nodes = strings.Split(pattern, ".")
} else {
nodes = strings.SplitN(pattern, ";", 2)
tags := nodes[1]
nodes = strings.Split(nodes[0], ".")
nodes[len(nodes)-1] += ";" + tags
}
// pos is the index of the first node with special chars, or one past the last node if exact
// for a query like foo.bar.baz, pos is 3
// for a query like foo.bar.* or foo.bar, pos is 2
// for a query like foo.b*.baz, pos is 1
pos := len(nodes)
for i := 0; i < len(nodes); i++ {
if strings.ContainsAny(nodes[i], "*{}[]?") {
log.Debug("memory-idx: found first pattern sequence at node %s pos %d", nodes[i], i)
pos = i
break
}
}
var branch string
if pos != 0 {
branch = strings.Join(nodes[:pos], ".")
}
log.Debug("memory-idx: starting search at orgId %d, node %q", orgId, branch)
startNode, ok := tree.Items[branch]
if !ok {
log.Debug("memory-idx: branch %q does not exist in the index for orgId %d", branch, orgId)
return nil, nil
}
if startNode == nil {
corruptIndex.Inc()
log.Error(3, "memory-idx: startNode is nil. org=%d,patt=%q,pos=%d,branch=%q", orgId, pattern, pos, branch)
return nil, errors.NewInternal("hit an empty path in the index")
}
children := []*Node{startNode}
for i := pos; i < len(nodes); i++ {
p := nodes[i]
matcher, err := getMatcher(p)
if err != nil {
return nil, err
}
var grandChildren []*Node
for _, c := range children {
if !c.HasChildren() {
log.Debug("memory-idx: end of branch reached at %s with no match found for %s", c.Path, pattern)
// expecting a branch
continue
}
log.Debug("memory-idx: searching %d children of %s that match %s", len(c.Children), c.Path, nodes[i])
matches := matcher(c.Children)
for _, m := range matches {
newBranch := c.Path + "." + m
if c.Path == "" {
newBranch = m
}
grandChild := tree.Items[newBranch]
if grandChild == nil {
corruptIndex.Inc()
log.Error(3, "memory-idx: grandChild is nil. org=%d,patt=%q,i=%d,pos=%d,p=%q,path=%q", orgId, pattern, i, pos, p, newBranch)
return nil, errors.NewInternal("hit an empty path in the index")
}
grandChildren = append(grandChildren, grandChild)
}
}
children = grandChildren
if len(children) == 0 {
log.Debug("memory-idx: pattern does not match any series.")