This repository has been archived by the owner on Jan 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
metric.go
123 lines (109 loc) · 2.46 KB
/
metric.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
package main
import (
"encoding/hex"
"fmt"
"log"
"strconv"
"strings"
"unicode/utf8"
"github.com/prometheus/client_golang/prometheus"
)
type metric struct {
typ prometheus.ValueType
aeroName string
desc string
}
// cmetrics is promkey -> prom metric
type cmetrics map[string]cmetric
type cmetric struct {
desc *prometheus.Desc
typ prometheus.ValueType
}
func parseFloatOrBool(v string) (float64, error) {
if f, err := strconv.ParseFloat(v, 64); err == nil {
return f, nil
}
if b, err := strconv.ParseBool(v); err == nil {
if b {
return 1, nil
}
return 0, nil
}
return 0, fmt.Errorf("not a float or bool: %q", v)
}
// infoCollect parses RequestInfo() results and handles the metrics
func infoCollect(
metrics cmetrics,
info string,
labelValues ...string,
) []prometheus.Metric {
var res []prometheus.Metric
stats := parseInfo(info)
validLabelValues := make([]string, len(labelValues))
for pos, lv := range labelValues {
validLabelValues[pos] = sanitizeLabelValue(lv)
}
for key, m := range metrics {
v, ok := stats[key]
if !ok {
// key presence depends on (namespace) configuration
continue
}
f, err := parseFloatOrBool(v)
if err != nil {
log.Printf("%q invalid value %q: %s", key, v, err)
continue
}
res = append(
res,
prometheus.MustNewConstMetric(m.desc, m.typ, f, validLabelValues...),
)
}
return res
}
func sanitizeLabelValue(lv string) string {
if utf8.ValidString(lv) {
return lv
}
fixUtf := func(r rune) rune {
if r == utf8.RuneError {
return 65533
}
return r
}
return strings.Map(fixUtf, lv) + " " + hex.EncodeToString([]byte(lv))
}
func parseInfo(s string) map[string]string {
r := map[string]string{}
for _, l := range strings.Split(s, ";") {
for _, v := range strings.Split(l, ":") {
kv := strings.SplitN(v, "=", 2)
if len(kv) > 1 {
r[kv[0]] = kv[1]
}
}
}
return r
}
// gauge is a helper to add an aerospike metric
func gauge(name string, desc string) metric {
return metric{
typ: prometheus.GaugeValue,
aeroName: name,
desc: desc,
}
}
// counter is a helper to add an aerospike metric
func counter(name string, desc string) metric {
return metric{
typ: prometheus.CounterValue,
aeroName: name,
desc: desc,
}
}
// promkey makes the prom metric name out of an aerospike stat name
func promkey(sys, key string) string {
replacer := strings.NewReplacer("-", "_", ".", "_")
k := replacer.Replace(key)
return namespace + "_" + sys + "_" + k
}