forked from prometheus/alertmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.go
74 lines (62 loc) · 1.41 KB
/
parse.go
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package parse
import (
"fmt"
"regexp"
"strings"
"github.com/prometheus/prometheus/pkg/labels"
)
var (
re = regexp.MustCompile(`(?:\s?)(\w+)(=|=~|!=|!~)(?:\"([^"=~!]+)\"|([^"=~!]+))`)
typeMap = map[string]labels.MatchType{
"=": labels.MatchEqual,
"!=": labels.MatchNotEqual,
"=~": labels.MatchRegexp,
"!~": labels.MatchNotRegexp,
}
)
func Matchers(s string) ([]*labels.Matcher, error) {
matchers := []*labels.Matcher{}
if strings.HasPrefix(s, "{") {
s = s[1:]
}
if strings.HasSuffix(s, "}") {
s = s[:len(s)-1]
}
for _, toParse := range strings.Split(s, ",") {
m, err := Matcher(toParse)
if err != nil {
return nil, err
}
matchers = append(matchers, m)
}
return matchers, nil
}
func Matcher(s string) (*labels.Matcher, error) {
name, value, matchType, err := Input(s)
if err != nil {
return nil, err
}
m, err := labels.NewMatcher(matchType, name, value)
if err != nil {
return nil, err
}
return m, nil
}
func Input(s string) (name, value string, matchType labels.MatchType, err error) {
ms := re.FindStringSubmatch(s)
if len(ms) < 4 {
return "", "", labels.MatchEqual, fmt.Errorf("bad matcher format")
}
var prs bool
name = ms[1]
matchType, prs = typeMap[ms[2]]
if ms[3] != "" {
value = ms[3]
} else {
value = ms[4]
}
if name == "" || value == "" || !prs {
return "", "", labels.MatchEqual, fmt.Errorf("failed to parse")
}
return name, value, matchType, nil
}