This repository has been archived by the owner on Aug 23, 2023. It is now read-only.
/
func_keeplastvalue.go
84 lines (72 loc) · 1.88 KB
/
func_keeplastvalue.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
package expr
import (
"fmt"
"math"
"github.com/grafana/metrictank/api/models"
"github.com/grafana/metrictank/schema"
)
type FuncKeepLastValue struct {
in GraphiteFunc
limit int64
}
func NewKeepLastValue() GraphiteFunc {
return &FuncKeepLastValue{limit: math.MaxInt64}
}
func (s *FuncKeepLastValue) Signature() ([]Arg, []Arg) {
var stub string
return []Arg{
ArgSeriesList{val: &s.in},
ArgIn{key: "limit",
opt: true,
args: []Arg{
ArgInt{val: &s.limit},
// Treats any string as infinity. This matches Graphite's behavior
// (although intended bevahior is to let user specify "INF" as the limit)
ArgString{val: &stub},
ArgQuotelessString{val: &stub},
},
},
},
[]Arg{ArgSeriesList{}}
}
func (s *FuncKeepLastValue) Context(context Context) Context {
return context
}
func (s *FuncKeepLastValue) Exec(dataMap DataMap) ([]models.Series, error) {
series, err := s.in.Exec(dataMap)
if err != nil {
return nil, err
}
limit := int(s.limit)
outSeries := make([]models.Series, 0, len(series))
for _, serie := range series {
serie.Target = fmt.Sprintf("keepLastValue(%s)", serie.Target)
serie.QueryPatt = serie.Target
out := pointSlicePool.Get().([]schema.Point)
var consecutiveNaNs int
lastVal := math.NaN()
for i, p := range serie.Datapoints {
out = append(out, p)
if math.IsNaN(p.Val) {
consecutiveNaNs++
continue
}
if 0 < consecutiveNaNs && consecutiveNaNs <= limit && !math.IsNaN(lastVal) {
for j := i - consecutiveNaNs; j < i; j++ {
out[j].Val = lastVal
}
}
consecutiveNaNs = 0
lastVal = p.Val
}
if 0 < consecutiveNaNs && consecutiveNaNs <= limit && !math.IsNaN(lastVal) {
for i := len(out) - consecutiveNaNs; i < len(out); i++ {
out[i].Val = lastVal
}
}
serie.Datapoints = out
outSeries = append(outSeries, serie)
}
dataMap.Add(Req{}, outSeries...)
return outSeries, nil
}