forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.go
83 lines (65 loc) · 1.86 KB
/
data.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
package collector
import (
"strconv"
"strings"
"github.com/elastic/beats/libbeat/common"
)
type PromEvent struct {
key string
value interface{}
labels common.MapStr
labelHash string
}
// NewPromEvent creates a prometheus event based on the given string
func NewPromEvent(line string) PromEvent {
// Separate key and value
splitPos := strings.LastIndex(line, " ")
split := []string{line[:splitPos], line[splitPos+1:]}
promEvent := PromEvent{
key: split[0],
labelHash: "_", // _ represents empty labels
}
// skip entries without a value
if split[1] == "NaN" {
promEvent.value = nil
} else {
promEvent.value = convertValue(split[1])
}
// Split key
startLabels := strings.Index(line, "{")
endLabels := strings.Index(line, "}")
// Handle labels
if startLabels != -1 {
// Overwrite key, as key contained labels until now too
promEvent.key = line[0:startLabels]
promEvent.labelHash = line[startLabels+1 : endLabels]
// Extract labels
promEvent.labels = extractLabels(promEvent.labelHash)
}
return promEvent
}
// extractLabels splits up a label string of format handler="alerts",quantile="0.5"
// into a key / value list
func extractLabels(labelsString string) common.MapStr {
keyValuePairs := common.MapStr{}
// Extract labels
labels := strings.Split(labelsString, "\",")
for _, label := range labels {
keyValue := strings.Split(label, "=")
// Remove " from value
keyValue[1] = strings.Trim(keyValue[1], "\"")
// Converts value to int or float if needed
keyValuePairs[keyValue[0]] = convertValue(keyValue[1])
}
return keyValuePairs
}
// convertValue takes the input string and converts it to int of float
func convertValue(value string) interface{} {
if i, err := strconv.ParseInt(value, 10, 64); err == nil {
return i
}
if f, err := strconv.ParseFloat(value, 64); err == nil {
return f
}
return value
}