forked from grafana/xk6-output-prometheus-remote
/
prometheus.go
52 lines (47 loc) · 1.22 KB
/
prometheus.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
package remotewrite
import (
"sort"
prompb "buf.build/gen/go/prometheus/prometheus/protocolbuffers/go"
"github.com/mstoykov/atlas"
"go.k6.io/k6/metrics"
)
const namelbl = "__name__"
// MapTagSet converts a k6 tag set into
// the equivalent set of Labels as expected from the
// Prometheus' data model.
func MapTagSet(t *metrics.TagSet) []*prompb.Label {
n := (*atlas.Node)(t)
if n.Len() < 1 {
return nil
}
labels := make([]*prompb.Label, 0, n.Len())
for !n.IsRoot() {
prev, key, value := n.Data()
n = prev
if key == "" || value == "" {
continue
}
labels = append(labels, &prompb.Label{Name: key, Value: value})
}
return labels
}
// MapSeries converts a k6 time series into
// the equivalent set of Labels (name+tags) as expected from the
// Prometheus' data model.
//
// The labels are lexicographic sorted as required
// from the Remote write's specification.
func MapSeries(series metrics.TimeSeries, suffix string) []*prompb.Label {
v := defaultMetricPrefix + series.Metric.Name
if suffix != "" {
v += "_" + suffix
}
lbls := append(MapTagSet(series.Tags), &prompb.Label{
Name: namelbl,
Value: v,
})
sort.Slice(lbls, func(i int, j int) bool {
return lbls[i].Name < lbls[j].Name
})
return lbls
}