-
Notifications
You must be signed in to change notification settings - Fork 2
/
evaluator.go
1019 lines (905 loc) · 23.8 KB
/
evaluator.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 logql
import (
"container/heap"
"context"
"math"
"sort"
"time"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/promql"
"github.com/credativ/vali/pkg/iter"
"github.com/credativ/vali/pkg/logproto"
"github.com/credativ/vali/pkg/logql/log"
"github.com/credativ/vali/pkg/util"
)
type QueryRangeType string
var (
InstantType QueryRangeType = "instant"
RangeType QueryRangeType = "range"
)
// Params details the parameters associated with a vali request
type Params interface {
Query() string
Start() time.Time
End() time.Time
Step() time.Duration
Interval() time.Duration
Limit() uint32
Direction() logproto.Direction
Shards() []string
}
func NewLiteralParams(
qs string,
start, end time.Time,
step, interval time.Duration,
direction logproto.Direction,
limit uint32,
shards []string,
) LiteralParams {
return LiteralParams{
qs: qs,
start: start,
end: end,
step: step,
interval: interval,
direction: direction,
limit: limit,
shards: shards,
}
}
// LiteralParams impls Params
type LiteralParams struct {
qs string
start, end time.Time
step time.Duration
interval time.Duration
direction logproto.Direction
limit uint32
shards []string
}
func (p LiteralParams) Copy() LiteralParams { return p }
// String impls Params
func (p LiteralParams) Query() string { return p.qs }
// Start impls Params
func (p LiteralParams) Start() time.Time { return p.start }
// End impls Params
func (p LiteralParams) End() time.Time { return p.end }
// Step impls Params
func (p LiteralParams) Step() time.Duration { return p.step }
// Interval impls Params
func (p LiteralParams) Interval() time.Duration { return p.interval }
// Limit impls Params
func (p LiteralParams) Limit() uint32 { return p.limit }
// Direction impls Params
func (p LiteralParams) Direction() logproto.Direction { return p.direction }
// Shards impls Params
func (p LiteralParams) Shards() []string { return p.shards }
// GetRangeType returns whether a query is an instant query or range query
func GetRangeType(q Params) QueryRangeType {
if q.Start() == q.End() && q.Step() == 0 {
return InstantType
}
return RangeType
}
// Evaluator is an interface for iterating over data at different nodes in the AST
type Evaluator interface {
SampleEvaluator
EntryEvaluator
}
type SampleEvaluator interface {
// StepEvaluator returns a StepEvaluator for a given SampleExpr. It's explicitly passed another StepEvaluator// in order to enable arbitrary computation of embedded expressions. This allows more modular & extensible
// StepEvaluator implementations which can be composed.
StepEvaluator(ctx context.Context, nextEvaluator SampleEvaluator, expr SampleExpr, p Params) (StepEvaluator, error)
}
type SampleEvaluatorFunc func(ctx context.Context, nextEvaluator SampleEvaluator, expr SampleExpr, p Params) (StepEvaluator, error)
func (s SampleEvaluatorFunc) StepEvaluator(ctx context.Context, nextEvaluator SampleEvaluator, expr SampleExpr, p Params) (StepEvaluator, error) {
return s(ctx, nextEvaluator, expr, p)
}
type EntryEvaluator interface {
// Iterator returns the iter.EntryIterator for a given LogSelectorExpr
Iterator(context.Context, LogSelectorExpr, Params) (iter.EntryIterator, error)
}
// EvaluatorUnsupportedType is a helper for signaling that an evaluator does not support an Expr type
func EvaluatorUnsupportedType(expr Expr, ev Evaluator) error {
return errors.Errorf("unexpected expr type (%T) for Evaluator type (%T) ", expr, ev)
}
type DefaultEvaluator struct {
maxLookBackPeriod time.Duration
querier Querier
}
// NewDefaultEvaluator constructs a DefaultEvaluator
func NewDefaultEvaluator(querier Querier, maxLookBackPeriod time.Duration) *DefaultEvaluator {
return &DefaultEvaluator{
querier: querier,
maxLookBackPeriod: maxLookBackPeriod,
}
}
func (ev *DefaultEvaluator) Iterator(ctx context.Context, expr LogSelectorExpr, q Params) (iter.EntryIterator, error) {
params := SelectLogParams{
QueryRequest: &logproto.QueryRequest{
Start: q.Start(),
End: q.End(),
Limit: q.Limit(),
Direction: q.Direction(),
Selector: expr.String(),
Shards: q.Shards(),
},
}
if GetRangeType(q) == InstantType {
params.Start = params.Start.Add(-ev.maxLookBackPeriod)
}
return ev.querier.SelectLogs(ctx, params)
}
func (ev *DefaultEvaluator) StepEvaluator(
ctx context.Context,
nextEv SampleEvaluator,
expr SampleExpr,
q Params,
) (StepEvaluator, error) {
switch e := expr.(type) {
case *vectorAggregationExpr:
if rangExpr, ok := e.left.(*rangeAggregationExpr); ok && e.operation == OpTypeSum {
// if range expression is wrapped with a vector expression
// we should send the vector expression for allowing reducing labels at the source.
nextEv = SampleEvaluatorFunc(func(ctx context.Context, nextEvaluator SampleEvaluator, expr SampleExpr, p Params) (StepEvaluator, error) {
it, err := ev.querier.SelectSamples(ctx, SelectSampleParams{
&logproto.SampleQueryRequest{
Start: q.Start().Add(-rangExpr.left.interval),
End: q.End(),
Selector: e.String(), // intentionally send the the vector for reducing labels.
Shards: q.Shards(),
},
})
if err != nil {
return nil, err
}
return rangeAggEvaluator(iter.NewPeekingSampleIterator(it), rangExpr, q)
})
}
return vectorAggEvaluator(ctx, nextEv, e, q)
case *rangeAggregationExpr:
it, err := ev.querier.SelectSamples(ctx, SelectSampleParams{
&logproto.SampleQueryRequest{
Start: q.Start().Add(-e.left.interval),
End: q.End(),
Selector: expr.String(),
Shards: q.Shards(),
},
})
if err != nil {
return nil, err
}
return rangeAggEvaluator(iter.NewPeekingSampleIterator(it), e, q)
case *binOpExpr:
return binOpStepEvaluator(ctx, nextEv, e, q)
case *labelReplaceExpr:
return labelReplaceEvaluator(ctx, nextEv, e, q)
default:
return nil, EvaluatorUnsupportedType(e, ev)
}
}
func vectorAggEvaluator(
ctx context.Context,
ev SampleEvaluator,
expr *vectorAggregationExpr,
q Params,
) (StepEvaluator, error) {
nextEvaluator, err := ev.StepEvaluator(ctx, ev, expr.left, q)
if err != nil {
return nil, err
}
lb := labels.NewBuilder(nil)
buf := make([]byte, 0, 1024)
sort.Strings(expr.grouping.groups)
return newStepEvaluator(func() (bool, int64, promql.Vector) {
next, ts, vec := nextEvaluator.Next()
if !next {
return false, 0, promql.Vector{}
}
result := map[uint64]*groupedAggregation{}
if expr.operation == OpTypeTopK || expr.operation == OpTypeBottomK {
if expr.params < 1 {
return next, ts, promql.Vector{}
}
}
for _, s := range vec {
metric := s.Metric
var groupingKey uint64
if expr.grouping.without {
groupingKey, buf = metric.HashWithoutLabels(buf, expr.grouping.groups...)
} else {
groupingKey, buf = metric.HashForLabels(buf, expr.grouping.groups...)
}
group, ok := result[groupingKey]
// Add a new group if it doesn't exist.
if !ok {
var m labels.Labels
if expr.grouping.without {
lb.Reset(metric)
lb.Del(expr.grouping.groups...)
lb.Del(labels.MetricName)
m = lb.Labels()
} else {
m = make(labels.Labels, 0, len(expr.grouping.groups))
for _, l := range metric {
for _, n := range expr.grouping.groups {
if l.Name == n {
m = append(m, l)
break
}
}
}
sort.Sort(m)
}
result[groupingKey] = &groupedAggregation{
labels: m,
value: s.V,
mean: s.V,
groupCount: 1,
}
inputVecLen := len(vec)
resultSize := expr.params
if expr.params > inputVecLen {
resultSize = inputVecLen
}
if expr.operation == OpTypeStdvar || expr.operation == OpTypeStddev {
result[groupingKey].value = 0.0
} else if expr.operation == OpTypeTopK {
result[groupingKey].heap = make(vectorByValueHeap, 0, resultSize)
heap.Push(&result[groupingKey].heap, &promql.Sample{
Point: promql.Point{V: s.V},
Metric: s.Metric,
})
} else if expr.operation == OpTypeBottomK {
result[groupingKey].reverseHeap = make(vectorByReverseValueHeap, 0, resultSize)
heap.Push(&result[groupingKey].reverseHeap, &promql.Sample{
Point: promql.Point{V: s.V},
Metric: s.Metric,
})
}
continue
}
switch expr.operation {
case OpTypeSum:
group.value += s.V
case OpTypeAvg:
group.groupCount++
group.mean += (s.V - group.mean) / float64(group.groupCount)
case OpTypeMax:
if group.value < s.V || math.IsNaN(group.value) {
group.value = s.V
}
case OpTypeMin:
if group.value > s.V || math.IsNaN(group.value) {
group.value = s.V
}
case OpTypeCount:
group.groupCount++
case OpTypeStddev, OpTypeStdvar:
group.groupCount++
delta := s.V - group.mean
group.mean += delta / float64(group.groupCount)
group.value += delta * (s.V - group.mean)
case OpTypeTopK:
if len(group.heap) < expr.params || group.heap[0].V < s.V || math.IsNaN(group.heap[0].V) {
if len(group.heap) == expr.params {
heap.Pop(&group.heap)
}
heap.Push(&group.heap, &promql.Sample{
Point: promql.Point{V: s.V},
Metric: s.Metric,
})
}
case OpTypeBottomK:
if len(group.reverseHeap) < expr.params || group.reverseHeap[0].V > s.V || math.IsNaN(group.reverseHeap[0].V) {
if len(group.reverseHeap) == expr.params {
heap.Pop(&group.reverseHeap)
}
heap.Push(&group.reverseHeap, &promql.Sample{
Point: promql.Point{V: s.V},
Metric: s.Metric,
})
}
default:
panic(errors.Errorf("expected aggregation operator but got %q", expr.operation))
}
}
vec = vec[:0]
for _, aggr := range result {
switch expr.operation {
case OpTypeAvg:
aggr.value = aggr.mean
case OpTypeCount:
aggr.value = float64(aggr.groupCount)
case OpTypeStddev:
aggr.value = math.Sqrt(aggr.value / float64(aggr.groupCount))
case OpTypeStdvar:
aggr.value = aggr.value / float64(aggr.groupCount)
case OpTypeTopK:
// The heap keeps the lowest value on top, so reverse it.
sort.Sort(sort.Reverse(aggr.heap))
for _, v := range aggr.heap {
vec = append(vec, promql.Sample{
Metric: v.Metric,
Point: promql.Point{
T: ts,
V: v.V,
},
})
}
continue // Bypass default append.
case OpTypeBottomK:
// The heap keeps the lowest value on top, so reverse it.
sort.Sort(sort.Reverse(aggr.reverseHeap))
for _, v := range aggr.reverseHeap {
vec = append(vec, promql.Sample{
Metric: v.Metric,
Point: promql.Point{
T: ts,
V: v.V,
},
})
}
continue // Bypass default append.
default:
}
vec = append(vec, promql.Sample{
Metric: aggr.labels,
Point: promql.Point{
T: ts,
V: aggr.value,
},
})
}
return next, ts, vec
}, nextEvaluator.Close, nextEvaluator.Error)
}
func rangeAggEvaluator(
it iter.PeekingSampleIterator,
expr *rangeAggregationExpr,
q Params,
) (StepEvaluator, error) {
agg, err := expr.aggregator()
if err != nil {
return nil, err
}
iter := newRangeVectorIterator(
it,
expr.left.interval.Nanoseconds(),
q.Step().Nanoseconds(),
q.Start().UnixNano(), q.End().UnixNano(),
)
if expr.operation == OpRangeTypeAbsent {
return &absentRangeVectorEvaluator{
iter: iter,
lbs: absentLabels(expr),
}, nil
}
return &rangeVectorEvaluator{
iter: iter,
agg: agg,
}, nil
}
type rangeVectorEvaluator struct {
agg RangeVectorAggregator
iter RangeVectorIterator
err error
}
func (r *rangeVectorEvaluator) Next() (bool, int64, promql.Vector) {
next := r.iter.Next()
if !next {
return false, 0, promql.Vector{}
}
ts, vec := r.iter.At(r.agg)
for _, s := range vec {
// Errors are not allowed in metrics.
if s.Metric.Has(log.ErrorLabel) {
r.err = newPipelineErr(s.Metric)
return false, 0, promql.Vector{}
}
}
return true, ts, vec
}
func (r rangeVectorEvaluator) Close() error { return r.iter.Close() }
func (r rangeVectorEvaluator) Error() error {
if r.err != nil {
return r.err
}
return r.iter.Error()
}
type absentRangeVectorEvaluator struct {
iter RangeVectorIterator
lbs labels.Labels
err error
}
func (r *absentRangeVectorEvaluator) Next() (bool, int64, promql.Vector) {
next := r.iter.Next()
if !next {
return false, 0, promql.Vector{}
}
ts, vec := r.iter.At(one)
for _, s := range vec {
// Errors are not allowed in metrics.
if s.Metric.Has(log.ErrorLabel) {
r.err = newPipelineErr(s.Metric)
return false, 0, promql.Vector{}
}
}
if len(vec) > 0 {
return next, ts, promql.Vector{}
}
// values are missing.
return next, ts, promql.Vector{
promql.Sample{
Point: promql.Point{
T: ts,
V: 1.,
},
Metric: r.lbs,
},
}
}
func (r absentRangeVectorEvaluator) Close() error { return r.iter.Close() }
func (r absentRangeVectorEvaluator) Error() error {
if r.err != nil {
return r.err
}
return r.iter.Error()
}
// binOpExpr explicitly does not handle when both legs are literals as
// it makes the type system simpler and these are reduced in mustNewBinOpExpr
func binOpStepEvaluator(
ctx context.Context,
ev SampleEvaluator,
expr *binOpExpr,
q Params,
) (StepEvaluator, error) {
// first check if either side is a literal
leftLit, lOk := expr.SampleExpr.(*literalExpr)
rightLit, rOk := expr.RHS.(*literalExpr)
// match a literal expr with all labels in the other leg
if lOk {
rhs, err := ev.StepEvaluator(ctx, ev, expr.RHS, q)
if err != nil {
return nil, err
}
return literalStepEvaluator(
expr.op,
leftLit,
rhs,
false,
expr.opts.ReturnBool,
)
}
if rOk {
lhs, err := ev.StepEvaluator(ctx, ev, expr.SampleExpr, q)
if err != nil {
return nil, err
}
return literalStepEvaluator(
expr.op,
rightLit,
lhs,
true,
expr.opts.ReturnBool,
)
}
// we have two non literal legs
lhs, err := ev.StepEvaluator(ctx, ev, expr.SampleExpr, q)
if err != nil {
return nil, err
}
rhs, err := ev.StepEvaluator(ctx, ev, expr.RHS, q)
if err != nil {
return nil, err
}
return newStepEvaluator(func() (bool, int64, promql.Vector) {
pairs := map[uint64][2]*promql.Sample{}
var ts int64
// populate pairs
for i, eval := range []StepEvaluator{lhs, rhs} {
next, timestamp, vec := eval.Next()
ts = timestamp
// These should _always_ happen at the same step on each evaluator.
if !next {
return next, ts, nil
}
for _, sample := range vec {
// TODO(owen-d): this seems wildly inefficient: we're calculating
// the hash on each sample & step per evaluator.
// We seem limited to this approach due to using the StepEvaluator ifc.
hash := sample.Metric.Hash()
pair := pairs[hash]
pair[i] = &promql.Sample{
Metric: sample.Metric,
Point: sample.Point,
}
pairs[hash] = pair
}
}
results := make(promql.Vector, 0, len(pairs))
for _, pair := range pairs {
// merge
if merged := mergeBinOp(expr.op, pair[0], pair[1], !expr.opts.ReturnBool, IsComparisonOperator(expr.op)); merged != nil {
results = append(results, *merged)
}
}
return true, ts, results
}, func() (lastError error) {
for _, ev := range []StepEvaluator{lhs, rhs} {
if err := ev.Close(); err != nil {
lastError = err
}
}
return lastError
}, func() error {
var errs []error
for _, ev := range []StepEvaluator{lhs, rhs} {
if err := ev.Error(); err != nil {
errs = append(errs, err)
}
}
switch len(errs) {
case 0:
return nil
case 1:
return errs[0]
default:
return util.MultiError(errs)
}
})
}
func mergeBinOp(op string, left, right *promql.Sample, filter, isVectorComparison bool) *promql.Sample {
var merger func(left, right *promql.Sample) *promql.Sample
switch op {
case OpTypeOr:
merger = func(left, right *promql.Sample) *promql.Sample {
// return the left entry found (prefers left hand side)
if left != nil {
return left
}
return right
}
case OpTypeAnd:
merger = func(left, right *promql.Sample) *promql.Sample {
// return left sample if there's a second sample for that label set
if left != nil && right != nil {
return left
}
return nil
}
case OpTypeUnless:
merger = func(left, right *promql.Sample) *promql.Sample {
// return left sample if there's not a second sample for that label set
if right == nil {
return left
}
return nil
}
case OpTypeAdd:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
res.Point.V += right.Point.V
return &res
}
case OpTypeSub:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
res.Point.V -= right.Point.V
return &res
}
case OpTypeMul:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
res.Point.V *= right.Point.V
return &res
}
case OpTypeDiv:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
// guard against divide by zero
if right.Point.V == 0 {
res.Point.V = math.NaN()
} else {
res.Point.V /= right.Point.V
}
return &res
}
case OpTypeMod:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
// guard against divide by zero
if right.Point.V == 0 {
res.Point.V = math.NaN()
} else {
res.Point.V = math.Mod(res.Point.V, right.Point.V)
}
return &res
}
case OpTypePow:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
res.Point.V = math.Pow(left.Point.V, right.Point.V)
return &res
}
case OpTypeCmpEQ:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := &promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
val := 0.
if left.Point.V == right.Point.V {
val = 1.
} else if filter {
return nil
}
res.Point.V = val
return res
}
case OpTypeNEQ:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := &promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
val := 0.
if left.Point.V != right.Point.V {
val = 1.
} else if filter {
return nil
}
res.Point.V = val
return res
}
case OpTypeGT:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := &promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
val := 0.
if left.Point.V > right.Point.V {
val = 1.
} else if filter {
return nil
}
res.Point.V = val
return res
}
case OpTypeGTE:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := &promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
val := 0.
if left.Point.V >= right.Point.V {
val = 1.
} else if filter {
return nil
}
res.Point.V = val
return res
}
case OpTypeLT:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := &promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
val := 0.
if left.Point.V < right.Point.V {
val = 1.
} else if filter {
return nil
}
res.Point.V = val
return res
}
case OpTypeLTE:
merger = func(left, right *promql.Sample) *promql.Sample {
if left == nil || right == nil {
return nil
}
res := &promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
val := 0.
if left.Point.V <= right.Point.V {
val = 1.
} else if filter {
return nil
}
res.Point.V = val
return res
}
default:
panic(errors.Errorf("should never happen: unexpected operation: (%s)", op))
}
res := merger(left, right)
if !isVectorComparison {
return res
}
if filter {
// if a filter-enabled vector-wise comparison has returned non-nil,
// ensure we return the left hand side's value (2) instead of the
// comparison operator's result (1: the truthy answer)
if res != nil {
return left
}
// otherwise it's been filtered out
return res
}
// This only leaves vector comparisons which are not filters.
// If we could not find a match but we have a left node to compare, create an entry with a 0 value.
// This can occur when we don't find a matching label set in the vectors.
if res == nil && left != nil && right == nil {
res = &promql.Sample{
Metric: left.Metric,
Point: left.Point,
}
res.Point.V = 0
}
return res
}
// literalStepEvaluator merges a literal with a StepEvaluator. Since order matters in
// non commutative operations, inverted should be true when the literalExpr is not the left argument.
func literalStepEvaluator(
op string,
lit *literalExpr,
eval StepEvaluator,
inverted bool,
returnBool bool,
) (StepEvaluator, error) {
return newStepEvaluator(
func() (bool, int64, promql.Vector) {
ok, ts, vec := eval.Next()
results := make(promql.Vector, 0, len(vec))
for _, sample := range vec {
literalPoint := promql.Sample{
Metric: sample.Metric,
Point: promql.Point{T: ts, V: lit.value},
}
left, right := &literalPoint, &sample
if inverted {
left, right = right, left
}
if merged := mergeBinOp(
op,
left,
right,
!returnBool,
IsComparisonOperator(op),
); merged != nil {
results = append(results, *merged)
}
}
return ok, ts, results
},
eval.Close,
eval.Error,
)
}
func labelReplaceEvaluator(
ctx context.Context,
ev SampleEvaluator,
expr *labelReplaceExpr,
q Params,
) (StepEvaluator, error) {
nextEvaluator, err := ev.StepEvaluator(ctx, ev, expr.left, q)
if err != nil {
return nil, err
}
buf := make([]byte, 0, 1024)
var labelCache map[uint64]labels.Labels
return newStepEvaluator(func() (bool, int64, promql.Vector) {
next, ts, vec := nextEvaluator.Next()
if !next {
return false, 0, promql.Vector{}
}
if labelCache == nil {
labelCache = make(map[uint64]labels.Labels, len(vec))
}
var hash uint64
for i, s := range vec {
hash, buf = s.Metric.HashWithoutLabels(buf)
if labels, ok := labelCache[hash]; ok {
vec[i].Metric = labels
continue
}
src := s.Metric.Get(expr.src)
indexes := expr.re.FindStringSubmatchIndex(src)
if indexes == nil {
// If there is no match, no replacement should take place.
labelCache[hash] = s.Metric
continue
}
res := expr.re.ExpandString([]byte{}, expr.replacement, src, indexes)
lb := labels.NewBuilder(s.Metric).Del(expr.dst)
if len(res) > 0 {
lb.Set(expr.dst, string(res))
}
outLbs := lb.Labels()
labelCache[hash] = outLbs
vec[i].Metric = outLbs
}
return next, ts, vec
}, nextEvaluator.Close, nextEvaluator.Error)
}
// This is to replace missing timeseries during absent_over_time aggregation.
func absentLabels(expr SampleExpr) labels.Labels {
m := labels.Labels{}
lm := expr.Selector().Matchers()
if len(lm) == 0 {
return m