/
client.go
151 lines (130 loc) · 3.51 KB
/
client.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
package prometheus
import (
"context"
"log/slog"
"math"
"strings"
"sync"
"time"
"github.com/hanapedia/metrics-processor/internal/domain"
"github.com/hanapedia/metrics-processor/pkg/promql"
"github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"github.com/prometheus/common/model"
)
type PrometheusAdapter struct {
client v1.API
queryRange v1.Range
queries []*promql.Query
}
func NewPrometheusAdapter(config *domain.Config) (*PrometheusAdapter, error) {
client, err := api.NewClient(api.Config{
Address: config.MetricsQueryEndpoint,
})
if err != nil {
return nil, err
}
return &PrometheusAdapter{
client: v1.NewAPI(client),
queryRange: v1.Range{
Start: config.EndTime.Add(-1 * config.Duration),
End: config.EndTime,
Step: config.Step,
},
}, nil
}
func (pa *PrometheusAdapter) RegisterQuery(query *promql.Query) {
pa.queries = append(pa.queries, query)
}
func (pa *PrometheusAdapter) Len() int {
return len(pa.queries)
}
func (pa *PrometheusAdapter) Query(metricsChan chan<- *domain.MetricsMatrix) {
var wg sync.WaitGroup
for _, query := range pa.queries {
wg.Add(1)
go func(q *promql.Query) {
defer wg.Done()
pa.runQuery(q, metricsChan)
}(query)
}
go func() {
wg.Wait()
close(metricsChan)
}()
}
func (pa *PrometheusAdapter) runQuery(query *promql.Query, metricsChan chan<- *domain.MetricsMatrix) {
slog.Info("Running Query.", "name", query.Name, "query", query.AsString())
result, warnings, err := pa.client.QueryRange(
context.Background(),
query.AsString(),
pa.queryRange,
v1.WithTimeout(5*time.Second),
)
if err != nil {
slog.Error("Query failed", "name", query.Name, "error", err, "query", query.AsString())
return
}
for _, warning := range warnings {
slog.Warn(warning)
}
if matrix, ok := result.(model.Matrix); ok {
metricsChan <- pa.handleMatrixResult(query.Name, &matrix)
} else {
slog.Warn("Query did not return matrix. Skipping.", "name", query.Name, "query", query.AsString())
}
}
func (pa *PrometheusAdapter) handleMatrixResult(name string, matrix *model.Matrix) *domain.MetricsMatrix {
metricsMatrix := domain.MetricsMatrix{
Name: name,
LabelType: "",
Matrix: make(map[string][]float64),
Timestamps: []int64{},
}
for i, sampleStream := range *matrix {
if i == 0 {
metricsMatrix.LabelType = extractLabelType(sampleStream.Metric)
metricsMatrix.Timestamps = extractTimestamps(sampleStream.Values)
}
label := extractLabelValue(sampleStream.Metric)
metricsMatrix.Matrix[label] = extractSampleValues(sampleStream.Values)
}
// replace NaN
return &metricsMatrix
}
func extractLabelType(metric model.Metric) string {
keys := []string{}
for k := range metric {
keys = append(keys, string(k))
}
return strings.Join(keys, "_")
}
func extractLabelValue(metric model.Metric) string {
values := []string{}
for _, v := range metric {
values = append(values, string(v))
}
return strings.Join(values, "_")
}
func extractTimestamps(samples []model.SamplePair) []int64 {
timestamps := []int64{}
for _, sample := range samples {
timestamps = append(timestamps, sample.Timestamp.Unix())
}
return timestamps
}
func extractSampleValues(samples []model.SamplePair) []float64 {
values := []float64{}
var lastValue float64 = 0
for _, sample := range samples {
thisValue := float64(sample.Value)
// if NaN, use last non NaN value
if math.IsNaN(thisValue) {
thisValue = lastValue
} else {
lastValue = thisValue
}
values = append(values, thisValue)
}
return values
}