Skip to content

Commit 8cd4ee2

Browse files
committed
Include active alert labels in alert subcommand
1 parent f27f59d commit 8cd4ee2

File tree

3 files changed

+23
-7
lines changed

3 files changed

+23
-7
lines changed

cmd/alert.go

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,13 +71,18 @@ inactive = 0`,
7171
// We use the Rules endpoint since it contains
7272
// the state of inactive Alert Rules, unlike the Alert endpoint
7373
// Search requested Alert in all Groups and all Rules
74-
alerts, err := c.API.Rules(ctx)
75-
if err != nil {
76-
check.ExitError(err)
74+
alertrules, errR := c.API.Rules(ctx)
75+
if errR != nil {
76+
check.ExitError(errR)
77+
}
78+
79+
alerts, errA := c.API.Alerts(ctx)
80+
if errA != nil {
81+
check.ExitError(errA)
7782
}
7883

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

8287
// If there are no rules we can exit early
8388
if len(rules) == 0 {

internal/alert/alert.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,18 @@ import (
1212
"github.com/prometheus/common/model"
1313
)
1414

15+
const (
16+
alertnameLabelKey = "alertname"
17+
)
18+
1519
// Internal representation of Prometheus Rules.
1620
// Alert attribute will be used when iterating over multiple AlertingRules.
1721
type Rule struct {
1822
AlertingRule v1.AlertingRule
1923
Alert *v1.Alert
2024
}
2125

22-
func FlattenRules(groups []v1.RuleGroup, wantedGroups []string) []Rule {
26+
func FlattenRules(groups []v1.RuleGroup, wantedGroups []string, alerts []v1.Alert) []Rule {
2327
// Flattens a list of RuleGroup containing a list of Rules into
2428
// a list of internal Alertingrules.
2529
var l int
@@ -50,6 +54,14 @@ func FlattenRules(groups []v1.RuleGroup, wantedGroups []string) []Rule {
5054
// since RecodingRules can simply be queried.
5155
if _, ok := rl.(v1.AlertingRule); ok {
5256
r.AlertingRule = rl.(v1.AlertingRule)
57+
// Merge labels from active alerts
58+
for _, al := range alerts {
59+
alertName := al.Labels[alertnameLabelKey]
60+
if r.AlertingRule.Name == string(alertName) {
61+
r.AlertingRule.Labels = r.AlertingRule.Labels.Merge(al.Labels)
62+
}
63+
}
64+
5365
rules = append(rules, r)
5466
}
5567
}

internal/alert/alert_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,9 +226,8 @@ func TestFlattenRules(t *testing.T) {
226226
},
227227
}
228228

229-
fr := FlattenRules(rg, nil)
229+
fr := FlattenRules(rg, nil, []v1.Alert{})
230230
if len(fr) != 1 {
231231
t.Error("\nActual: ", fr)
232232
}
233-
234233
}

0 commit comments

Comments
 (0)