-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
bucket.go
3897 lines (3376 loc) · 125 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 (
"bufio"
"bytes"
"context"
"encoding/binary"
"fmt"
"hash"
"io"
"math"
"os"
"path"
"sort"
"strings"
"sync"
"time"
"github.com/alecthomas/units"
"github.com/cespare/xxhash"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/gogo/protobuf/types"
"github.com/oklog/ulid"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/chunks"
"github.com/prometheus/prometheus/tsdb/encoding"
"github.com/prometheus/prometheus/tsdb/index"
"github.com/weaveworks/common/httpgrpc"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/thanos-io/objstore"
"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/extprom"
"github.com/thanos-io/thanos/pkg/gate"
"github.com/thanos-io/thanos/pkg/info/infopb"
"github.com/thanos-io/thanos/pkg/model"
"github.com/thanos-io/thanos/pkg/pool"
"github.com/thanos-io/thanos/pkg/runutil"
storecache "github.com/thanos-io/thanos/pkg/store/cache"
"github.com/thanos-io/thanos/pkg/store/hintspb"
"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/tenancy"
"github.com/thanos-io/thanos/pkg/tracing"
)
type StoreDataType int
const (
PostingsFetched StoreDataType = iota
PostingsTouched
SeriesFetched
SeriesTouched
ChunksFetched
ChunksTouched
)
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
// EstimatedMaxChunkSize is average max of chunk size. This can be exceeded though in very rare (valid) cases.
EstimatedMaxChunkSize = 16000
EstimatedMaxSeriesSize = 64 * 1024
// Relatively large in order to reduce memory waste, yet small enough to avoid excessive allocations.
chunkBytesPoolMinSize = 64 * 1024 // 64 KiB
chunkBytesPoolMaxSize = 64 * 1024 * 1024 // 64 MiB
// 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"
// DefaultPostingOffsetInMemorySampling represents default value for --store.index-header-posting-offsets-in-mem-sampling.
// 32 value is chosen as it's a good balance for common setups. Sampling that is not too large (too many CPU cycles) and
// not too small (too much memory).
DefaultPostingOffsetInMemorySampling = 32
PartitionerMaxGapSize = 512 * 1024
// Labels for metrics.
labelEncode = "encode"
labelDecode = "decode"
minBlockSyncConcurrency = 1
enableChunkHashCalculation = true
// SeriesBatchSize is the default batch size when fetching series from object storage.
SeriesBatchSize = 10000
// checkContextEveryNIterations is used in some tight loops to check if the context is done.
checkContextEveryNIterations = 128
)
var (
errBlockSyncConcurrencyNotValid = errors.New("the block sync concurrency must be equal or greater than 1.")
hashPool = sync.Pool{New: func() interface{} { return xxhash.New() }}
)
type bucketStoreMetrics struct {
blocksLoaded prometheus.Gauge
blockLoads prometheus.Counter
blockLoadFailures prometheus.Counter
lastLoadedBlock prometheus.Gauge
blockDrops prometheus.Counter
blockDropFailures prometheus.Counter
blockLoadDuration prometheus.Histogram
seriesDataTouched *prometheus.HistogramVec
seriesDataFetched *prometheus.HistogramVec
seriesDataSizeTouched *prometheus.HistogramVec
seriesDataSizeFetched *prometheus.HistogramVec
seriesBlocksQueried *prometheus.HistogramVec
seriesGetAllDuration *prometheus.HistogramVec
seriesMergeDuration *prometheus.HistogramVec
resultSeriesCount *prometheus.HistogramVec
chunkSizeBytes *prometheus.HistogramVec
postingsSizeBytes *prometheus.HistogramVec
queriesDropped *prometheus.CounterVec
seriesRefetches *prometheus.CounterVec
chunkRefetches *prometheus.CounterVec
emptyPostingCount *prometheus.CounterVec
lazyExpandedPostingsCount prometheus.Counter
lazyExpandedPostingSizeBytes prometheus.Counter
lazyExpandedPostingSeriesOverfetchedSizeBytes prometheus.Counter
cachedPostingsCompressions *prometheus.CounterVec
cachedPostingsCompressionErrors *prometheus.CounterVec
cachedPostingsCompressionTimeSeconds *prometheus.CounterVec
cachedPostingsOriginalSizeBytes *prometheus.CounterVec
cachedPostingsCompressedSizeBytes *prometheus.CounterVec
seriesFetchDuration *prometheus.HistogramVec
// Counts time for fetching series across all batches.
seriesFetchDurationSum *prometheus.HistogramVec
postingsFetchDuration *prometheus.HistogramVec
// chunkFetchDuration counts total time loading chunks, but since we spawn
// multiple goroutines the actual latency is usually much lower than it.
chunkFetchDuration *prometheus.HistogramVec
// Actual absolute total time for loading chunks.
chunkFetchDurationSum *prometheus.HistogramVec
}
func newBucketStoreMetrics(reg prometheus.Registerer) *bucketStoreMetrics {
var m bucketStoreMetrics
m.blockLoads = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_block_loads_total",
Help: "Total number of remote block loading attempts.",
})
m.blockLoadFailures = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_block_load_failures_total",
Help: "Total number of failed remote block loading attempts.",
})
m.blockDrops = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_block_drops_total",
Help: "Total number of local blocks that were dropped.",
})
m.blockDropFailures = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_block_drop_failures_total",
Help: "Total number of local blocks that failed to be dropped.",
})
m.blocksLoaded = promauto.With(reg).NewGauge(prometheus.GaugeOpts{
Name: "thanos_bucket_store_blocks_loaded",
Help: "Number of currently loaded blocks.",
})
m.lastLoadedBlock = promauto.With(reg).NewGauge(prometheus.GaugeOpts{
Name: "thanos_bucket_store_blocks_last_loaded_timestamp_seconds",
Help: "Timestamp when last block got loaded.",
})
m.blockLoadDuration = promauto.With(reg).NewHistogram(prometheus.HistogramOpts{
Name: "thanos_bucket_store_block_load_duration_seconds",
Help: "The total time taken to load a block in seconds.",
Buckets: []float64{0.1, 0.2, 0.5, 1, 2, 5, 15, 30, 60, 90, 120, 300},
})
m.seriesDataTouched = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_data_touched",
Help: "Number of items of a data type touched to fulfill a single Store API series request.",
Buckets: prometheus.ExponentialBuckets(200, 2, 15),
}, []string{"data_type", tenancy.MetricLabel})
m.seriesDataFetched = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_data_fetched",
Help: "Number of items of a data type retrieved to fulfill a single Store API series request.",
Buckets: prometheus.ExponentialBuckets(200, 2, 15),
}, []string{"data_type", tenancy.MetricLabel})
m.seriesDataSizeTouched = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_data_size_touched_bytes",
Help: "Total size of items of a data type touched to fulfill a single Store API series request in Bytes.",
Buckets: prometheus.ExponentialBuckets(1024, 2, 15),
}, []string{"data_type", tenancy.MetricLabel})
m.seriesDataSizeFetched = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_data_size_fetched_bytes",
Help: "Total size of items of a data type fetched to fulfill a single Store API series request in Bytes.",
Buckets: prometheus.ExponentialBuckets(1024, 2, 15),
}, []string{"data_type", tenancy.MetricLabel})
m.seriesBlocksQueried = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_blocks_queried",
Help: "Number of blocks in a bucket store that were touched to satisfy a query.",
Buckets: prometheus.ExponentialBuckets(1, 2, 10),
}, []string{tenancy.MetricLabel})
m.seriesGetAllDuration = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_get_all_duration_seconds",
Help: "Time it takes until all per-block prepares and loads 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},
}, []string{tenancy.MetricLabel})
m.seriesMergeDuration = promauto.With(reg).NewHistogramVec(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},
}, []string{tenancy.MetricLabel})
m.resultSeriesCount = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_result_series",
Help: "Number of series observed in the final result of a query.",
Buckets: prometheus.ExponentialBuckets(100, 2, 15), // From 100 to 1638400.
}, []string{tenancy.MetricLabel})
m.chunkSizeBytes = promauto.With(reg).NewHistogramVec(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,
},
}, []string{tenancy.MetricLabel})
m.postingsSizeBytes = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_postings_size_bytes",
Help: "Size in bytes of the postings for a single series call.",
Buckets: []float64{
32, 256, 512, 1024, 32 * 1024, 256 * 1024, 512 * 1024, 1024 * 1024, 32 * 1024 * 1024, 128 * 1024 * 1024, 256 * 1024 * 1024, 512 * 1024 * 1024, 768 * 1024 * 1024, 1024 * 1024 * 1024,
},
}, []string{tenancy.MetricLabel})
m.queriesDropped = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_bucket_store_queries_dropped_total",
Help: "Number of queries that were dropped due to the limit.",
}, []string{"reason", tenancy.MetricLabel})
m.seriesRefetches = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_bucket_store_series_refetches_total",
Help: "Total number of cases where configured estimated series bytes was not enough was to fetch series from index, resulting in refetch.",
}, []string{tenancy.MetricLabel})
m.chunkRefetches = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_bucket_store_chunk_refetches_total",
Help: "Total number of cases where configured estimated chunk bytes was not enough was to fetch chunks from object store, resulting in refetch.",
}, []string{tenancy.MetricLabel})
m.cachedPostingsCompressions = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_bucket_store_cached_postings_compressions_total",
Help: "Number of postings compressions before storing to index cache.",
}, []string{"op", tenancy.MetricLabel})
m.cachedPostingsCompressions.WithLabelValues(labelEncode, tenancy.DefaultTenant)
m.cachedPostingsCompressions.WithLabelValues(labelDecode, tenancy.DefaultTenant)
m.cachedPostingsCompressionErrors = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_bucket_store_cached_postings_compression_errors_total",
Help: "Number of postings compression errors.",
}, []string{"op", tenancy.MetricLabel})
m.cachedPostingsCompressionErrors.WithLabelValues(labelEncode, tenancy.DefaultTenant)
m.cachedPostingsCompressionErrors.WithLabelValues(labelDecode, tenancy.DefaultTenant)
m.cachedPostingsCompressionTimeSeconds = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_bucket_store_cached_postings_compression_time_seconds_total",
Help: "Time spent compressing postings before storing them into postings cache.",
}, []string{"op", tenancy.MetricLabel})
m.cachedPostingsCompressionTimeSeconds.WithLabelValues(labelEncode, tenancy.DefaultTenant)
m.cachedPostingsCompressionTimeSeconds.WithLabelValues(labelDecode, tenancy.DefaultTenant)
m.cachedPostingsOriginalSizeBytes = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_bucket_store_cached_postings_original_size_bytes_total",
Help: "Original size of postings stored into cache.",
}, []string{tenancy.MetricLabel})
m.cachedPostingsCompressedSizeBytes = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_bucket_store_cached_postings_compressed_size_bytes_total",
Help: "Compressed size of postings stored into cache.",
}, []string{tenancy.MetricLabel})
m.seriesFetchDuration = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_fetch_duration_seconds",
Help: "The time it takes to fetch series to respond to a request sent to a store gateway. It includes both the time to fetch it from the cache and from storage in case of cache misses.",
Buckets: []float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120},
}, []string{tenancy.MetricLabel})
m.seriesFetchDurationSum = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_series_fetch_duration_sum_seconds",
Help: "The total time it takes to fetch series to respond to a request sent to a store gateway across all series batches. It includes both the time to fetch it from the cache and from storage in case of cache misses.",
Buckets: []float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120},
}, []string{tenancy.MetricLabel})
m.postingsFetchDuration = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_postings_fetch_duration_seconds",
Help: "The time it takes to fetch postings to respond to a request sent to a store gateway. It includes both the time to fetch it from the cache and from storage in case of cache misses.",
Buckets: []float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120},
}, []string{tenancy.MetricLabel})
m.chunkFetchDuration = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_chunks_fetch_duration_seconds",
Help: "The total time spent fetching chunks within a single request for one block.",
Buckets: []float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120},
}, []string{tenancy.MetricLabel})
m.chunkFetchDurationSum = promauto.With(reg).NewHistogramVec(prometheus.HistogramOpts{
Name: "thanos_bucket_store_chunks_fetch_duration_sum_seconds",
Help: "The total absolute time spent fetching chunks within a single request for one block.",
Buckets: []float64{0.001, 0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120},
}, []string{tenancy.MetricLabel})
m.emptyPostingCount = promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_bucket_store_empty_postings_total",
Help: "Total number of empty postings when fetching block series.",
}, []string{tenancy.MetricLabel})
m.lazyExpandedPostingsCount = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_lazy_expanded_postings_total",
Help: "Total number of times when lazy expanded posting optimization applies.",
})
m.lazyExpandedPostingSizeBytes = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_lazy_expanded_posting_size_bytes_total",
Help: "Total number of lazy posting group size in bytes.",
})
m.lazyExpandedPostingSeriesOverfetchedSizeBytes = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_bucket_store_lazy_expanded_posting_series_overfetched_size_bytes_total",
Help: "Total number of series size in bytes overfetched due to posting lazy expansion.",
})
return &m
}
// FilterConfig is a configuration, which Store uses for filtering metrics based on time.
type FilterConfig struct {
MinTime, MaxTime model.TimeOrDurationValue
}
type BlockEstimator func(meta metadata.Meta) uint64
// BucketStore implements the store API backed by a bucket. It loads all index
// files to local disk.
//
// NOTE: Bucket store reencodes postings using diff+varint+snappy when storing to cache.
// This makes them smaller, but takes extra CPU and memory.
// When used with in-memory cache, memory usage should decrease overall, thanks to postings being smaller.
type BucketStore struct {
logger log.Logger
reg prometheus.Registerer // TODO(metalmatze) remove and add via BucketStoreOption
metrics *bucketStoreMetrics
bkt objstore.InstrumentedBucketReader
fetcher block.MetadataFetcher
dir string
indexCache storecache.IndexCache
indexReaderPool *indexheader.ReaderPool
buffers sync.Pool
chunkPool pool.Pool[byte]
seriesBatchSize int
// 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.Gate
// chunksLimiterFactory creates a new limiter used to limit the number of chunks fetched by each Series() call.
chunksLimiterFactory ChunksLimiterFactory
// seriesLimiterFactory creates a new limiter used to limit the number of touched series by each Series() call,
// or LabelName and LabelValues calls when used with matchers.
seriesLimiterFactory SeriesLimiterFactory
// bytesLimiterFactory creates a new limiter used to limit the amount of bytes fetched/touched by each Series() call.
bytesLimiterFactory BytesLimiterFactory
partitioner Partitioner
filterConfig *FilterConfig
advLabelSets []labelpb.ZLabelSet
enableCompatibilityLabel bool
// Every how many posting offset entry we pool in heap memory. Default in Prometheus is 32.
postingOffsetsInMemSampling int
// Enables hints in the Series() response.
enableSeriesResponseHints bool
enableChunkHashCalculation bool
enabledLazyExpandedPostings bool
sortingStrategy sortingStrategy
blockEstimatedMaxSeriesFunc BlockEstimator
blockEstimatedMaxChunkFunc BlockEstimator
indexHeaderLazyDownloadStrategy indexheader.LazyDownloadIndexHeaderFunc
requestLoggerFunc RequestLoggerFunc
}
func (s *BucketStore) validate() error {
if s.blockSyncConcurrency < minBlockSyncConcurrency {
return errBlockSyncConcurrencyNotValid
}
return nil
}
type noopCache struct{}
func (noopCache) StorePostings(ulid.ULID, labels.Label, []byte, string) {}
func (noopCache) FetchMultiPostings(_ context.Context, _ ulid.ULID, keys []labels.Label, tenant string) (map[labels.Label][]byte, []labels.Label) {
return map[labels.Label][]byte{}, keys
}
func (noopCache) StoreExpandedPostings(_ ulid.ULID, _ []*labels.Matcher, _ []byte, tenant string) {}
func (noopCache) FetchExpandedPostings(_ context.Context, _ ulid.ULID, _ []*labels.Matcher, tenant string) ([]byte, bool) {
return []byte{}, false
}
func (noopCache) StoreSeries(ulid.ULID, storage.SeriesRef, []byte, string) {}
func (noopCache) FetchMultiSeries(_ context.Context, _ ulid.ULID, ids []storage.SeriesRef, tenant string) (map[storage.SeriesRef][]byte, []storage.SeriesRef) {
return map[storage.SeriesRef][]byte{}, ids
}
// BucketStoreOption are functions that configure BucketStore.
type BucketStoreOption func(s *BucketStore)
// WithLogger sets the BucketStore logger to the one you pass.
func WithLogger(logger log.Logger) BucketStoreOption {
return func(s *BucketStore) {
s.logger = logger
}
}
type RequestLoggerFunc func(ctx context.Context, log log.Logger) log.Logger
func NoopRequestLoggerFunc(_ context.Context, logger log.Logger) log.Logger {
return logger
}
// WithRequestLoggerFunc sets the BucketStore to use the passed RequestLoggerFunc
// to initialize logger during query time.
func WithRequestLoggerFunc(loggerFunc RequestLoggerFunc) BucketStoreOption {
return func(s *BucketStore) {
s.requestLoggerFunc = loggerFunc
}
}
// WithRegistry sets a registry that BucketStore uses to register metrics with.
func WithRegistry(reg prometheus.Registerer) BucketStoreOption {
return func(s *BucketStore) {
s.reg = reg
}
}
// WithIndexCache sets a indexCache to use instead of a noopCache.
func WithIndexCache(cache storecache.IndexCache) BucketStoreOption {
return func(s *BucketStore) {
s.indexCache = cache
}
}
// WithQueryGate sets a queryGate to use instead of a noopGate.
func WithQueryGate(queryGate gate.Gate) BucketStoreOption {
return func(s *BucketStore) {
s.queryGate = queryGate
}
}
// WithChunkPool sets a pool.Bytes to use for chunks.
func WithChunkPool(chunkPool pool.Pool[byte]) BucketStoreOption {
return func(s *BucketStore) {
s.chunkPool = chunkPool
}
}
// WithFilterConfig sets a filter which Store uses for filtering metrics based on time.
func WithFilterConfig(filter *FilterConfig) BucketStoreOption {
return func(s *BucketStore) {
s.filterConfig = filter
}
}
// WithDebugLogging enables debug logging.
func WithDebugLogging() BucketStoreOption {
return func(s *BucketStore) {
s.debugLogging = true
}
}
func WithChunkHashCalculation(enableChunkHashCalculation bool) BucketStoreOption {
return func(s *BucketStore) {
s.enableChunkHashCalculation = enableChunkHashCalculation
}
}
func WithSeriesBatchSize(seriesBatchSize int) BucketStoreOption {
return func(s *BucketStore) {
s.seriesBatchSize = seriesBatchSize
}
}
func WithBlockEstimatedMaxSeriesFunc(f BlockEstimator) BucketStoreOption {
return func(s *BucketStore) {
s.blockEstimatedMaxSeriesFunc = f
}
}
func WithBlockEstimatedMaxChunkFunc(f BlockEstimator) BucketStoreOption {
return func(s *BucketStore) {
s.blockEstimatedMaxChunkFunc = f
}
}
// WithLazyExpandedPostings enables lazy expanded postings.
func WithLazyExpandedPostings(enabled bool) BucketStoreOption {
return func(s *BucketStore) {
s.enabledLazyExpandedPostings = enabled
}
}
// WithDontResort disables series resorting in Store Gateway.
func WithDontResort(true bool) BucketStoreOption {
return func(s *BucketStore) {
if true {
s.sortingStrategy = sortingStrategyNone
}
}
}
// WithIndexHeaderLazyDownloadStrategy specifies what block to lazy download its index header.
// Only used when lazy mmap is enabled at the same time.
func WithIndexHeaderLazyDownloadStrategy(strategy indexheader.LazyDownloadIndexHeaderFunc) BucketStoreOption {
return func(s *BucketStore) {
s.indexHeaderLazyDownloadStrategy = strategy
}
}
// 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(
bkt objstore.InstrumentedBucketReader,
fetcher block.MetadataFetcher,
dir string,
chunksLimiterFactory ChunksLimiterFactory,
seriesLimiterFactory SeriesLimiterFactory,
bytesLimiterFactory BytesLimiterFactory,
partitioner Partitioner,
blockSyncConcurrency int,
enableCompatibilityLabel bool,
postingOffsetsInMemSampling int,
enableSeriesResponseHints bool, // TODO(pracucci) Thanos 0.12 and below doesn't gracefully handle new fields in SeriesResponse. Drop this flag and always enable hints once we can drop backward compatibility.
lazyIndexReaderEnabled bool,
lazyIndexReaderIdleTimeout time.Duration,
options ...BucketStoreOption,
) (*BucketStore, error) {
s := &BucketStore{
logger: log.NewNopLogger(),
bkt: bkt,
fetcher: fetcher,
dir: dir,
indexCache: noopCache{},
buffers: sync.Pool{New: func() interface{} {
b := make([]byte, 0, initialBufSize)
return &b
}},
chunkPool: pool.NoopPool[byte]{},
blocks: map[ulid.ULID]*bucketBlock{},
blockSets: map[uint64]*bucketBlockSet{},
blockSyncConcurrency: blockSyncConcurrency,
queryGate: gate.NewNoop(),
chunksLimiterFactory: chunksLimiterFactory,
seriesLimiterFactory: seriesLimiterFactory,
bytesLimiterFactory: bytesLimiterFactory,
partitioner: partitioner,
enableCompatibilityLabel: enableCompatibilityLabel,
postingOffsetsInMemSampling: postingOffsetsInMemSampling,
enableSeriesResponseHints: enableSeriesResponseHints,
enableChunkHashCalculation: enableChunkHashCalculation,
seriesBatchSize: SeriesBatchSize,
sortingStrategy: sortingStrategyStore,
indexHeaderLazyDownloadStrategy: indexheader.AlwaysEagerDownloadIndexHeader,
requestLoggerFunc: NoopRequestLoggerFunc,
}
for _, option := range options {
option(s)
}
// Depend on the options
indexReaderPoolMetrics := indexheader.NewReaderPoolMetrics(extprom.WrapRegistererWithPrefix("thanos_bucket_store_", s.reg))
s.indexReaderPool = indexheader.NewReaderPool(s.logger, lazyIndexReaderEnabled, lazyIndexReaderIdleTimeout, indexReaderPoolMetrics, s.indexHeaderLazyDownloadStrategy)
s.metrics = newBucketStoreMetrics(s.reg) // TODO(metalmatze): Might be possible via Option too
if err := s.validate(); err != nil {
return nil, errors.Wrap(err, "validate config")
}
if dir == "" {
return s, nil
}
if err := os.MkdirAll(dir, 0750); err != nil {
return nil, errors.Wrap(err, "create dir")
}
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")
}
s.indexReaderPool.Close()
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.
s.mtx.Lock()
s.advLabelSets = make([]labelpb.ZLabelSet, 0, len(s.advLabelSets))
for _, bs := range s.blockSets {
s.advLabelSets = append(s.advLabelSets, labelpb.ZLabelSet{Labels: labelpb.ZLabelsFromPromLabels(bs.labels.Copy())})
}
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")
}
if s.dir == "" {
return nil
}
fis, err := os.ReadDir(s.dir)
if err != nil {
return errors.Wrap(err, "read dir")
}
names := make([]string, 0, len(fis))
for _, fi := range fis {
names = append(names, fi.Name())
}
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) {
var dir string
if s.dir != "" {
dir = path.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 dir != "" {
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.blockLoadDuration.Observe(time.Since(start).Seconds())
}
}()
s.metrics.blockLoads.Inc()
lset := labels.FromMap(meta.Thanos.Labels)
h := lset.Hash()
indexHeaderReader, err := s.indexReaderPool.NewBinaryReader(
ctx,
s.logger,
s.bkt,
s.dir,
meta.ULID,
s.postingOffsetsInMemSampling,
meta,
)
if err != nil {
return errors.Wrap(err, "create index header reader")
}
defer func() {
if err != nil {
runutil.CloseWithErrCapture(&err, indexHeaderReader, "index-header")
}
}()
b, err := newBucketBlock(
ctx,
s.metrics,
meta,
s.bkt,
dir,
s.indexCache,
s.chunkPool,
indexHeaderReader,
s.partitioner,
s.blockEstimatedMaxSeriesFunc,
s.blockEstimatedMaxChunkFunc,
)
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()
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()
s.metrics.lastLoadedBlock.SetToCurrentTime()
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")
}
if b.dir == "" {
return nil
}
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
}
// TSDBInfos returns a list of infopb.TSDBInfos for blocks in the bucket store.
func (s *BucketStore) TSDBInfos() []infopb.TSDBInfo {
s.mtx.RLock()
defer s.mtx.RUnlock()
infoMap := make(map[uint64][]infopb.TSDBInfo, len(s.blocks))
for _, b := range s.blocks {
lbls := labels.FromMap(b.meta.Thanos.Labels)
hash := lbls.Hash()
infoMap[hash] = append(infoMap[hash], infopb.TSDBInfo{
Labels: labelpb.ZLabelSet{
Labels: labelpb.ZLabelsFromPromLabels(lbls),
},
MinTime: b.meta.MinTime,
MaxTime: b.meta.MaxTime,
})
}
// join adjacent blocks so we emit less TSDBInfos
res := make([]infopb.TSDBInfo, 0, len(s.blocks))
for _, infos := range infoMap {
sort.Slice(infos, func(i, j int) bool { return infos[i].MinTime < infos[j].MinTime })
cur := infos[0]
for i, info := range infos {
if info.MinTime > cur.MaxTime {
res = append(res, cur)
cur = info
continue
}
cur.MaxTime = info.MaxTime
if i == len(infos)-1 {
res = append(res, cur)
}
}
}
return res
}
func (s *BucketStore) LabelSet() []labelpb.ZLabelSet {
s.mtx.RLock()
labelSets := s.advLabelSets
s.mtx.RUnlock()
if s.enableCompatibilityLabel && len(labelSets) > 0 {
labelSets = append(labelSets, labelpb.ZLabelSet{Labels: []labelpb.ZLabel{{Name: CompatibilityTypeLabelName, Value: "store"}}})
}
return labelSets
}
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 labels.Labels
refs []chunks.ChunkRef
chks []storepb.AggrChunk
}
// blockSeriesClient is a storepb.Store_SeriesClient for a
// single TSDB block in object storage.
type blockSeriesClient struct {
grpc.ClientStream
ctx context.Context
logger log.Logger
extLset labels.Labels
extLsetToRemove map[string]struct{}
mint int64
maxt int64
seriesLimit int
indexr *bucketIndexReader
chunkr *bucketChunkReader