From cf7157f683960b220237eba9f4d281f27a0e2562 Mon Sep 17 00:00:00 2001 From: Alexander Weaver Date: Tue, 18 Apr 2023 14:21:28 -0500 Subject: [PATCH] Alerting: Capture refID of rule's condition expression in Loki state history entries (#66419) * Capture condition from rule * Add test --- pkg/services/ngalert/state/historian/loki.go | 2 ++ pkg/services/ngalert/state/historian/loki_test.go | 15 +++++++++++++++ .../ngalert/state/historian/model/rule.go | 2 ++ 3 files changed, 19 insertions(+) diff --git a/pkg/services/ngalert/state/historian/loki.go b/pkg/services/ngalert/state/historian/loki.go index 99364a788ad..1f8ff0e8196 100644 --- a/pkg/services/ngalert/state/historian/loki.go +++ b/pkg/services/ngalert/state/historian/loki.go @@ -260,6 +260,7 @@ func statesToStream(rule history_model.RuleMeta, states []state.StateTransition, Previous: state.PreviousFormatted(), Current: state.Formatted(), Values: valuesAsDataBlob(state.State), + Condition: rule.Condition, DashboardUID: rule.DashboardUID, PanelID: rule.PanelID, InstanceLabels: removePrivateLabels(state.Labels), @@ -302,6 +303,7 @@ type lokiEntry struct { Current string `json:"current"` Error string `json:"error,omitempty"` Values *simplejson.Json `json:"values"` + Condition string `json:"condition"` DashboardUID string `json:"dashboardUID"` PanelID int64 `json:"panelID"` // InstanceLabels is exactly the set of labels associated with the alert instance in Alertmanager. diff --git a/pkg/services/ngalert/state/historian/loki_test.go b/pkg/services/ngalert/state/historian/loki_test.go index d254b5c05d0..b2c6a9b5ece 100644 --- a/pkg/services/ngalert/state/historian/loki_test.go +++ b/pkg/services/ngalert/state/historian/loki_test.go @@ -139,6 +139,21 @@ func TestRemoteLokiBackend(t *testing.T) { require.InDelta(t, 2.0, entry.Values.Get("A").MustFloat64(), 1e-4) require.InDelta(t, 5.5, entry.Values.Get("B").MustFloat64(), 1e-4) }) + + t.Run("captures condition from rule", func(t *testing.T) { + rule := createTestRule() + rule.Condition = "some-condition" + l := log.NewNopLogger() + states := singleFromNormal(&state.State{ + State: eval.Alerting, + Labels: data.Labels{"a": "b"}, + }) + + res := statesToStream(rule, states, nil, l) + + entry := requireSingleEntry(t, res) + require.Equal(t, rule.Condition, entry.Condition) + }) }) t.Run("selector string", func(t *testing.T) { diff --git a/pkg/services/ngalert/state/historian/model/rule.go b/pkg/services/ngalert/state/historian/model/rule.go index 5a76d60c9ce..288a84a8e6e 100644 --- a/pkg/services/ngalert/state/historian/model/rule.go +++ b/pkg/services/ngalert/state/historian/model/rule.go @@ -19,6 +19,7 @@ type RuleMeta struct { NamespaceUID string DashboardUID string PanelID int64 + Condition string } func NewRuleMeta(r *models.AlertRule, log log.Logger) RuleMeta { @@ -43,6 +44,7 @@ func NewRuleMeta(r *models.AlertRule, log log.Logger) RuleMeta { NamespaceUID: r.NamespaceUID, DashboardUID: dashUID, PanelID: panelID, + Condition: r.Condition, } }