Skip to content

Commit dd3060f

Browse files
committed
feat(alerting): calculate avg of valid points
1 parent c17064f commit dd3060f

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

pkg/services/alerting/conditions/reducer.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,17 @@ func (s *SimpleReducer) Reduce(series *tsdb.TimeSeries) null.Float {
2727

2828
switch s.Type {
2929
case "avg":
30+
validPointsCount := 0
3031
for _, point := range series.Points {
3132
if point[0].Valid {
3233
value += point[0].Float64
34+
validPointsCount += 1
3335
allNull = false
3436
}
3537
}
36-
value = value / float64(len(series.Points))
38+
if validPointsCount > 0 {
39+
value = value / float64(validPointsCount)
40+
}
3741
case "sum":
3842
for _, point := range series.Points {
3943
if point[0].Valid {
@@ -90,7 +94,6 @@ func (s *SimpleReducer) Reduce(series *tsdb.TimeSeries) null.Float {
9094
value = (values[(length/2)-1] + values[length/2]) / 2
9195
}
9296
}
93-
9497
}
9598

9699
if allNull {

pkg/services/alerting/conditions/reducer_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,20 @@ func TestSimpleReducer(t *testing.T) {
1616
So(result, ShouldEqual, float64(2))
1717
})
1818

19+
Convey("avg of none null data", func() {
20+
reducer := NewSimpleReducer("avg")
21+
series := &tsdb.TimeSeries{
22+
Name: "test time serie",
23+
}
24+
25+
series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(3), 1))
26+
series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFromPtr(nil), 2))
27+
series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFromPtr(nil), 3))
28+
series.Points = append(series.Points, tsdb.NewTimePoint(null.FloatFrom(3), 4))
29+
30+
So(reducer.Reduce(series).Float64, ShouldEqual, float64(3))
31+
})
32+
1933
Convey("sum", func() {
2034
result := testReducer("sum", 1, 2, 3)
2135
So(result, ShouldEqual, float64(6))

0 commit comments

Comments
 (0)