-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathfetcher.go
1087 lines (925 loc) · 33.5 KB
/
fetcher.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 block
import (
"context"
"encoding/json"
"io"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/golang/groupcache/singleflight"
"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/model/relabel"
"github.com/thanos-io/objstore"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v2"
"github.com/thanos-io/thanos/pkg/block/metadata"
"github.com/thanos-io/thanos/pkg/errutil"
"github.com/thanos-io/thanos/pkg/extprom"
"github.com/thanos-io/thanos/pkg/model"
"github.com/thanos-io/thanos/pkg/runutil"
)
const FetcherConcurrency = 32
// BaseFetcherMetrics holds metrics tracked by the base fetcher. This struct and its fields are exported
// to allow depending projects (eg. Cortex) to implement their own custom metadata fetcher while tracking
// compatible metrics.
type BaseFetcherMetrics struct {
Syncs prometheus.Counter
}
// FetcherMetrics holds metrics tracked by the metadata fetcher. This struct and its fields are exported
// to allow depending projects (eg. Cortex) to implement their own custom metadata fetcher while tracking
// compatible metrics.
type FetcherMetrics struct {
Syncs prometheus.Counter
SyncFailures prometheus.Counter
SyncDuration prometheus.Observer
Synced *extprom.TxGaugeVec
Modified *extprom.TxGaugeVec
}
// Submit applies new values for metrics tracked by transaction GaugeVec.
func (s *FetcherMetrics) Submit() {
s.Synced.Submit()
s.Modified.Submit()
}
// ResetTx starts new transaction for metrics tracked by transaction GaugeVec.
func (s *FetcherMetrics) ResetTx() {
s.Synced.ResetTx()
s.Modified.ResetTx()
}
const (
FetcherSubSys = "blocks_meta"
CorruptedMeta = "corrupted-meta-json"
NoMeta = "no-meta-json"
LoadedMeta = "loaded"
FailedMeta = "failed"
// Synced label values.
labelExcludedMeta = "label-excluded"
timeExcludedMeta = "time-excluded"
tooFreshMeta = "too-fresh"
duplicateMeta = "duplicate"
// Blocks that are marked for deletion can be loaded as well. This is done to make sure that we load blocks that are meant to be deleted,
// but don't have a replacement block yet.
MarkedForDeletionMeta = "marked-for-deletion"
// MarkedForNoCompactionMeta is label for blocks which are loaded but also marked for no compaction. This label is also counted in `loaded` label metric.
MarkedForNoCompactionMeta = "marked-for-no-compact"
// MarkedForNoDownsampleMeta is label for blocks which are loaded but also marked for no downsample. This label is also counted in `loaded` label metric.
MarkedForNoDownsampleMeta = "marked-for-no-downsample"
// Modified label values.
replicaRemovedMeta = "replica-label-removed"
)
func NewBaseFetcherMetrics(reg prometheus.Registerer) *BaseFetcherMetrics {
var m BaseFetcherMetrics
m.Syncs = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Subsystem: FetcherSubSys,
Name: "base_syncs_total",
Help: "Total blocks metadata synchronization attempts by base Fetcher",
})
return &m
}
func NewFetcherMetrics(reg prometheus.Registerer, syncedExtraLabels, modifiedExtraLabels [][]string) *FetcherMetrics {
var m FetcherMetrics
m.Syncs = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Subsystem: FetcherSubSys,
Name: "syncs_total",
Help: "Total blocks metadata synchronization attempts",
})
m.SyncFailures = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Subsystem: FetcherSubSys,
Name: "sync_failures_total",
Help: "Total blocks metadata synchronization failures",
})
m.SyncDuration = promauto.With(reg).NewHistogram(prometheus.HistogramOpts{
Subsystem: FetcherSubSys,
Name: "sync_duration_seconds",
Help: "Duration of the blocks metadata synchronization in seconds",
Buckets: []float64{0.01, 1, 10, 100, 300, 600, 1000},
})
m.Synced = extprom.NewTxGaugeVec(
reg,
prometheus.GaugeOpts{
Subsystem: FetcherSubSys,
Name: "synced",
Help: "Number of block metadata synced",
},
[]string{"state"},
append(DefaultSyncedStateLabelValues(), syncedExtraLabels...)...,
)
m.Modified = extprom.NewTxGaugeVec(
reg,
prometheus.GaugeOpts{
Subsystem: FetcherSubSys,
Name: "modified",
Help: "Number of blocks whose metadata changed",
},
[]string{"modified"},
append(DefaultModifiedLabelValues(), modifiedExtraLabels...)...,
)
return &m
}
func DefaultSyncedStateLabelValues() [][]string {
return [][]string{
{CorruptedMeta},
{NoMeta},
{LoadedMeta},
{tooFreshMeta},
{FailedMeta},
{labelExcludedMeta},
{timeExcludedMeta},
{duplicateMeta},
{MarkedForDeletionMeta},
{MarkedForNoCompactionMeta},
}
}
func DefaultModifiedLabelValues() [][]string {
return [][]string{
{replicaRemovedMeta},
}
}
// Lister lists block IDs from a bucket.
type Lister interface {
// GetActiveAndPartialBlockIDs GetActiveBlocksIDs returning it via channel (streaming) and response.
// Active blocks are blocks which contain meta.json, while partial blocks are blocks without meta.json
GetActiveAndPartialBlockIDs(ctx context.Context, ch chan<- ulid.ULID) (partialBlocks map[ulid.ULID]bool, err error)
}
// RecursiveLister lists block IDs by recursively iterating through a bucket.
type RecursiveLister struct {
logger log.Logger
bkt objstore.InstrumentedBucketReader
}
func NewRecursiveLister(logger log.Logger, bkt objstore.InstrumentedBucketReader) *RecursiveLister {
return &RecursiveLister{
logger: logger,
bkt: bkt,
}
}
func (f *RecursiveLister) GetActiveAndPartialBlockIDs(ctx context.Context, ch chan<- ulid.ULID) (partialBlocks map[ulid.ULID]bool, err error) {
partialBlocks = make(map[ulid.ULID]bool)
err = f.bkt.Iter(ctx, "", func(name string) error {
parts := strings.Split(name, "/")
dir, file := parts[0], parts[len(parts)-1]
id, ok := IsBlockDir(dir)
if !ok {
return nil
}
if _, ok := partialBlocks[id]; !ok {
partialBlocks[id] = true
}
if !IsBlockMetaFile(file) {
return nil
}
partialBlocks[id] = false
select {
case <-ctx.Done():
return ctx.Err()
case ch <- id:
}
return nil
}, objstore.WithRecursiveIter())
return partialBlocks, err
}
// ConcurrentLister lists block IDs by doing a top level iteration of the bucket
// followed by one Exists call for each discovered block to detect partial blocks.
type ConcurrentLister struct {
logger log.Logger
bkt objstore.InstrumentedBucketReader
}
func NewConcurrentLister(logger log.Logger, bkt objstore.InstrumentedBucketReader) *ConcurrentLister {
return &ConcurrentLister{
logger: logger,
bkt: bkt,
}
}
func (f *ConcurrentLister) GetActiveAndPartialBlockIDs(ctx context.Context, ch chan<- ulid.ULID) (partialBlocks map[ulid.ULID]bool, err error) {
const concurrency = 64
partialBlocks = make(map[ulid.ULID]bool)
var (
metaChan = make(chan ulid.ULID, concurrency)
eg, gCtx = errgroup.WithContext(ctx)
mu sync.Mutex
)
for i := 0; i < concurrency; i++ {
eg.Go(func() error {
for uid := range metaChan {
// TODO(bwplotka): If that causes problems (obj store rate limits), add longer ttl to cached items.
// For 1y and 100 block sources this generates ~1.5-3k HEAD RPM. AWS handles 330k RPM per prefix.
// TODO(bwplotka): Consider filtering by consistency delay here (can't do until compactor healthyOverride work).
metaFile := path.Join(uid.String(), MetaFilename)
ok, err := f.bkt.Exists(gCtx, metaFile)
if err != nil {
return errors.Wrapf(err, "meta.json file exists: %v", uid)
}
if !ok {
mu.Lock()
partialBlocks[uid] = true
mu.Unlock()
continue
}
select {
case <-gCtx.Done():
return gCtx.Err()
case ch <- uid:
}
}
return nil
})
}
if err = f.bkt.Iter(ctx, "", func(name string) error {
id, ok := IsBlockDir(name)
if !ok {
return nil
}
select {
case <-gCtx.Done():
return gCtx.Err()
case metaChan <- id:
}
return nil
}); err != nil {
return nil, err
}
close(metaChan)
if err := eg.Wait(); err != nil {
return nil, err
}
return partialBlocks, nil
}
type MetadataFetcher interface {
Fetch(ctx context.Context) (metas map[ulid.ULID]*metadata.Meta, partial map[ulid.ULID]error, err error)
UpdateOnChange(func([]metadata.Meta, error))
}
// GaugeVec hides something like a Prometheus GaugeVec or an extprom.TxGaugeVec.
type GaugeVec interface {
WithLabelValues(lvs ...string) prometheus.Gauge
}
// Filter allows filtering or modifying metas from the provided map or returns error.
type MetadataFilter interface {
Filter(ctx context.Context, metas map[ulid.ULID]*metadata.Meta, synced GaugeVec, modified GaugeVec) error
}
// BaseFetcher is a struct that synchronizes filtered metadata of all block in the object storage with the local state.
// Go-routine safe.
type BaseFetcher struct {
logger log.Logger
concurrency int
bkt objstore.InstrumentedBucketReader
blockIDsLister Lister
// Optional local directory to cache meta.json files.
cacheDir string
syncs prometheus.Counter
g singleflight.Group
mtx sync.Mutex
cached map[ulid.ULID]*metadata.Meta
}
// NewBaseFetcher constructs BaseFetcher.
func NewBaseFetcher(logger log.Logger, concurrency int, bkt objstore.InstrumentedBucketReader, blockIDsFetcher Lister, dir string, reg prometheus.Registerer) (*BaseFetcher, error) {
return NewBaseFetcherWithMetrics(logger, concurrency, bkt, blockIDsFetcher, dir, NewBaseFetcherMetrics(reg))
}
// NewBaseFetcherWithMetrics constructs BaseFetcher.
func NewBaseFetcherWithMetrics(logger log.Logger, concurrency int, bkt objstore.InstrumentedBucketReader, blockIDsLister Lister, dir string, metrics *BaseFetcherMetrics) (*BaseFetcher, error) {
if logger == nil {
logger = log.NewNopLogger()
}
cacheDir := ""
if dir != "" {
cacheDir = filepath.Join(dir, "meta-syncer")
if err := os.MkdirAll(cacheDir, os.ModePerm); err != nil {
return nil, err
}
}
return &BaseFetcher{
logger: log.With(logger, "component", "block.BaseFetcher"),
concurrency: concurrency,
bkt: bkt,
blockIDsLister: blockIDsLister,
cacheDir: cacheDir,
cached: map[ulid.ULID]*metadata.Meta{},
syncs: metrics.Syncs,
}, nil
}
// NewRawMetaFetcher returns basic meta fetcher without proper handling for eventual consistent backends or partial uploads.
// NOTE: Not suitable to use in production.
func NewRawMetaFetcher(logger log.Logger, bkt objstore.InstrumentedBucketReader, blockIDsFetcher Lister) (*MetaFetcher, error) {
return NewMetaFetcher(logger, 1, bkt, blockIDsFetcher, "", nil, nil)
}
// NewMetaFetcher returns meta fetcher.
func NewMetaFetcher(logger log.Logger, concurrency int, bkt objstore.InstrumentedBucketReader, blockIDsFetcher Lister, dir string, reg prometheus.Registerer, filters []MetadataFilter) (*MetaFetcher, error) {
b, err := NewBaseFetcher(logger, concurrency, bkt, blockIDsFetcher, dir, reg)
if err != nil {
return nil, err
}
return b.NewMetaFetcher(reg, filters), nil
}
// NewMetaFetcherWithMetrics returns meta fetcher.
func NewMetaFetcherWithMetrics(logger log.Logger, concurrency int, bkt objstore.InstrumentedBucketReader, blockIDsFetcher Lister, dir string, baseFetcherMetrics *BaseFetcherMetrics, fetcherMetrics *FetcherMetrics, filters []MetadataFilter) (*MetaFetcher, error) {
b, err := NewBaseFetcherWithMetrics(logger, concurrency, bkt, blockIDsFetcher, dir, baseFetcherMetrics)
if err != nil {
return nil, err
}
return b.NewMetaFetcherWithMetrics(fetcherMetrics, filters), nil
}
// NewMetaFetcher transforms BaseFetcher into actually usable *MetaFetcher.
func (f *BaseFetcher) NewMetaFetcher(reg prometheus.Registerer, filters []MetadataFilter, logTags ...interface{}) *MetaFetcher {
return f.NewMetaFetcherWithMetrics(NewFetcherMetrics(reg, nil, nil), filters, logTags...)
}
// NewMetaFetcherWithMetrics transforms BaseFetcher into actually usable *MetaFetcher.
func (f *BaseFetcher) NewMetaFetcherWithMetrics(fetcherMetrics *FetcherMetrics, filters []MetadataFilter, logTags ...interface{}) *MetaFetcher {
return &MetaFetcher{metrics: fetcherMetrics, wrapped: f, filters: filters, logger: log.With(f.logger, logTags...)}
}
var (
ErrorSyncMetaNotFound = errors.New("meta.json not found")
ErrorSyncMetaCorrupted = errors.New("meta.json corrupted")
)
// loadMeta returns metadata from object storage or error.
// It returns `ErrorSyncMetaNotFound` and `ErrorSyncMetaCorrupted` sentinel errors in those cases.
func (f *BaseFetcher) loadMeta(ctx context.Context, id ulid.ULID) (*metadata.Meta, error) {
var (
metaFile = path.Join(id.String(), MetaFilename)
cachedBlockDir = filepath.Join(f.cacheDir, id.String())
)
if m, seen := f.cached[id]; seen {
return m, nil
}
// Best effort load from local dir.
if f.cacheDir != "" {
m, err := metadata.ReadFromDir(cachedBlockDir)
if err == nil {
return m, nil
}
if !errors.Is(err, os.ErrNotExist) {
level.Warn(f.logger).Log("msg", "best effort read of the local meta.json failed; removing cached block dir", "dir", cachedBlockDir, "err", err)
if err := os.RemoveAll(cachedBlockDir); err != nil {
level.Warn(f.logger).Log("msg", "best effort remove of cached dir failed; ignoring", "dir", cachedBlockDir, "err", err)
}
}
}
r, err := f.bkt.ReaderWithExpectedErrs(f.bkt.IsObjNotFoundErr).Get(ctx, metaFile)
if f.bkt.IsObjNotFoundErr(err) {
// Meta.json was deleted between bkt.Exists and here.
return nil, errors.Wrapf(ErrorSyncMetaNotFound, "%v", err)
}
if err != nil {
return nil, errors.Wrapf(err, "get meta file: %v", metaFile)
}
defer runutil.CloseWithLogOnErr(f.logger, r, "close bkt meta get")
metaContent, err := io.ReadAll(r)
if err != nil {
return nil, errors.Wrapf(err, "read meta file: %v", metaFile)
}
m := &metadata.Meta{}
if err := json.Unmarshal(metaContent, m); err != nil {
return nil, errors.Wrapf(ErrorSyncMetaCorrupted, "meta.json %v unmarshal: %v", metaFile, err)
}
if m.Version != metadata.TSDBVersion1 {
return nil, errors.Errorf("unexpected meta file: %s version: %d", metaFile, m.Version)
}
// Best effort cache in local dir.
if f.cacheDir != "" {
if err := os.MkdirAll(cachedBlockDir, os.ModePerm); err != nil {
level.Warn(f.logger).Log("msg", "best effort mkdir of the meta.json block dir failed; ignoring", "dir", cachedBlockDir, "err", err)
}
if err := m.WriteToDir(f.logger, cachedBlockDir); err != nil {
level.Warn(f.logger).Log("msg", "best effort save of the meta.json to local dir failed; ignoring", "dir", cachedBlockDir, "err", err)
}
}
return m, nil
}
type response struct {
metas map[ulid.ULID]*metadata.Meta
partial map[ulid.ULID]error
// If metaErr > 0 it means incomplete view, so some metas, failed to be loaded.
metaErrs errutil.MultiError
noMetas float64
corruptedMetas float64
}
func (f *BaseFetcher) fetchMetadata(ctx context.Context) (interface{}, error) {
f.syncs.Inc()
var (
resp = response{
metas: make(map[ulid.ULID]*metadata.Meta),
partial: make(map[ulid.ULID]error),
}
eg errgroup.Group
ch = make(chan ulid.ULID, f.concurrency)
mtx sync.Mutex
)
level.Debug(f.logger).Log("msg", "fetching meta data", "concurrency", f.concurrency)
for i := 0; i < f.concurrency; i++ {
eg.Go(func() error {
for id := range ch {
meta, err := f.loadMeta(ctx, id)
if err == nil {
mtx.Lock()
resp.metas[id] = meta
mtx.Unlock()
continue
}
switch errors.Cause(err) {
default:
mtx.Lock()
resp.metaErrs.Add(err)
mtx.Unlock()
continue
case ErrorSyncMetaNotFound:
mtx.Lock()
resp.noMetas++
mtx.Unlock()
case ErrorSyncMetaCorrupted:
mtx.Lock()
resp.corruptedMetas++
mtx.Unlock()
}
mtx.Lock()
resp.partial[id] = err
mtx.Unlock()
}
return nil
})
}
var partialBlocks map[ulid.ULID]bool
var err error
// Workers scheduled, distribute blocks.
eg.Go(func() error {
defer close(ch)
partialBlocks, err = f.blockIDsLister.GetActiveAndPartialBlockIDs(ctx, ch)
return err
})
if err := eg.Wait(); err != nil {
return nil, errors.Wrap(err, "BaseFetcher: iter bucket")
}
mtx.Lock()
for blockULID, isPartial := range partialBlocks {
if isPartial {
resp.partial[blockULID] = errors.Errorf("block %s has no meta file", blockULID)
resp.noMetas++
}
}
mtx.Unlock()
if len(resp.metaErrs) > 0 {
return resp, nil
}
// Only for complete view of blocks update the cache.
cached := make(map[ulid.ULID]*metadata.Meta, len(resp.metas))
for id, m := range resp.metas {
cached[id] = m
}
f.mtx.Lock()
f.cached = cached
f.mtx.Unlock()
// Best effort cleanup of disk-cached metas.
if f.cacheDir != "" {
fis, err := os.ReadDir(f.cacheDir)
names := make([]string, 0, len(fis))
for _, fi := range fis {
names = append(names, fi.Name())
}
if err != nil {
level.Warn(f.logger).Log("msg", "best effort remove of not needed cached dirs failed; ignoring", "err", err)
} else {
for _, n := range names {
id, ok := IsBlockDir(n)
if !ok {
continue
}
if _, ok := resp.metas[id]; ok {
continue
}
cachedBlockDir := filepath.Join(f.cacheDir, id.String())
// No such block loaded, remove the local dir.
if err := os.RemoveAll(cachedBlockDir); err != nil {
level.Warn(f.logger).Log("msg", "best effort remove of not needed cached dir failed; ignoring", "dir", cachedBlockDir, "err", err)
}
}
}
}
return resp, nil
}
func (f *BaseFetcher) fetch(ctx context.Context, metrics *FetcherMetrics, filters []MetadataFilter) (_ map[ulid.ULID]*metadata.Meta, _ map[ulid.ULID]error, err error) {
start := time.Now()
defer func() {
metrics.SyncDuration.Observe(time.Since(start).Seconds())
if err != nil {
metrics.SyncFailures.Inc()
}
}()
// Run this in thread safe run group.
// TODO(bwplotka): Consider custom singleflight with ttl.
v, err := f.g.Do("", func() (i interface{}, err error) {
// NOTE: First go routine context will go through.
return f.fetchMetadata(ctx)
})
if err != nil {
return nil, nil, err
}
resp := v.(response)
// Copy as same response might be reused by different goroutines.
metas := make(map[ulid.ULID]*metadata.Meta, len(resp.metas))
for id, m := range resp.metas {
metas[id] = m
}
metrics.Synced.WithLabelValues(FailedMeta).Set(float64(len(resp.metaErrs)))
metrics.Synced.WithLabelValues(NoMeta).Set(resp.noMetas)
metrics.Synced.WithLabelValues(CorruptedMeta).Set(resp.corruptedMetas)
for _, filter := range filters {
// NOTE: filter can update synced metric accordingly to the reason of the exclude.
if err := filter.Filter(ctx, metas, metrics.Synced, metrics.Modified); err != nil {
return nil, nil, errors.Wrap(err, "filter metas")
}
}
metrics.Synced.WithLabelValues(LoadedMeta).Set(float64(len(metas)))
if len(resp.metaErrs) > 0 {
return metas, resp.partial, errors.Wrap(resp.metaErrs.Err(), "incomplete view")
}
level.Info(f.logger).Log("msg", "successfully synchronized block metadata", "duration", time.Since(start).String(), "duration_ms", time.Since(start).Milliseconds(), "cached", f.countCached(), "returned", len(metas), "partial", len(resp.partial))
return metas, resp.partial, nil
}
func (f *BaseFetcher) countCached() int {
f.mtx.Lock()
defer f.mtx.Unlock()
return len(f.cached)
}
type MetaFetcher struct {
wrapped *BaseFetcher
metrics *FetcherMetrics
filters []MetadataFilter
listener func([]metadata.Meta, error)
logger log.Logger
}
// Fetch returns all block metas as well as partial blocks (blocks without or with corrupted meta file) from the bucket.
// It's caller responsibility to not change the returned metadata files. Maps can be modified.
//
// Returned error indicates a failure in fetching metadata. Returned meta can be assumed as correct, with some blocks missing.
func (f *MetaFetcher) Fetch(ctx context.Context) (metas map[ulid.ULID]*metadata.Meta, partial map[ulid.ULID]error, err error) {
f.metrics.Syncs.Inc()
f.metrics.ResetTx()
metas, partial, err = f.wrapped.fetch(ctx, f.metrics, f.filters)
if f.listener != nil {
blocks := make([]metadata.Meta, 0, len(metas))
for _, meta := range metas {
blocks = append(blocks, *meta)
}
f.listener(blocks, err)
}
f.metrics.Submit()
return metas, partial, err
}
// UpdateOnChange allows to add listener that will be update on every change.
func (f *MetaFetcher) UpdateOnChange(listener func([]metadata.Meta, error)) {
f.listener = listener
}
var _ MetadataFilter = &TimePartitionMetaFilter{}
// TimePartitionMetaFilter is a BaseFetcher filter that filters out blocks that are outside of specified time range.
// Not go-routine safe.
type TimePartitionMetaFilter struct {
minTime, maxTime model.TimeOrDurationValue
}
// NewTimePartitionMetaFilter creates TimePartitionMetaFilter.
func NewTimePartitionMetaFilter(MinTime, MaxTime model.TimeOrDurationValue) *TimePartitionMetaFilter {
return &TimePartitionMetaFilter{minTime: MinTime, maxTime: MaxTime}
}
// Filter filters out blocks that are outside of specified time range.
func (f *TimePartitionMetaFilter) Filter(_ context.Context, metas map[ulid.ULID]*metadata.Meta, synced GaugeVec, modified GaugeVec) error {
for id, m := range metas {
if m.MaxTime >= f.minTime.PrometheusTimestamp() && m.MinTime <= f.maxTime.PrometheusTimestamp() {
continue
}
synced.WithLabelValues(timeExcludedMeta).Inc()
delete(metas, id)
}
return nil
}
var _ MetadataFilter = &LabelShardedMetaFilter{}
// LabelShardedMetaFilter represents struct that allows sharding.
// Not go-routine safe.
type LabelShardedMetaFilter struct {
relabelConfig []*relabel.Config
}
// NewLabelShardedMetaFilter creates LabelShardedMetaFilter.
func NewLabelShardedMetaFilter(relabelConfig []*relabel.Config) *LabelShardedMetaFilter {
return &LabelShardedMetaFilter{relabelConfig: relabelConfig}
}
// Special label that will have an ULID of the meta.json being referenced to.
const BlockIDLabel = "__block_id"
// Filter filters out blocks that have no labels after relabelling of each block external (Thanos) labels.
func (f *LabelShardedMetaFilter) Filter(_ context.Context, metas map[ulid.ULID]*metadata.Meta, synced GaugeVec, modified GaugeVec) error {
var b labels.Builder
for id, m := range metas {
b.Reset(labels.EmptyLabels())
b.Set(BlockIDLabel, id.String())
for k, v := range m.Thanos.Labels {
b.Set(k, v)
}
if processedLabels, _ := relabel.Process(b.Labels(), f.relabelConfig...); processedLabels.IsEmpty() {
synced.WithLabelValues(labelExcludedMeta).Inc()
delete(metas, id)
}
}
return nil
}
var _ MetadataFilter = &DefaultDeduplicateFilter{}
type DeduplicateFilter interface {
DuplicateIDs() []ulid.ULID
}
// DefaultDeduplicateFilter is a BaseFetcher filter that filters out older blocks that have exactly the same data.
// Not go-routine safe.
type DefaultDeduplicateFilter struct {
duplicateIDs []ulid.ULID
concurrency int
mu sync.Mutex
}
// NewDeduplicateFilter creates DefaultDeduplicateFilter.
func NewDeduplicateFilter(concurrency int) *DefaultDeduplicateFilter {
return &DefaultDeduplicateFilter{concurrency: concurrency}
}
// Filter filters out duplicate blocks that can be formed
// from two or more overlapping blocks that fully submatches the source blocks of the older blocks.
func (f *DefaultDeduplicateFilter) Filter(_ context.Context, metas map[ulid.ULID]*metadata.Meta, synced GaugeVec, modified GaugeVec) error {
f.duplicateIDs = f.duplicateIDs[:0]
var wg sync.WaitGroup
var groupChan = make(chan []*metadata.Meta)
// Start up workers to deduplicate workgroups when they're ready.
for i := 0; i < f.concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for group := range groupChan {
f.filterGroup(group, metas, synced)
}
}()
}
// We need only look within a compaction group for duplicates, so splitting by group key gives us parallelizable streams.
metasByCompactionGroup := make(map[string][]*metadata.Meta)
for _, meta := range metas {
groupKey := meta.Thanos.GroupKey()
metasByCompactionGroup[groupKey] = append(metasByCompactionGroup[groupKey], meta)
}
for _, group := range metasByCompactionGroup {
groupChan <- group
}
close(groupChan)
wg.Wait()
return nil
}
func (f *DefaultDeduplicateFilter) filterGroup(metaSlice []*metadata.Meta, metas map[ulid.ULID]*metadata.Meta, synced GaugeVec) {
sort.Slice(metaSlice, func(i, j int) bool {
ilen := len(metaSlice[i].Compaction.Sources)
jlen := len(metaSlice[j].Compaction.Sources)
if ilen == jlen {
return metaSlice[i].ULID.Compare(metaSlice[j].ULID) < 0
}
return ilen-jlen > 0
})
var coveringSet []*metadata.Meta
var duplicates []ulid.ULID
childLoop:
for _, child := range metaSlice {
childSources := child.Compaction.Sources
for _, parent := range coveringSet {
parentSources := parent.Compaction.Sources
// child's sources are present in parent's sources, filter it out.
if contains(parentSources, childSources) {
duplicates = append(duplicates, child.ULID)
continue childLoop
}
}
// Child's sources not covered by any member of coveringSet, add it to coveringSet.
coveringSet = append(coveringSet, child)
}
f.mu.Lock()
for _, duplicate := range duplicates {
if metas[duplicate] != nil {
f.duplicateIDs = append(f.duplicateIDs, duplicate)
}
synced.WithLabelValues(duplicateMeta).Inc()
delete(metas, duplicate)
}
f.mu.Unlock()
}
// DuplicateIDs returns slice of block ids that are filtered out by DefaultDeduplicateFilter.
func (f *DefaultDeduplicateFilter) DuplicateIDs() []ulid.ULID {
return f.duplicateIDs
}
func contains(s1, s2 []ulid.ULID) bool {
for _, a := range s2 {
found := false
for _, e := range s1 {
if a.Compare(e) == 0 {
found = true
break
}
}
if !found {
return false
}
}
return true
}
var _ MetadataFilter = &ReplicaLabelRemover{}
// ReplicaLabelRemover is a BaseFetcher filter that modifies external labels of existing blocks, it removes given replica labels from the metadata of blocks that have it.
type ReplicaLabelRemover struct {
logger log.Logger
replicaLabels []string
}
// NewReplicaLabelRemover creates a ReplicaLabelRemover.
func NewReplicaLabelRemover(logger log.Logger, replicaLabels []string) *ReplicaLabelRemover {
return &ReplicaLabelRemover{logger: logger, replicaLabels: replicaLabels}
}
// Filter modifies external labels of existing blocks, it removes given replica labels from the metadata of blocks that have it.
func (r *ReplicaLabelRemover) Filter(_ context.Context, metas map[ulid.ULID]*metadata.Meta, synced GaugeVec, modified GaugeVec) error {
if len(r.replicaLabels) == 0 {
return nil
}
countReplicaLabelRemoved := make(map[string]int, len(metas))
for u, meta := range metas {
l := make(map[string]string)
for n, v := range meta.Thanos.Labels {
l[n] = v
}
for _, replicaLabel := range r.replicaLabels {
if _, exists := l[replicaLabel]; exists {
delete(l, replicaLabel)
countReplicaLabelRemoved[replicaLabel] += 1
modified.WithLabelValues(replicaRemovedMeta).Inc()
}
}
if len(l) == 0 {
level.Warn(r.logger).Log("msg", "block has no labels left, creating one", r.replicaLabels[0], "deduped")
l[r.replicaLabels[0]] = "deduped"
}
nm := *meta
nm.Thanos.Labels = l
metas[u] = &nm
}
for replicaLabelRemoved, count := range countReplicaLabelRemoved {
level.Debug(r.logger).Log("msg", "removed replica label", "label", replicaLabelRemoved, "count", count)
}
return nil
}
// ConsistencyDelayMetaFilter is a BaseFetcher filter that filters out blocks that are created before a specified consistency delay.
// Not go-routine safe.
type ConsistencyDelayMetaFilter struct {
logger log.Logger
consistencyDelay time.Duration
}
// NewConsistencyDelayMetaFilter creates ConsistencyDelayMetaFilter.
func NewConsistencyDelayMetaFilter(logger log.Logger, consistencyDelay time.Duration, reg prometheus.Registerer) *ConsistencyDelayMetaFilter {
_ = promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{
Name: "consistency_delay_seconds",
Help: "Configured consistency delay in seconds.",
}, func() float64 {
return consistencyDelay.Seconds()
})
return NewConsistencyDelayMetaFilterWithoutMetrics(logger, consistencyDelay)
}
// NewConsistencyDelayMetaFilterWithoutMetrics creates ConsistencyDelayMetaFilter.
func NewConsistencyDelayMetaFilterWithoutMetrics(logger log.Logger, consistencyDelay time.Duration) *ConsistencyDelayMetaFilter {
if logger == nil {
logger = log.NewNopLogger()
}
return &ConsistencyDelayMetaFilter{
logger: logger,
consistencyDelay: consistencyDelay,
}
}
// Filter filters out blocks that filters blocks that have are created before a specified consistency delay.
func (f *ConsistencyDelayMetaFilter) Filter(_ context.Context, metas map[ulid.ULID]*metadata.Meta, synced GaugeVec, modified GaugeVec) error {
for id, meta := range metas {
// TODO(khyatisoneji): Remove the checks about Thanos Source
// by implementing delete delay to fetch metas.
// TODO(bwplotka): Check consistency delay based on file upload / modification time instead of ULID.
if ulid.Now()-id.Time() < uint64(f.consistencyDelay/time.Millisecond) &&
meta.Thanos.Source != metadata.BucketRepairSource &&
meta.Thanos.Source != metadata.CompactorSource &&
meta.Thanos.Source != metadata.CompactorRepairSource {
level.Debug(f.logger).Log("msg", "block is too fresh for now", "block", id)
synced.WithLabelValues(tooFreshMeta).Inc()
delete(metas, id)
}
}
return nil
}
// IgnoreDeletionMarkFilter is a filter that filters out the blocks that are marked for deletion after a given delay.
// The delay duration is to make sure that the replacement block can be fetched before we filter out the old block.
// Delay is not considered when computing DeletionMarkBlocks map.
// Not go-routine safe.
type IgnoreDeletionMarkFilter struct {
logger log.Logger
delay time.Duration
concurrency int
bkt objstore.InstrumentedBucketReader
mtx sync.Mutex
deletionMarkMap map[ulid.ULID]*metadata.DeletionMark
}
// NewIgnoreDeletionMarkFilter creates IgnoreDeletionMarkFilter.
func NewIgnoreDeletionMarkFilter(logger log.Logger, bkt objstore.InstrumentedBucketReader, delay time.Duration, concurrency int) *IgnoreDeletionMarkFilter {
return &IgnoreDeletionMarkFilter{
logger: logger,
bkt: bkt,
delay: delay,
concurrency: concurrency,
}
}
// DeletionMarkBlocks returns block ids that were marked for deletion.
func (f *IgnoreDeletionMarkFilter) DeletionMarkBlocks() map[ulid.ULID]*metadata.DeletionMark {
f.mtx.Lock()
defer f.mtx.Unlock()
deletionMarkMap := make(map[ulid.ULID]*metadata.DeletionMark, len(f.deletionMarkMap))
for id, meta := range f.deletionMarkMap {
deletionMarkMap[id] = meta
}
return deletionMarkMap
}
// Filter filters out blocks that are marked for deletion after a given delay.
// It also returns the blocks that can be deleted since they were uploaded delay duration before current time.
func (f *IgnoreDeletionMarkFilter) Filter(ctx context.Context, metas map[ulid.ULID]*metadata.Meta, synced GaugeVec, modified GaugeVec) error {
deletionMarkMap := make(map[ulid.ULID]*metadata.DeletionMark)
// Make a copy of block IDs to check, in order to avoid concurrency issues
// between the scheduler and workers.
blockIDs := make([]ulid.ULID, 0, len(metas))
for id := range metas {
blockIDs = append(blockIDs, id)
}
var (