-
Notifications
You must be signed in to change notification settings - Fork 1
/
parse.go
129 lines (119 loc) · 2.4 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import "strconv"
func ParseMetric(m []byte) (*Metric, error) {
var n int
if len(m) == 0 {
return nil, Error("Metric name missing")
}
n = -1
for i, ch := range m {
if ch == ':' {
n = i
break
} else if ch < 32 || ch == '/' || ch == '\\' || ch == '"' {
return nil, Error("Invalid characters in metric name")
}
}
if n == 0 {
return nil, Error("Metric name missing")
} else if n == -1 || n == len(m)-1 {
return nil, Error("Metric value missing")
}
name := m[:n]
n, m = -1, m[n+1:]
for i, ch := range m {
if ch == '|' {
n = i
break
}
}
if n == 0 {
return nil, Error("Metric value missing")
} else if n == -1 || n == len(m)-1 {
return nil, Error("Metric type missing")
}
value, err := strconv.ParseFloat(string(m[:n]), 64)
if err != nil {
return nil, Error("Metric value invalid")
}
n, m = -1, m[n+1:]
for i, ch := range m {
if ch == '|' {
n = i
break
}
}
if n == -1 {
n = len(m)
}
typ := MetricType(-1)
if n == 1 {
switch m[0] {
case 'c':
typ = Counter
case 'g':
typ = Gauge
case 'a':
typ = Averager
}
} else if n == 2 {
if m[0] == 'm' && m[1] == 's' {
typ = Timer
} else if m[0] == 'a' && m[1] == 'c' {
typ = Accumulator
}
}
if typ == MetricType(-1) {
return nil, Error("Metric type invalid")
}
sr := 1.0
if n != len(m) {
if n == len(m)-1 {
return nil, Error("Sample rate missing")
}
if m[n+1] != '@' {
return nil, Error("Sample rate invalid")
}
s, err := strconv.ParseFloat(string(m[n+2:]), 64)
if err != nil || s <= 0 {
return nil, Error("Sample rate invalid")
}
sr = s
}
return &Metric{string(name), typ, value, sr}, nil
}
func CheckMetricName(name string) error {
if len(name) == 0 {
return Error("Empty metric name")
}
for _, ch := range name {
if ch < 32 || ch == '/' || ch == '\\' || ch == '"' || ch == ':' {
return Error("Invalid characters in metric name")
}
}
return nil
}
func MatchMetricName(name, pattern string) bool {
for len(pattern) > 0 {
if pattern[0] != '*' {
if len(name) == 0 || pattern[0] != name[0] {
return false
} else {
pattern, name = pattern[1:], name[1:]
}
} else {
pattern = pattern[1:]
if len(pattern) == 0 {
return true
}
for len(name) > 0 && name[0] != pattern[0] {
name = name[1:]
}
if len(name) == 0 {
return false
}
pattern, name = pattern[1:], name[1:]
}
}
return len(name) == 0
}