-
Notifications
You must be signed in to change notification settings - Fork 2k
/
custom.go
543 lines (467 loc) · 13.2 KB
/
custom.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package storepb
import (
"bytes"
"encoding/binary"
"fmt"
"sort"
"strconv"
"strings"
"github.com/gogo/protobuf/types"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/model/labels"
"github.com/thanos-io/thanos/pkg/store/labelpb"
)
var PartialResponseStrategyValues = func() []string {
var s []string
for k := range PartialResponseStrategy_value {
s = append(s, k)
}
sort.Strings(s)
return s
}()
func NewWarnSeriesResponse(err error) *SeriesResponse {
return &SeriesResponse{
Result: &SeriesResponse_Warning{
Warning: err.Error(),
},
}
}
func NewSeriesResponse(series *Series) *SeriesResponse {
return &SeriesResponse{
Result: &SeriesResponse_Series{
Series: series,
},
}
}
func NewHintsSeriesResponse(hints *types.Any) *SeriesResponse {
return &SeriesResponse{
Result: &SeriesResponse_Hints{
Hints: hints,
},
}
}
type emptySeriesSet struct{}
func (emptySeriesSet) Next() bool { return false }
func (emptySeriesSet) At() (labels.Labels, []AggrChunk) { return nil, nil }
func (emptySeriesSet) Err() error { return nil }
// EmptySeriesSet returns a new series set that contains no series.
func EmptySeriesSet() SeriesSet {
return emptySeriesSet{}
}
// MergeSeriesSets takes all series sets and returns as a union single series set.
// It assumes series are sorted by labels within single SeriesSet, similar to remote read guarantees.
// However, they can be partial: in such case, if the single SeriesSet returns the same series within many iterations,
// MergeSeriesSets will merge those into one.
//
// It also assumes in a "best effort" way that chunks are sorted by min time. It's done as an optimization only, so if input
// series' chunks are NOT sorted, the only consequence is that the duplicates might be not correctly removed. This is double checked
// which on just-before PromQL level as well, so the only consequence is increased network bandwidth.
// If all chunks were sorted, MergeSeriesSet ALSO returns sorted chunks by min time.
//
// Chunks within the same series can also overlap (within all SeriesSet
// as well as single SeriesSet alone). If the chunk ranges overlap, the *exact* chunk duplicates will be removed
// (except one), and any other overlaps will be appended into on chunks slice.
func MergeSeriesSets(all ...SeriesSet) SeriesSet {
switch len(all) {
case 0:
return emptySeriesSet{}
case 1:
return newUniqueSeriesSet(all[0])
}
h := len(all) / 2
return newMergedSeriesSet(
MergeSeriesSets(all[:h]...),
MergeSeriesSets(all[h:]...),
)
}
// SeriesSet is a set of series and their corresponding chunks.
// The set is sorted by the label sets. Chunks may be overlapping or expected of order.
type SeriesSet interface {
Next() bool
At() (labels.Labels, []AggrChunk)
Err() error
}
// mergedSeriesSet takes two series sets as a single series set.
type mergedSeriesSet struct {
a, b SeriesSet
lset labels.Labels
chunks []AggrChunk
adone, bdone bool
}
func newMergedSeriesSet(a, b SeriesSet) *mergedSeriesSet {
s := &mergedSeriesSet{a: a, b: b}
// Initialize first elements of both sets as Next() needs
// one element look-ahead.
s.adone = !s.a.Next()
s.bdone = !s.b.Next()
return s
}
func (s *mergedSeriesSet) At() (labels.Labels, []AggrChunk) {
return s.lset, s.chunks
}
func (s *mergedSeriesSet) Err() error {
if s.a.Err() != nil {
return s.a.Err()
}
return s.b.Err()
}
func (s *mergedSeriesSet) compare() int {
if s.adone {
return 1
}
if s.bdone {
return -1
}
lsetA, _ := s.a.At()
lsetB, _ := s.b.At()
return labels.Compare(lsetA, lsetB)
}
func (s *mergedSeriesSet) Next() bool {
if s.adone && s.bdone || s.Err() != nil {
return false
}
d := s.compare()
if d > 0 {
s.lset, s.chunks = s.b.At()
s.bdone = !s.b.Next()
return true
}
if d < 0 {
s.lset, s.chunks = s.a.At()
s.adone = !s.a.Next()
return true
}
// Both a and b contains the same series. Go through all chunks, remove duplicates and concatenate chunks from both
// series sets. We best effortly assume chunks are sorted by min time. If not, we will not detect all deduplicate which will
// be account on select layer anyway. We do it still for early optimization.
lset, chksA := s.a.At()
_, chksB := s.b.At()
s.lset = lset
// Slice reuse is not generally safe with nested merge iterators.
// We err on the safe side an create a new slice.
s.chunks = make([]AggrChunk, 0, len(chksA)+len(chksB))
b := 0
Outer:
for a := range chksA {
for {
if b >= len(chksB) {
// No more b chunks.
s.chunks = append(s.chunks, chksA[a:]...)
break Outer
}
cmp := chksA[a].Compare(chksB[b])
if cmp > 0 {
s.chunks = append(s.chunks, chksA[a])
break
}
if cmp < 0 {
s.chunks = append(s.chunks, chksB[b])
b++
continue
}
// Exact duplicated chunks, discard one from b.
b++
}
}
if b < len(chksB) {
s.chunks = append(s.chunks, chksB[b:]...)
}
s.adone = !s.a.Next()
s.bdone = !s.b.Next()
return true
}
// uniqueSeriesSet takes one series set and ensures each iteration contains single, full series.
type uniqueSeriesSet struct {
SeriesSet
done bool
peek *Series
lset labels.Labels
chunks []AggrChunk
}
func newUniqueSeriesSet(wrapped SeriesSet) *uniqueSeriesSet {
return &uniqueSeriesSet{SeriesSet: wrapped}
}
func (s *uniqueSeriesSet) At() (labels.Labels, []AggrChunk) {
return s.lset, s.chunks
}
func (s *uniqueSeriesSet) Next() bool {
if s.Err() != nil {
return false
}
for !s.done {
if s.done = !s.SeriesSet.Next(); s.done {
break
}
lset, chks := s.SeriesSet.At()
if s.peek == nil {
s.peek = &Series{Labels: labelpb.ZLabelsFromPromLabels(lset), Chunks: chks}
continue
}
if labels.Compare(lset, s.peek.PromLabels()) != 0 {
s.lset, s.chunks = s.peek.PromLabels(), s.peek.Chunks
s.peek = &Series{Labels: labelpb.ZLabelsFromPromLabels(lset), Chunks: chks}
return true
}
// We assume non-overlapping, sorted chunks. This is best effort only, if it's otherwise it
// will just be duplicated, but well handled by StoreAPI consumers.
s.peek.Chunks = append(s.peek.Chunks, chks...)
}
if s.peek == nil {
return false
}
s.lset, s.chunks = s.peek.PromLabels(), s.peek.Chunks
s.peek = nil
return true
}
// Compare returns positive 1 if chunk is smaller -1 if larger than b by min time, then max time.
// It returns 0 if chunks are exactly the same.
func (m AggrChunk) Compare(b AggrChunk) int {
if m.MinTime < b.MinTime {
return 1
}
if m.MinTime > b.MinTime {
return -1
}
// Same min time.
if m.MaxTime < b.MaxTime {
return 1
}
if m.MaxTime > b.MaxTime {
return -1
}
// We could use proto.Equal, but we need ordering as well.
for _, cmp := range []func() int{
func() int { return m.Raw.Compare(b.Raw) },
func() int { return m.Count.Compare(b.Count) },
func() int { return m.Sum.Compare(b.Sum) },
func() int { return m.Min.Compare(b.Min) },
func() int { return m.Max.Compare(b.Max) },
func() int { return m.Counter.Compare(b.Counter) },
} {
if c := cmp(); c == 0 {
continue
} else {
return c
}
}
return 0
}
// Compare returns positive 1 if chunk is smaller -1 if larger.
// It returns 0 if chunks are exactly the same.
func (m *Chunk) Compare(b *Chunk) int {
if m == nil && b == nil {
return 0
}
if b == nil {
return 1
}
if m == nil {
return -1
}
if m.Type < b.Type {
return 1
}
if m.Type > b.Type {
return -1
}
return bytes.Compare(m.Data, b.Data)
}
func (x *PartialResponseStrategy) UnmarshalJSON(entry []byte) error {
fieldStr, err := strconv.Unquote(string(entry))
if err != nil {
return errors.Wrapf(err, fmt.Sprintf("failed to unqote %v, in order to unmarshal as 'partial_response_strategy'. Possible values are %s", string(entry), strings.Join(PartialResponseStrategyValues, ",")))
}
if fieldStr == "" {
// NOTE: For Rule default is abort as this is recommended for alerting.
*x = PartialResponseStrategy_ABORT
return nil
}
strategy, ok := PartialResponseStrategy_value[strings.ToUpper(fieldStr)]
if !ok {
return errors.Errorf(fmt.Sprintf("failed to unmarshal %v as 'partial_response_strategy'. Possible values are %s", string(entry), strings.Join(PartialResponseStrategyValues, ",")))
}
*x = PartialResponseStrategy(strategy)
return nil
}
func (x *PartialResponseStrategy) MarshalJSON() ([]byte, error) {
return []byte(strconv.Quote(x.String())), nil
}
// PromMatchersToMatchers returns proto matchers from Prometheus matchers.
// NOTE: It allocates memory.
func PromMatchersToMatchers(ms ...*labels.Matcher) ([]LabelMatcher, error) {
res := make([]LabelMatcher, 0, len(ms))
for _, m := range ms {
var t LabelMatcher_Type
switch m.Type {
case labels.MatchEqual:
t = LabelMatcher_EQ
case labels.MatchNotEqual:
t = LabelMatcher_NEQ
case labels.MatchRegexp:
t = LabelMatcher_RE
case labels.MatchNotRegexp:
t = LabelMatcher_NRE
default:
return nil, errors.Errorf("unrecognized matcher type %d", m.Type)
}
res = append(res, LabelMatcher{Type: t, Name: m.Name, Value: m.Value})
}
return res, nil
}
// MatchersToPromMatchers returns Prometheus matchers from proto matchers.
// NOTE: It allocates memory.
func MatchersToPromMatchers(ms ...LabelMatcher) ([]*labels.Matcher, error) {
res := make([]*labels.Matcher, 0, len(ms))
for _, m := range ms {
var t labels.MatchType
switch m.Type {
case LabelMatcher_EQ:
t = labels.MatchEqual
case LabelMatcher_NEQ:
t = labels.MatchNotEqual
case LabelMatcher_RE:
t = labels.MatchRegexp
case LabelMatcher_NRE:
t = labels.MatchNotRegexp
default:
return nil, errors.Errorf("unrecognized label matcher type %d", m.Type)
}
m, err := labels.NewMatcher(t, m.Name, m.Value)
if err != nil {
return nil, err
}
res = append(res, m)
}
return res, nil
}
// MatchersToString converts label matchers to string format.
// String should be parsable as a valid PromQL query metric selector.
func MatchersToString(ms ...LabelMatcher) string {
var res string
for i, m := range ms {
res += m.PromString()
if i < len(ms)-1 {
res += ", "
}
}
return "{" + res + "}"
}
// PromMatchersToString converts prometheus label matchers to string format.
// String should be parsable as a valid PromQL query metric selector.
func PromMatchersToString(ms ...*labels.Matcher) string {
var res string
for i, m := range ms {
res += m.String()
if i < len(ms)-1 {
res += ", "
}
}
return "{" + res + "}"
}
func (m *LabelMatcher) PromString() string {
return fmt.Sprintf("%s%s%q", m.Name, m.Type.PromString(), m.Value)
}
func (x LabelMatcher_Type) PromString() string {
typeToStr := map[LabelMatcher_Type]string{
LabelMatcher_EQ: "=",
LabelMatcher_NEQ: "!=",
LabelMatcher_RE: "=~",
LabelMatcher_NRE: "!~",
}
if str, ok := typeToStr[x]; ok {
return str
}
panic("unknown match type")
}
// PromLabels return Prometheus labels.Labels without extra allocation.
func (m *Series) PromLabels() labels.Labels {
return labelpb.ZLabelsToPromLabels(m.Labels)
}
// Deprecated.
// TODO(bwplotka): Remove this once Cortex dep will stop using it.
type Label = labelpb.ZLabel
// Deprecated.
// TODO(bwplotka): Remove this in next PR. Done to reduce diff only.
type LabelSet = labelpb.ZLabelSet
// Deprecated.
// TODO(bwplotka): Remove this once Cortex dep will stop using it.
func CompareLabels(a, b []Label) int {
return labels.Compare(labelpb.ZLabelsToPromLabels(a), labelpb.ZLabelsToPromLabels(b))
}
// Deprecated.
// TODO(bwplotka): Remove this once Cortex dep will stop using it.
func LabelsToPromLabelsUnsafe(lset []Label) labels.Labels {
return labelpb.ZLabelsToPromLabels(lset)
}
// XORNumSamples return number of samples. Returns 0 if it's not XOR chunk.
func (m *Chunk) XORNumSamples() int {
if m.Type == Chunk_XOR {
return int(binary.BigEndian.Uint16(m.Data))
}
return 0
}
type SeriesStatsCounter struct {
lastSeriesHash uint64
Series int
Chunks int
Samples int
}
func (c *SeriesStatsCounter) CountSeries(seriesLabels []labelpb.ZLabel) {
seriesHash := labelpb.HashWithPrefix("", seriesLabels)
if c.lastSeriesHash != 0 || seriesHash != c.lastSeriesHash {
c.lastSeriesHash = seriesHash
c.Series++
}
}
func (c *SeriesStatsCounter) Count(series *Series) {
c.CountSeries(series.Labels)
for _, chk := range series.Chunks {
if chk.Raw != nil {
c.Chunks++
c.Samples += chk.Raw.XORNumSamples()
}
if chk.Count != nil {
c.Chunks++
c.Samples += chk.Count.XORNumSamples()
}
if chk.Counter != nil {
c.Chunks++
c.Samples += chk.Counter.XORNumSamples()
}
if chk.Max != nil {
c.Chunks++
c.Samples += chk.Max.XORNumSamples()
}
if chk.Min != nil {
c.Chunks++
c.Samples += chk.Min.XORNumSamples()
}
if chk.Sum != nil {
c.Chunks++
c.Samples += chk.Sum.XORNumSamples()
}
}
}
func (m *SeriesRequest) ToPromQL() string {
return m.QueryHints.toPromQL(m.Matchers)
}
// IsSafeToExecute returns true if the function or aggregation from the query hint
// can be safely executed by the underlying Prometheus instance without affecting the
// result of the query.
func (m *QueryHints) IsSafeToExecute() bool {
distributiveOperations := []string{
"max",
"max_over_time",
"min",
"min_over_time",
"group",
}
for _, op := range distributiveOperations {
if m.Func.Name == op {
return true
}
}
return false
}