summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/pkg/prometheus/selector/selector.go
blob: 28203fca1340e5770c44f84208e8681ebc3fd82a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// SPDX-License-Identifier: GPL-3.0-or-later

package selector

import (
	"github.com/netdata/netdata/go/go.d.plugin/pkg/matcher"

	"github.com/prometheus/prometheus/model/labels"
)

type Selector interface {
	Matches(lbs labels.Labels) bool
}

const (
	OpEqual             = "="
	OpNegEqual          = "!="
	OpRegexp            = "=~"
	OpNegRegexp         = "!~"
	OpSimplePatterns    = "=*"
	OpNegSimplePatterns = "!*"
)

type labelSelector struct {
	name string
	m    matcher.Matcher
}

func (s labelSelector) Matches(lbs labels.Labels) bool {
	if s.name == labels.MetricName {
		return s.m.MatchString(lbs[0].Value)
	}
	if label, ok := lookupLabel(s.name, lbs[1:]); ok {
		return s.m.MatchString(label.Value)
	}
	return false
}

type Func func(lbs labels.Labels) bool

func (fn Func) Matches(lbs labels.Labels) bool {
	return fn(lbs)
}

func lookupLabel(name string, lbs labels.Labels) (labels.Label, bool) {
	for _, label := range lbs {
		if label.Name == name {
			return label, true
		}
	}
	return labels.Label{}, false
}