prometheus/labels/selector.go

87 lines
2.5 KiB
Go
Raw Normal View History

2017-04-10 11:59:45 -07:00
// Copyright 2017 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2016-12-21 00:39:01 -08:00
package labels
import "regexp"
// Selector holds constraints for matching against a label set.
type Selector []Matcher
// Matches returns whether the labels satisfy all matchers.
func (s Selector) Matches(labels Labels) bool {
for _, m := range s {
if v := labels.Get(m.Name()); !m.Matches(v) {
return false
}
}
return true
}
// Matcher specifies a constraint for the value of a label.
type Matcher interface {
// Name returns the label name the matcher should apply to.
Name() string
// Matches checks whether a value fulfills the constraints.
Matches(v string) bool
}
2017-03-19 09:05:01 -07:00
// EqualMatcher matches on equality.
type EqualMatcher struct {
2016-12-28 02:02:19 -08:00
name, value string
2016-12-21 00:39:01 -08:00
}
2017-03-19 09:05:01 -07:00
// Name implements Matcher interface.
func (m *EqualMatcher) Name() string { return m.name }
// Matches implements Matcher interface.
2016-12-28 02:02:19 -08:00
func (m *EqualMatcher) Matches(v string) bool { return v == m.value }
2016-12-21 00:39:01 -08:00
2017-04-05 05:14:30 -07:00
// Value returns the matched value.
func (m *EqualMatcher) Value() string { return m.value }
2016-12-21 00:39:01 -08:00
// NewEqualMatcher returns a new matcher matching an exact label value.
func NewEqualMatcher(name, value string) Matcher {
2016-12-28 02:02:19 -08:00
return &EqualMatcher{name: name, value: value}
2016-12-21 00:39:01 -08:00
}
type regexpMatcher struct {
name string
re *regexp.Regexp
}
func (m *regexpMatcher) Name() string { return m.name }
func (m *regexpMatcher) Matches(v string) bool { return m.re.MatchString(v) }
// NewRegexpMatcher returns a new matcher verifying that a value matches
// the regular expression pattern.
func NewRegexpMatcher(name, pattern string) (Matcher, error) {
re, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
return &regexpMatcher{name: name, re: re}, nil
}
// notMatcher inverts the matching result for a matcher.
type notMatcher struct {
Matcher
}
2016-12-28 02:02:19 -08:00
func (m *notMatcher) Matches(v string) bool { return !m.Matcher.Matches(v) }
2016-12-21 00:39:01 -08:00
// Not inverts the matcher's matching result.
func Not(m Matcher) Matcher {
return &notMatcher{m}
}