-
Notifications
You must be signed in to change notification settings - Fork 456
/
bucket.go
2109 lines (1806 loc) · 70.3 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
// SPDX-License-Identifier: AGPL-3.0-only
// Provenance-includes-location: https://github.com/thanos-io/thanos/blob/main/pkg/store/bucket.go
// Provenance-includes-license: Apache-2.0
// Provenance-includes-copyright: The Thanos Authors.
package storegateway
import (
"bytes"
"context"
"fmt"
"io"
"math"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"sync"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/gogo/protobuf/types"
"github.com/grafana/dskit/gate"
"github.com/grafana/dskit/grpcutil"
"github.com/grafana/dskit/multierror"
"github.com/grafana/dskit/runutil"
"github.com/oklog/ulid"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb/chunks"
"github.com/prometheus/prometheus/tsdb/encoding"
"github.com/prometheus/prometheus/tsdb/hashcache"
"github.com/prometheus/prometheus/tsdb/index"
"github.com/thanos-io/objstore"
"go.uber.org/atomic"
"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/grafana/mimir/pkg/mimirpb"
"github.com/grafana/mimir/pkg/storage/sharding"
"github.com/grafana/mimir/pkg/storage/tsdb"
"github.com/grafana/mimir/pkg/storage/tsdb/block"
"github.com/grafana/mimir/pkg/storage/tsdb/bucketcache"
"github.com/grafana/mimir/pkg/storegateway/hintspb"
"github.com/grafana/mimir/pkg/storegateway/indexcache"
"github.com/grafana/mimir/pkg/storegateway/indexheader"
streamindex "github.com/grafana/mimir/pkg/storegateway/indexheader/index"
"github.com/grafana/mimir/pkg/storegateway/storegatewaypb"
"github.com/grafana/mimir/pkg/storegateway/storepb"
"github.com/grafana/mimir/pkg/util"
"github.com/grafana/mimir/pkg/util/globalerror"
"github.com/grafana/mimir/pkg/util/pool"
"github.com/grafana/mimir/pkg/util/spanlogger"
)
const (
// Labels for metrics.
labelEncode = "encode"
labelDecode = "decode"
targetQueryStreamBatchMessageSize = 1 * 1024 * 1024
)
type BucketStoreStats struct {
// BlocksLoaded is the number of blocks currently loaded in the bucket store
// indexed by the duration of the block.
BlocksLoaded map[time.Duration]int
}
// 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 {
userID string
logger log.Logger
metrics *BucketStoreMetrics
bkt objstore.InstrumentedBucketReader
fetcher block.MetadataFetcher
dir string
indexCache indexcache.IndexCache
indexReaderPool *indexheader.ReaderPool
seriesHashCache *hashcache.SeriesHashCache
// Sets of blocks that have the same labels. They are indexed by a hash over their label set.
blocksMx sync.RWMutex
blocks map[ulid.ULID]*bucketBlock
blockSet *bucketBlockSet
// Number of goroutines to use when syncing blocks from object storage.
blockSyncConcurrency int
// maxSeriesPerBatch controls the batch size to use when fetching series.
// This is not restricted to the Series() RPC.
// This value must be greater than zero.
maxSeriesPerBatch int
// Query gate which limits the maximum amount of concurrent queries.
queryGate gate.Gate
// Gate used to limit concurrency on loading index-headers across all tenants.
lazyLoadingGate 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
partitioners blockPartitioners
// Every how many posting offset entry we pool in heap memory. Default in Prometheus is 32.
postingOffsetsInMemSampling int
// Additional configuration for experimental indexheader.BinaryReader behaviour.
indexHeaderCfg indexheader.Config
// postingsStrategy is a strategy shared among all tenants.
postingsStrategy postingsSelectionStrategy
}
type noopCache struct{}
func (noopCache) StorePostings(string, ulid.ULID, labels.Label, []byte, time.Duration) {}
func (noopCache) FetchMultiPostings(_ context.Context, _ string, _ ulid.ULID, keys []labels.Label) indexcache.BytesResult {
return &indexcache.MapIterator[labels.Label]{Keys: keys}
}
func (noopCache) StoreSeriesForRef(string, ulid.ULID, storage.SeriesRef, []byte, time.Duration) {}
func (noopCache) FetchMultiSeriesForRefs(_ context.Context, _ string, _ ulid.ULID, ids []storage.SeriesRef) (map[storage.SeriesRef][]byte, []storage.SeriesRef) {
return map[storage.SeriesRef][]byte{}, ids
}
func (c noopCache) StoreExpandedPostings(_ string, _ ulid.ULID, _ indexcache.LabelMatchersKey, _ string, _ []byte) {
}
func (c noopCache) FetchExpandedPostings(_ context.Context, _ string, _ ulid.ULID, _ indexcache.LabelMatchersKey, _ string) ([]byte, bool) {
return nil, false
}
func (noopCache) StoreSeriesForPostings(string, ulid.ULID, *sharding.ShardSelector, indexcache.PostingsKey, []byte) {
}
func (noopCache) FetchSeriesForPostings(context.Context, string, ulid.ULID, *sharding.ShardSelector, indexcache.PostingsKey) ([]byte, bool) {
return nil, false
}
func (noopCache) StoreLabelNames(_ string, _ ulid.ULID, _ indexcache.LabelMatchersKey, _ []byte) {
}
func (noopCache) FetchLabelNames(_ context.Context, _ string, _ ulid.ULID, _ indexcache.LabelMatchersKey) ([]byte, bool) {
return nil, false
}
func (noopCache) StoreLabelValues(_ string, _ ulid.ULID, _ string, _ indexcache.LabelMatchersKey, _ []byte) {
}
func (noopCache) FetchLabelValues(_ context.Context, _ string, _ ulid.ULID, _ string, _ indexcache.LabelMatchersKey) ([]byte, bool) {
return nil, false
}
// 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
}
}
// WithIndexCache sets a indexCache to use instead of a noopCache.
func WithIndexCache(cache indexcache.IndexCache) BucketStoreOption {
return func(s *BucketStore) {
s.indexCache = cache
}
}
// WithQueryGate sets a queryGate to use instead of a gate.NewNoop().
func WithQueryGate(queryGate gate.Gate) BucketStoreOption {
return func(s *BucketStore) {
s.queryGate = queryGate
}
}
// WithLazyLoadingGate sets a lazyLoadingGate to use instead of a gate.NewNoop().
func WithLazyLoadingGate(lazyLoadingGate gate.Gate) BucketStoreOption {
return func(s *BucketStore) {
s.lazyLoadingGate = lazyLoadingGate
}
}
// 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(
userID string,
bkt objstore.InstrumentedBucketReader,
fetcher block.MetadataFetcher,
dir string,
bucketStoreConfig tsdb.BucketStoreConfig,
postingsStrategy postingsSelectionStrategy,
chunksLimiterFactory ChunksLimiterFactory,
seriesLimiterFactory SeriesLimiterFactory,
partitioners blockPartitioners,
seriesHashCache *hashcache.SeriesHashCache,
metrics *BucketStoreMetrics,
options ...BucketStoreOption,
) (*BucketStore, error) {
s := &BucketStore{
logger: log.NewNopLogger(),
bkt: bkt,
fetcher: fetcher,
dir: dir,
indexCache: noopCache{},
blocks: map[ulid.ULID]*bucketBlock{},
blockSet: newBucketBlockSet(),
blockSyncConcurrency: bucketStoreConfig.BlockSyncConcurrency,
queryGate: gate.NewNoop(),
lazyLoadingGate: gate.NewNoop(),
chunksLimiterFactory: chunksLimiterFactory,
seriesLimiterFactory: seriesLimiterFactory,
partitioners: partitioners,
postingOffsetsInMemSampling: bucketStoreConfig.PostingOffsetsInMemSampling,
indexHeaderCfg: bucketStoreConfig.IndexHeader,
seriesHashCache: seriesHashCache,
metrics: metrics,
userID: userID,
maxSeriesPerBatch: bucketStoreConfig.StreamingBatchSize,
postingsStrategy: postingsStrategy,
}
for _, option := range options {
option(s)
}
lazyLoadedSnapshotConfig := indexheader.LazyLoadedHeadersSnapshotConfig{
Path: dir,
UserID: userID,
}
// Depend on the options
s.indexReaderPool = indexheader.NewReaderPool(s.logger, bucketStoreConfig.IndexHeader, s.lazyLoadingGate, metrics.indexHeaderReaderMetrics, lazyLoadedSnapshotConfig)
if err := os.MkdirAll(dir, 0750); err != nil {
return nil, errors.Wrap(err, "create dir")
}
return s, nil
}
// RemoveBlocksAndClose remove all blocks from local disk and releases all resources associated with the BucketStore.
func (s *BucketStore) RemoveBlocksAndClose() error {
err := s.removeAllBlocks()
// Release other resources even if it failed to close some blocks.
s.indexReaderPool.Close()
return err
}
// Stats returns statistics about the BucketStore instance.
func (s *BucketStore) Stats(durations []time.Duration) BucketStoreStats {
s.blocksMx.RLock()
defer s.blocksMx.RUnlock()
return buildStoreStats(durations, s.blocks)
}
func buildStoreStats(durations []time.Duration, blocks map[ulid.ULID]*bucketBlock) BucketStoreStats {
stats := BucketStoreStats{}
stats.BlocksLoaded = make(map[time.Duration]int)
if len(durations) != 0 {
for _, b := range blocks {
// Bucket each block into one of the possible block durations we're creating.
bucketed := bucketBlockDuration(durations, b.blockDuration())
stats.BlocksLoaded[bucketed]++
}
}
return stats
}
func bucketBlockDuration(buckets tsdb.DurationList, duration time.Duration) time.Duration {
for _, d := range buckets {
if duration <= d {
return d
}
}
return buckets[len(buckets)-1]
}
// 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 {
return s.syncBlocks(ctx, false)
}
func (s *BucketStore) syncBlocks(ctx context.Context, initialSync bool) 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 *block.Meta)
for i := 0; i < s.blockSyncConcurrency; i++ {
wg.Add(1)
go func() {
for meta := range blockc {
if err := s.addBlock(ctx, meta, initialSync); 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)
}
level.Info(s.logger).Log("msg", "dropped outdated block", "block", id)
}
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, true); err != nil {
return errors.Wrap(err, "sync block")
}
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.blocksMx.RLock()
defer s.blocksMx.RUnlock()
return s.blocks[id]
}
func (s *BucketStore) addBlock(ctx context.Context, meta *block.Meta, initialSync bool) (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.Error(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()
indexHeaderReader, err := s.indexReaderPool.NewBinaryReader(
ctx,
s.logger,
s.bkt,
s.dir,
meta.ULID,
s.postingOffsetsInMemSampling,
s.indexHeaderCfg,
initialSync,
)
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.userID,
log.With(s.logger, "block", meta.ULID),
s.metrics,
meta,
s.bkt,
dir,
s.indexCache,
indexHeaderReader,
s.partitioners,
)
if err != nil {
return errors.Wrap(err, "new bucket block")
}
defer func() {
if err != nil {
runutil.CloseWithErrCapture(&err, b, "index-header")
}
}()
s.blocksMx.Lock()
defer s.blocksMx.Unlock()
if err = s.blockSet.add(b); err != nil {
return errors.Wrap(err, "add block to set")
}
s.blocks[b.meta.ULID] = b
return nil
}
func (s *BucketStore) removeBlock(id ulid.ULID) (returnErr error) {
defer func() {
if returnErr != nil {
s.metrics.blockDropFailures.Inc()
}
}()
s.blocksMx.Lock()
b, ok := s.blocks[id]
if ok {
s.blockSet.remove(id)
delete(s.blocks, id)
}
s.blocksMx.Unlock()
if !ok {
return nil
}
// The block has already been removed from BucketStore, so we track it as removed
// even if releasing its resources could fail below.
s.metrics.blockDrops.Inc()
if err := b.Close(); err != nil {
return errors.Wrap(err, "close block")
}
if err := os.RemoveAll(b.dir); err != nil {
return errors.Wrap(err, "delete block")
}
return nil
}
func (s *BucketStore) removeAllBlocks() error {
// Build a list of blocks to remove.
s.blocksMx.Lock()
blockIDs := make([]ulid.ULID, 0, len(s.blocks))
for id := range s.blocks {
blockIDs = append(blockIDs, id)
}
s.blocksMx.Unlock()
// Close all blocks.
errs := multierror.New()
for _, id := range blockIDs {
if err := s.removeBlock(id); err != nil {
errs.Add(errors.Wrap(err, fmt.Sprintf("block: %s", id.String())))
}
}
return errs.Err()
}
// TimeRange returns the minimum and maximum timestamp of data available in the store.
func (s *BucketStore) TimeRange() (mint, maxt int64) {
s.blocksMx.RLock()
defer s.blocksMx.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
}
}
return mint, maxt
}
type seriesChunks struct {
lset labels.Labels
chks []storepb.AggrChunk
}
// Series implements the storegatewaypb.StoreGatewayServer interface.
func (s *BucketStore) Series(req *storepb.SeriesRequest, srv storegatewaypb.StoreGateway_SeriesServer) (err error) {
if req.SkipChunks {
// We don't do the streaming call if we are not requesting the chunks.
req.StreamingChunksBatchSize = 0
}
defer func() { err = mapSeriesError(err) }()
matchers, err := storepb.MatchersToPromMatchers(req.Matchers...)
if err != nil {
return status.Error(codes.InvalidArgument, err.Error())
}
// Check if matchers include the query shard selector.
shardSelector, matchers, err := sharding.RemoveShardFromMatchers(matchers)
if err != nil {
return status.Error(codes.InvalidArgument, errors.Wrap(err, "parse query sharding label").Error())
}
var (
spanLogger = spanlogger.FromContext(srv.Context(), s.logger)
ctx = srv.Context()
stats = newSafeQueryStats()
reqBlockMatchers []*labels.Matcher
)
defer s.recordSeriesCallResult(stats)
defer s.recordRequestAmbientTime(stats, time.Now())
if req.Hints != nil {
reqHints := &hintspb.SeriesRequestHints{}
if err := types.UnmarshalAny(req.Hints, reqHints); err != nil {
return status.Error(codes.InvalidArgument, errors.Wrap(err, "unmarshal series request hints").Error())
}
reqBlockMatchers, err = storepb.MatchersToPromMatchers(reqHints.BlockMatchers...)
if err != nil {
return status.Error(codes.InvalidArgument, errors.Wrap(err, "translate request hints labels matchers").Error())
}
}
logSeriesRequestToSpan(srv.Context(), s.logger, req.MinTime, req.MaxTime, matchers, reqBlockMatchers, shardSelector, req.StreamingChunksBatchSize)
blocks, indexReaders, chunkReaders := s.openBlocksForReading(ctx, req.SkipChunks, req.MinTime, req.MaxTime, reqBlockMatchers, stats)
// We must keep the readers open until all their data has been sent.
for _, r := range indexReaders {
defer runutil.CloseWithLogOnErr(s.logger, r, "close block index reader")
}
for _, r := range chunkReaders {
defer runutil.CloseWithLogOnErr(s.logger, r, "close block chunk reader")
}
var readers *bucketChunkReaders
if !req.SkipChunks {
readers = newChunkReaders(chunkReaders)
}
// Wait for the query gate only after opening blocks. Opening blocks is usually fast (~1ms),
// but sometimes it can take minutes if the block isn't loaded and there is a surge in queries for unloaded blocks.
done, err := s.limitConcurrentQueries(ctx, stats)
if err != nil {
return err
}
defer done()
var (
// If we are streaming the series labels and chunks separately, we don't need to fetch the postings
// twice. So we use these slices to re-use them. Each reuse[i] corresponds to a single block.
reuse []*reusedPostingsAndMatchers
resHints = &hintspb.SeriesResponseHints{}
)
for _, b := range blocks {
resHints.AddQueriedBlock(b.meta.ULID)
if b.meta.Compaction.Level == 1 && b.meta.Thanos.Source == block.ReceiveSource && !b.queried.Load() {
level.Debug(s.logger).Log("msg", "queried non-compacted block", "blockId", b.meta.ULID, "ooo", b.meta.Compaction.FromOutOfOrder())
}
b.queried.Store(true)
}
if err := s.sendHints(srv, resHints); err != nil {
return err
}
streamingSeriesCount := 0
if req.StreamingChunksBatchSize > 0 {
var (
seriesSet storepb.SeriesSet
seriesLoadStart = time.Now()
chunksLimiter = s.chunksLimiterFactory(s.metrics.queriesDropped.WithLabelValues("chunks"))
seriesLimiter = s.seriesLimiterFactory(s.metrics.queriesDropped.WithLabelValues("series"))
)
seriesSet, reuse, err = s.streamingSeriesForBlocks(ctx, req, blocks, indexReaders, shardSelector, matchers, chunksLimiter, seriesLimiter, stats)
if err != nil {
return err
}
streamingSeriesCount, err = s.sendStreamingSeriesLabelsAndStats(req, srv, stats, seriesSet)
if err != nil {
return err
}
spanLogger.DebugLog(
"msg", "sent streaming series",
"num_series", streamingSeriesCount,
"duration", time.Since(seriesLoadStart),
)
if streamingSeriesCount == 0 {
// There is no series to send chunks for.
return nil
}
}
// We create the limiter twice in the case of streaming so that we don't double count the series
// and hit the limit prematurely.
chunksLimiter := s.chunksLimiterFactory(s.metrics.queriesDropped.WithLabelValues("chunks"))
seriesLimiter := s.seriesLimiterFactory(s.metrics.queriesDropped.WithLabelValues("series"))
start := time.Now()
if req.StreamingChunksBatchSize > 0 {
var seriesChunkIt iterator[seriesChunksSet]
seriesChunkIt, err = s.streamingChunksSetForBlocks(ctx, req, blocks, indexReaders, readers, shardSelector, matchers, chunksLimiter, seriesLimiter, stats, reuse)
if err != nil {
return err
}
err = s.sendStreamingChunks(req, srv, seriesChunkIt, stats, streamingSeriesCount)
} else {
var seriesSet storepb.SeriesSet
seriesSet, err = s.nonStreamingSeriesSetForBlocks(ctx, req, blocks, indexReaders, readers, shardSelector, matchers, chunksLimiter, seriesLimiter, stats)
if err != nil {
return err
}
err = s.sendSeriesChunks(req, srv, seriesSet, stats)
}
if err != nil {
return
}
numSeries, numChunks := stats.seriesAndChunksCount()
debugMessage := "sent series"
if req.StreamingChunksBatchSize > 0 {
debugMessage = "sent streaming chunks"
}
spanLogger.DebugLog(
"msg", debugMessage,
"num_series", numSeries,
"num_chunks", numChunks,
"duration", time.Since(start),
)
if req.StreamingChunksBatchSize == 0 {
// Stats were not sent before, so send it now.
return s.sendStats(srv, stats)
}
return nil
}
func mapSeriesError(err error) error {
if err == nil {
return err
}
var stGwErr storeGatewayError
switch {
case errors.As(err, &stGwErr):
switch cause := stGwErr.errorCause(); cause {
case mimirpb.INSTANCE_LIMIT:
return globalerror.WrapErrorWithGRPCStatus(stGwErr, codes.Unavailable, &mimirpb.ErrorDetails{Cause: cause}).Err()
default:
return globalerror.WrapErrorWithGRPCStatus(stGwErr, codes.Internal, &mimirpb.ErrorDetails{Cause: cause}).Err()
}
default:
code := codes.Internal
if st, ok := grpcutil.ErrorToStatus(err); ok {
code = st.Code()
} else if errors.Is(err, context.Canceled) {
code = codes.Canceled
}
return status.Error(code, err.Error())
}
}
func (s *BucketStore) recordRequestAmbientTime(stats *safeQueryStats, requestStart time.Time) {
stats.update(func(stats *queryStats) {
stats.streamingSeriesAmbientTime += time.Since(requestStart)
})
}
func (s *BucketStore) limitConcurrentQueries(ctx context.Context, stats *safeQueryStats) (done func(), err error) {
span, spanCtx := opentracing.StartSpanFromContext(ctx, "store_query_gate_ismyturn")
defer span.Finish()
waitStart := time.Now()
err = s.queryGate.Start(spanCtx)
stats.update(func(stats *queryStats) {
stats.streamingSeriesConcurrencyLimitWaitDuration = time.Since(waitStart)
})
if err != nil {
return nil, errors.Wrapf(err, "failed to wait for turn")
}
return s.queryGate.Done, nil
}
// sendStreamingSeriesLabelsAndStats sends the labels of the streaming series.
// Since hints and stats need to be sent before the "end of stream" streaming series message,
// this function also sends the hints and the stats.
func (s *BucketStore) sendStreamingSeriesLabelsAndStats(
req *storepb.SeriesRequest,
srv storegatewaypb.StoreGateway_SeriesServer,
stats *safeQueryStats,
seriesSet storepb.SeriesSet,
) (numSeries int, err error) {
var (
encodeDuration = time.Duration(0)
sendDuration = time.Duration(0)
)
defer stats.update(func(stats *queryStats) {
stats.streamingSeriesEncodeResponseDuration += encodeDuration
stats.streamingSeriesSendResponseDuration += sendDuration
})
seriesBuffer := make([]*storepb.StreamingSeries, req.StreamingChunksBatchSize)
for i := range seriesBuffer {
seriesBuffer[i] = &storepb.StreamingSeries{}
}
seriesBatch := &storepb.StreamingSeriesBatch{
Series: seriesBuffer[:0],
}
// TODO: can we send this in parallel while we start fetching the chunks below?
for seriesSet.Next() {
numSeries++
var lset labels.Labels
// Although subsequent call to seriesSet.Next() may release the memory of this series object,
// it is safe to hold onto the labels because they are not released.
lset, _ = seriesSet.At()
// We are re-using the slice for every batch this way.
seriesBatch.Series = seriesBatch.Series[:len(seriesBatch.Series)+1]
seriesBatch.Series[len(seriesBatch.Series)-1].Labels = mimirpb.FromLabelsToLabelAdapters(lset)
if len(seriesBatch.Series) == int(req.StreamingChunksBatchSize) {
err := s.sendMessage("streaming series", srv, storepb.NewStreamingSeriesResponse(seriesBatch), &encodeDuration, &sendDuration)
if err != nil {
return 0, err
}
seriesBatch.Series = seriesBatch.Series[:0]
}
}
if seriesSet.Err() != nil {
return 0, errors.Wrap(seriesSet.Err(), "expand series set")
}
// We need to send stats before sending IsEndOfSeriesStream=true.
if err := s.sendStats(srv, stats); err != nil {
return 0, err
}
// Send any remaining series and signal that there are no more series.
seriesBatch.IsEndOfSeriesStream = true
err = s.sendMessage("streaming series", srv, storepb.NewStreamingSeriesResponse(seriesBatch), &encodeDuration, &sendDuration)
return numSeries, err
}
func (s *BucketStore) sendStreamingChunks(
req *storepb.SeriesRequest,
srv storegatewaypb.StoreGateway_SeriesServer,
it iterator[seriesChunksSet],
stats *safeQueryStats,
totalSeriesCount int,
) error {
var (
encodeDuration time.Duration
sendDuration time.Duration
seriesCount, chunksCount int
)
defer stats.update(func(stats *queryStats) {
stats.mergedSeriesCount += seriesCount
stats.mergedChunksCount += chunksCount
stats.streamingSeriesEncodeResponseDuration += encodeDuration
stats.streamingSeriesSendResponseDuration += sendDuration
})
var (
batchSizeBytes int
chunksBuffer = make([]*storepb.StreamingChunks, req.StreamingChunksBatchSize)
)
for i := range chunksBuffer {
chunksBuffer[i] = &storepb.StreamingChunks{}
}
haveSentEstimatedChunks := false
chunksBatch := &storepb.StreamingChunksBatch{Series: chunksBuffer[:0]}
for it.Next() {
set := it.At()
if len(set.series) == 0 {
set.release()
continue
}
// We send the estimate before any chunks.
if !haveSentEstimatedChunks {
seriesInBatch := len(set.series)
chunksInBatch := 0
for _, sc := range set.series {
chunksInBatch += len(sc.chks)
}
estimate := uint64(totalSeriesCount * chunksInBatch / seriesInBatch)
err := s.sendMessage("streaming chunks estimate", srv, storepb.NewStreamingChunksEstimate(estimate), &encodeDuration, &sendDuration)
if err != nil {
return err
}
haveSentEstimatedChunks = true
}
for _, sc := range set.series {
seriesCount++
chunksBatch.Series = chunksBatch.Series[:len(chunksBatch.Series)+1]
lastSeries := chunksBatch.Series[len(chunksBatch.Series)-1]
lastSeries.Chunks = sc.chks
lastSeries.SeriesIndex = uint64(seriesCount - 1)
batchSizeBytes += lastSeries.Size()
chunksCount += len(sc.chks)
s.metrics.chunkSizeBytes.Observe(float64(chunksSize(sc.chks)))
// We are not strictly required to be under targetQueryStreamBatchMessageSize.
// The aim is to not hit gRPC and TCP limits, hence some overage is ok.
if batchSizeBytes > targetQueryStreamBatchMessageSize || len(chunksBatch.Series) >= int(req.StreamingChunksBatchSize) {
err := s.sendMessage("streaming chunks", srv, storepb.NewStreamingChunksResponse(chunksBatch), &encodeDuration, &sendDuration)
if err != nil {
return err
}
chunksBatch.Series = chunksBatch.Series[:0]
batchSizeBytes = 0
}
}
if len(chunksBatch.Series) > 0 {
// Still some chunks left to send before we release the batch.
err := s.sendMessage("streaming chunks", srv, storepb.NewStreamingChunksResponse(chunksBatch), &encodeDuration, &sendDuration)
if err != nil {
return err
}
chunksBatch.Series = chunksBatch.Series[:0]
batchSizeBytes = 0
}
set.release()
}
if it.Err() != nil {
return it.Err()
}
// If we never sent an estimate (because there were no batches, or no batch had any series), send it now.
if !haveSentEstimatedChunks {
err := s.sendMessage("streaming chunks estimate", srv, storepb.NewStreamingChunksEstimate(0), &encodeDuration, &sendDuration)
if err != nil {
return err
}
}
return it.Err()
}
func (s *BucketStore) sendSeriesChunks(
req *storepb.SeriesRequest,
srv storegatewaypb.StoreGateway_SeriesServer,
seriesSet storepb.SeriesSet,
stats *safeQueryStats,
) error {
var (
encodeDuration time.Duration
sendDuration time.Duration
seriesCount, chunksCount int
)
defer stats.update(func(stats *queryStats) {
stats.mergedSeriesCount += seriesCount
stats.mergedChunksCount += chunksCount
stats.streamingSeriesEncodeResponseDuration += encodeDuration
stats.streamingSeriesSendResponseDuration += sendDuration
})
for seriesSet.Next() {
seriesCount++
// IMPORTANT: do not retain the memory returned by seriesSet.At() beyond this loop cycle
// because the subsequent call to seriesSet.Next() may release it. But it is safe to hold
// onto lset because the labels are not released.
lset, chks := seriesSet.At()
series := storepb.Series{
Labels: mimirpb.FromLabelsToLabelAdapters(lset),
}
if !req.SkipChunks {
series.Chunks = chks
chunksCount += len(chks)
s.metrics.chunkSizeBytes.Observe(float64(chunksSize(chks)))
}
err := s.sendMessage("series", srv, storepb.NewSeriesResponse(&series), &encodeDuration, &sendDuration)
if err != nil {
return err
}
}
if seriesSet.Err() != nil {
return errors.Wrap(seriesSet.Err(), "expand series set")
}
return nil
}
func (s *BucketStore) sendMessage(typ string, srv storegatewaypb.StoreGateway_SeriesServer, msg interface{}, encodeDuration, sendDuration *time.Duration) error {
// We encode it ourselves into a PreparedMsg in order to measure the time it takes.
encodeBegin := time.Now()
pmsg := &grpc.PreparedMsg{}
err := pmsg.Encode(srv, msg)
*encodeDuration += time.Since(encodeBegin)
if err != nil {
return status.Error(codes.Internal, errors.Wrapf(err, "encode %s response", typ).Error())
}
sendBegin := time.Now()
err = srv.SendMsg(pmsg)
*sendDuration += time.Since(sendBegin)
if err != nil {
return status.Error(codes.Unknown, errors.Wrapf(err, "send %s response", typ).Error())
}
return nil
}
func (s *BucketStore) sendHints(srv storegatewaypb.StoreGateway_SeriesServer, resHints *hintspb.SeriesResponseHints) error {
var anyHints *types.Any
var err error
if anyHints, err = types.MarshalAny(resHints); err != nil {
return status.Error(codes.Internal, errors.Wrap(err, "marshal series response hints").Error())
}
if err := srv.Send(storepb.NewHintsSeriesResponse(anyHints)); err != nil {
return status.Error(codes.Unknown, errors.Wrap(err, "send series response hints").Error())
}
return nil
}
func (s *BucketStore) sendStats(srv storegatewaypb.StoreGateway_SeriesServer, stats *safeQueryStats) error {
var encodeDuration, sendDuration time.Duration
defer stats.update(func(stats *queryStats) {
stats.streamingSeriesSendResponseDuration += sendDuration