/
provider.go
295 lines (260 loc) · 9.43 KB
/
provider.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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/*
Copyright 2023 The Kapacity Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package prometheus
import (
"context"
"fmt"
"sync"
"time"
promapi "github.com/prometheus/client_golang/api"
promapiv1 "github.com/prometheus/client_golang/api/prometheus/v1"
prommodel "github.com/prometheus/common/model"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/prometheus-adapter/pkg/naming"
"github.com/traas-stack/kapacity/pkg/metric"
metricprovider "github.com/traas-stack/kapacity/pkg/metric/provider"
)
const (
maxPointsPerPromTimeSeries = 11000
)
// MetricProvider provides metrics from Prometheus.
type MetricProvider struct {
client client.Client
dynamicClient dynamic.Interface
promAPI promapiv1.API
workloadPodNamePatternMap map[schema.GroupKind]string
cpuQuery, memQuery *resourceQuery
resourceQueryWindow time.Duration
metricsRelistInterval time.Duration
metricsMaxAge time.Duration
objectMetricNamers []naming.MetricNamer
objectSeriesRegistry *objectSeriesRegistry
externalMetricNamers []naming.MetricNamer
externalSeriesRegistry *externalSeriesRegistry
}
type shardQueryResult struct {
Index int
Series []*metric.Series
Err error
}
// NewMetricProvider creates a new MetricProvider with the given Prometheus client and rate metrics calculating window.
func NewMetricProvider(client client.Client, dynamicClient dynamic.Interface, promClient promapi.Client, metricsConfig *MetricsDiscoveryConfig, metricsRelistInterval, metricsMaxAge time.Duration) (metricprovider.Interface, error) {
workloadPodNamePatternMap := make(map[schema.GroupKind]string, len(metricsConfig.WorkloadPodNamePatterns))
for _, p := range metricsConfig.WorkloadPodNamePatterns {
workloadPodNamePatternMap[schema.GroupKind{Group: p.Group, Kind: p.Kind}] = p.Pattern
}
resourceRules := metricsConfig.ResourceRules
if resourceRules == nil {
return nil, fmt.Errorf("missing resource rules in metrics discovery config")
}
cpuQuery, err := newResourceQuery(resourceRules.CPU, client.RESTMapper())
if err != nil {
return nil, fmt.Errorf("unable to construct querier for CPU metrics: %v", err)
}
memQuery, err := newResourceQuery(resourceRules.Memory, client.RESTMapper())
if err != nil {
return nil, fmt.Errorf("unable to construct querier for memory metrics: %v", err)
}
objectMetricNamers, err := naming.NamersFromConfig(metricsConfig.Rules, client.RESTMapper())
if err != nil {
return nil, fmt.Errorf("unable to construct object metrics naming scheme from metrics rules: %v", err)
}
externalMetricNamers, err := naming.NamersFromConfig(metricsConfig.ExternalRules, client.RESTMapper())
if err != nil {
return nil, fmt.Errorf("unable to construct external metrics naming scheme from metrics rules: %v", err)
}
return &MetricProvider{
client: client,
dynamicClient: dynamicClient,
promAPI: promapiv1.NewAPI(promClient),
workloadPodNamePatternMap: workloadPodNamePatternMap,
cpuQuery: cpuQuery,
memQuery: memQuery,
resourceQueryWindow: time.Duration(resourceRules.Window),
metricsRelistInterval: metricsRelistInterval,
metricsMaxAge: metricsMaxAge,
objectMetricNamers: objectMetricNamers,
objectSeriesRegistry: &objectSeriesRegistry{Mapper: client.RESTMapper()},
externalMetricNamers: externalMetricNamers,
externalSeriesRegistry: &externalSeriesRegistry{},
}, nil
}
func (p *MetricProvider) QueryLatest(ctx context.Context, query *metric.Query) ([]*metric.Sample, error) {
l := log.FromContext(ctx)
promQuery, window, err := p.buildPromQuery(ctx, query)
if err != nil {
return nil, fmt.Errorf("failed to build prom queries: %v", err)
}
now := time.Now()
res, warns, err := p.promAPI.Query(ctx, promQuery, now)
if len(warns) > 0 {
l.Info("got warnings from prom query", "warnings", warns, "query", promQuery, "time", now)
}
if err != nil {
return nil, fmt.Errorf("prom query failed with query %q at %v: %v", promQuery, now, err)
}
samples, err := convertPromResultToSamples(res, window)
if err != nil {
return nil, fmt.Errorf("failed to convert prom result %q to metric samples: %v", res.String(), err)
}
return samples, nil
}
func (p *MetricProvider) Query(ctx context.Context, query *metric.Query, start, end time.Time, step time.Duration) ([]*metric.Series, error) {
l := log.FromContext(ctx)
promQuery, window, err := p.buildPromQuery(ctx, query)
if err != nil {
return nil, fmt.Errorf("failed to build prom queries: %v", err)
}
// query range by shards to avoid exceeding maximum points limitation per timeseries of prometheus api
shards := promQueryRangeSharding(start, end, step)
shardResCh := make(chan *shardQueryResult, len(shards))
var wg sync.WaitGroup
for i := range shards {
wg.Add(1)
go func(index int) {
defer wg.Done()
shardRes := &shardQueryResult{Index: index}
res, warns, err := p.promAPI.QueryRange(ctx, promQuery, shards[index])
if len(warns) > 0 {
l.Info("got warnings from prom query range", "warnings", warns, "query", promQuery,
"start", start, "end", end, "step", step)
}
if err != nil {
shardRes.Err = fmt.Errorf("prom query range failed with query %q from %v to %v with step %v: %v",
promQuery, start, end, step, err)
shardResCh <- shardRes
return
}
series, err := convertPromResultToSeries(res, window)
if err != nil {
shardRes.Err = fmt.Errorf("failed to convert prom result %q to metric series: %v", res.String(), err)
shardResCh <- shardRes
return
}
shardRes.Series = series
shardResCh <- shardRes
}(i)
}
wg.Wait()
close(shardResCh)
// merge series shards by their labels
orderedShardRes := make([]*shardQueryResult, len(shards))
for shardRes := range shardResCh {
orderedShardRes[shardRes.Index] = shardRes
}
seriesMap := make(map[string]*metric.Series)
errs := make([]error, 0)
for _, shardRes := range orderedShardRes {
if shardRes.Err != nil {
errs = append(errs, shardRes.Err)
continue
}
for _, series := range shardRes.Series {
key := series.Labels.String()
if prevSeries, ok := seriesMap[key]; ok {
prevSeries.Points = append(prevSeries.Points, series.Points...)
} else {
seriesMap[key] = series
}
}
}
if len(errs) > 0 {
return nil, fmt.Errorf("%v", errs)
}
series := make([]*metric.Series, 0, len(seriesMap))
for _, s := range seriesMap {
series = append(series, s)
}
return series, nil
}
func promQueryRangeSharding(start, end time.Time, step time.Duration) []promapiv1.Range {
shards := make([]promapiv1.Range, 0)
for shardStart, complete := start, false; !complete; {
shardEnd := shardStart.Add(step * maxPointsPerPromTimeSeries)
if !shardEnd.Before(end) {
shardEnd = end
complete = true
}
shards = append(shards, promapiv1.Range{
Start: shardStart,
End: shardEnd,
Step: step,
})
shardStart = shardEnd.Add(step)
if shardStart.After(end) {
complete = true
}
}
return shards
}
func convertPromResultToSamples(value prommodel.Value, window *time.Duration) ([]*metric.Sample, error) {
if value.Type() != prommodel.ValVector {
return nil, fmt.Errorf("cannot convert prom value of type %q to samples", value.Type())
}
vector, ok := value.(prommodel.Vector)
if !ok {
return nil, fmt.Errorf("failed to convert prom value to vector")
}
samples := make([]*metric.Sample, 0)
for _, promSample := range vector {
if promSample == nil {
continue
}
samples = append(samples, convertPromSampleToSample(promSample, window))
}
return samples, nil
}
func convertPromResultToSeries(value prommodel.Value, window *time.Duration) ([]*metric.Series, error) {
if value.Type() != prommodel.ValMatrix {
return nil, fmt.Errorf("cannot convert prom value of type %q to series", value.Type())
}
matrix, ok := value.(prommodel.Matrix)
if !ok {
return nil, fmt.Errorf("failed to convert prom value to matrix")
}
series := make([]*metric.Series, 0)
for _, promSampleStream := range matrix {
if promSampleStream == nil {
continue
}
series = append(series, convertPromSampleStreamToSeries(promSampleStream, window))
}
return series, nil
}
func convertPromSampleToSample(promSample *prommodel.Sample, window *time.Duration) *metric.Sample {
return &metric.Sample{
Point: metric.Point{
Timestamp: promSample.Timestamp,
Value: float64(promSample.Value),
},
Labels: prommodel.LabelSet(promSample.Metric),
Window: window,
}
}
func convertPromSampleStreamToSeries(promSampleStream *prommodel.SampleStream, window *time.Duration) *metric.Series {
points := make([]metric.Point, 0, len(promSampleStream.Values))
for _, promSamplePair := range promSampleStream.Values {
points = append(points, metric.Point{
Timestamp: promSamplePair.Timestamp,
Value: float64(promSamplePair.Value),
})
}
return &metric.Series{
Points: points,
Labels: prommodel.LabelSet(promSampleStream.Metric),
Window: window,
}
}