-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.go
94 lines (77 loc) · 1.93 KB
/
sample.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
package types
import (
"strings"
"time"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/prompb"
"github.com/F1997/categraf/pkg/conv"
)
type Sample struct {
Metric string `json:"metric"`
Timestamp time.Time `json:"timestamp"`
Value interface{} `json:"value"`
Labels map[string]string `json:"labels"`
}
var (
labelReplacer = strings.NewReplacer("-", "_", ".", "_", " ", "_", "/", "_")
metricReplacer = strings.NewReplacer("-", "_", ".", "_", " ", "_", "'", "_", "\"", "_")
zeroTime = time.Unix(0, 0)
)
func NewSample(prefix, metric string, value interface{}, labels ...map[string]string) *Sample {
s := &Sample{
Metric: metric,
Value: value,
Labels: make(map[string]string),
}
if len(prefix) > 0 {
s.Metric = prefix + "_" + metricReplacer.Replace(s.Metric)
} else {
s.Metric = metricReplacer.Replace(s.Metric)
}
for i := 0; i < len(labels); i++ {
for k, v := range labels[i] {
s.Labels[k] = v
}
}
return s
}
func (item *Sample) ConvertTimeSeries(precision string) *prompb.TimeSeries {
value, err := conv.ToFloat64(item.Value)
if err != nil {
// If the Labels is empty, it means it is abnormal data
return nil
}
pt := prompb.TimeSeries{}
timestamp := item.Timestamp.UnixMilli()
switch precision {
case "s":
timestamp = timestamp / 1000 * 1000
case "m":
ts := timestamp / 1000 * 1000 // ms
timestamp = ts - ts%60000
}
pt.Samples = append(pt.Samples, prompb.Sample{
Timestamp: timestamp,
Value: value,
})
// add label: metric
pt.Labels = append(pt.Labels, prompb.Label{
Name: model.MetricNameLabel,
Value: item.Metric,
})
// add other labels
for k, v := range item.Labels {
pt.Labels = append(pt.Labels, prompb.Label{
Name: labelReplacer.Replace(k),
Value: v,
})
}
return &pt
}
func (s *Sample) SetTime(t time.Time) *Sample {
if t.IsZero() || zeroTime.Equal(t) {
return s
}
s.Timestamp = t
return s
}