From 95b9fa33468ed25596704e7a59ecaf50fc44b4c7 Mon Sep 17 00:00:00 2001 From: Jorge Luis Betancourt Date: Tue, 11 Oct 2022 14:40:18 +0200 Subject: [PATCH] Alerting: Fix duration calculation when testing a rule (#56616) When testing a rule within the legacy alerting the `timeMs` field could sometimes show negative (and/or wrongly calculated) durations. This happens if the alert evaluation crosses a second boundary. This change uses the full timestamp to compute the eval duration. --- pkg/services/alerting/eval_context.go | 2 +- pkg/services/alerting/eval_context_test.go | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/pkg/services/alerting/eval_context.go b/pkg/services/alerting/eval_context.go index e4b3a8a2fbf..c67804c163c 100644 --- a/pkg/services/alerting/eval_context.go +++ b/pkg/services/alerting/eval_context.go @@ -107,7 +107,7 @@ func (c *EvalContext) shouldUpdateAlertState() bool { // GetDurationMs returns the duration of the alert evaluation. func (c *EvalContext) GetDurationMs() float64 { - return float64(c.EndTime.Nanosecond()-c.StartTime.Nanosecond()) / float64(1000000) + return float64(c.EndTime.Sub(c.StartTime).Nanoseconds()) / float64(time.Millisecond) } // GetNotificationTitle returns the title of the alert rule including alert state. diff --git a/pkg/services/alerting/eval_context_test.go b/pkg/services/alerting/eval_context_test.go index d05ea3b995c..b731ed3542c 100644 --- a/pkg/services/alerting/eval_context_test.go +++ b/pkg/services/alerting/eval_context_test.go @@ -404,3 +404,18 @@ func TestEvaluateNotificationTemplateFields(t *testing.T) { }) } } + +func TestGetDurationFromEvalContext(t *testing.T) { + startTime, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", "2022-10-03 11:33:14.438803 +0200 CEST") + require.NoError(t, err) + + endTime, err := time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", "2022-10-03 11:33:15.291075 +0200 CEST") + require.NoError(t, err) + + evalContext := EvalContext{ + StartTime: startTime, + EndTime: endTime, + } + + assert.Equal(t, float64(852.272), evalContext.GetDurationMs()) +}