Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add matcher support to Query Rules endpoint #5111

Merged
merged 5 commits into from
Feb 3, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ We use *breaking :warning:* to mark changes that are not backward compatible (re
- [#4974](https://github.com/thanos-io/thanos/pull/4974) Store: Support tls_config configuration for connecting with Azure storage.
- [#4999](https://github.com/thanos-io/thanos/pull/4999) COS: Support `endpoint` configuration for vpc internal endpoint.
- [#5059](https://github.com/thanos-io/thanos/pull/5059) Compactor: Adding minimum retention flag validation for downsampling retention.
- [#5111](https://github.com/thanos-io/thanos/pull/5111) Add matcher support to Query Rules endpoint
Copy link
Member

Choose a reason for hiding this comment

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

A small nit: add dot at the line end.

Copy link
Member Author

Choose a reason for hiding this comment

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

Done! Also, have added tests! 🙂


### Fixed

Expand Down
5 changes: 5 additions & 0 deletions pkg/api/query/v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -787,10 +787,15 @@ func NewRulesHandler(client rules.UnaryClient, enablePartialResponse bool) func(
typ = int32(rulespb.RulesRequest_ALL)
}

if err := r.ParseForm(); err != nil {
return nil, nil, &api.ApiError{Typ: api.ErrorInternal, Err: errors.Errorf("error parsing request form='%v'", typeParam)}
}

// TODO(bwplotka): Allow exactly the same functionality as query API: passing replica, dedup and partial response as HTTP params as well.
req := &rulespb.RulesRequest{
Type: rulespb.RulesRequest_Type(typ),
PartialResponseStrategy: ps,
MatcherString: r.Form[MatcherParam],
}
tracing.DoInSpan(ctx, "retrieve_rules", func(ctx context.Context) {
groups, warnings, err = client.Rules(ctx, req)
Expand Down
59 changes: 59 additions & 0 deletions pkg/rules/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@ import (
"context"
"sort"
"sync"
"text/template"
"text/template/parse"

"github.com/pkg/errors"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql/parser"
"github.com/prometheus/prometheus/storage"

"github.com/thanos-io/thanos/pkg/rules/rulespb"
Expand Down Expand Up @@ -58,6 +61,16 @@ func (rr *GRPCClient) Rules(ctx context.Context, req *rulespb.RulesRequest) (*ru
return nil, nil, errors.Wrap(err, "proxy Rules")
}

var matcherSets [][]*labels.Matcher
Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we pre-allocate here? We know the final slice's length, right?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, will pre-allocate!

Copy link
Member Author

Choose a reason for hiding this comment

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

Done!

for _, s := range req.MatcherString {
matchers, err := parser.ParseMetricSelector(s)
if err != nil {
return nil, nil, errors.Wrap(err, "proxy Rules")
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: Should make the error description just a tiny bit clearer?

Suggested change
return nil, nil, errors.Wrap(err, "proxy Rules")
return nil, nil, errors.Wrap(err, "parser ParseMetricSelector")

Copy link
Member Author

Choose a reason for hiding this comment

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

Ah! Nice catch, will change this!

Copy link
Member Author

Choose a reason for hiding this comment

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

Done!

}
matcherSets = append(matcherSets, matchers)
}

resp.groups = filterRules(resp.groups, matcherSets)
// TODO(bwplotka): Move to SortInterface with equal method and heap.
resp.groups = dedupGroups(resp.groups)
for _, g := range resp.groups {
Expand All @@ -67,6 +80,52 @@ func (rr *GRPCClient) Rules(ctx context.Context, req *rulespb.RulesRequest) (*ru
return &rulespb.RuleGroups{Groups: resp.groups}, resp.warnings, nil
}

// filterRules filters rules in a group according to given matcherSets.
func filterRules(ruleGroups []*rulespb.RuleGroup, matcherSets [][]*labels.Matcher) []*rulespb.RuleGroup {
if len(matcherSets) == 0 || len(ruleGroups) == 0 {
return ruleGroups
}

for _, g := range ruleGroups {
filteredRules := []*rulespb.Rule{}
Copy link
Member

Choose a reason for hiding this comment

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

A small advice: use filteredRules := g.Rules[:0] avoid allocate.
https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating

Copy link
Member Author

Choose a reason for hiding this comment

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

Done!

for _, r := range g.Rules {
rl := r.GetLabels()
if matches(matcherSets, rl) {
filteredRules = append(filteredRules, r)
}
}
g.Rules = filteredRules
}

return ruleGroups
}

// matches returns whether the non-templated labels satisfy all the matchers in matcherSets.
func matches(matcherSets [][]*labels.Matcher, l labels.Labels) bool {
if len(matcherSets) == 0 {
return true
}

var nonTemplatedLabels labels.Labels
labelTemplate := template.New("label")
for _, label := range l {
t, err := labelTemplate.Parse(label.Value)
// Label value is non-templated if it is one node of type NodeText.
if err == nil && len(t.Root.Nodes) == 1 && t.Root.Nodes[0].Type() == parse.NodeText {
nonTemplatedLabels = append(nonTemplatedLabels, label)
}
}

for _, matchers := range matcherSets {
for _, m := range matchers {
if v := nonTemplatedLabels.Get(m.Name); !m.Matches(v) {
return false
}
}
}
return true
}

// dedupRules re-sorts the set so that the same series with different replica
// labels are coming right after each other.
func dedupRules(rules []*rulespb.Rule, replicaLabels map[string]struct{}) []*rulespb.Rule {
Expand Down
177 changes: 113 additions & 64 deletions pkg/rules/rulespb/rpc.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pkg/rules/rulespb/rpc.proto
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ message RulesRequest {
}
Type type = 1;
PartialResponseStrategy partial_response_strategy = 2;
repeated string MatcherString = 3;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should we keep this field name snake_case?

Copy link
Member Author

Choose a reason for hiding this comment

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

Sure, let me change!

Copy link
Member Author

Choose a reason for hiding this comment

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

Done!

}

message RulesResponse {
Expand Down