-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
bucket.go
1997 lines (1696 loc) · 56.6 KB
/
bucket.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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package store
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"math"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/oklog/ulid"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/chunks"
"github.com/prometheus/prometheus/tsdb/encoding"
"github.com/prometheus/prometheus/tsdb/fileutil"
"github.com/prometheus/prometheus/tsdb/index"
"github.com/thanos-io/thanos/pkg/block"
"github.com/thanos-io/thanos/pkg/block/indexheader"
"github.com/thanos-io/thanos/pkg/block/metadata"
"github.com/thanos-io/thanos/pkg/compact/downsample"
"github.com/thanos-io/thanos/pkg/component"
"github.com/thanos-io/thanos/pkg/extprom"
"github.com/thanos-io/thanos/pkg/gate"
"github.com/thanos-io/thanos/pkg/model"
"github.com/thanos-io/thanos/pkg/objstore"
"github.com/thanos-io/thanos/pkg/pool"
"github.com/thanos-io/thanos/pkg/promclient"
"github.com/thanos-io/thanos/pkg/runutil"
storecache "github.com/thanos-io/thanos/pkg/store/cache"
"github.com/thanos-io/thanos/pkg/store/storepb"
"github.com/thanos-io/thanos/pkg/strutil"
"github.com/thanos-io/thanos/pkg/tracing"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// maxSamplesPerChunk is approximately the max number of samples that we may have in any given chunk. This is needed
// for precalculating the number of samples that we may have to retrieve and decode for any given query
// without downloading them. Please take a look at https://github.com/prometheus/tsdb/pull/397 to know
// where this number comes from. Long story short: TSDB is made in such a way, and it is made in such a way
// because you barely get any improvements in compression when the number of samples is beyond this.
// Take a look at Figure 6 in this whitepaper http://www.vldb.org/pvldb/vol8/p1816-teller.pdf.
maxSamplesPerChunk = 120
maxChunkSize = 16000
maxSeriesSize = 64 * 1024
// CompatibilityTypeLabelName is an artificial label that Store Gateway can optionally advertise. This is required for compatibility
// with pre v0.8.0 Querier. Previous Queriers was strict about duplicated external labels of all StoreAPIs that had any labels.
// Now with newer Store Gateway advertising all the external labels it has access to, there was simple case where
// Querier was blocking Store Gateway as duplicate with sidecar.
//
// Newer Queriers are not strict, no duplicated external labels check is there anymore.
// Additionally newer Queriers removes/ignore this exact labels from UI and querying.
//
// This label name is intentionally against Prometheus label style.
// TODO(bwplotka): Remove it at some point.
CompatibilityTypeLabelName = "@thanos_compatibility_store_type"
partitionerMaxGapSize = 512 * 1024
)
type bucketStoreMetrics struct {
blocksLoaded prometheus.Gauge
blockLoads prometheus.Counter
blockLoadFailures prometheus.Counter
blockDrops prometheus.Counter
blockDropFailures prometheus.Counter
seriesDataTouched *prometheus.SummaryVec
seriesDataFetched *prometheus.SummaryVec
seriesDataSizeTouched *prometheus.SummaryVec
seriesDataSizeFetched *prometheus.SummaryVec
seriesBlocksQueried prometheus.Summary
seriesGetAllDuration prometheus.Histogram
seriesMergeDuration prometheus.Histogram
resultSeriesCount prometheus.Summary
chunkSizeBytes prometheus.Histogram
queriesDropped prometheus.Counter
queriesLimit prometheus.Gauge
seriesRefetches prometheus.Counter
}
func newBucketStoreMetrics(reg prometheus.Registerer) *bucketStoreMetrics {
var m bucketStoreMetrics
m.blockLoads = prometheus.NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_block_loads_total",
Help: "Total number of remote block loading attempts.",
})
m.blockLoadFailures = prometheus.NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_block_load_failures_total",
Help: "Total number of failed remote block loading attempts.",
})
m.blockDrops = prometheus.NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_block_drops_total",
Help: "Total number of local blocks that were dropped.",
})
m.blockDropFailures = prometheus.NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_block_drop_failures_total",
Help: "Total number of local blocks that failed to be dropped.",
})
m.blocksLoaded = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "thanos_bucket_store_blocks_loaded",
Help: "Number of currently loaded blocks.",
})
m.seriesDataTouched = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "thanos_bucket_store_series_data_touched",
Help: "How many items of a data type in a block were touched for a single series request.",
}, []string{"data_type"})
m.seriesDataFetched = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "thanos_bucket_store_series_data_fetched",
Help: "How many items of a data type in a block were fetched for a single series request.",
}, []string{"data_type"})
m.seriesDataSizeTouched = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "thanos_bucket_store_series_data_size_touched_bytes",
Help: "Size of all items of a data type in a block were touched for a single series request.",
}, []string{"data_type"})
m.seriesDataSizeFetched = prometheus.NewSummaryVec(prometheus.SummaryOpts{
Name: "thanos_bucket_store_series_data_size_fetched_bytes",
Help: "Size of all items of a data type in a block were fetched for a single series request.",
}, []string{"data_type"})
m.seriesBlocksQueried = prometheus.NewSummary(prometheus.SummaryOpts{
Name: "thanos_bucket_store_series_blocks_queried",
Help: "Number of blocks in a bucket store that were touched to satisfy a query.",
})
m.seriesGetAllDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_get_all_duration_seconds",
Help: "Time it takes until all per-block prepares and preloads for a query are finished.",
Buckets: []float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120},
})
m.seriesMergeDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_merge_duration_seconds",
Help: "Time it takes to merge sub-results from all queried blocks into a single result.",
Buckets: []float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120},
})
m.resultSeriesCount = prometheus.NewSummary(prometheus.SummaryOpts{
Name: "thanos_bucket_store_series_result_series",
Help: "Number of series observed in the final result of a query.",
})
m.chunkSizeBytes = prometheus.NewHistogram(prometheus.HistogramOpts{
Name: "thanos_bucket_store_sent_chunk_size_bytes",
Help: "Size in bytes of the chunks for the single series, which is adequate to the gRPC message size sent to querier.",
Buckets: []float64{
32, 256, 512, 1024, 32 * 1024, 256 * 1024, 512 * 1024, 1024 * 1024, 32 * 1024 * 1024, 256 * 1024 * 1024, 512 * 1024 * 1024,
},
})
m.queriesDropped = prometheus.NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_queries_dropped_total",
Help: "Number of queries that were dropped due to the sample limit.",
})
m.queriesLimit = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "thanos_bucket_store_queries_concurrent_max",
Help: "Number of maximum concurrent queries.",
})
m.seriesRefetches = prometheus.NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_series_refetches_total",
Help: fmt.Sprintf("Total number of cases where %v bytes was not enough was to fetch series from index, resulting in refetch.", maxSeriesSize),
})
if reg != nil {
reg.MustRegister(
m.blockLoads,
m.blockLoadFailures,
m.blockDrops,
m.blockDropFailures,
m.blocksLoaded,
m.seriesDataTouched,
m.seriesDataFetched,
m.seriesDataSizeTouched,
m.seriesDataSizeFetched,
m.seriesBlocksQueried,
m.seriesGetAllDuration,
m.seriesMergeDuration,
m.resultSeriesCount,
m.chunkSizeBytes,
m.queriesDropped,
m.queriesLimit,
m.seriesRefetches,
)
}
return &m
}
// FilterConfig is a configuration, which Store uses for filtering metrics based on time.
type FilterConfig struct {
MinTime, MaxTime model.TimeOrDurationValue
}
// BucketStore implements the store API backed by a bucket. It loads all index
// files to local disk.
type BucketStore struct {
logger log.Logger
metrics *bucketStoreMetrics
bkt objstore.BucketReader
fetcher block.MetadataFetcher
dir string
indexCache storecache.IndexCache
chunkPool pool.BytesPool
// Sets of blocks that have the same labels. They are indexed by a hash over their label set.
mtx sync.RWMutex
blocks map[ulid.ULID]*bucketBlock
blockSets map[uint64]*bucketBlockSet
// Verbose enabled additional logging.
debugLogging bool
// Number of goroutines to use when syncing blocks from object storage.
blockSyncConcurrency int
// Query gate which limits the maximum amount of concurrent queries.
queryGate gate.Gater
// samplesLimiter limits the number of samples per each Series() call.
samplesLimiter SampleLimiter
partitioner partitioner
filterConfig *FilterConfig
advLabelSets []storepb.LabelSet
enableCompatibilityLabel bool
enableIndexHeader bool
}
// NewBucketStore creates a new bucket backed store that implements the store API against
// an object store bucket. It is optimized to work against high latency backends.
func NewBucketStore(
logger log.Logger,
reg prometheus.Registerer,
bucket objstore.BucketReader,
fetcher block.MetadataFetcher,
dir string,
indexCache storecache.IndexCache,
maxChunkPoolBytes uint64,
maxSampleCount uint64,
maxConcurrent int,
debugLogging bool,
blockSyncConcurrency int,
filterConfig *FilterConfig,
enableCompatibilityLabel bool,
enableIndexHeader bool,
) (*BucketStore, error) {
if logger == nil {
logger = log.NewNopLogger()
}
if maxConcurrent < 0 {
return nil, errors.Errorf("max concurrency value cannot be lower than 0 (got %v)", maxConcurrent)
}
chunkPool, err := pool.NewBucketedBytesPool(maxChunkSize, 50e6, 2, maxChunkPoolBytes)
if err != nil {
return nil, errors.Wrap(err, "create chunk pool")
}
metrics := newBucketStoreMetrics(reg)
s := &BucketStore{
logger: logger,
bkt: bucket,
fetcher: fetcher,
dir: dir,
indexCache: indexCache,
chunkPool: chunkPool,
blocks: map[ulid.ULID]*bucketBlock{},
blockSets: map[uint64]*bucketBlockSet{},
debugLogging: debugLogging,
blockSyncConcurrency: blockSyncConcurrency,
filterConfig: filterConfig,
queryGate: gate.NewGate(
maxConcurrent,
extprom.WrapRegistererWithPrefix("thanos_bucket_store_series_", reg),
),
samplesLimiter: NewLimiter(maxSampleCount, metrics.queriesDropped),
partitioner: gapBasedPartitioner{maxGapSize: partitionerMaxGapSize},
enableCompatibilityLabel: enableCompatibilityLabel,
enableIndexHeader: enableIndexHeader,
}
s.metrics = metrics
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, errors.Wrap(err, "create dir")
}
s.metrics.queriesLimit.Set(float64(maxConcurrent))
return s, nil
}
// Close the store.
func (s *BucketStore) Close() (err error) {
s.mtx.Lock()
defer s.mtx.Unlock()
for _, b := range s.blocks {
runutil.CloseWithErrCapture(&err, b, "closing Bucket Block")
}
return err
}
// SyncBlocks synchronizes the stores state with the Bucket bucket.
// It will reuse disk space as persistent cache based on s.dir param.
func (s *BucketStore) SyncBlocks(ctx context.Context) error {
metas, _, metaFetchErr := s.fetcher.Fetch(ctx)
// For partial view allow adding new blocks at least.
if metaFetchErr != nil && metas == nil {
return metaFetchErr
}
var wg sync.WaitGroup
blockc := make(chan *metadata.Meta)
for i := 0; i < s.blockSyncConcurrency; i++ {
wg.Add(1)
go func() {
for meta := range blockc {
if err := s.addBlock(ctx, meta); err != nil {
continue
}
}
wg.Done()
}()
}
for id, meta := range metas {
if b := s.getBlock(id); b != nil {
continue
}
select {
case <-ctx.Done():
case blockc <- meta:
}
}
close(blockc)
wg.Wait()
if metaFetchErr != nil {
return metaFetchErr
}
// Drop all blocks that are no longer present in the bucket.
for id := range s.blocks {
if _, ok := metas[id]; ok {
continue
}
if err := s.removeBlock(id); err != nil {
level.Warn(s.logger).Log("msg", "drop of outdated block failed", "block", id, "err", err)
s.metrics.blockDropFailures.Inc()
}
level.Info(s.logger).Log("msg", "dropped outdated block", "block", id)
s.metrics.blockDrops.Inc()
}
// Sync advertise labels.
var storeLabels []storepb.Label
s.mtx.Lock()
s.advLabelSets = s.advLabelSets[:0]
for _, bs := range s.blockSets {
storeLabels := storeLabels[:0]
for _, l := range bs.labels {
storeLabels = append(storeLabels, storepb.Label{Name: l.Name, Value: l.Value})
}
s.advLabelSets = append(s.advLabelSets, storepb.LabelSet{Labels: storeLabels})
}
sort.Slice(s.advLabelSets, func(i, j int) bool {
return strings.Compare(s.advLabelSets[i].String(), s.advLabelSets[j].String()) < 0
})
s.mtx.Unlock()
return nil
}
// InitialSync perform blocking sync with extra step at the end to delete locally saved blocks that are no longer
// present in the bucket. The mismatch of these can only happen between restarts, so we can do that only once per startup.
func (s *BucketStore) InitialSync(ctx context.Context) error {
if err := s.SyncBlocks(ctx); err != nil {
return errors.Wrap(err, "sync block")
}
names, err := fileutil.ReadDir(s.dir)
if err != nil {
return errors.Wrap(err, "read dir")
}
for _, n := range names {
id, ok := block.IsBlockDir(n)
if !ok {
continue
}
if b := s.getBlock(id); b != nil {
continue
}
// No such block loaded, remove the local dir.
if err := os.RemoveAll(path.Join(s.dir, id.String())); err != nil {
level.Warn(s.logger).Log("msg", "failed to remove block which is not needed", "err", err)
}
}
return nil
}
func (s *BucketStore) getBlock(id ulid.ULID) *bucketBlock {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.blocks[id]
}
func (s *BucketStore) addBlock(ctx context.Context, meta *metadata.Meta) (err error) {
dir := filepath.Join(s.dir, meta.ULID.String())
start := time.Now()
level.Debug(s.logger).Log("msg", "loading new block", "id", meta.ULID)
defer func() {
if err != nil {
s.metrics.blockLoadFailures.Inc()
if err2 := os.RemoveAll(dir); err2 != nil {
level.Warn(s.logger).Log("msg", "failed to remove block we cannot load", "err", err2)
}
level.Warn(s.logger).Log("msg", "loading block failed", "elapsed", time.Since(start), "id", meta.ULID, "err", err)
} else {
level.Info(s.logger).Log("msg", "loaded new block", "elapsed", time.Since(start), "id", meta.ULID)
}
}()
s.metrics.blockLoads.Inc()
lset := labels.FromMap(meta.Thanos.Labels)
h := lset.Hash()
var indexHeaderReader indexheader.Reader
if s.enableIndexHeader {
indexHeaderReader, err = indexheader.NewBinaryReader(ctx, s.logger, s.bkt, s.dir, meta.ULID)
if err != nil {
return errors.Wrap(err, "create index header reader")
}
} else {
indexHeaderReader, err = indexheader.NewJSONReader(ctx, s.logger, s.bkt, s.dir, meta.ULID)
if err != nil {
return errors.Wrap(err, "create index cache reader")
}
}
defer func() {
if err != nil {
runutil.CloseWithErrCapture(&err, indexHeaderReader, "index-header")
}
}()
b, err := newBucketBlock(
ctx,
log.With(s.logger, "block", meta.ULID),
meta,
s.bkt,
dir,
s.indexCache,
s.chunkPool,
indexHeaderReader,
s.partitioner,
s.metrics.seriesRefetches,
)
if err != nil {
return errors.Wrap(err, "new bucket block")
}
defer func() {
if err != nil {
runutil.CloseWithErrCapture(&err, b, "index-header")
}
}()
s.mtx.Lock()
defer s.mtx.Unlock()
sort.Sort(lset)
set, ok := s.blockSets[h]
if !ok {
set = newBucketBlockSet(lset)
s.blockSets[h] = set
}
if err = set.add(b); err != nil {
return errors.Wrap(err, "add block to set")
}
s.blocks[b.meta.ULID] = b
s.metrics.blocksLoaded.Inc()
return nil
}
func (s *BucketStore) removeBlock(id ulid.ULID) error {
s.mtx.Lock()
b, ok := s.blocks[id]
if ok {
lset := labels.FromMap(b.meta.Thanos.Labels)
s.blockSets[lset.Hash()].remove(id)
delete(s.blocks, id)
}
s.mtx.Unlock()
if !ok {
return nil
}
s.metrics.blocksLoaded.Dec()
if err := b.Close(); err != nil {
return errors.Wrap(err, "close block")
}
return os.RemoveAll(b.dir)
}
// TimeRange returns the minimum and maximum timestamp of data available in the store.
func (s *BucketStore) TimeRange() (mint, maxt int64) {
s.mtx.RLock()
defer s.mtx.RUnlock()
mint = math.MaxInt64
maxt = math.MinInt64
for _, b := range s.blocks {
if b.meta.MinTime < mint {
mint = b.meta.MinTime
}
if b.meta.MaxTime > maxt {
maxt = b.meta.MaxTime
}
}
mint = s.limitMinTime(mint)
maxt = s.limitMaxTime(maxt)
return mint, maxt
}
// Info implements the storepb.StoreServer interface.
func (s *BucketStore) Info(context.Context, *storepb.InfoRequest) (*storepb.InfoResponse, error) {
mint, maxt := s.TimeRange()
res := &storepb.InfoResponse{
StoreType: component.Store.ToProto(),
MinTime: mint,
MaxTime: maxt,
}
s.mtx.RLock()
// Should we clone?
res.LabelSets = s.advLabelSets
s.mtx.RUnlock()
if s.enableCompatibilityLabel && len(res.LabelSets) > 0 {
// This is for compatibility with Querier v0.7.0.
// See query.StoreCompatibilityTypeLabelName comment for details.
res.LabelSets = append(res.LabelSets, storepb.LabelSet{Labels: []storepb.Label{{Name: CompatibilityTypeLabelName, Value: "store"}}})
}
return res, nil
}
func (s *BucketStore) limitMinTime(mint int64) int64 {
if s.filterConfig == nil {
return mint
}
filterMinTime := s.filterConfig.MinTime.PrometheusTimestamp()
if mint < filterMinTime {
return filterMinTime
}
return mint
}
func (s *BucketStore) limitMaxTime(maxt int64) int64 {
if s.filterConfig == nil {
return maxt
}
filterMaxTime := s.filterConfig.MaxTime.PrometheusTimestamp()
if maxt > filterMaxTime {
maxt = filterMaxTime
}
return maxt
}
type seriesEntry struct {
lset []storepb.Label
refs []uint64
chks []storepb.AggrChunk
}
type bucketSeriesSet struct {
set []seriesEntry
i int
err error
}
func newBucketSeriesSet(set []seriesEntry) *bucketSeriesSet {
return &bucketSeriesSet{
set: set,
i: -1,
}
}
func (s *bucketSeriesSet) Next() bool {
if s.i >= len(s.set)-1 {
return false
}
s.i++
return true
}
func (s *bucketSeriesSet) At() ([]storepb.Label, []storepb.AggrChunk) {
return s.set[s.i].lset, s.set[s.i].chks
}
func (s *bucketSeriesSet) Err() error {
return s.err
}
func blockSeries(
extLset map[string]string,
indexr *bucketIndexReader,
chunkr *bucketChunkReader,
matchers []*labels.Matcher,
req *storepb.SeriesRequest,
samplesLimiter SampleLimiter,
) (storepb.SeriesSet, *queryStats, error) {
ps, err := indexr.ExpandedPostings(matchers)
if err != nil {
return nil, nil, errors.Wrap(err, "expanded matching posting")
}
if len(ps) == 0 {
return storepb.EmptySeriesSet(), indexr.stats, nil
}
// Preload all series index data.
// TODO(bwplotka): Consider not keeping all series in memory all the time.
// TODO(bwplotka): Do lazy loading in one step as `ExpandingPostings` method.
if err := indexr.PreloadSeries(ps); err != nil {
return nil, nil, errors.Wrap(err, "preload series")
}
// Transform all series into the response types and mark their relevant chunks
// for preloading.
var (
res []seriesEntry
lset labels.Labels
chks []chunks.Meta
)
for _, id := range ps {
if err := indexr.LoadedSeries(id, &lset, &chks); err != nil {
return nil, nil, errors.Wrap(err, "read series")
}
s := seriesEntry{
lset: make([]storepb.Label, 0, len(lset)+len(extLset)),
refs: make([]uint64, 0, len(chks)),
chks: make([]storepb.AggrChunk, 0, len(chks)),
}
for _, l := range lset {
// Skip if the external labels of the block overrule the series' label.
// NOTE(fabxc): maybe move it to a prefixed version to still ensure uniqueness of series?
if extLset[l.Name] != "" {
continue
}
s.lset = append(s.lset, storepb.Label{
Name: l.Name,
Value: l.Value,
})
}
for ln, lv := range extLset {
s.lset = append(s.lset, storepb.Label{
Name: ln,
Value: lv,
})
}
sort.Slice(s.lset, func(i, j int) bool {
return s.lset[i].Name < s.lset[j].Name
})
for _, meta := range chks {
if meta.MaxTime < req.MinTime {
continue
}
if meta.MinTime > req.MaxTime {
break
}
if err := chunkr.addPreload(meta.Ref); err != nil {
return nil, nil, errors.Wrap(err, "add chunk preload")
}
s.chks = append(s.chks, storepb.AggrChunk{
MinTime: meta.MinTime,
MaxTime: meta.MaxTime,
})
s.refs = append(s.refs, meta.Ref)
}
if len(s.chks) > 0 {
res = append(res, s)
}
}
// Preload all chunks that were marked in the previous stage.
if err := chunkr.preload(samplesLimiter); err != nil {
return nil, nil, errors.Wrap(err, "preload chunks")
}
// Transform all chunks into the response format.
for _, s := range res {
for i, ref := range s.refs {
chk, err := chunkr.Chunk(ref)
if err != nil {
return nil, nil, errors.Wrap(err, "get chunk")
}
if err := populateChunk(&s.chks[i], chk, req.Aggregates); err != nil {
return nil, nil, errors.Wrap(err, "populate chunk")
}
}
}
return newBucketSeriesSet(res), indexr.stats.merge(chunkr.stats), nil
}
func populateChunk(out *storepb.AggrChunk, in chunkenc.Chunk, aggrs []storepb.Aggr) error {
if in.Encoding() == chunkenc.EncXOR {
out.Raw = &storepb.Chunk{Type: storepb.Chunk_XOR, Data: in.Bytes()}
return nil
}
if in.Encoding() != downsample.ChunkEncAggr {
return errors.Errorf("unsupported chunk encoding %d", in.Encoding())
}
ac := downsample.AggrChunk(in.Bytes())
for _, at := range aggrs {
switch at {
case storepb.Aggr_COUNT:
x, err := ac.Get(downsample.AggrCount)
if err != nil {
return errors.Errorf("aggregate %s does not exist", downsample.AggrCount)
}
out.Count = &storepb.Chunk{Type: storepb.Chunk_XOR, Data: x.Bytes()}
case storepb.Aggr_SUM:
x, err := ac.Get(downsample.AggrSum)
if err != nil {
return errors.Errorf("aggregate %s does not exist", downsample.AggrSum)
}
out.Sum = &storepb.Chunk{Type: storepb.Chunk_XOR, Data: x.Bytes()}
case storepb.Aggr_MIN:
x, err := ac.Get(downsample.AggrMin)
if err != nil {
return errors.Errorf("aggregate %s does not exist", downsample.AggrMin)
}
out.Min = &storepb.Chunk{Type: storepb.Chunk_XOR, Data: x.Bytes()}
case storepb.Aggr_MAX:
x, err := ac.Get(downsample.AggrMax)
if err != nil {
return errors.Errorf("aggregate %s does not exist", downsample.AggrMax)
}
out.Max = &storepb.Chunk{Type: storepb.Chunk_XOR, Data: x.Bytes()}
case storepb.Aggr_COUNTER:
x, err := ac.Get(downsample.AggrCounter)
if err != nil {
return errors.Errorf("aggregate %s does not exist", downsample.AggrCounter)
}
out.Counter = &storepb.Chunk{Type: storepb.Chunk_XOR, Data: x.Bytes()}
}
}
return nil
}
// debugFoundBlockSetOverview logs on debug level what exactly blocks we used for query in terms of
// labels and resolution. This is important because we allow mixed resolution results, so it is quite crucial
// to be aware what exactly resolution we see on query.
// TODO(bplotka): Consider adding resolution label to all results to propagate that info to UI and Query API.
func debugFoundBlockSetOverview(logger log.Logger, mint, maxt, maxResolutionMillis int64, lset labels.Labels, bs []*bucketBlock) {
if len(bs) == 0 {
level.Debug(logger).Log("msg", "No block found", "mint", mint, "maxt", maxt, "lset", lset.String())
return
}
var (
parts []string
currRes = int64(-1)
currMin, currMax int64
)
for _, b := range bs {
if currRes == b.meta.Thanos.Downsample.Resolution {
currMax = b.meta.MaxTime
continue
}
if currRes != -1 {
parts = append(parts, fmt.Sprintf("Range: %d-%d Resolution: %d", currMin, currMax, currRes))
}
currRes = b.meta.Thanos.Downsample.Resolution
currMin = b.meta.MinTime
currMax = b.meta.MaxTime
}
parts = append(parts, fmt.Sprintf("Range: %d-%d Resolution: %d", currMin, currMax, currRes))
level.Debug(logger).Log("msg", "Blocks source resolutions", "blocks", len(bs), "Maximum Resolution", maxResolutionMillis, "mint", mint, "maxt", maxt, "lset", lset.String(), "spans", strings.Join(parts, "\n"))
}
// Series implements the storepb.StoreServer interface.
func (s *BucketStore) Series(req *storepb.SeriesRequest, srv storepb.Store_SeriesServer) (err error) {
{
span, _ := tracing.StartSpan(srv.Context(), "store_query_gate_ismyturn")
err := s.queryGate.IsMyTurn(srv.Context())
span.Finish()
if err != nil {
return errors.Wrapf(err, "failed to wait for turn")
}
}
defer s.queryGate.Done()
matchers, err := promclient.TranslateMatchers(req.Matchers)
if err != nil {
return status.Error(codes.InvalidArgument, err.Error())
}
req.MinTime = s.limitMinTime(req.MinTime)
req.MaxTime = s.limitMaxTime(req.MaxTime)
var (
stats = &queryStats{}
res []storepb.SeriesSet
mtx sync.Mutex
g, ctx = errgroup.WithContext(srv.Context())
)
s.mtx.RLock()
for _, bs := range s.blockSets {
blockMatchers, ok := bs.labelMatchers(matchers...)
if !ok {
continue
}
blocks := bs.getFor(req.MinTime, req.MaxTime, req.MaxResolutionWindow)
mtx.Lock()
stats.blocksQueried += len(blocks)
mtx.Unlock()
if s.debugLogging {
debugFoundBlockSetOverview(s.logger, req.MinTime, req.MaxTime, req.MaxResolutionWindow, bs.labels, blocks)
}
for _, b := range blocks {
b := b
// We must keep the readers open until all their data has been sent.
indexr := b.indexReader(ctx)
chunkr := b.chunkReader(ctx)
// Defer all closes to the end of Series method.
defer runutil.CloseWithLogOnErr(s.logger, indexr, "series block")
defer runutil.CloseWithLogOnErr(s.logger, chunkr, "series block")
g.Go(func() error {
part, pstats, err := blockSeries(
b.meta.Thanos.Labels,
indexr,
chunkr,
blockMatchers,
req,
s.samplesLimiter,
)
if err != nil {
return errors.Wrapf(err, "fetch series for block %s", b.meta.ULID)
}
mtx.Lock()
res = append(res, part)
stats = stats.merge(pstats)
mtx.Unlock()
return nil
})
}
}
s.mtx.RUnlock()
defer func() {
s.metrics.seriesDataTouched.WithLabelValues("postings").Observe(float64(stats.postingsTouched))
s.metrics.seriesDataFetched.WithLabelValues("postings").Observe(float64(stats.postingsFetched))
s.metrics.seriesDataSizeTouched.WithLabelValues("postings").Observe(float64(stats.postingsTouchedSizeSum))
s.metrics.seriesDataSizeFetched.WithLabelValues("postings").Observe(float64(stats.postingsFetchedSizeSum))
s.metrics.seriesDataTouched.WithLabelValues("series").Observe(float64(stats.seriesTouched))
s.metrics.seriesDataFetched.WithLabelValues("series").Observe(float64(stats.seriesFetched))
s.metrics.seriesDataSizeTouched.WithLabelValues("series").Observe(float64(stats.seriesTouchedSizeSum))
s.metrics.seriesDataSizeFetched.WithLabelValues("series").Observe(float64(stats.seriesFetchedSizeSum))
s.metrics.seriesDataTouched.WithLabelValues("chunks").Observe(float64(stats.chunksTouched))
s.metrics.seriesDataFetched.WithLabelValues("chunks").Observe(float64(stats.chunksFetched))
s.metrics.seriesDataSizeTouched.WithLabelValues("chunks").Observe(float64(stats.chunksTouchedSizeSum))
s.metrics.seriesDataSizeFetched.WithLabelValues("chunks").Observe(float64(stats.chunksFetchedSizeSum))
s.metrics.resultSeriesCount.Observe(float64(stats.mergedSeriesCount))
level.Debug(s.logger).Log("msg", "stats query processed",
"stats", fmt.Sprintf("%+v", stats), "err", err)
}()
// Concurrently get data from all blocks.
{
span, _ := tracing.StartSpan(srv.Context(), "bucket_store_preload_all")
begin := time.Now()
err := g.Wait()
span.Finish()
if err != nil {
return status.Error(codes.Aborted, err.Error())
}
stats.getAllDuration = time.Since(begin)
s.metrics.seriesGetAllDuration.Observe(stats.getAllDuration.Seconds())
s.metrics.seriesBlocksQueried.Observe(float64(stats.blocksQueried))
}
// Merge the sub-results from each selected block.
{
span, _ := tracing.StartSpan(srv.Context(), "bucket_store_merge_all")
defer span.Finish()
begin := time.Now()
// Merge series set into an union of all block sets. This exposes all blocks are single seriesSet.
// Chunks of returned series might be out of order w.r.t to their time range.
// This must be accounted for later by clients.
set := storepb.MergeSeriesSets(res...)
for set.Next() {
var series storepb.Series
stats.mergedSeriesCount++
if req.SkipChunks {
series.Labels, _ = set.At()
} else {
series.Labels, series.Chunks = set.At()
stats.mergedChunksCount += len(series.Chunks)
s.metrics.chunkSizeBytes.Observe(float64(chunksSize(series.Chunks)))
}
if err := srv.Send(storepb.NewSeriesResponse(&series)); err != nil {
return status.Error(codes.Unknown, errors.Wrap(err, "send series response").Error())
}
}
if set.Err() != nil {
return status.Error(codes.Unknown, errors.Wrap(set.Err(), "expand series set").Error())
}
stats.mergeDuration = time.Since(begin)
s.metrics.seriesMergeDuration.Observe(stats.mergeDuration.Seconds())
}
return nil
}
func chunksSize(chks []storepb.AggrChunk) (size int) {
for _, chk := range chks {
size += chk.Size() // This gets the encoded proto size.
}
return size
}
// LabelNames implements the storepb.StoreServer interface.
func (s *BucketStore) LabelNames(ctx context.Context, _ *storepb.LabelNamesRequest) (*storepb.LabelNamesResponse, error) {
g, gctx := errgroup.WithContext(ctx)
s.mtx.RLock()
var mtx sync.Mutex
var sets [][]string
for _, b := range s.blocks {
indexr := b.indexReader(gctx)
g.Go(func() error {
defer runutil.CloseWithLogOnErr(s.logger, indexr, "label names")
// Do it via index reader to have pending reader registered correctly.
res := indexr.block.indexHeaderReader.LabelNames()