forked from thanos-io/thanos
/
bucket.go
1755 lines (1501 loc) · 48.5 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
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/improbable-eng/thanos/pkg/block"
"github.com/improbable-eng/thanos/pkg/block/metadata"
"github.com/improbable-eng/thanos/pkg/compact/downsample"
"github.com/improbable-eng/thanos/pkg/component"
"github.com/improbable-eng/thanos/pkg/objstore"
"github.com/improbable-eng/thanos/pkg/pool"
"github.com/improbable-eng/thanos/pkg/runutil"
"github.com/improbable-eng/thanos/pkg/store/storepb"
"github.com/improbable-eng/thanos/pkg/strutil"
"github.com/improbable-eng/thanos/pkg/tracing"
"github.com/oklog/run"
"github.com/oklog/ulid"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/tsdb/chunkenc"
"github.com/prometheus/tsdb/chunks"
"github.com/prometheus/tsdb/fileutil"
"github.com/prometheus/tsdb/index"
"github.com/prometheus/tsdb/labels"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
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
}
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.01, 0.05, 0.1, 0.25, 0.6, 1, 2, 3.5, 5, 7.5, 10, 15, 30, 60,
},
})
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.01, 0.05, 0.1, 0.25, 0.6, 1, 2, 3.5, 5, 7.5, 10, 15, 30, 60,
},
})
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,
},
})
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,
)
}
return &m
}
// 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
bucket objstore.BucketReader
dir string
indexCache *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
partitioner partitioner
}
// 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,
dir string,
indexCacheSizeBytes uint64,
maxChunkPoolBytes uint64,
debugLogging bool,
blockSyncConcurrency int,
) (*BucketStore, error) {
if logger == nil {
logger = log.NewNopLogger()
}
indexCache, err := newIndexCache(reg, indexCacheSizeBytes)
if err != nil {
return nil, errors.Wrap(err, "create index cache")
}
chunkPool, err := pool.NewBytesPool(2e5, 50e6, 2, maxChunkPoolBytes)
if err != nil {
return nil, errors.Wrap(err, "create chunk pool")
}
const maxGapSize = 512 * 1024
s := &BucketStore{
logger: logger,
bucket: bucket,
dir: dir,
indexCache: indexCache,
chunkPool: chunkPool,
blocks: map[ulid.ULID]*bucketBlock{},
blockSets: map[uint64]*bucketBlockSet{},
debugLogging: debugLogging,
blockSyncConcurrency: blockSyncConcurrency,
partitioner: gapBasedPartitioner{maxGapSize: maxGapSize},
}
s.metrics = newBucketStoreMetrics(reg)
if err := os.MkdirAll(dir, 0777); 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 {
if e := b.Close(); e != nil {
level.Warn(s.logger).Log("msg", "closing Bucket block failed", "err", err)
err = e
}
}
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 {
var wg sync.WaitGroup
blockc := make(chan ulid.ULID)
for i := 0; i < s.blockSyncConcurrency; i++ {
wg.Add(1)
go func() {
for id := range blockc {
if err := s.addBlock(ctx, id); err != nil {
level.Warn(s.logger).Log("msg", "loading block failed", "id", id, "err", err)
continue
}
}
wg.Done()
}()
}
allIDs := map[ulid.ULID]struct{}{}
err := s.bucket.Iter(ctx, "", func(name string) error {
// Strip trailing slash indicating a directory.
id, err := ulid.Parse(name[:len(name)-1])
if err != nil {
return nil
}
allIDs[id] = struct{}{}
if b := s.getBlock(id); b != nil {
return nil
}
select {
case <-ctx.Done():
case blockc <- id:
}
return nil
})
close(blockc)
wg.Wait()
if err != nil {
return errors.Wrap(err, "iter")
}
// Drop all blocks that are no longer present in the bucket.
for id := range s.blocks {
if _, ok := allIDs[id]; ok {
continue
}
if err := s.removeBlock(id); err != nil {
level.Warn(s.logger).Log("msg", "drop outdated block", "block", id, "err", err)
s.metrics.blockDropFailures.Inc()
}
s.metrics.blockDrops.Inc()
}
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) numBlocks() int {
s.mtx.RLock()
defer s.mtx.RUnlock()
return len(s.blocks)
}
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, id ulid.ULID) (err error) {
dir := filepath.Join(s.dir, id.String())
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)
}
}
}()
s.metrics.blockLoads.Inc()
b, err := newBucketBlock(
ctx,
log.With(s.logger, "block", id),
s.bucket,
id,
dir,
s.indexCache,
s.chunkPool,
s.partitioner,
)
if err != nil {
return errors.Wrap(err, "new bucket block")
}
s.mtx.Lock()
defer s.mtx.Unlock()
lset := labels.FromMap(b.meta.Thanos.Labels)
h := lset.Hash()
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
}
}
return mint, maxt
}
// Info implements the storepb.StoreServer interface.
func (s *BucketStore) Info(context.Context, *storepb.InfoRequest) (*storepb.InfoResponse, error) {
mint, maxt := s.TimeRange()
// Store nodes hold global data and thus have no labels.
return &storepb.InfoResponse{
StoreType: component.Store.ToProto(),
MinTime: mint,
MaxTime: maxt,
}, nil
}
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 (s *BucketStore) blockSeries(
ctx context.Context,
ulid ulid.ULID,
extLset map[string]string,
indexr *bucketIndexReader,
chunkr *bucketChunkReader,
matchers []labels.Matcher,
req *storepb.SeriesRequest,
) (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)),
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(); 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 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), "mint", mint, "maxt", maxt, "lset", lset.String(), "spans", strings.Join(parts, "\n"))
}
// Series implements the storepb.StoreServer interface.
// TODO(bwplotka): It buffers all chunks in memory and only then streams to client.
// 1. Either count chunk sizes and error out too big query.
// 2. Stream posting -> series -> chunk all together.
func (s *BucketStore) Series(req *storepb.SeriesRequest, srv storepb.Store_SeriesServer) error {
matchers, err := translateMatchers(req.Matchers)
if err != nil {
return status.Error(codes.InvalidArgument, err.Error())
}
var (
stats = &queryStats{}
g run.Group
res []storepb.SeriesSet
mtx sync.Mutex
)
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)
if s.debugLogging {
debugFoundBlockSetOverview(s.logger, req.MinTime, req.MaxTime, bs.labels, blocks)
}
for _, b := range blocks {
stats.blocksQueried++
b := b
ctx, cancel := context.WithCancel(srv.Context())
// 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.Add(func() error {
part, pstats, err := s.blockSeries(ctx,
b.meta.ULID,
b.meta.Thanos.Labels,
indexr,
chunkr,
blockMatchers,
req,
)
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
}, func(err error) {
if err != nil {
cancel()
}
})
}
}
s.mtx.RUnlock()
// Concurrently get data from all blocks.
{
span, _ := tracing.StartSpan(srv.Context(), "bucket_store_preload_all")
begin := time.Now()
err := g.Run()
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
series.Labels, series.Chunks = set.At()
stats.mergedSeriesCount++
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())
}
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", "series query processed",
"stats", fmt.Sprintf("%+v", stats))
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(context.Context, *storepb.LabelNamesRequest) (*storepb.LabelNamesResponse, error) {
return nil, status.Error(codes.Unimplemented, "not implemented")
}
// LabelValues implements the storepb.StoreServer interface.
func (s *BucketStore) LabelValues(ctx context.Context, req *storepb.LabelValuesRequest) (*storepb.LabelValuesResponse, 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)
// TODO(fabxc): only aggregate chunk metas first and add a subsequent fetch stage
// where we consolidate requests.
g.Go(func() error {
defer runutil.CloseWithLogOnErr(s.logger, indexr, "label values")
res := indexr.LabelValues(req.Label)
mtx.Lock()
sets = append(sets, res)
mtx.Unlock()
return nil
})
}
s.mtx.RUnlock()
if err := g.Wait(); err != nil {
return nil, status.Error(codes.Aborted, err.Error())
}
return &storepb.LabelValuesResponse{
Values: strutil.MergeSlices(sets...),
}, nil
}
// bucketBlockSet holds all blocks of an equal label set. It internally splits
// them up by downsampling resolution and allows querying
type bucketBlockSet struct {
labels labels.Labels
mtx sync.RWMutex
resolutions []int64 // available resolution, high to low
blocks [][]*bucketBlock // ordered buckets for the existing resolutions
}
// newBucketBlockSet initializes a new set with the known downsampling windows hard-configured.
// The set currently does not support arbitrary ranges.
func newBucketBlockSet(lset labels.Labels) *bucketBlockSet {
return &bucketBlockSet{
labels: lset,
resolutions: []int64{downsample.ResLevel2, downsample.ResLevel1, downsample.ResLevel0},
blocks: make([][]*bucketBlock, 3),
}
}
func (s *bucketBlockSet) add(b *bucketBlock) error {
if !s.labels.Equals(labels.FromMap(b.meta.Thanos.Labels)) {
return errors.New("block's label set does not match set")
}
s.mtx.Lock()
defer s.mtx.Unlock()
i := int64index(s.resolutions, b.meta.Thanos.Downsample.Resolution)
if i < 0 {
return errors.Errorf("unsupported downsampling resolution %d", b.meta.Thanos.Downsample.Resolution)
}
bs := append(s.blocks[i], b)
s.blocks[i] = bs
sort.Slice(bs, func(j, k int) bool {
if bs[j].meta.MinTime < bs[k].meta.MinTime {
return true
}
return false
})
return nil
}
func (s *bucketBlockSet) remove(id ulid.ULID) {
s.mtx.Lock()
defer s.mtx.Unlock()
for i, bs := range s.blocks {
for j, b := range bs {
if b.meta.ULID != id {
continue
}
s.blocks[i] = append(bs[:j], bs[j+1:]...)
return
}
}
}
func int64index(s []int64, x int64) int {
for i, v := range s {
if v == x {
return i
}
}
return -1
}
// getFor returns a time-ordered list of blocks that cover date between mint and maxt.
// Blocks with the lowest resolution possible but not lower than the given resolution are returned.
func (s *bucketBlockSet) getFor(mint, maxt, minResolution int64) (bs []*bucketBlock) {
if mint == maxt {
return nil
}
s.mtx.RLock()
defer s.mtx.RUnlock()
// Find first matching resolution.
i := 0
for ; i < len(s.resolutions) && s.resolutions[i] > minResolution; i++ {
}
// Base case, we fill the given interval with the closest resolution.
for _, b := range s.blocks[i] {
if b.meta.MaxTime <= mint {
continue
}
if b.meta.MinTime >= maxt {
break
}
bs = append(bs, b)
}
// Our current resolution might not cover all data, recursively fill the gaps at the start
// and end of [mint, maxt] with higher resolution blocks.
i++
// No higher resolution left, we are done.
if i >= len(s.resolutions) {
return bs
}
if len(bs) == 0 {
return s.getFor(mint, maxt, s.resolutions[i])
}
left := s.getFor(mint, bs[0].meta.MinTime, s.resolutions[i])
right := s.getFor(bs[len(bs)-1].meta.MaxTime, maxt, s.resolutions[i])
return append(left, append(bs, right...)...)
}
// labelMatchers verifies whether the block set matches the given matchers and returns a new
// set of matchers that is equivalent when querying data within the block.
func (s *bucketBlockSet) labelMatchers(matchers ...labels.Matcher) ([]labels.Matcher, bool) {
res := make([]labels.Matcher, 0, len(matchers))
for _, m := range matchers {
v := s.labels.Get(m.Name())
if v == "" {
res = append(res, m)
continue
}
if !m.Matches(v) {
return nil, false
}
}
return res, true
}
// bucketBlock represents a block that is located in a bucket. It holds intermediate
// state for the block on local disk.
type bucketBlock struct {
logger log.Logger
bucket objstore.BucketReader
meta *metadata.Meta
dir string
indexCache *indexCache
chunkPool *pool.BytesPool
indexVersion int
symbols map[uint32]string
lvals map[string][]string
postings map[labels.Label]index.Range
indexObj string
chunkObjs []string
pendingReaders sync.WaitGroup
partitioner partitioner
}
func newBucketBlock(
ctx context.Context,
logger log.Logger,
bkt objstore.BucketReader,
id ulid.ULID,
dir string,