-
Notifications
You must be signed in to change notification settings - Fork 457
/
Copy pathbuiltin_functions.go
1951 lines (1741 loc) · 66.3 KB
/
builtin_functions.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
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package native
import (
"bytes"
"fmt"
"math"
"math/rand"
"regexp"
"sort"
"strings"
"time"
"github.com/m3db/m3/src/query/graphite/common"
"github.com/m3db/m3/src/query/graphite/errors"
"github.com/m3db/m3/src/query/graphite/ts"
)
const (
millisPerSecond = 1000
secondsPerDay = 24 * 3600
daysPerWeek = 7
secondsPerWeek = secondsPerDay * daysPerWeek
cactiStyleFormat = "%.2f"
wrappingFmt = "%s(%s)"
alpha = 0.1
gamma = 0.1
beta = 0.0035
)
func joinPathExpr(series ts.SeriesList) string {
seen := make(map[string]struct{})
joined := make([]string, 0, series.Len())
for _, s := range series.Values {
if len(s.Specification) == 0 {
continue
}
if _, exists := seen[s.Specification]; exists {
continue
}
seen[s.Specification] = struct{}{}
joined = append(joined, s.Specification)
}
return strings.Join(joined, ",")
}
// sortByName sorts timeseries results by their names
func sortByName(_ *common.Context, series singlePathSpec) (ts.SeriesList, error) {
sorted := make([]*ts.Series, len(series.Values))
for i := range series.Values {
sorted[i] = series.Values[i]
}
sort.Sort(ts.SeriesByName(sorted))
r := ts.SeriesList(series)
r.Values = sorted
r.SortApplied = true
return r, nil
}
// sortByTotal sorts timeseries results by the sum of values.
func sortByTotal(ctx *common.Context, series singlePathSpec) (ts.SeriesList, error) {
return highestSum(ctx, series, len(series.Values))
}
// sortByMaxima sorts timeseries by the maximum value across the time period specified.
func sortByMaxima(ctx *common.Context, series singlePathSpec) (ts.SeriesList, error) {
return highestMax(ctx, series, len(series.Values))
}
type valueComparator func(v, threshold float64) bool
func compareByFunction(
_ *common.Context,
series singlePathSpec,
sr ts.SeriesReducer,
vc valueComparator,
threshold float64,
) (ts.SeriesList, error) {
res := make([]*ts.Series, 0, len(series.Values))
for _, s := range series.Values {
stats := sr(s)
if vc(stats, threshold) {
res = append(res, s)
}
}
r := ts.SeriesList(series)
r.Values = res
return r, nil
}
func aboveByFunction(
ctx *common.Context,
series singlePathSpec,
sr ts.SeriesReducer,
threshold float64,
) (ts.SeriesList, error) {
return compareByFunction(ctx, series, sr, func(stats, threshold float64) bool {
return stats > threshold
}, threshold)
}
func belowByFunction(
ctx *common.Context,
series singlePathSpec,
sr ts.SeriesReducer,
threshold float64,
) (ts.SeriesList, error) {
return compareByFunction(ctx, series, sr, func(stats, threshold float64) bool {
return stats < threshold
}, threshold)
}
// maximumAbove takes one metric or a wildcard seriesList followed by an floating point number n,
// returns only the metrics with a maximum value above n.
func maximumAbove(ctx *common.Context, series singlePathSpec, n float64) (ts.SeriesList, error) {
sr := ts.SeriesReducerMax.Reducer()
return aboveByFunction(ctx, series, sr, n)
}
// minimumAbove takes one metric or a wildcard seriesList followed by an floating point number n,
// returns only the metrics with a minimum value above n.
func minimumAbove(ctx *common.Context, series singlePathSpec, n float64) (ts.SeriesList, error) {
sr := ts.SeriesReducerMin.Reducer()
return aboveByFunction(ctx, series, sr, n)
}
// averageAbove takes one metric or a wildcard seriesList followed by an floating point number n,
// returns only the metrics with an average value above n.
func averageAbove(ctx *common.Context, series singlePathSpec, n float64) (ts.SeriesList, error) {
sr := ts.SeriesReducerAvg.Reducer()
return aboveByFunction(ctx, series, sr, n)
}
// currentAbove takes one metric or a wildcard seriesList followed by an floating point number n,
// returns only the metrics with the last value above n.
func currentAbove(ctx *common.Context, series singlePathSpec, n float64) (ts.SeriesList, error) {
sr := ts.SeriesReducerLast.Reducer()
return aboveByFunction(ctx, series, sr, n)
}
// currentBelow takes one metric or a wildcard seriesList followed by an floating point number n,
// returns only the metrics with the last value below n.
func currentBelow(ctx *common.Context, series singlePathSpec, n float64) (ts.SeriesList, error) {
sr := ts.SeriesReducerLast.Reducer()
return belowByFunction(ctx, series, sr, n)
}
// constantLine takes value and creates a constant line at value.
func constantLine(ctx *common.Context, value float64) (ts.SeriesList, error) {
newSeries, err := common.ConstantLine(ctx, value)
if err != nil {
return ts.SeriesList{}, err
}
return ts.SeriesList{Values: []*ts.Series{newSeries}}, nil
}
// identity returns datapoints where the value equals the timestamp of the datapoint.
func identity(ctx *common.Context, name string) (ts.SeriesList, error) {
return common.Identity(ctx, name)
}
// limit takes one metric or a wildcard seriesList followed by an integer N, and draws
// the first N metrics.
func limit(_ *common.Context, series singlePathSpec, n int) (ts.SeriesList, error) {
if n < 0 {
return ts.SeriesList{}, errors.NewInvalidParamsError(fmt.Errorf("invalid limit parameter n: %d", n))
}
upperBound := int(math.Min(float64(len(series.Values)), float64(n)))
r := ts.SeriesList(series)
r.Values = series.Values[0:upperBound]
return r, nil
}
// timeShift draws the selected metrics shifted in time. If no sign is given, a minus sign ( - ) is
// implied which will shift the metric back in time. If a plus sign ( + ) is given, the metric will
// be shifted forward in time
func timeShift(
_ *common.Context,
_ singlePathSpec,
timeShiftS string,
_ bool,
) (*unaryContextShifter, error) {
// TODO: implement resetEnd
if !(strings.HasPrefix(timeShiftS, "+") || strings.HasPrefix(timeShiftS, "-")) {
timeShiftS = "-" + timeShiftS
}
shift, err := common.ParseInterval(timeShiftS)
if err != nil {
return nil, errors.NewInvalidParamsError(fmt.Errorf("invalid timeShift parameter %s: %v", timeShiftS, err))
}
contextShiftingFn := func(c *common.Context) *common.Context {
opts := common.NewChildContextOptions()
opts.AdjustTimeRange(shift, shift, 0, 0)
childCtx := c.NewChildContext(opts)
return childCtx
}
transformerFn := func(input ts.SeriesList) (ts.SeriesList, error) {
output := make([]*ts.Series, input.Len())
for i, in := range input.Values {
// NB(jayp): opposite direction
output[i] = in.Shift(-1 * shift).RenamedTo(fmt.Sprintf("timeShift(%s, %s)", in.Name(), timeShiftS))
}
input.Values = output
return input, nil
}
return &unaryContextShifter{
ContextShiftFunc: contextShiftingFn,
UnaryTransformer: transformerFn,
}, nil
}
// absolute returns the absolute value of each element in the series.
func absolute(ctx *common.Context, input singlePathSpec) (ts.SeriesList, error) {
return transform(ctx, input,
func(fname string) string { return fmt.Sprintf(wrappingFmt, "absolute", fname) },
math.Abs)
}
// scale multiplies each element of a collection of time series by a given value
func scale(ctx *common.Context, input singlePathSpec, scale float64) (ts.SeriesList, error) {
return transform(
ctx,
input,
func(fname string) string {
newName := fmt.Sprintf("%s,"+common.FloatingPointFormat, fname, scale)
return fmt.Sprintf(wrappingFmt, "scale", newName)
},
common.Scale(scale),
)
}
// scaleToSeconds makes a wildcard seriesList and returns "value per seconds"
func scaleToSeconds(
ctx *common.Context,
seriesList singlePathSpec,
seconds int,
) (ts.SeriesList, error) {
output := make([]*ts.Series, len(seriesList.Values))
for i, series := range seriesList.Values {
var (
outvals = ts.NewValues(ctx, series.MillisPerStep(), series.Len())
name = fmt.Sprintf("scaleToSeconds(%s,%d)", series.Name(), seconds)
factor = float64(seconds*1000) / float64(series.MillisPerStep()) // convert seconds to millis
)
for step := 0; step < series.Len(); step++ {
value := series.ValueAt(step)
outvals.SetValueAt(step, value*factor)
}
output[i] = ts.NewSeries(ctx, name, series.StartTime(), outvals)
}
r := ts.SeriesList(seriesList)
r.Values = output
return r, nil
}
// offset adds a value to each element of a collection of time series
func offset(ctx *common.Context, input singlePathSpec, factor float64) (ts.SeriesList, error) {
return transform(
ctx,
input,
func(fname string) string {
newName := fmt.Sprintf("%s,"+common.FloatingPointFormat, fname, factor)
return fmt.Sprintf(wrappingFmt, "offset", newName)
},
common.Offset(factor),
)
}
// transform converts values in a timeseries according to the valueTransformer.
func transform(ctx *common.Context, input singlePathSpec,
fname func(inputName string) string, fn common.TransformFunc) (ts.SeriesList, error) {
t := common.NewStatelessTransformer(fn)
return common.Transform(ctx, ts.SeriesList(input), t, func(in *ts.Series) string {
return fname(in.Name())
})
}
// perSecond computes a derivative adjusted for the series time interval,
// useful for taking a running total metric and showing how many occurrences
// per second were handled
func perSecond(ctx *common.Context, input singlePathSpec, _ float64) (ts.SeriesList, error) {
// TODO: we are ignoring maxValue; we may need to implement it
return common.PerSecond(ctx, ts.SeriesList(input), func(series *ts.Series) string {
return fmt.Sprintf("perSecond(%s)", series.Name())
})
}
// transformNull transforms all nulls (NaNs) in a time series to a defaultValue.
func transformNull(ctx *common.Context, input singlePathSpec, defaultValue float64) (ts.SeriesList, error) {
return transform(
ctx,
input,
func(fname string) string {
newName := fmt.Sprintf("%s,"+common.FloatingPointFormat, fname, defaultValue)
return fmt.Sprintf(wrappingFmt, "transformNull", newName)
},
common.TransformNull(defaultValue),
)
}
// isNonNull takes a metric or wild card seriesList and counts up how many non-null values are specified.
// This is useful for understanding which metrics have data at a given point in time
// (ie, to count which servers are alive).
func isNonNull(ctx *common.Context, input singlePathSpec) (ts.SeriesList, error) {
return transform(ctx,
input,
func(fname string) string { return fmt.Sprintf(wrappingFmt, "isNonNull", fname) },
common.IsNonNull())
}
// keepLastValue takes one metric or a wildcard seriesList, and optionally a limit to the number of
// NaN values to skip over. If not specified, limit has a default value of -1, meaning all NaNs will
// be replaced by the closest preceding value that's not an NaN.
func keepLastValue(ctx *common.Context, input singlePathSpec, limit int) (ts.SeriesList, error) {
output := make([]*ts.Series, 0, len(input.Values))
for _, series := range input.Values {
consecutiveNaNs := 0
numSteps := series.Len()
vals := ts.NewValues(ctx, series.MillisPerStep(), numSteps)
for i := 0; i < numSteps; i++ {
value := series.ValueAt(i)
vals.SetValueAt(i, value)
if i == 0 {
continue
}
if math.IsNaN(value) {
consecutiveNaNs++
} else {
if limit == -1 || (consecutiveNaNs > 0 && consecutiveNaNs <= limit) {
v := series.ValueAt(i - consecutiveNaNs - 1)
if !math.IsNaN(v) {
for index := i - consecutiveNaNs; index < i; index++ {
vals.SetValueAt(index, v)
}
}
}
consecutiveNaNs = 0
}
}
if limit == -1 || (consecutiveNaNs > 0 && consecutiveNaNs <= limit) {
for index := numSteps - consecutiveNaNs; index < numSteps; index++ {
vals.SetValueAt(index, series.ValueAt(numSteps-consecutiveNaNs-1))
}
}
name := fmt.Sprintf("keepLastValue(%s)", series.Name())
newSeries := ts.NewSeries(ctx, name, series.StartTime(), vals)
output = append(output, newSeries)
}
r := ts.SeriesList(input)
r.Values = output
return r, nil
}
type comparator func(float64, float64) bool
// lessOrEqualFunc checks whether x is less than or equal to y
func lessOrEqualFunc(x float64, y float64) bool {
return x <= y
}
// greaterOrEqualFunc checks whether x is greater or equal to y
func greaterOrEqualFunc(x float64, y float64) bool {
return x >= y
}
func sustainedCompare(ctx *common.Context, input singlePathSpec, threshold float64, intervalString string,
comparisonFunction comparator, zeroValue float64, funcName string) (ts.SeriesList, error) {
output := make([]*ts.Series, 0, len(input.Values))
interval, err := common.ParseInterval(intervalString)
if err != nil {
return ts.SeriesList{}, err
}
intervalMillis := int(interval / time.Millisecond)
for _, series := range input.Values {
numSteps := series.Len()
vals := ts.NewValues(ctx, series.MillisPerStep(), numSteps)
minSteps := intervalMillis / series.MillisPerStep()
currSteps := 0
for i := 0; i < numSteps; i++ {
value := series.ValueAt(i)
if comparisonFunction(value, threshold) {
currSteps++
} else {
currSteps = 0
}
if currSteps >= minSteps {
vals.SetValueAt(i, value)
} else {
vals.SetValueAt(i, zeroValue)
}
}
name := fmt.Sprintf("%s(%s, %f, '%s')",
funcName, series.Name(), threshold, intervalString)
newSeries := ts.NewSeries(ctx, name, series.StartTime(), vals)
output = append(output, newSeries)
}
r := ts.SeriesList(input)
r.Values = output
return r, nil
}
func sustainedAbove(ctx *common.Context, input singlePathSpec, threshold float64, intervalString string) (ts.SeriesList, error) {
return sustainedCompare(ctx, input, threshold, intervalString, greaterOrEqualFunc, threshold-math.Abs(threshold), "sustainedAbove")
}
func sustainedBelow(ctx *common.Context, input singlePathSpec, threshold float64, intervalString string) (ts.SeriesList, error) {
return sustainedCompare(ctx, input, threshold, intervalString, lessOrEqualFunc, threshold+math.Abs(threshold), "sustainedBelow")
}
// removeBelowValue removes data below the given threshold from the series or list of series provided.
// Values below this threshold are assigned a value of None.
func removeBelowValue(ctx *common.Context, input singlePathSpec, n float64) (ts.SeriesList, error) {
return transform(ctx, input,
func(inputName string) string {
return fmt.Sprintf("removeBelowValue(%s, "+common.FloatingPointFormat+")", inputName, n)
},
common.Filter(func(v float64) bool { return v >= n }))
}
// removeAboveValue removes data above the given threshold from the series or list of series provided.
// Values above this threshold are assigned a value of None.
func removeAboveValue(ctx *common.Context, input singlePathSpec, n float64) (ts.SeriesList, error) {
return transform(ctx, input,
func(inputName string) string {
return fmt.Sprintf("removeAboveValue(%s, "+common.FloatingPointFormat+")", inputName, n)
},
common.Filter(func(v float64) bool { return v <= n }))
}
// removeEmptySeries returns only the time-series with non-empty data
func removeEmptySeries(ctx *common.Context, input singlePathSpec) (ts.SeriesList, error) {
return common.RemoveEmpty(ctx, ts.SeriesList(input))
}
func takeByFunction(input singlePathSpec, n int, sr ts.SeriesReducer, sort ts.Direction) (ts.SeriesList, error) {
series, err := ts.SortSeries(input.Values, sr, sort)
if err != nil {
return ts.SeriesList{}, err
}
r := ts.SeriesList{
Values: series,
SortApplied: true,
}
return common.Head(r, n)
}
// highestSum takes one metric or a wildcard seriesList followed by an integer
// n. Out of all metrics passed, draws only the N metrics with the highest
// total value in the time period specified.
func highestSum(_ *common.Context, input singlePathSpec, n int) (ts.SeriesList, error) {
sr := ts.SeriesReducerSum.Reducer()
return takeByFunction(input, n, sr, ts.Descending)
}
// highestMax takes one metric or a wildcard seriesList followed by an integer
// n. Out of all metrics passed, draws only the N metrics with the highest
// maximum value in the time period specified.
func highestMax(_ *common.Context, input singlePathSpec, n int) (ts.SeriesList, error) {
sr := ts.SeriesReducerMax.Reducer()
return takeByFunction(input, n, sr, ts.Descending)
}
// highestCurrent takes one metric or a wildcard seriesList followed by an
// integer n. Out of all metrics passed, draws only the N metrics with the
// highest value at the end of the time period specified.
func highestCurrent(_ *common.Context, input singlePathSpec, n int) (ts.SeriesList, error) {
sr := ts.SeriesReducerLast.Reducer()
return takeByFunction(input, n, sr, ts.Descending)
}
// highestAverage takes one metric or a wildcard seriesList followed by an
// integer n. Out of all metrics passed, draws only the top N metrics with the
// highest average value for the time period specified.
func highestAverage(_ *common.Context, input singlePathSpec, n int) (ts.SeriesList, error) {
sr := ts.SeriesReducerAvg.Reducer()
return takeByFunction(input, n, sr, ts.Descending)
}
// fallbackSeries takes one metric or a wildcard seriesList, and a second fallback metric.
// If the wildcard does not match any series, draws the fallback metric.
func fallbackSeries(_ *common.Context, input singlePathSpec, fallback singlePathSpec) (ts.SeriesList, error) {
if len(input.Values) > 0 {
return ts.SeriesList(input), nil
}
return ts.SeriesList(fallback), nil
}
// mostDeviant takes one metric or a wildcard seriesList followed by an integer
// N. Draws the N most deviant metrics. To find the deviants, the standard
// deviation (sigma) of each series is taken and ranked. The top N standard
// deviations are returned.
func mostDeviant(_ *common.Context, input singlePathSpec, n int) (ts.SeriesList, error) {
sr := ts.SeriesReducerStdDev.Reducer()
return takeByFunction(input, n, sr, ts.Descending)
}
// lowestAverage takes one metric or a wildcard seriesList followed by an
// integer n. Out of all metrics passed, draws only the top N metrics with the
// lowest average value for the time period specified.
func lowestAverage(_ *common.Context, input singlePathSpec, n int) (ts.SeriesList, error) {
sr := ts.SeriesReducerAvg.Reducer()
return takeByFunction(input, n, sr, ts.Ascending)
}
// lowestCurrent takes one metric or a wildcard seriesList followed by an
// integer n. Out of all metrics passed, draws only the N metrics with the
// lowest value at the end of the time period specified.
func lowestCurrent(_ *common.Context, input singlePathSpec, n int) (ts.SeriesList, error) {
sr := ts.SeriesReducerLast.Reducer()
return takeByFunction(input, n, sr, ts.Ascending)
}
// windowSizeFunc calculates window size for moving average calculation
type windowSizeFunc func(stepSize int) int
// movingAverage calculates the moving average of a metric (or metrics) over a time interval.
func movingAverage(ctx *common.Context, input singlePathSpec, windowSizeValue genericInterface) (*binaryContextShifter, error) {
if len(input.Values) == 0 {
return nil, nil
}
var delta time.Duration
var wf windowSizeFunc
var ws string
switch windowSizeValue := windowSizeValue.(type) {
case string:
interval, err := common.ParseInterval(windowSizeValue)
if err != nil {
return nil, err
}
if interval <= 0 {
err := errors.NewInvalidParamsError(fmt.Errorf(
"windowSize must be positive but instead is %v",
interval))
return nil, err
}
wf = func(stepSize int) int { return int(int64(delta/time.Millisecond) / int64(stepSize)) }
ws = fmt.Sprintf("%q", windowSizeValue)
delta = interval
case float64:
windowSizeInt := int(windowSizeValue)
if windowSizeInt <= 0 {
err := errors.NewInvalidParamsError(fmt.Errorf(
"windowSize must be positive but instead is %d",
windowSizeInt))
return nil, err
}
wf = func(_ int) int { return windowSizeInt }
ws = fmt.Sprintf("%d", windowSizeInt)
maxStepSize := input.Values[0].MillisPerStep()
for i := 1; i < len(input.Values); i++ {
maxStepSize = int(math.Max(float64(maxStepSize), float64(input.Values[i].MillisPerStep())))
}
delta = time.Duration(maxStepSize*windowSizeInt) * time.Millisecond
default:
err := errors.NewInvalidParamsError(fmt.Errorf(
"windowSize must be either a string or an int but instead is a %T",
windowSizeValue))
return nil, err
}
contextShiftingFn := func(c *common.Context) *common.Context {
opts := common.NewChildContextOptions()
opts.AdjustTimeRange(0, 0, delta, 0)
childCtx := c.NewChildContext(opts)
return childCtx
}
bootstrapStartTime, bootstrapEndTime := ctx.StartTime.Add(-delta), ctx.StartTime
transformerFn := func(bootstrapped, original ts.SeriesList) (ts.SeriesList, error) {
bootstrapList, err := combineBootstrapWithOriginal(ctx,
bootstrapStartTime, bootstrapEndTime,
bootstrapped, singlePathSpec(original))
if err != nil {
return ts.SeriesList{}, err
}
results := make([]*ts.Series, 0, original.Len())
for i, bootstrap := range bootstrapList.Values {
series := original.Values[i]
stepSize := series.MillisPerStep()
windowPoints := wf(stepSize)
if windowPoints == 0 {
err := errors.NewInvalidParamsError(fmt.Errorf(
"windowSize should not be smaller than stepSize, windowSize=%v, stepSize=%d",
windowSizeValue, stepSize))
return ts.SeriesList{}, err
}
numSteps := series.Len()
offset := bootstrap.Len() - numSteps
vals := ts.NewValues(ctx, series.MillisPerStep(), numSteps)
sum := 0.0
num := 0
for i := 0; i < numSteps; i++ {
// skip if the number of points received is less than the number of points
// in the lookback window.
if offset < windowPoints {
continue
}
if i == 0 {
for j := offset - windowPoints; j < offset; j++ {
v := bootstrap.ValueAt(j)
if !math.IsNaN(v) {
sum += v
num++
}
}
} else {
prev := bootstrap.ValueAt(i + offset - windowPoints - 1)
next := bootstrap.ValueAt(i + offset - 1)
if !math.IsNaN(prev) {
sum -= prev
num--
}
if !math.IsNaN(next) {
sum += next
num++
}
}
if num > 0 {
vals.SetValueAt(i, sum/float64(num))
}
}
name := fmt.Sprintf("movingAverage(%s,%s)", series.Name(), ws)
newSeries := ts.NewSeries(ctx, name, series.StartTime(), vals)
results = append(results, newSeries)
}
original.Values = results
return original, nil
}
return &binaryContextShifter{
ContextShiftFunc: contextShiftingFn,
BinaryTransformer: transformerFn,
}, nil
}
// totalFunc takes an index and returns a total value for that index
type totalFunc func(int) float64
func totalBySum(seriesList []*ts.Series, index int) float64 {
s, hasValue := 0.0, false
for _, series := range seriesList {
v := series.ValueAt(index)
if !math.IsNaN(v) {
hasValue = true
s += v
}
}
if hasValue {
return s
}
return math.NaN()
}
// asPercent calculates a percentage of the total of a wildcard series.
func asPercent(ctx *common.Context, input singlePathSpec, total genericInterface) (ts.SeriesList, error) {
if len(input.Values) == 0 {
return ts.SeriesList(input), nil
}
var toNormalize, normalized []*ts.Series
var tf totalFunc
var totalText string
switch totalArg := total.(type) {
case ts.SeriesList, singlePathSpec:
var total ts.SeriesList
switch v := totalArg.(type) {
case ts.SeriesList:
total = v
case singlePathSpec:
total = ts.SeriesList(v)
}
if total.Len() == 0 {
// normalize input and sum up input as the total series
toNormalize = input.Values
tf = func(idx int) float64 { return totalBySum(normalized, idx) }
} else {
// check total is a single-series list and normalize all of them
if total.Len() != 1 {
err := errors.NewInvalidParamsError(errors.New("total must be a single series"))
return ts.SeriesList{}, err
}
toNormalize = append(input.Values, total.Values[0])
tf = func(idx int) float64 { return normalized[len(normalized)-1].ValueAt(idx) }
totalText = total.Values[0].Name()
}
case float64:
toNormalize = input.Values
tf = func(idx int) float64 { return totalArg }
totalText = fmt.Sprintf(common.FloatingPointFormat, totalArg)
default:
err := errors.NewInvalidParamsError(errors.New("total is neither an int nor a series"))
return ts.SeriesList{}, err
}
result, _, _, _, err := common.Normalize(ctx, ts.SeriesList{
Values: toNormalize,
})
if err != nil {
return ts.SeriesList{}, err
}
normalized = result.Values
numInputSeries := len(input.Values)
values := make([]ts.MutableValues, 0, numInputSeries)
for i := 0; i < numInputSeries; i++ {
percents := ts.NewValues(ctx, normalized[i].MillisPerStep(), normalized[i].Len())
values = append(values, percents)
}
for i := 0; i < normalized[0].Len(); i++ {
t := tf(i)
for j := 0; j < numInputSeries; j++ {
v := normalized[j].ValueAt(i)
if !math.IsNaN(v) && !math.IsNaN(t) && t != 0 {
values[j].SetValueAt(i, 100.0*v/t)
}
}
}
results := make([]*ts.Series, 0, numInputSeries)
for i := 0; i < numInputSeries; i++ {
var totalName string
if len(totalText) == 0 {
totalName = normalized[i].Specification
} else {
totalName = totalText
}
newName := fmt.Sprintf("asPercent(%s, %s)", normalized[i].Name(), totalName)
newSeries := ts.NewSeries(ctx, newName, normalized[i].StartTime(), values[i])
results = append(results, newSeries)
}
r := ts.SeriesList(input)
r.Values = results
return r, nil
}
// exclude takes a metric or a wildcard seriesList, followed by a regular
// expression in double quotes. Excludes metrics that match the regular
// expression.
func exclude(_ *common.Context, input singlePathSpec, pattern string) (ts.SeriesList, error) {
rePattern, err := regexp.Compile(pattern)
//NB(rooz): we decided to just fail if regex compilation fails to
//differentiate it from an all-excluding regex
if err != nil {
return ts.SeriesList{}, err
}
output := make([]*ts.Series, 0, len(input.Values))
for _, in := range input.Values {
if m := rePattern.FindStringSubmatch(strings.TrimSpace(in.Name())); len(m) == 0 {
output = append(output, in)
}
}
r := ts.SeriesList(input)
r.Values = output
return r, nil
}
// logarithm takes one metric or a wildcard seriesList, and draws the y-axis in
// logarithmic format.
func logarithm(ctx *common.Context, input singlePathSpec, base int) (ts.SeriesList, error) {
if base <= 0 {
err := errors.NewInvalidParamsError(fmt.Errorf("invalid log base %d", base))
return ts.SeriesList{}, err
}
results := make([]*ts.Series, 0, len(input.Values))
for _, series := range input.Values {
vals := ts.NewValues(ctx, series.MillisPerStep(), series.Len())
newName := fmt.Sprintf("log(%s, %d)", series.Name(), base)
if series.AllNaN() {
results = append(results, ts.NewSeries(ctx, newName, series.StartTime(), vals))
continue
}
for i := 0; i < series.Len(); i++ {
n := series.ValueAt(i)
if !math.IsNaN(n) && n > 0 {
vals.SetValueAt(i, math.Log10(n)/math.Log10(float64(base)))
}
}
results = append(results, ts.NewSeries(ctx, newName, series.StartTime(), vals))
}
r := ts.SeriesList(input)
r.Values = results
return r, nil
}
// group takes an arbitrary number of pathspecs and adds them to a single timeseries array.
// This function is used to pass multiple pathspecs to a function which only takes one
func group(_ *common.Context, input multiplePathSpecs) (ts.SeriesList, error) {
return ts.SeriesList(input), nil
}
func derivativeTemplate(ctx *common.Context, input singlePathSpec, nameTemplate string,
fn func(float64, float64) float64) (ts.SeriesList, error) {
output := make([]*ts.Series, len(input.Values))
for i, in := range input.Values {
derivativeValues := ts.NewValues(ctx, in.MillisPerStep(), in.Len())
previousValue := math.NaN()
for step := 0; step < in.Len(); step++ {
value := in.ValueAt(step)
if math.IsNaN(value) || math.IsNaN(previousValue) {
derivativeValues.SetValueAt(step, math.NaN())
} else {
derivativeValues.SetValueAt(step, fn(value, previousValue))
}
previousValue = value
}
name := fmt.Sprintf("%s(%s)", nameTemplate, in.Name())
output[i] = ts.NewSeries(ctx, name, in.StartTime(), derivativeValues)
}
r := ts.SeriesList(input)
r.Values = output
return r, nil
}
// integral shows the sum over time, sort of like a continuous addition function.
// Useful for finding totals or trends in metrics that are collected per minute.
func integral(ctx *common.Context, input singlePathSpec) (ts.SeriesList, error) {
results := make([]*ts.Series, 0, len(input.Values))
for _, series := range input.Values {
if series.AllNaN() {
results = append(results, series)
continue
}
outvals := ts.NewValues(ctx, series.MillisPerStep(), series.Len())
var current float64
for i := 0; i < series.Len(); i++ {
n := series.ValueAt(i)
if !math.IsNaN(n) {
current += n
outvals.SetValueAt(i, current)
}
}
newName := fmt.Sprintf("integral(%s)", series.Name())
results = append(results, ts.NewSeries(ctx, newName, series.StartTime(), outvals))
}
r := ts.SeriesList(input)
r.Values = results
return r, nil
}
// This is the opposite of the integral function. This is useful for taking a
// running total metric and calculating the delta between subsequent data
// points.
func derivative(ctx *common.Context, input singlePathSpec) (ts.SeriesList, error) {
return derivativeTemplate(ctx, input, "derivative", func(value, previousValue float64) float64 {
return value - previousValue
})
}
// Same as the derivative function above, but ignores datapoints that trend down.
func nonNegativeDerivative(ctx *common.Context, input singlePathSpec, maxValue float64) (ts.SeriesList, error) {
return derivativeTemplate(ctx, input, "nonNegativeDerivative", func(value, previousValue float64) float64 {
difference := value - previousValue
if difference >= 0 {
return difference
} else if !math.IsNaN(maxValue) && maxValue >= value {
return (maxValue - previousValue) + value + 1.0
} else {
return math.NaN()
}
})
}
// nPercentile returns percentile-percent of each series in the seriesList.
func nPercentile(ctx *common.Context, seriesList singlePathSpec, percentile float64) (ts.SeriesList, error) {
return common.NPercentile(ctx, ts.SeriesList(seriesList), percentile, func(name string, percentile float64) string {
return fmt.Sprintf("nPercentile(%s, "+common.FloatingPointFormat+")", name, percentile)
})
}
func percentileOfSeries(ctx *common.Context, seriesList singlePathSpec, percentile float64, interpolateValue genericInterface) (ts.SeriesList, error) {
if percentile <= 0 || percentile > 100 {
err := errors.NewInvalidParamsError(fmt.Errorf(
"the requested percentile value must be betwween 0 and 100"))
return ts.SeriesList{}, err
}
var interpolate bool
switch interpolateValue := interpolateValue.(type) {
case bool:
interpolate = interpolateValue
case string:
if interpolateValue == "true" {
interpolate = true
} else if interpolateValue != "false" {
err := errors.NewInvalidParamsError(fmt.Errorf(
"interpolateValue must be either true or false but instead is %s",
interpolateValue))
return ts.SeriesList{}, err
}
default:
err := errors.NewInvalidParamsError(fmt.Errorf(
"interpolateValue must be either a boolean or a string but instead is %T",
interpolateValue))
return ts.SeriesList{}, err
}
if len(seriesList.Values) == 0 {
err := errors.NewInvalidParamsError(fmt.Errorf("series list cannot be empty"))
return ts.SeriesList{}, err
}
normalize, _, _, _, err := common.Normalize(ctx, ts.SeriesList(seriesList))
if err != nil {
return ts.SeriesList{}, err
}
step := seriesList.Values[0].MillisPerStep()
for _, series := range seriesList.Values[1:] {
if step != series.MillisPerStep() {
err := errors.NewInvalidParamsError(fmt.Errorf(
"different step sizes in input series not supported"))
return ts.SeriesList{}, err
}
}
// TODO: This is wrong when MillisPerStep is different across
// the timeseries.
min := seriesList.Values[0].Len()
for _, series := range seriesList.Values[1:] {
numSteps := series.Len()
if numSteps < min {
min = numSteps
}
}
percentiles := make([]float64, min)
for i := 0; i < min; i++ {
row := make([]float64, len(seriesList.Values))
for j, series := range seriesList.Values {
row[j] = series.ValueAt(i)
}
percentiles[i] = common.GetPercentile(row, percentile, interpolate)
}
percentilesSeries := ts.NewValues(ctx, normalize.Values[0].MillisPerStep(), min)
for k := 0; k < min; k++ {