-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
sample.go
122 lines (109 loc) · 2.46 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
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
package record
import (
"math"
"strings"
"time"
"github.com/ccfos/nightingale/v6/models"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/prompb"
)
const (
LabelName = "__name__"
)
func ConvertToTimeSeries(value model.Value, rule *models.RecordingRule) (lst []prompb.TimeSeries) {
switch value.Type() {
case model.ValVector:
items, ok := value.(model.Vector)
if !ok {
return
}
for _, item := range items {
if math.IsNaN(float64(item.Value)) {
continue
}
s := prompb.Sample{}
s.Timestamp = time.Unix(item.Timestamp.Unix(), 0).UnixNano() / 1e6
s.Value = float64(item.Value)
l := labelsToLabelsProto(item.Metric, rule)
lst = append(lst, prompb.TimeSeries{
Labels: l,
Samples: []prompb.Sample{s},
})
}
case model.ValMatrix:
items, ok := value.(model.Matrix)
if !ok {
return
}
for _, item := range items {
if len(item.Values) == 0 {
return
}
last := item.Values[len(item.Values)-1]
if math.IsNaN(float64(last.Value)) {
continue
}
l := labelsToLabelsProto(item.Metric, rule)
var slst []prompb.Sample
for _, v := range item.Values {
if math.IsNaN(float64(v.Value)) {
continue
}
slst = append(slst, prompb.Sample{
Timestamp: time.Unix(v.Timestamp.Unix(), 0).UnixNano() / 1e6,
Value: float64(v.Value),
})
}
lst = append(lst, prompb.TimeSeries{
Labels: l,
Samples: slst,
})
}
case model.ValScalar:
item, ok := value.(*model.Scalar)
if !ok {
return
}
if math.IsNaN(float64(item.Value)) {
return
}
lst = append(lst, prompb.TimeSeries{
Labels: nil,
Samples: []prompb.Sample{{Value: float64(item.Value), Timestamp: time.Unix(item.Timestamp.Unix(), 0).UnixNano() / 1e6}},
})
default:
return
}
return
}
func labelsToLabelsProto(labels model.Metric, rule *models.RecordingRule) (result []prompb.Label) {
//name
nameLs := prompb.Label{
Name: LabelName,
Value: rule.Name,
}
result = append(result, nameLs)
for k, v := range labels {
if k == LabelName {
continue
}
if model.LabelNameRE.MatchString(string(k)) {
result = append(result, prompb.Label{
Name: string(k),
Value: string(v),
})
}
}
if len(rule.AppendTagsJSON) != 0 {
for _, v := range rule.AppendTagsJSON {
index := strings.Index(v, "=")
if model.LabelNameRE.MatchString(v[:index]) {
result = append(result, prompb.Label{
Name: v[:index],
Value: v[index+1:],
})
}
}
}
return result
}