Skip to content
Merged
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
4 changes: 4 additions & 0 deletions docs/querying/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -673,7 +673,11 @@ GET /api/v1/rules
```

URL query parameters:

- `type=alert|record`: return only the alerting rules (e.g. `type=alert`) or the recording rules (e.g. `type=record`). When the parameter is absent or empty, no filtering is done.
- `rule_name[]=<string>`: only return rules with the given rule name. If the parameter is repeated, rules with any of the provided names are returned. If we've filtered out all the rules of a group, the group is not returned. When the parameter is absent or empty, no filtering is done.
- `rule_group[]=<string>`: only return rules with the given rule group name. If the parameter is repeated, rules with any of the provided rule group names are returned. When the parameter is absent or empty, no filtering is done.
- `file[]=<string>`: only return rules with the given filepath. If the parameter is repeated, rules with any of the provided filepaths are returned. When the parameter is absent or empty, no filtering is done.

```json
$ curl http://localhost:9090/api/v1/rules
Expand Down
55 changes: 48 additions & 7 deletions web/api/v1/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -1292,8 +1292,24 @@ type RecordingRule struct {
}

func (api *API) rules(r *http.Request) apiFuncResult {
if err := r.ParseForm(); err != nil {
return apiFuncResult{nil, &apiError{errorBadData, errors.Wrapf(err, "error parsing form values")}, nil, nil}
}

queryFormToSet := func(values []string) map[string]struct{} {
set := make(map[string]struct{}, len(values))
for _, v := range values {
set[v] = struct{}{}
}
return set
}

rnSet := queryFormToSet(r.Form["rule_name[]"])
rgSet := queryFormToSet(r.Form["rule_group[]"])
fSet := queryFormToSet(r.Form["file[]"])

ruleGroups := api.rulesRetriever(r.Context()).RuleGroups()
res := &RuleDiscovery{RuleGroups: make([]*RuleGroup, len(ruleGroups))}
res := &RuleDiscovery{RuleGroups: make([]*RuleGroup, 0, len(ruleGroups))}
typ := strings.ToLower(r.URL.Query().Get("type"))

if typ != "" && typ != "alert" && typ != "record" {
Expand All @@ -1303,7 +1319,20 @@ func (api *API) rules(r *http.Request) apiFuncResult {
returnAlerts := typ == "" || typ == "alert"
returnRecording := typ == "" || typ == "record"

for i, grp := range ruleGroups {
rgs := make([]*RuleGroup, 0, len(ruleGroups))
for _, grp := range ruleGroups {
if len(rgSet) > 0 {
if _, ok := rgSet[grp.Name()]; !ok {
continue
}
}

if len(fSet) > 0 {
if _, ok := fSet[grp.File()]; !ok {
continue
}
}

apiRuleGroup := &RuleGroup{
Name: grp.Name(),
File: grp.File(),
Expand All @@ -1313,14 +1342,20 @@ func (api *API) rules(r *http.Request) apiFuncResult {
EvaluationTime: grp.GetEvaluationTime().Seconds(),
LastEvaluation: grp.GetLastEvaluation(),
}
for _, r := range grp.Rules() {
for _, rr := range grp.Rules() {
Copy link
Member Author

@gotjosh gotjosh Apr 18, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drive-by fix because r was shadowed by r *http.Request

var enrichedRule Rule

if len(rnSet) > 0 {
if _, ok := rnSet[rr.Name()]; !ok {
continue
}
}

lastError := ""
if r.LastError() != nil {
lastError = r.LastError().Error()
if rr.LastError() != nil {
lastError = rr.LastError().Error()
}
switch rule := r.(type) {
switch rule := rr.(type) {
case *rules.AlertingRule:
if !returnAlerts {
break
Expand Down Expand Up @@ -1358,12 +1393,18 @@ func (api *API) rules(r *http.Request) apiFuncResult {
err := errors.Errorf("failed to assert type of rule '%v'", rule.Name())
return apiFuncResult{nil, &apiError{errorInternal, err}, nil, nil}
}

if enrichedRule != nil {
apiRuleGroup.Rules = append(apiRuleGroup.Rules, enrichedRule)
}
}
res.RuleGroups[i] = apiRuleGroup

// If the rule group response has no rules, skip it - this means we filtered all the rules of this group.
if len(apiRuleGroup.Rules) > 0 {
rgs = append(rgs, apiRuleGroup)
}
}
res.RuleGroups = rgs
return apiFuncResult{res, nil, nil, nil}
}

Expand Down
59 changes: 59 additions & 0 deletions web/api/v1/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1973,6 +1973,65 @@ func testEndpoints(t *testing.T, api *API, tr *testTargetRetriever, es storage.E
},
},
},
{
endpoint: api.rules,
query: url.Values{"rule_name[]": []string{"test_metric4"}},
response: &RuleDiscovery{
RuleGroups: []*RuleGroup{
{
Name: "grp",
File: "/path/to/file",
Interval: 1,
Limit: 0,
Rules: []Rule{
AlertingRule{
State: "inactive",
Name: "test_metric4",
Query: "up == 1",
Duration: 1,
Labels: labels.Labels{},
Annotations: labels.Labels{},
Alerts: []*Alert{},
Health: "unknown",
Type: "alerting",
},
},
},
},
},
},
{
endpoint: api.rules,
query: url.Values{"rule_group[]": []string{"respond-with-nothing"}},
response: &RuleDiscovery{RuleGroups: []*RuleGroup{}},
},
{
endpoint: api.rules,
query: url.Values{"file[]": []string{"/path/to/file"}, "rule_name[]": []string{"test_metric4"}},
response: &RuleDiscovery{
RuleGroups: []*RuleGroup{
{
Name: "grp",
File: "/path/to/file",
Interval: 1,
Limit: 0,
Rules: []Rule{
AlertingRule{
State: "inactive",
Name: "test_metric4",
Query: "up == 1",
Duration: 1,
Labels: labels.Labels{},
Annotations: labels.Labels{},
Alerts: []*Alert{},
Health: "unknown",
Type: "alerting",
},
},
},
},
},
},
{
endpoint: api.queryExemplars,
query: url.Values{
Expand Down