Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions cmd/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,18 @@ inactive = 0`,
// We use the Rules endpoint since it contains
// the state of inactive Alert Rules, unlike the Alert endpoint
// Search requested Alert in all Groups and all Rules
alerts, err := c.API.Rules(ctx)
if err != nil {
check.ExitError(err)
alertrules, errR := c.API.Rules(ctx)
if errR != nil {
check.ExitError(errR)
}

alerts, errA := c.API.Alerts(ctx)
if errA != nil {
check.ExitError(errA)
}

// Get all rules from all groups into a single list
rules := alert.FlattenRules(alerts.Groups, cliAlertConfig.Group)
rules := alert.FlattenRules(alertrules.Groups, cliAlertConfig.Group, alerts.Alerts)

// If there are no rules we can exit early
if len(rules) == 0 {
Expand Down
14 changes: 13 additions & 1 deletion internal/alert/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,18 @@ import (
"github.com/prometheus/common/model"
)

const (
alertnameLabelKey = "alertname"
)

// Internal representation of Prometheus Rules.
// Alert attribute will be used when iterating over multiple AlertingRules.
type Rule struct {
AlertingRule v1.AlertingRule
Alert *v1.Alert
}

func FlattenRules(groups []v1.RuleGroup, wantedGroups []string) []Rule {
func FlattenRules(groups []v1.RuleGroup, wantedGroups []string, alerts []v1.Alert) []Rule {
// Flattens a list of RuleGroup containing a list of Rules into
// a list of internal Alertingrules.
var l int
Expand Down Expand Up @@ -50,6 +54,14 @@ func FlattenRules(groups []v1.RuleGroup, wantedGroups []string) []Rule {
// since RecodingRules can simply be queried.
if _, ok := rl.(v1.AlertingRule); ok {
r.AlertingRule = rl.(v1.AlertingRule)
// Merge labels from active alerts
for _, al := range alerts {
alertName := al.Labels[alertnameLabelKey]
if r.AlertingRule.Name == string(alertName) {
r.AlertingRule.Labels = r.AlertingRule.Labels.Merge(al.Labels)
}
}

rules = append(rules, r)
}
}
Expand Down
17 changes: 13 additions & 4 deletions internal/alert/alert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,15 @@ func TestGetOutput(t *testing.T) {
func TestFlattenRules(t *testing.T) {
testTime := time.Now()

alerts := []v1.Alert{
v1.Alert{
Labels: model.LabelSet{
"alertname": "HighRequestLatency",
"instance": "node01",
},
},
}

rg := []v1.RuleGroup{
{
Name: "example",
Expand Down Expand Up @@ -226,9 +235,9 @@ func TestFlattenRules(t *testing.T) {
},
}

fr := FlattenRules(rg, nil)
if len(fr) != 1 {
t.Error("\nActual: ", fr)
}
actual := FlattenRules(rg, nil, alerts)

if len(actual) != 1 {
t.Error("\nActual: ", actual)
}
}