-
Notifications
You must be signed in to change notification settings - Fork 2k
/
proxy.go
786 lines (677 loc) · 22.5 KB
/
proxy.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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package store
import (
"context"
"fmt"
"io"
"math"
"strings"
"sync"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/tracing"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/prometheus/model/labels"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/thanos-io/thanos/pkg/component"
"github.com/thanos-io/thanos/pkg/store/labelpb"
"github.com/thanos-io/thanos/pkg/store/storepb"
"github.com/thanos-io/thanos/pkg/strutil"
"github.com/thanos-io/thanos/pkg/tracing"
)
type ctxKey int
// StoreMatcherKey is the context key for the store's allow list.
const StoreMatcherKey = ctxKey(0)
// Client holds meta information about a store.
type Client interface {
// StoreClient to access the store.
storepb.StoreClient
// LabelSets that each apply to some data exposed by the backing store.
LabelSets() []labels.Labels
// TimeRange returns minimum and maximum time range of data in the store.
TimeRange() (mint int64, maxt int64)
// SupportsSharding returns true if sharding is supported by the underlying store.
SupportsSharding() bool
String() string
// Addr returns address of a Client.
Addr() string
}
// ProxyStore implements the store API that proxies request to all given underlying stores.
type ProxyStore struct {
logger log.Logger
stores func() []Client
component component.StoreAPI
selectorLabels labels.Labels
buffers sync.Pool
responseTimeout time.Duration
metrics *proxyStoreMetrics
}
type proxyStoreMetrics struct {
emptyStreamResponses prometheus.Counter
}
func newProxyStoreMetrics(reg prometheus.Registerer) *proxyStoreMetrics {
var m proxyStoreMetrics
m.emptyStreamResponses = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_proxy_store_empty_stream_responses_total",
Help: "Total number of empty responses received.",
})
return &m
}
func RegisterStoreServer(storeSrv storepb.StoreServer) func(*grpc.Server) {
return func(s *grpc.Server) {
storepb.RegisterStoreServer(s, storeSrv)
}
}
// NewProxyStore returns a new ProxyStore that uses the given clients that implements storeAPI to fan-in all series to the client.
// Note that there is no deduplication support. Deduplication should be done on the highest level (just before PromQL).
func NewProxyStore(
logger log.Logger,
reg prometheus.Registerer,
stores func() []Client,
component component.StoreAPI,
selectorLabels labels.Labels,
responseTimeout time.Duration,
) *ProxyStore {
if logger == nil {
logger = log.NewNopLogger()
}
metrics := newProxyStoreMetrics(reg)
s := &ProxyStore{
logger: logger,
stores: stores,
component: component,
selectorLabels: selectorLabels,
buffers: sync.Pool{New: func() interface{} {
b := make([]byte, 0, initialBufSize)
return &b
}},
responseTimeout: responseTimeout,
metrics: metrics,
}
return s
}
// Info returns store information about the external labels this store have.
func (s *ProxyStore) Info(_ context.Context, _ *storepb.InfoRequest) (*storepb.InfoResponse, error) {
res := &storepb.InfoResponse{
StoreType: s.component.ToProto(),
Labels: labelpb.ZLabelsFromPromLabels(s.selectorLabels),
}
minTime := int64(math.MaxInt64)
maxTime := int64(0)
stores := s.stores()
// Edge case: we have no data if there are no stores.
if len(stores) == 0 {
res.MaxTime = 0
res.MinTime = 0
return res, nil
}
for _, s := range stores {
mint, maxt := s.TimeRange()
if mint < minTime {
minTime = mint
}
if maxt > maxTime {
maxTime = maxt
}
}
res.MaxTime = maxTime
res.MinTime = minTime
labelSets := make(map[uint64]labelpb.ZLabelSet, len(stores))
for _, st := range stores {
for _, lset := range st.LabelSets() {
mergedLabelSet := labelpb.ExtendSortedLabels(lset, s.selectorLabels)
labelSets[mergedLabelSet.Hash()] = labelpb.ZLabelSet{Labels: labelpb.ZLabelsFromPromLabels(mergedLabelSet)}
}
}
res.LabelSets = make([]labelpb.ZLabelSet, 0, len(labelSets))
for _, v := range labelSets {
res.LabelSets = append(res.LabelSets, v)
}
// We always want to enforce announcing the subset of data that
// selector-labels represents. If no label-sets are announced by the
// store-proxy's discovered stores, then we still want to enforce
// announcing this subset by announcing the selector as the label-set.
if len(res.LabelSets) == 0 && len(res.Labels) > 0 {
res.LabelSets = append(res.LabelSets, labelpb.ZLabelSet{Labels: res.Labels})
}
return res, nil
}
func (s *ProxyStore) LabelSet() []labelpb.ZLabelSet {
stores := s.stores()
if len(stores) == 0 {
return []labelpb.ZLabelSet{}
}
mergedLabelSets := make(map[uint64]labelpb.ZLabelSet, len(stores))
for _, st := range stores {
for _, lset := range st.LabelSets() {
mergedLabelSet := labelpb.ExtendSortedLabels(lset, s.selectorLabels)
mergedLabelSets[mergedLabelSet.Hash()] = labelpb.ZLabelSet{Labels: labelpb.ZLabelsFromPromLabels(mergedLabelSet)}
}
}
labelSets := make([]labelpb.ZLabelSet, 0, len(mergedLabelSets))
for _, v := range mergedLabelSets {
labelSets = append(labelSets, v)
}
// We always want to enforce announcing the subset of data that
// selector-labels represents. If no label-sets are announced by the
// store-proxy's discovered stores, then we still want to enforce
// announcing this subset by announcing the selector as the label-set.
selectorLabels := labelpb.ZLabelsFromPromLabels(s.selectorLabels)
if len(labelSets) == 0 && len(selectorLabels) > 0 {
labelSets = append(labelSets, labelpb.ZLabelSet{Labels: selectorLabels})
}
return labelSets
}
func (s *ProxyStore) TimeRange() (int64, int64) {
stores := s.stores()
if len(stores) == 0 {
return math.MinInt64, math.MaxInt64
}
var minTime, maxTime int64 = math.MaxInt64, math.MinInt64
for _, s := range stores {
storeMinTime, storeMaxTime := s.TimeRange()
if storeMinTime < minTime {
minTime = storeMinTime
}
if storeMaxTime > maxTime {
maxTime = storeMaxTime
}
}
return minTime, maxTime
}
// cancelableRespSender is a response channel that does need to be exhausted on cancel.
type cancelableRespSender struct {
ctx context.Context
ch chan<- *storepb.SeriesResponse
}
func newCancelableRespChannel(ctx context.Context, buffer int) (*cancelableRespSender, chan *storepb.SeriesResponse) {
respCh := make(chan *storepb.SeriesResponse, buffer)
return &cancelableRespSender{ctx: ctx, ch: respCh}, respCh
}
// send or return on cancel.
func (s cancelableRespSender) send(r *storepb.SeriesResponse) {
select {
case <-s.ctx.Done():
case s.ch <- r:
}
}
// Series returns all series for a requested time range and label matcher. Requested series are taken from other
// stores and proxied to RPC client. NOTE: Resulted data are not trimmed exactly to min and max time range.
func (s *ProxyStore) Series(r *storepb.SeriesRequest, srv storepb.Store_SeriesServer) error {
// TODO(bwplotka): This should be part of request logger, otherwise it does not make much sense. Also, could be
// tiggered by tracing span to reduce cognitive load.
reqLogger := log.With(s.logger, "component", "proxy", "request", r.String())
match, matchers, err := matchesExternalLabels(r.Matchers, s.selectorLabels)
if err != nil {
return status.Error(codes.InvalidArgument, err.Error())
}
if !match {
return nil
}
if len(matchers) == 0 {
return status.Error(codes.InvalidArgument, errors.New("no matchers specified (excluding selector labels)").Error())
}
storeMatchers, _ := storepb.PromMatchersToMatchers(matchers...) // Error would be returned by matchesExternalLabels, so skip check.
g, gctx := errgroup.WithContext(srv.Context())
// Allow to buffer max 10 series response.
// Each might be quite large (multi chunk long series given by sidecar).
respSender, respCh := newCancelableRespChannel(gctx, 10)
g.Go(func() error {
// This go routine is responsible for calling store's Series concurrently. Merged results
// are passed to respCh and sent concurrently to client (if buffer of 10 have room).
// When this go routine finishes or is canceled, respCh channel is closed.
var (
seriesSet []storepb.SeriesSet
storeDebugMsgs []string
r = &storepb.SeriesRequest{
MinTime: r.MinTime,
MaxTime: r.MaxTime,
Matchers: storeMatchers,
Aggregates: r.Aggregates,
MaxResolutionWindow: r.MaxResolutionWindow,
SkipChunks: r.SkipChunks,
QueryHints: r.QueryHints,
ShardInfo: r.ShardInfo,
PartialResponseDisabled: r.PartialResponseDisabled,
}
wg = &sync.WaitGroup{}
)
defer func() {
wg.Wait()
close(respCh)
}()
for _, st := range s.stores() {
// We might be able to skip the store if its meta information indicates it cannot have series matching our query.
if ok, reason := storeMatches(gctx, st, r.MinTime, r.MaxTime, matchers...); !ok {
storeDebugMsgs = append(storeDebugMsgs, fmt.Sprintf("store %s filtered out: %v", st, reason))
continue
}
storeDebugMsgs = append(storeDebugMsgs, fmt.Sprintf("Store %s queried", st))
// This is used to cancel this stream when one operation takes too long.
seriesCtx, closeSeries := context.WithCancel(gctx)
seriesCtx = grpc_opentracing.ClientAddContextTags(seriesCtx, opentracing.Tags{
"target": st.Addr(),
})
defer closeSeries()
storeID := labelpb.PromLabelSetsToString(st.LabelSets())
if storeID == "" {
storeID = "Store Gateway"
}
span, seriesCtx := tracing.StartSpan(seriesCtx, "proxy.series", tracing.Tags{
"store.id": storeID,
"store.addr": st.Addr(),
})
sc, err := st.Series(seriesCtx, r)
if err != nil {
err = errors.Wrapf(err, "fetch series for %s %s", storeID, st)
span.SetTag("err", err.Error())
span.Finish()
if r.PartialResponseDisabled {
level.Error(reqLogger).Log("err", err, "msg", "partial response disabled; aborting request")
return err
}
respSender.send(storepb.NewWarnSeriesResponse(err))
continue
}
// Schedule streamSeriesSet that translates gRPC streamed response
// into seriesSet (if series) or respCh if warnings.
seriesSet = append(seriesSet,
startStreamSeriesSet(
seriesCtx,
reqLogger,
span,
closeSeries,
wg,
sc,
respSender,
st.String(),
!r.PartialResponseDisabled,
s.responseTimeout,
s.metrics.emptyStreamResponses,
st.SupportsSharding(),
&s.buffers,
r.ShardInfo,
))
}
level.Debug(reqLogger).Log("msg", "Series: started fanout streams", "status", strings.Join(storeDebugMsgs, ";"))
if len(seriesSet) == 0 {
// This is indicates that configured StoreAPIs are not the ones end user expects.
err := errors.New("No StoreAPIs matched for this query")
level.Warn(reqLogger).Log("err", err, "stores", strings.Join(storeDebugMsgs, ";"))
respSender.send(storepb.NewWarnSeriesResponse(err))
return nil
}
// TODO(bwplotka): Currently we stream into big frames. Consider ensuring 1MB maximum.
// This however does not matter much when used with QueryAPI. Matters for federated Queries a lot.
// https://github.com/thanos-io/thanos/issues/2332
// Series are not necessarily merged across themselves.
mergedSet := storepb.MergeSeriesSets(seriesSet...)
for mergedSet.Next() {
lset, chk := mergedSet.At()
respSender.send(storepb.NewSeriesResponse(&storepb.Series{Labels: labelpb.ZLabelsFromPromLabels(lset), Chunks: chk}))
}
return mergedSet.Err()
})
g.Go(func() error {
// Go routine for gathering merged responses and sending them over to client. It stops when
// respCh channel is closed OR on error from client.
for resp := range respCh {
if err := srv.Send(resp); err != nil {
return status.Error(codes.Unknown, errors.Wrap(err, "send series response").Error())
}
}
return nil
})
if err := g.Wait(); err != nil {
// TODO(bwplotka): Replace with request logger.
level.Error(reqLogger).Log("err", err)
return err
}
return nil
}
type directSender interface {
send(*storepb.SeriesResponse)
}
// streamSeriesSet iterates over incoming stream of series.
// All errors are sent out of band via warning channel.
type streamSeriesSet struct {
ctx context.Context
logger log.Logger
stream storepb.Store_SeriesClient
warnCh directSender
currSeries *storepb.Series
recvCh chan *storepb.Series
errMtx sync.Mutex
err error
name string
partialResponse bool
responseTimeout time.Duration
closeSeries context.CancelFunc
}
type recvResponse struct {
r *storepb.SeriesResponse
err error
}
func frameCtx(responseTimeout time.Duration) (context.Context, context.CancelFunc) {
frameTimeoutCtx := context.Background()
var cancel context.CancelFunc
if responseTimeout != 0 {
frameTimeoutCtx, cancel = context.WithTimeout(frameTimeoutCtx, responseTimeout)
return frameTimeoutCtx, cancel
}
return frameTimeoutCtx, func() {}
}
func startStreamSeriesSet(
ctx context.Context,
logger log.Logger,
span tracing.Span,
closeSeries context.CancelFunc,
wg *sync.WaitGroup,
stream storepb.Store_SeriesClient,
warnCh directSender,
name string,
partialResponse bool,
responseTimeout time.Duration,
emptyStreamResponses prometheus.Counter,
storeSupportsSharding bool,
buffers *sync.Pool,
shardInfo *storepb.ShardInfo,
) *streamSeriesSet {
s := &streamSeriesSet{
ctx: ctx,
logger: logger,
closeSeries: closeSeries,
stream: stream,
warnCh: warnCh,
recvCh: make(chan *storepb.Series, 10),
name: name,
partialResponse: partialResponse,
responseTimeout: responseTimeout,
}
wg.Add(1)
go func() {
seriesStats := &storepb.SeriesStatsCounter{}
bytesProcessed := 0
defer func() {
span.SetTag("processed.series", seriesStats.Series)
span.SetTag("processed.chunks", seriesStats.Chunks)
span.SetTag("processed.samples", seriesStats.Samples)
span.SetTag("processed.bytes", bytesProcessed)
span.Finish()
close(s.recvCh)
wg.Done()
}()
numResponses := 0
defer func() {
if numResponses == 0 {
emptyStreamResponses.Inc()
}
}()
rCh := make(chan *recvResponse)
done := make(chan struct{})
go func() {
for {
r, err := s.stream.Recv()
select {
case <-done:
close(rCh)
return
case rCh <- &recvResponse{r: r, err: err}:
}
}
}()
shardMatcher := shardInfo.Matcher(buffers)
defer shardMatcher.Close()
applySharding := shardInfo != nil && !storeSupportsSharding
if applySharding {
msg := "Applying series sharding in the proxy since there is not support in the underlying store"
level.Debug(logger).Log("msg", msg, "store", name)
}
// The `defer` only executed when function return, we do `defer cancel` in for loop,
// so make the loop body as a function, release timers created by context as early.
handleRecvResponse := func() (next bool) {
frameTimeoutCtx, cancel := frameCtx(s.responseTimeout)
defer cancel()
var rr *recvResponse
select {
case <-ctx.Done():
s.handleErr(errors.Wrapf(ctx.Err(), "failed to receive any data from %s", s.name), done)
return false
case <-frameTimeoutCtx.Done():
s.handleErr(errors.Wrapf(frameTimeoutCtx.Err(), "failed to receive any data in %s from %s", s.responseTimeout.String(), s.name), done)
return false
case rr = <-rCh:
}
if rr.err == io.EOF {
close(done)
return false
}
if rr.err != nil {
s.handleErr(errors.Wrapf(rr.err, "receive series from %s", s.name), done)
return false
}
numResponses++
bytesProcessed += rr.r.Size()
if w := rr.r.GetWarning(); w != "" {
s.warnCh.send(storepb.NewWarnSeriesResponse(errors.New(w)))
}
if series := rr.r.GetSeries(); series != nil {
if applySharding && !shardMatcher.MatchesZLabels(series.Labels) {
return true
}
seriesStats.Count(series)
select {
case s.recvCh <- series:
case <-ctx.Done():
s.handleErr(errors.Wrapf(ctx.Err(), "failed to receive any data from %s", s.name), done)
return false
}
}
return true
}
for {
if !handleRecvResponse() {
return
}
}
}()
return s
}
func (s *streamSeriesSet) handleErr(err error, done chan struct{}) {
defer close(done)
s.closeSeries()
if s.partialResponse {
level.Warn(s.logger).Log("err", err, "msg", "returning partial response")
s.warnCh.send(storepb.NewWarnSeriesResponse(err))
return
}
s.errMtx.Lock()
s.err = err
s.errMtx.Unlock()
}
// Next blocks until new message is received or stream is closed or operation is timed out.
func (s *streamSeriesSet) Next() (ok bool) {
s.currSeries, ok = <-s.recvCh
return ok
}
func (s *streamSeriesSet) At() (labels.Labels, []storepb.AggrChunk) {
if s.currSeries == nil {
return nil, nil
}
return s.currSeries.PromLabels(), s.currSeries.Chunks
}
func (s *streamSeriesSet) Err() error {
s.errMtx.Lock()
defer s.errMtx.Unlock()
return errors.Wrap(s.err, s.name)
}
// storeMatches returns boolean if the given store may hold data for the given label matchers, time ranges and debug store matches gathered from context.
// It also produces tracing span.
func storeMatches(ctx context.Context, s Client, mint, maxt int64, matchers ...*labels.Matcher) (ok bool, reason string) {
span, ctx := tracing.StartSpan(ctx, "store_matches")
defer span.Finish()
var storeDebugMatcher [][]*labels.Matcher
if ctxVal := ctx.Value(StoreMatcherKey); ctxVal != nil {
if value, ok := ctxVal.([][]*labels.Matcher); ok {
storeDebugMatcher = value
}
}
storeMinTime, storeMaxTime := s.TimeRange()
if mint > storeMaxTime || maxt < storeMinTime {
return false, fmt.Sprintf("does not have data within this time period: [%v,%v]. Store time ranges: [%v,%v]", mint, maxt, storeMinTime, storeMaxTime)
}
if ok, reason := storeMatchDebugMetadata(s, storeDebugMatcher); !ok {
return false, reason
}
extLset := s.LabelSets()
if !labelSetsMatch(matchers, extLset...) {
return false, fmt.Sprintf("external labels %v does not match request label matchers: %v", extLset, matchers)
}
return true, ""
}
// storeMatchDebugMetadata return true if the store's address match the storeDebugMatchers.
func storeMatchDebugMetadata(s Client, storeDebugMatchers [][]*labels.Matcher) (ok bool, reason string) {
if len(storeDebugMatchers) == 0 {
return true, ""
}
match := false
for _, sm := range storeDebugMatchers {
match = match || labelSetsMatch(sm, labels.FromStrings("__address__", s.Addr()))
}
if !match {
return false, fmt.Sprintf("__address__ %v does not match debug store metadata matchers: %v", s.Addr(), storeDebugMatchers)
}
return true, ""
}
// labelSetsMatch returns false if all label-set do not match the matchers (aka: OR is between all label-sets).
func labelSetsMatch(matchers []*labels.Matcher, lset ...labels.Labels) bool {
if len(lset) == 0 {
return true
}
for _, ls := range lset {
notMatched := false
for _, m := range matchers {
if lv := ls.Get(m.Name); lv != "" && !m.Matches(lv) {
notMatched = true
break
}
}
if !notMatched {
return true
}
}
return false
}
// LabelNames returns all known label names.
func (s *ProxyStore) LabelNames(ctx context.Context, r *storepb.LabelNamesRequest) (
*storepb.LabelNamesResponse, error,
) {
var (
warnings []string
names [][]string
mtx sync.Mutex
g, gctx = errgroup.WithContext(ctx)
storeDebugMsgs []string
)
for _, st := range s.stores() {
st := st
// We might be able to skip the store if its meta information indicates it cannot have series matching our query.
if ok, reason := storeMatches(gctx, st, r.Start, r.End); !ok {
storeDebugMsgs = append(storeDebugMsgs, fmt.Sprintf("Store %s filtered out due to %v", st, reason))
continue
}
storeDebugMsgs = append(storeDebugMsgs, fmt.Sprintf("Store %s queried", st))
g.Go(func() error {
resp, err := st.LabelNames(gctx, &storepb.LabelNamesRequest{
PartialResponseDisabled: r.PartialResponseDisabled,
Start: r.Start,
End: r.End,
Matchers: r.Matchers,
})
if err != nil {
err = errors.Wrapf(err, "fetch label names from store %s", st)
if r.PartialResponseDisabled {
return err
}
mtx.Lock()
warnings = append(warnings, err.Error())
mtx.Unlock()
return nil
}
mtx.Lock()
warnings = append(warnings, resp.Warnings...)
names = append(names, resp.Names)
mtx.Unlock()
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
level.Debug(s.logger).Log("msg", strings.Join(storeDebugMsgs, ";"))
return &storepb.LabelNamesResponse{
Names: strutil.MergeUnsortedSlices(names...),
Warnings: warnings,
}, nil
}
// LabelValues returns all known label values for a given label name.
func (s *ProxyStore) LabelValues(ctx context.Context, r *storepb.LabelValuesRequest) (
*storepb.LabelValuesResponse, error,
) {
var (
warnings []string
all [][]string
mtx sync.Mutex
g, gctx = errgroup.WithContext(ctx)
storeDebugMsgs []string
)
for _, st := range s.stores() {
st := st
// We might be able to skip the store if its meta information indicates it cannot have series matching our query.
if ok, reason := storeMatches(gctx, st, r.Start, r.End); !ok {
storeDebugMsgs = append(storeDebugMsgs, fmt.Sprintf("Store %s filtered out due to %v", st, reason))
continue
}
storeDebugMsgs = append(storeDebugMsgs, fmt.Sprintf("Store %s queried", st))
g.Go(func() error {
resp, err := st.LabelValues(gctx, &storepb.LabelValuesRequest{
Label: r.Label,
PartialResponseDisabled: r.PartialResponseDisabled,
Start: r.Start,
End: r.End,
Matchers: r.Matchers,
})
if err != nil {
err = errors.Wrapf(err, "fetch label values from store %s", st)
if r.PartialResponseDisabled {
return err
}
mtx.Lock()
warnings = append(warnings, errors.Wrap(err, "fetch label values").Error())
mtx.Unlock()
return nil
}
mtx.Lock()
warnings = append(warnings, resp.Warnings...)
all = append(all, resp.Values)
mtx.Unlock()
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
level.Debug(s.logger).Log("msg", strings.Join(storeDebugMsgs, ";"))
return &storepb.LabelValuesResponse{
Values: strutil.MergeUnsortedSlices(all...),
Warnings: warnings,
}, nil
}