From aa9a0447033a6487c20226d8938eef8140b66a76 Mon Sep 17 00:00:00 2001 From: Thomas Jackson Date: Tue, 17 Sep 2024 13:56:06 -0700 Subject: [PATCH] Fix AddLabelClient handling of multiple matching labels As reported in #665 the initial implementation fixed *some* cases but not all. This fixes the typo and edge-case handling missed in the previous PR. Fixes #665 --- pkg/promclient/label.go | 19 +++++++++++++------ pkg/promclient/label_test.go | 15 +++++++++++++++ 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/pkg/promclient/label.go b/pkg/promclient/label.go index abc39479..2186f790 100644 --- a/pkg/promclient/label.go +++ b/pkg/promclient/label.go @@ -59,24 +59,31 @@ func (c *AddLabelClient) Key() model.LabelSet { func (c *AddLabelClient) filterMatchers(matchers []string) ([]string, bool, error) { ret := make([]string, 0, len(matchers)) - for i, matcher := range matchers { + for _, matcher := range matchers { selectors, err := parser.ParseMetricSelector(matcher) if err != nil { return nil, true, err } + filteredSelectors := make([]*labels.Matcher, 0, len(selectors)) + // If the selector matches our value -- remove the selector // if the selector doesn't match, return empty - for sI, s := range selectors { + for _, s := range selectors { if v, ok := c.Labels[model.LabelName(s.Name)]; ok { - if s.Matches(string(v)) { - selectors = append(selectors[:sI], selectors[i+1:]...) - } else { + // If the selector doesn't match the labels from our client; we don't match + if !s.Matches(string(v)) { return nil, false, nil } + } else { // Otherwise if the selector isn't part of the `Labels` we add; we pass it along + filteredSelectors = append(filteredSelectors, s) } } - newMatcher, err := promhttputil.MatcherToString(selectors) + // If the selector is cleared -- then we skip it in the return + if len(filteredSelectors) == 0 { + continue + } + newMatcher, err := promhttputil.MatcherToString(filteredSelectors) if err != nil { return nil, false, err } diff --git a/pkg/promclient/label_test.go b/pkg/promclient/label_test.go index 9f97ff11..c03694e8 100644 --- a/pkg/promclient/label_test.go +++ b/pkg/promclient/label_test.go @@ -181,6 +181,21 @@ func TestAddLabelClient(t *testing.T) { labelValues: []string{"1"}, matchers: []string{`{b="1"}`}, }, + { + labelSet: model.LabelSet{"b": "1", "c": "1"}, + labelValues: []string{"1"}, + matchers: []string{`{b="1", c="1"}`}, + }, + { + labelSet: model.LabelSet{"b": "1", "c": "1", "d": "1"}, + labelValues: []string{"1"}, + matchers: []string{`{b="1", c="1"}`}, + }, + { + labelSet: model.LabelSet{"b": "1", "c": "1", "d": "1"}, + labelValues: []string{"1"}, + matchers: []string{`{a="1", b="1", c="1"}`}, + }, } for i, test := range tests {