-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathevaluator.go
1340 lines (1197 loc) · 34.1 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"
"fmt"
"math"
"sort"
"time"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql"
"golang.org/x/sync/errgroup"
"github.com/grafana/loki/v3/pkg/iter"
"github.com/grafana/loki/v3/pkg/logproto"
"github.com/grafana/loki/v3/pkg/logql/syntax"
"github.com/grafana/loki/v3/pkg/logqlmodel"
"github.com/grafana/loki/v3/pkg/querier/plan"
"github.com/grafana/loki/v3/pkg/storage/chunk/cache/resultscache"
"github.com/grafana/loki/v3/pkg/util"
)
type QueryRangeType string
const trueString = "true"
var (
InstantType QueryRangeType = "instant"
RangeType QueryRangeType = "range"
)
// Params details the parameters associated with a loki request
type Params interface {
QueryString() string
Start() time.Time
End() time.Time
Step() time.Duration
Interval() time.Duration
Limit() uint32
Direction() logproto.Direction
Shards() []string
GetExpression() syntax.Expr
GetStoreChunks() *logproto.ChunkRefGroup
CachingOptions() resultscache.CachingOptions
}
func NewLiteralParams(
qs string,
start, end time.Time,
step, interval time.Duration,
direction logproto.Direction,
limit uint32,
shards []string,
storeChunks *logproto.ChunkRefGroup,
) (LiteralParams, error) {
return newLiteralParams(
qs,
start,
end,
step,
interval,
direction,
limit,
shards,
storeChunks,
resultscache.CachingOptions{},
)
}
func NewLiteralParamsWithCaching(
qs string,
start, end time.Time,
step, interval time.Duration,
direction logproto.Direction,
limit uint32,
shards []string,
storeChunks *logproto.ChunkRefGroup,
cachingOptions resultscache.CachingOptions,
) (LiteralParams, error) {
return newLiteralParams(
qs,
start,
end,
step,
interval,
direction,
limit,
shards,
storeChunks,
cachingOptions,
)
}
func newLiteralParams(
qs string,
start, end time.Time,
step, interval time.Duration,
direction logproto.Direction,
limit uint32,
shards []string,
storeChunks *logproto.ChunkRefGroup,
cachingOptions resultscache.CachingOptions,
) (LiteralParams, error) {
p := LiteralParams{
queryString: qs,
start: start,
end: end,
step: step,
interval: interval,
direction: direction,
limit: limit,
shards: shards,
storeChunks: storeChunks,
cachingOptions: cachingOptions,
}
var err error
p.queryExpr, err = syntax.ParseExpr(qs)
return p, err
}
// LiteralParams impls Params
type LiteralParams struct {
queryString string
start, end time.Time
step, interval time.Duration
direction logproto.Direction
limit uint32
shards []string
queryExpr syntax.Expr
storeChunks *logproto.ChunkRefGroup
cachingOptions resultscache.CachingOptions
}
func (p LiteralParams) Copy() LiteralParams { return p }
// String impls Params
func (p LiteralParams) QueryString() string { return p.queryString }
// GetExpression impls Params
func (p LiteralParams) GetExpression() syntax.Expr { return p.queryExpr }
// 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 }
// StoreChunks impls Params
func (p LiteralParams) GetStoreChunks() *logproto.ChunkRefGroup { return p.storeChunks }
// CachingOptions returns whether Loki query created from this params should be cached.
func (p LiteralParams) CachingOptions() resultscache.CachingOptions {
return p.cachingOptions
}
// 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
}
// ParamsWithExpressionOverride overrides the query expression so that the query
// string and the expression can differ. This is useful for for query planning
// when plan my not match externally available logql syntax
type ParamsWithExpressionOverride struct {
Params
ExpressionOverride syntax.Expr
}
// GetExpression returns the parsed expression of the query.
func (p ParamsWithExpressionOverride) GetExpression() syntax.Expr {
return p.ExpressionOverride
}
// ParamsWithExpressionOverride overrides the shards. Since the backing
// implementation of the Params interface is unknown they are embedded and the
// original shards are shadowed.
type ParamsWithShardsOverride struct {
Params
ShardsOverride []string
}
// Shards returns this overwriting shards.
func (p ParamsWithShardsOverride) Shards() []string {
return p.ShardsOverride
}
type ParamsWithChunkOverrides struct {
Params
StoreChunksOverride *logproto.ChunkRefGroup
}
func (p ParamsWithChunkOverrides) GetStoreChunks() *logproto.ChunkRefGroup {
return p.StoreChunksOverride
}
func ParamOverridesFromShard(base Params, shard *ShardWithChunkRefs) (result Params) {
if shard == nil {
return base
}
result = ParamsWithShardsOverride{
Params: base,
ShardsOverride: Shards{shard.Shard}.Encode(),
}
if shard.chunks != nil {
result = ParamsWithChunkOverrides{
Params: result,
StoreChunksOverride: shard.chunks,
}
}
return result
}
// Sortable logql contain sort or sort_desc.
func Sortable(q Params) (bool, error) {
switch expr := q.GetExpression().(type) {
case syntax.VariantsExpr:
return false, nil
case syntax.SampleExpr:
var sortable bool
expr.Walk(func(e syntax.Expr) {
if rangeExpr, ok := e.(*syntax.VectorAggregationExpr); ok {
if rangeExpr.Operation == syntax.OpTypeSort || rangeExpr.Operation == syntax.OpTypeSortDesc {
sortable = true
return
}
}
})
return sortable, nil
default:
return false, errors.New("only sample and variants expressions supported")
}
}
// EvaluatorFactory is an interface for iterating over data at different nodes in the AST
type EvaluatorFactory interface {
SampleEvaluatorFactory
EntryEvaluatorFactory
}
type SampleEvaluatorFactory interface {
// NewStepEvaluator returns a NewStepEvaluator for a given SampleExpr. It's explicitly passed another NewStepEvaluator// in order to enable arbitrary computation of embedded expressions. This allows more modular & extensible
// NewStepEvaluator implementations which can be composed.
NewStepEvaluator(ctx context.Context, nextEvaluatorFactory SampleEvaluatorFactory, expr syntax.SampleExpr, p Params) (StepEvaluator, error)
}
type SampleEvaluatorFunc func(ctx context.Context, nextEvaluatorFactory SampleEvaluatorFactory, expr syntax.SampleExpr, p Params) (StepEvaluator, error)
func (s SampleEvaluatorFunc) NewStepEvaluator(ctx context.Context, nextEvaluatorFactory SampleEvaluatorFactory, expr syntax.SampleExpr, p Params) (StepEvaluator, error) {
return s(ctx, nextEvaluatorFactory, expr, p)
}
type EntryEvaluatorFactory interface {
// NewIterator returns the iter.EntryIterator for a given LogSelectorExpr
NewIterator(context.Context, syntax.LogSelectorExpr, Params) (iter.EntryIterator, error)
}
// EvaluatorUnsupportedType is a helper for signaling that an evaluator does not support an Expr type
func EvaluatorUnsupportedType(expr syntax.Expr, ev EvaluatorFactory) error {
return errors.Errorf("unexpected expr type (%T) for Evaluator type (%T) ", expr, ev)
}
type DefaultEvaluator struct {
maxLookBackPeriod time.Duration
maxCountMinSketchHeapSize int
querier Querier
}
// NewDefaultEvaluator constructs a DefaultEvaluator
func NewDefaultEvaluator(querier Querier, maxLookBackPeriod time.Duration, maxCountMinSketchHeapSize int) *DefaultEvaluator {
return &DefaultEvaluator{
querier: querier,
maxLookBackPeriod: maxLookBackPeriod,
maxCountMinSketchHeapSize: maxCountMinSketchHeapSize,
}
}
func (ev *DefaultEvaluator) NewIterator(ctx context.Context, expr syntax.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(),
Plan: &plan.QueryPlan{
AST: expr,
},
StoreChunks: q.GetStoreChunks(),
},
}
if GetRangeType(q) == InstantType {
params.Start = params.Start.Add(-ev.maxLookBackPeriod)
}
return ev.querier.SelectLogs(ctx, params)
}
func (ev *DefaultEvaluator) NewStepEvaluator(
ctx context.Context,
nextEvFactory SampleEvaluatorFactory,
expr syntax.SampleExpr,
q Params,
) (StepEvaluator, error) {
switch e := expr.(type) {
case *syntax.VectorAggregationExpr:
if rangExpr, ok := e.Left.(*syntax.RangeAggregationExpr); ok && e.Operation == syntax.OpTypeSum {
// if range expression is wrapped with a vector expression
// we should send the vector expression for allowing reducing labels at the source.
nextEvFactory = SampleEvaluatorFunc(func(ctx context.Context, _ SampleEvaluatorFactory, _ syntax.SampleExpr, _ Params) (StepEvaluator, error) {
it, err := ev.querier.SelectSamples(ctx, SelectSampleParams{
&logproto.SampleQueryRequest{
// extend startTs backwards by step
Start: q.Start().Add(-rangExpr.Left.Interval).Add(-rangExpr.Left.Offset),
// add leap nanosecond to endTs to include lines exactly at endTs. range iterators work on start exclusive, end inclusive ranges
End: q.End().Add(-rangExpr.Left.Offset).Add(time.Nanosecond),
// intentionally send the vector for reducing labels.
Selector: e.String(),
Shards: q.Shards(),
Plan: &plan.QueryPlan{
AST: expr,
},
StoreChunks: q.GetStoreChunks(),
},
})
if err != nil {
return nil, err
}
return newRangeAggEvaluator(iter.NewPeekingSampleIterator(it), rangExpr, q, rangExpr.Left.Offset)
})
}
return newVectorAggEvaluator(ctx, nextEvFactory, e, q, ev.maxCountMinSketchHeapSize)
case *syntax.RangeAggregationExpr:
it, err := ev.querier.SelectSamples(ctx, SelectSampleParams{
&logproto.SampleQueryRequest{
// extend startTs backwards by step
Start: q.Start().Add(-e.Left.Interval).Add(-e.Left.Offset),
// add leap nanosecond to endTs to include lines exactly at endTs. range iterators work on start exclusive, end inclusive ranges
End: q.End().Add(-e.Left.Offset).Add(time.Nanosecond),
// intentionally send the vector for reducing labels.
Selector: e.String(),
Shards: q.Shards(),
Plan: &plan.QueryPlan{
AST: expr,
},
StoreChunks: q.GetStoreChunks(),
},
})
if err != nil {
return nil, err
}
return newRangeAggEvaluator(iter.NewPeekingSampleIterator(it), e, q, e.Left.Offset)
case *syntax.BinOpExpr:
return newBinOpStepEvaluator(ctx, nextEvFactory, e, q)
case *syntax.LabelReplaceExpr:
return newLabelReplaceEvaluator(ctx, nextEvFactory, e, q)
case *syntax.VectorExpr:
val, err := e.Value()
if err != nil {
return nil, err
}
return newVectorIterator(val, q.Step().Milliseconds(), q.Start().UnixMilli(), q.End().UnixMilli()), nil
default:
return nil, EvaluatorUnsupportedType(e, ev)
}
}
func newVectorAggEvaluator(
ctx context.Context,
evFactory SampleEvaluatorFactory,
expr *syntax.VectorAggregationExpr,
q Params,
maxCountMinSketchHeapSize int,
) (StepEvaluator, error) {
if expr.Grouping == nil {
return nil, errors.Errorf("aggregation operator '%q' without grouping", expr.Operation)
}
nextEvaluator, err := evFactory.NewStepEvaluator(ctx, evFactory, expr.Left, q)
if err != nil {
return nil, err
}
sort.Strings(expr.Grouping.Groups)
if expr.Operation == syntax.OpTypeCountMinSketch {
return newCountMinSketchVectorAggEvaluator(nextEvaluator, expr, maxCountMinSketchHeapSize)
}
return &VectorAggEvaluator{
nextEvaluator: nextEvaluator,
expr: expr,
buf: make([]byte, 0, 1024),
lb: labels.NewBuilder(nil),
}, nil
}
type VectorAggEvaluator struct {
nextEvaluator StepEvaluator
expr *syntax.VectorAggregationExpr
buf []byte
lb *labels.Builder
}
func (e *VectorAggEvaluator) Next() (bool, int64, StepResult) {
next, ts, r := e.nextEvaluator.Next()
if !next {
return false, 0, SampleVector{}
}
vec := r.SampleVector()
result := map[uint64]*groupedAggregation{}
if e.expr.Operation == syntax.OpTypeTopK || e.expr.Operation == syntax.OpTypeBottomK {
if e.expr.Params < 1 {
return next, ts, SampleVector{}
}
}
for _, s := range vec {
metric := s.Metric
var groupingKey uint64
if e.expr.Grouping.Without {
groupingKey, e.buf = metric.HashWithoutLabels(e.buf, e.expr.Grouping.Groups...)
} else {
groupingKey, e.buf = metric.HashForLabels(e.buf, e.expr.Grouping.Groups...)
}
group, ok := result[groupingKey]
// Add a new group if it doesn't exist.
if !ok {
var m labels.Labels
if e.expr.Grouping.Without {
e.lb.Reset(metric)
e.lb.Del(e.expr.Grouping.Groups...)
e.lb.Del(labels.MetricName)
m = e.lb.Labels()
} else {
m = make(labels.Labels, 0, len(e.expr.Grouping.Groups))
for _, l := range metric {
for _, n := range e.expr.Grouping.Groups {
if l.Name == n {
m = append(m, l)
break
}
}
}
sort.Sort(m)
}
result[groupingKey] = &groupedAggregation{
labels: m,
value: s.F,
mean: s.F,
groupCount: 1,
}
inputVecLen := len(vec)
resultSize := e.expr.Params
if e.expr.Params > inputVecLen {
resultSize = inputVecLen
}
if e.expr.Operation == syntax.OpTypeStdvar || e.expr.Operation == syntax.OpTypeStddev {
result[groupingKey].value = 0.0
} else if e.expr.Operation == syntax.OpTypeTopK {
result[groupingKey].heap = make(vectorByValueHeap, 0, resultSize)
heap.Push(&result[groupingKey].heap, &promql.Sample{
F: s.F,
Metric: s.Metric,
})
} else if e.expr.Operation == syntax.OpTypeBottomK {
result[groupingKey].reverseHeap = make(vectorByReverseValueHeap, 0, resultSize)
heap.Push(&result[groupingKey].reverseHeap, &promql.Sample{
F: s.F,
Metric: s.Metric,
})
} else if e.expr.Operation == syntax.OpTypeSortDesc {
result[groupingKey].heap = make(vectorByValueHeap, 0)
heap.Push(&result[groupingKey].heap, &promql.Sample{
F: s.F,
Metric: s.Metric,
})
} else if e.expr.Operation == syntax.OpTypeSort {
result[groupingKey].reverseHeap = make(vectorByReverseValueHeap, 0)
heap.Push(&result[groupingKey].reverseHeap, &promql.Sample{
F: s.F,
Metric: s.Metric,
})
}
continue
}
switch e.expr.Operation {
case syntax.OpTypeSum:
group.value += s.F
case syntax.OpTypeAvg:
group.groupCount++
group.mean += (s.F - group.mean) / float64(group.groupCount)
case syntax.OpTypeMax:
if group.value < s.F || math.IsNaN(group.value) {
group.value = s.F
}
case syntax.OpTypeMin:
if group.value > s.F || math.IsNaN(group.value) {
group.value = s.F
}
case syntax.OpTypeCount:
group.groupCount++
case syntax.OpTypeStddev, syntax.OpTypeStdvar:
group.groupCount++
delta := s.F - group.mean
group.mean += delta / float64(group.groupCount)
group.value += delta * (s.F - group.mean)
case syntax.OpTypeTopK:
if len(group.heap) < e.expr.Params || group.heap[0].F < s.F || math.IsNaN(group.heap[0].F) {
if len(group.heap) == e.expr.Params {
heap.Pop(&group.heap)
}
heap.Push(&group.heap, &promql.Sample{
F: s.F,
Metric: s.Metric,
})
}
case syntax.OpTypeBottomK:
if len(group.reverseHeap) < e.expr.Params || group.reverseHeap[0].F > s.F || math.IsNaN(group.reverseHeap[0].F) {
if len(group.reverseHeap) == e.expr.Params {
heap.Pop(&group.reverseHeap)
}
heap.Push(&group.reverseHeap, &promql.Sample{
F: s.F,
Metric: s.Metric,
})
}
case syntax.OpTypeSortDesc:
heap.Push(&group.heap, &promql.Sample{
F: s.F,
Metric: s.Metric,
})
case syntax.OpTypeSort:
heap.Push(&group.reverseHeap, &promql.Sample{
F: s.F,
Metric: s.Metric,
})
default:
panic(errors.Errorf("expected aggregation operator but got %q", e.expr.Operation))
}
}
vec = vec[:0]
for _, aggr := range result {
switch e.expr.Operation {
case syntax.OpTypeAvg:
aggr.value = aggr.mean
case syntax.OpTypeCount:
aggr.value = float64(aggr.groupCount)
case syntax.OpTypeStddev:
aggr.value = math.Sqrt(aggr.value / float64(aggr.groupCount))
case syntax.OpTypeStdvar:
aggr.value = aggr.value / float64(aggr.groupCount)
case syntax.OpTypeTopK, syntax.OpTypeSortDesc:
// 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,
T: ts,
F: v.F,
})
}
continue // Bypass default append.
case syntax.OpTypeBottomK, syntax.OpTypeSort:
// 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,
T: ts,
F: v.F,
})
}
continue // Bypass default append.
default:
}
vec = append(vec, promql.Sample{
Metric: aggr.labels,
T: ts,
F: aggr.value,
})
}
return next, ts, SampleVector(vec)
}
func (e *VectorAggEvaluator) Close() error {
return e.nextEvaluator.Close()
}
func (e *VectorAggEvaluator) Error() error {
return e.nextEvaluator.Error()
}
func newRangeAggEvaluator(
it iter.PeekingSampleIterator,
expr *syntax.RangeAggregationExpr,
q Params,
o time.Duration,
) (StepEvaluator, error) {
switch expr.Operation {
case syntax.OpRangeTypeAbsent:
iter, err := newRangeVectorIterator(
it, expr,
expr.Left.Interval.Nanoseconds(),
q.Step().Nanoseconds(),
q.Start().UnixNano(), q.End().UnixNano(), o.Nanoseconds(),
)
if err != nil {
return nil, err
}
absentLabels, err := absentLabels(expr)
if err != nil {
return nil, err
}
return &AbsentRangeVectorEvaluator{
iter: iter,
lbs: absentLabels,
}, nil
case syntax.OpRangeTypeQuantileSketch:
iter := newQuantileSketchIterator(
it,
expr.Left.Interval.Nanoseconds(),
q.Step().Nanoseconds(),
q.Start().UnixNano(), q.End().UnixNano(), o.Nanoseconds(),
)
return &QuantileSketchStepEvaluator{
iter: iter,
}, nil
case syntax.OpRangeTypeFirstWithTimestamp:
iter := newFirstWithTimestampIterator(
it,
expr.Left.Interval.Nanoseconds(),
q.Step().Nanoseconds(),
q.Start().UnixNano(), q.End().UnixNano(), o.Nanoseconds(),
)
return &RangeVectorEvaluator{
iter: iter,
}, nil
case syntax.OpRangeTypeLastWithTimestamp:
iter := newLastWithTimestampIterator(
it,
expr.Left.Interval.Nanoseconds(),
q.Step().Nanoseconds(),
q.Start().UnixNano(), q.End().UnixNano(), o.Nanoseconds(),
)
return &RangeVectorEvaluator{
iter: iter,
}, nil
default:
iter, err := newRangeVectorIterator(
it, expr,
expr.Left.Interval.Nanoseconds(),
q.Step().Nanoseconds(),
q.Start().UnixNano(), q.End().UnixNano(), o.Nanoseconds(),
)
if err != nil {
return nil, err
}
return &RangeVectorEvaluator{
iter: iter,
}, nil
}
}
type RangeVectorEvaluator struct {
iter RangeVectorIterator
err error
}
func (r *RangeVectorEvaluator) Next() (bool, int64, StepResult) {
next := r.iter.Next()
if !next {
return false, 0, SampleVector{}
}
ts, vec := r.iter.At()
for _, s := range vec.SampleVector() {
// Errors are not allowed in metrics unless they've been specifically requested.
if s.Metric.Has(logqlmodel.ErrorLabel) && s.Metric.Get(logqlmodel.PreserveErrorLabel) != trueString {
r.err = logqlmodel.NewPipelineErr(s.Metric)
return false, 0, SampleVector{}
}
}
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, StepResult) {
next := r.iter.Next()
if !next {
return false, 0, SampleVector{}
}
ts, vec := r.iter.At()
for _, s := range vec.SampleVector() {
// Errors are not allowed in metrics unless they've been specifically requested.
if s.Metric.Has(logqlmodel.ErrorLabel) && s.Metric.Get(logqlmodel.PreserveErrorLabel) != trueString {
r.err = logqlmodel.NewPipelineErr(s.Metric)
return false, 0, SampleVector{}
}
}
if len(vec.SampleVector()) > 0 {
return next, ts, SampleVector{}
}
// values are missing.
return next, ts, SampleVector{
promql.Sample{
T: ts,
F: 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()
}
// newBinOpStepEvaluator explicitly does not handle when both legs are literals as
// it makes the type system simpler and these are reduced in mustNewBinOpExpr
func newBinOpStepEvaluator(
ctx context.Context,
evFactory SampleEvaluatorFactory,
expr *syntax.BinOpExpr,
q Params,
) (StepEvaluator, error) {
// first check if either side is a literal
leftLit, lOk := expr.SampleExpr.(*syntax.LiteralExpr)
rightLit, rOk := expr.RHS.(*syntax.LiteralExpr)
// match a literal expr with all labels in the other leg
if lOk {
rhs, err := evFactory.NewStepEvaluator(ctx, evFactory, expr.RHS, q)
if err != nil {
return nil, err
}
return newLiteralStepEvaluator(
expr.Op,
leftLit,
rhs,
false,
expr.Opts.ReturnBool,
)
}
if rOk {
lhs, err := evFactory.NewStepEvaluator(ctx, evFactory, expr.SampleExpr, q)
if err != nil {
return nil, err
}
return newLiteralStepEvaluator(
expr.Op,
rightLit,
lhs,
true,
expr.Opts.ReturnBool,
)
}
var lse, rse StepEvaluator
ctx, cancel := context.WithCancelCause(ctx)
g := errgroup.Group{}
// We have two non-literal legs,
// load them in parallel
g.Go(func() error {
var err error
lse, err = evFactory.NewStepEvaluator(ctx, evFactory, expr.SampleExpr, q)
if err != nil {
cancel(fmt.Errorf("new step evaluator for left leg errored: %w", err))
}
return err
})
g.Go(func() error {
var err error
rse, err = evFactory.NewStepEvaluator(ctx, evFactory, expr.RHS, q)
if err != nil {
cancel(fmt.Errorf("new step evaluator for right leg errored: %w", err))
}
return err
})
// ensure both sides are loaded before returning the combined evaluator
if err := g.Wait(); err != nil {
return nil, err
}
return &BinOpStepEvaluator{
rse: rse,
lse: lse,
expr: expr,
}, nil
}
type BinOpStepEvaluator struct {
rse StepEvaluator
lse StepEvaluator
expr *syntax.BinOpExpr
lastErr error
}
func (e *BinOpStepEvaluator) Next() (bool, int64, StepResult) {
var (
ts int64
next bool
lhs, rhs promql.Vector
r StepResult
)
next, ts, r = e.rse.Next()
// These should _always_ happen at the same step on each evaluator.
if !next {
return next, ts, nil
}
rhs = r.SampleVector()
// build matching signature for each sample in right vector
rsigs := make([]uint64, len(rhs))
for i, sample := range rhs {
rsigs[i] = matchingSignature(sample, e.expr.Opts)
}
next, ts, r = e.lse.Next()
if !next {
return next, ts, nil
}
lhs = r.SampleVector()
// build matching signature for each sample in left vector
lsigs := make([]uint64, len(lhs))
for i, sample := range lhs {
lsigs[i] = matchingSignature(sample, e.expr.Opts)
}
var results promql.Vector
switch e.expr.Op {
case syntax.OpTypeAnd:
results = vectorAnd(lhs, rhs, lsigs, rsigs)
case syntax.OpTypeOr:
results = vectorOr(lhs, rhs, lsigs, rsigs)
case syntax.OpTypeUnless:
results = vectorUnless(lhs, rhs, lsigs, rsigs)
default:
results, e.lastErr = vectorBinop(e.expr.Op, e.expr.Opts, lhs, rhs, lsigs, rsigs)
}
return true, ts, SampleVector(results)
}
func (e *BinOpStepEvaluator) Close() (lastError error) {
for _, ev := range []StepEvaluator{e.lse, e.rse} {
if err := ev.Close(); err != nil {
lastError = err
}
}
return lastError
}
func (e *BinOpStepEvaluator) Error() error {
var errs []error
if e.lastErr != nil {
errs = append(errs, e.lastErr)
}
for _, ev := range []StepEvaluator{e.lse, e.rse} {
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 matchingSignature(sample promql.Sample, opts *syntax.BinOpOptions) uint64 {
if opts == nil || opts.VectorMatching == nil {
return sample.Metric.Hash()
} else if opts.VectorMatching.On {
return labels.NewBuilder(sample.Metric).Keep(opts.VectorMatching.MatchingLabels...).Labels().Hash()
}
return labels.NewBuilder(sample.Metric).Del(opts.VectorMatching.MatchingLabels...).Labels().Hash()
}
func vectorBinop(op string, opts *syntax.BinOpOptions, lhs, rhs promql.Vector, lsigs, rsigs []uint64) (promql.Vector, error) {
// handle one-to-one or many-to-one matching
// for one-to-many, swap
if opts != nil && opts.VectorMatching.Card == syntax.CardOneToMany {
lhs, rhs = rhs, lhs
lsigs, rsigs = rsigs, lsigs
}
rightSigs := make(map[uint64]*promql.Sample)
matchedSigs := make(map[uint64]map[uint64]struct{})
results := make(promql.Vector, 0)
// Add all rhs samples to a map, so we can easily find matches later.
for i, sample := range rhs {
sig := rsigs[i]
if rightSigs[sig] != nil {
side := "right"
if opts.VectorMatching.Card == syntax.CardOneToMany {
side = "left"
}
return nil, fmt.Errorf("found duplicate series on the %s hand-side"+
";many-to-many matching not allowed: matching labels must be unique on one side", side)
}
rightSigs[sig] = &promql.Sample{
Metric: sample.Metric,
T: sample.T,
F: sample.F,
}
}
for i, sample := range lhs {
ls := &sample
sig := lsigs[i]
rs, found := rightSigs[sig] // Look for a match in the rhs Vector.
if !found {
continue
}
metric := resultMetric(ls.Metric, rs.Metric, opts)
insertedSigs, exists := matchedSigs[sig]
filter := true
if opts != nil {
if opts.VectorMatching.Card == syntax.CardOneToOne {
if exists {
return nil, errors.New("multiple matches for labels: many-to-one matching must be explicit (group_left/group_right)")
}
matchedSigs[sig] = nil
} else {
insertSig := metric.Hash()
if !exists {
insertedSigs = map[uint64]struct{}{}
matchedSigs[sig] = insertedSigs
} else if _, duplicate := insertedSigs[insertSig]; duplicate {
return nil, errors.New("multiple matches for labels: grouping labels must ensure unique matches")
}
insertedSigs[insertSig] = struct{}{}