diff --git a/pkg/services/alerting/conditions/reducer.go b/pkg/services/alerting/conditions/reducer.go index 0f396e2ffc3..6eaa21b958e 100644 --- a/pkg/services/alerting/conditions/reducer.go +++ b/pkg/services/alerting/conditions/reducer.go @@ -94,6 +94,53 @@ func (s *SimpleReducer) Reduce(series *tsdb.TimeSeries) null.Float { value = (values[(length/2)-1] + values[length/2]) / 2 } } + case "diff": + var ( + points = series.Points + first float64 + i int + ) + // get the newest point + for i = len(points) - 1; i >= 0; i-- { + if points[i][0].Valid { + allNull = false + first = points[i][0].Float64 + break + } + } + // get other points + points = points[0:i] + for i := len(points) - 1; i >= 0; i-- { + if points[i][0].Valid { + allNull = false + value = first - points[i][0].Float64 + break + } + } + case "percent_diff": + var ( + points = series.Points + first float64 + i int + ) + // get the newest point + for i = len(points) - 1; i >= 0; i-- { + if points[i][0].Valid { + allNull = false + first = points[i][0].Float64 + break + } + } + // get other points + points = points[0:i] + for i := len(points) - 1; i >= 0; i-- { + if points[i][0].Valid { + allNull = false + val := (first - points[i][0].Float64) / points[i][0].Float64 * 100 + value = math.Abs(val) + break + } + } } if allNull { diff --git a/pkg/services/alerting/conditions/reducer_test.go b/pkg/services/alerting/conditions/reducer_test.go index ff6105a06ec..f0147e9021a 100644 --- a/pkg/services/alerting/conditions/reducer_test.go +++ b/pkg/services/alerting/conditions/reducer_test.go @@ -80,6 +80,17 @@ func TestSimpleReducer(t *testing.T) { So(reducer.Reduce(series).Float64, ShouldEqual, float64(3)) }) + + Convey("diff", func() { + result := testReducer("diff", 30, 40) + So(result, ShouldEqual, float64(10)) + }) + + Convey("percent_diff", func() { + result := testReducer("percent_diff", 30, 40) + So(result, ShouldEqual, float64(33.33333333333333)) + }) + }) } diff --git a/public/app/features/alerting/alert_def.ts b/public/app/features/alerting/alert_def.ts index 48cd4b056d9..51cbbd9691f 100644 --- a/public/app/features/alerting/alert_def.ts +++ b/public/app/features/alerting/alert_def.ts @@ -49,6 +49,8 @@ var reducerTypes = [ {text: 'count()', value: 'count'}, {text: 'last()', value: 'last'}, {text: 'median()', value: 'median'}, + {text: 'diff()', value: 'diff'}, + {text: 'percent_diff()', value: 'percent_diff'}, ]; var noDataModes = [