-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
compact.go
1693 lines (1484 loc) · 58.1 KB
/
compact.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 compact
import (
"context"
"fmt"
"math"
"os"
"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/opentracing/opentracing-go"
"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/tsdb"
"github.com/thanos-io/objstore"
"golang.org/x/sync/errgroup"
"github.com/thanos-io/thanos/pkg/block"
"github.com/thanos-io/thanos/pkg/block/metadata"
"github.com/thanos-io/thanos/pkg/compact/downsample"
"github.com/thanos-io/thanos/pkg/errutil"
"github.com/thanos-io/thanos/pkg/runutil"
"github.com/thanos-io/thanos/pkg/tracing"
)
type ResolutionLevel int64
const (
ResolutionLevelRaw = ResolutionLevel(downsample.ResLevel0)
ResolutionLevel5m = ResolutionLevel(downsample.ResLevel1)
ResolutionLevel1h = ResolutionLevel(downsample.ResLevel2)
)
const (
// DedupAlgorithmPenalty is the penalty based compactor series merge algorithm.
// This is the same as the online deduplication of querier except counter reset handling.
DedupAlgorithmPenalty = "penalty"
)
// Syncer synchronizes block metas from a bucket into a local directory.
// It sorts them into compaction groups based on equal label sets.
type Syncer struct {
logger log.Logger
bkt objstore.Bucket
fetcher block.MetadataFetcher
mtx sync.Mutex
blocks map[ulid.ULID]*metadata.Meta
partial map[ulid.ULID]error
metrics *SyncerMetrics
duplicateBlocksFilter block.DeduplicateFilter
ignoreDeletionMarkFilter *block.IgnoreDeletionMarkFilter
syncMetasTimeout time.Duration
g singleflight.Group
}
// SyncerMetrics holds metrics tracked by the syncer. This struct and its fields are exported
// to allow depending projects (eg. Cortex) to implement their own custom syncer while tracking
// compatible metrics.
type SyncerMetrics struct {
GarbageCollectedBlocks prometheus.Counter
GarbageCollections prometheus.Counter
GarbageCollectionFailures prometheus.Counter
GarbageCollectionDuration prometheus.Observer
BlocksMarkedForDeletion prometheus.Counter
}
func NewSyncerMetrics(reg prometheus.Registerer, blocksMarkedForDeletion, garbageCollectedBlocks prometheus.Counter) *SyncerMetrics {
var m SyncerMetrics
m.GarbageCollectedBlocks = garbageCollectedBlocks
m.GarbageCollections = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_compact_garbage_collection_total",
Help: "Total number of garbage collection operations.",
})
m.GarbageCollectionFailures = promauto.With(reg).NewCounter(prometheus.CounterOpts{
Name: "thanos_compact_garbage_collection_failures_total",
Help: "Total number of failed garbage collection operations.",
})
m.GarbageCollectionDuration = promauto.With(reg).NewHistogram(prometheus.HistogramOpts{
Name: "thanos_compact_garbage_collection_duration_seconds",
Help: "Time it took to perform garbage collection iteration.",
Buckets: []float64{0.01, 0.1, 0.3, 0.6, 1, 3, 6, 9, 20, 30, 60, 90, 120, 240, 360, 720},
})
m.BlocksMarkedForDeletion = blocksMarkedForDeletion
return &m
}
// NewMetaSyncer returns a new Syncer for the given Bucket and directory.
// Blocks must be at least as old as the sync delay for being considered.
func NewMetaSyncer(logger log.Logger, reg prometheus.Registerer, bkt objstore.Bucket, fetcher block.MetadataFetcher, duplicateBlocksFilter block.DeduplicateFilter, ignoreDeletionMarkFilter *block.IgnoreDeletionMarkFilter, blocksMarkedForDeletion, garbageCollectedBlocks prometheus.Counter, syncMetasTimeout time.Duration) (*Syncer, error) {
return NewMetaSyncerWithMetrics(logger,
NewSyncerMetrics(reg, blocksMarkedForDeletion, garbageCollectedBlocks),
bkt,
fetcher,
duplicateBlocksFilter,
ignoreDeletionMarkFilter,
syncMetasTimeout,
)
}
func NewMetaSyncerWithMetrics(logger log.Logger, metrics *SyncerMetrics, bkt objstore.Bucket, fetcher block.MetadataFetcher, duplicateBlocksFilter block.DeduplicateFilter, ignoreDeletionMarkFilter *block.IgnoreDeletionMarkFilter, syncMetasTimeout time.Duration) (*Syncer, error) {
if logger == nil {
logger = log.NewNopLogger()
}
return &Syncer{
syncMetasTimeout: syncMetasTimeout,
logger: logger,
bkt: bkt,
fetcher: fetcher,
blocks: map[ulid.ULID]*metadata.Meta{},
metrics: metrics,
duplicateBlocksFilter: duplicateBlocksFilter,
ignoreDeletionMarkFilter: ignoreDeletionMarkFilter,
}, nil
}
// UntilNextDownsampling calculates how long it will take until the next downsampling operation.
// Returns an error if there will be no downsampling.
func UntilNextDownsampling(m *metadata.Meta) (time.Duration, error) {
timeRange := time.Duration((m.MaxTime - m.MinTime) * int64(time.Millisecond))
switch m.Thanos.Downsample.Resolution {
case downsample.ResLevel2:
return time.Duration(0), errors.New("no downsampling")
case downsample.ResLevel1:
return time.Duration(downsample.ResLevel2DownsampleRange*time.Millisecond) - timeRange, nil
case downsample.ResLevel0:
return time.Duration(downsample.ResLevel1DownsampleRange*time.Millisecond) - timeRange, nil
default:
panic(errors.Errorf("invalid resolution %v", m.Thanos.Downsample.Resolution))
}
}
// SyncMetas synchronizes local state of block metas with what we have in the bucket.
func (s *Syncer) SyncMetas(ctx context.Context) error {
var cancel func() = func() {}
if s.syncMetasTimeout > 0 {
ctx, cancel = context.WithTimeout(ctx, s.syncMetasTimeout)
}
defer cancel()
type metasContainer struct {
metas map[ulid.ULID]*metadata.Meta
partial map[ulid.ULID]error
}
container, err := s.g.Do("", func() (interface{}, error) {
metas, partial, err := s.fetcher.Fetch(ctx)
return metasContainer{metas, partial}, err
})
if err != nil {
return retry(err)
}
s.mtx.Lock()
s.blocks = container.(metasContainer).metas
s.partial = container.(metasContainer).partial
s.mtx.Unlock()
return nil
}
// Partial returns partial blocks since last sync.
func (s *Syncer) Partial() map[ulid.ULID]error {
s.mtx.Lock()
defer s.mtx.Unlock()
return s.partial
}
// Metas returns loaded metadata blocks since last sync.
func (s *Syncer) Metas() map[ulid.ULID]*metadata.Meta {
s.mtx.Lock()
defer s.mtx.Unlock()
metas := make(map[ulid.ULID]*metadata.Meta, len(s.blocks))
for k, v := range s.blocks {
metas[k] = v
}
return metas
}
// GarbageCollect marks blocks for deletion from bucket if their data is available as part of a
// block with a higher compaction level.
// Call to SyncMetas function is required to populate duplicateIDs in duplicateBlocksFilter.
func (s *Syncer) GarbageCollect(ctx context.Context) error {
begin := time.Now()
// Ignore filter exists before deduplicate filter.
deletionMarkMap := s.ignoreDeletionMarkFilter.DeletionMarkBlocks()
duplicateIDs := s.duplicateBlocksFilter.DuplicateIDs()
// GarbageIDs contains the duplicateIDs, since these blocks can be replaced with other blocks.
// We also remove ids present in deletionMarkMap since these blocks are already marked for deletion.
garbageIDs := []ulid.ULID{}
for _, id := range duplicateIDs {
if _, exists := deletionMarkMap[id]; exists {
continue
}
garbageIDs = append(garbageIDs, id)
}
for _, id := range garbageIDs {
if ctx.Err() != nil {
return ctx.Err()
}
// Spawn a new context so we always mark a block for deletion in full on shutdown.
delCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
level.Info(s.logger).Log("msg", "marking outdated block for deletion", "block", id)
err := block.MarkForDeletion(delCtx, s.logger, s.bkt, id, "outdated block", s.metrics.BlocksMarkedForDeletion)
cancel()
if err != nil {
s.metrics.GarbageCollectionFailures.Inc()
return retry(errors.Wrapf(err, "mark block %s for deletion", id))
}
// Immediately update our in-memory state so no further call to SyncMetas is needed
// after running garbage collection.
s.mtx.Lock()
delete(s.blocks, id)
s.mtx.Unlock()
s.metrics.GarbageCollectedBlocks.Inc()
}
s.metrics.GarbageCollections.Inc()
s.metrics.GarbageCollectionDuration.Observe(time.Since(begin).Seconds())
return nil
}
// Grouper is responsible to group all known blocks into sub groups which are safe to be
// compacted concurrently.
type Grouper interface {
// Groups returns the compaction groups for all blocks currently known to the syncer.
// It creates all groups from the scratch on every call.
Groups(blocks map[ulid.ULID]*metadata.Meta) (res []*Group, err error)
}
// DefaultGrouper is the Thanos built-in grouper. It groups blocks based on downsample
// resolution and block's labels.
type DefaultGrouper struct {
bkt objstore.Bucket
logger log.Logger
acceptMalformedIndex bool
enableVerticalCompaction bool
compactions *prometheus.CounterVec
compactionRunsStarted *prometheus.CounterVec
compactionRunsCompleted *prometheus.CounterVec
compactionFailures *prometheus.CounterVec
verticalCompactions *prometheus.CounterVec
garbageCollectedBlocks prometheus.Counter
blocksMarkedForDeletion prometheus.Counter
blocksMarkedForNoCompact prometheus.Counter
hashFunc metadata.HashFunc
blockFilesConcurrency int
compactBlocksFetchConcurrency int
}
// NewDefaultGrouper makes a new DefaultGrouper.
func NewDefaultGrouper(
logger log.Logger,
bkt objstore.Bucket,
acceptMalformedIndex bool,
enableVerticalCompaction bool,
reg prometheus.Registerer,
blocksMarkedForDeletion prometheus.Counter,
garbageCollectedBlocks prometheus.Counter,
blocksMarkedForNoCompact prometheus.Counter,
hashFunc metadata.HashFunc,
blockFilesConcurrency int,
compactBlocksFetchConcurrency int,
) *DefaultGrouper {
return &DefaultGrouper{
bkt: bkt,
logger: logger,
acceptMalformedIndex: acceptMalformedIndex,
enableVerticalCompaction: enableVerticalCompaction,
compactions: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_compact_group_compactions_total",
Help: "Total number of group compaction attempts that resulted in a new block.",
}, []string{"resolution"}),
compactionRunsStarted: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_compact_group_compaction_runs_started_total",
Help: "Total number of group compaction attempts.",
}, []string{"resolution"}),
compactionRunsCompleted: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_compact_group_compaction_runs_completed_total",
Help: "Total number of group completed compaction runs. This also includes compactor group runs that resulted with no compaction.",
}, []string{"resolution"}),
compactionFailures: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_compact_group_compactions_failures_total",
Help: "Total number of failed group compactions.",
}, []string{"resolution"}),
verticalCompactions: promauto.With(reg).NewCounterVec(prometheus.CounterOpts{
Name: "thanos_compact_group_vertical_compactions_total",
Help: "Total number of group compaction attempts that resulted in a new block based on overlapping blocks.",
}, []string{"resolution"}),
blocksMarkedForNoCompact: blocksMarkedForNoCompact,
garbageCollectedBlocks: garbageCollectedBlocks,
blocksMarkedForDeletion: blocksMarkedForDeletion,
hashFunc: hashFunc,
blockFilesConcurrency: blockFilesConcurrency,
compactBlocksFetchConcurrency: compactBlocksFetchConcurrency,
}
}
// NewDefaultGrouperWithMetrics makes a new DefaultGrouper.
func NewDefaultGrouperWithMetrics(
logger log.Logger,
bkt objstore.Bucket,
acceptMalformedIndex bool,
enableVerticalCompaction bool,
compactions *prometheus.CounterVec,
compactionRunsStarted *prometheus.CounterVec,
compactionRunsCompleted *prometheus.CounterVec,
compactionFailures *prometheus.CounterVec,
verticalCompactions *prometheus.CounterVec,
blocksMarkedForDeletion prometheus.Counter,
garbageCollectedBlocks prometheus.Counter,
blocksMarkedForNoCompact prometheus.Counter,
hashFunc metadata.HashFunc,
blockFilesConcurrency int,
compactBlocksFetchConcurrency int,
) *DefaultGrouper {
return &DefaultGrouper{
bkt: bkt,
logger: logger,
acceptMalformedIndex: acceptMalformedIndex,
enableVerticalCompaction: enableVerticalCompaction,
compactions: compactions,
compactionRunsStarted: compactionRunsStarted,
compactionRunsCompleted: compactionRunsCompleted,
compactionFailures: compactionFailures,
verticalCompactions: verticalCompactions,
blocksMarkedForNoCompact: blocksMarkedForNoCompact,
garbageCollectedBlocks: garbageCollectedBlocks,
blocksMarkedForDeletion: blocksMarkedForDeletion,
hashFunc: hashFunc,
blockFilesConcurrency: blockFilesConcurrency,
compactBlocksFetchConcurrency: compactBlocksFetchConcurrency,
}
}
// Groups returns the compaction groups for all blocks currently known to the syncer.
// It creates all groups from the scratch on every call.
func (g *DefaultGrouper) Groups(blocks map[ulid.ULID]*metadata.Meta) (res []*Group, err error) {
groups := map[string]*Group{}
for _, m := range blocks {
groupKey := m.Thanos.GroupKey()
group, ok := groups[groupKey]
if !ok {
lbls := labels.FromMap(m.Thanos.Labels)
resolutionLabel := m.Thanos.ResolutionString()
group, err = NewGroup(
log.With(g.logger, "group", fmt.Sprintf("%s@%v", resolutionLabel, lbls.String()), "groupKey", groupKey),
g.bkt,
groupKey,
lbls,
m.Thanos.Downsample.Resolution,
g.acceptMalformedIndex,
g.enableVerticalCompaction,
g.compactions.WithLabelValues(resolutionLabel),
g.compactionRunsStarted.WithLabelValues(resolutionLabel),
g.compactionRunsCompleted.WithLabelValues(resolutionLabel),
g.compactionFailures.WithLabelValues(resolutionLabel),
g.verticalCompactions.WithLabelValues(resolutionLabel),
g.garbageCollectedBlocks,
g.blocksMarkedForDeletion,
g.blocksMarkedForNoCompact,
g.hashFunc,
g.blockFilesConcurrency,
g.compactBlocksFetchConcurrency,
)
if err != nil {
return nil, errors.Wrap(err, "create compaction group")
}
groups[groupKey] = group
res = append(res, group)
}
if err := group.AppendMeta(m); err != nil {
return nil, errors.Wrap(err, "add compaction group")
}
}
sort.Slice(res, func(i, j int) bool {
return res[i].Key() < res[j].Key()
})
return res, nil
}
// Group captures a set of blocks that have the same origin labels and downsampling resolution.
// Those blocks generally contain the same series and can thus efficiently be compacted.
type Group struct {
logger log.Logger
bkt objstore.Bucket
key string
labels labels.Labels
resolution int64
mtx sync.Mutex
metasByMinTime []*metadata.Meta
acceptMalformedIndex bool
enableVerticalCompaction bool
compactions prometheus.Counter
compactionRunsStarted prometheus.Counter
compactionRunsCompleted prometheus.Counter
compactionFailures prometheus.Counter
verticalCompactions prometheus.Counter
groupGarbageCollectedBlocks prometheus.Counter
blocksMarkedForDeletion prometheus.Counter
blocksMarkedForNoCompact prometheus.Counter
hashFunc metadata.HashFunc
blockFilesConcurrency int
compactBlocksFetchConcurrency int
extensions any
}
// NewGroup returns a new compaction group.
func NewGroup(
logger log.Logger,
bkt objstore.Bucket,
key string,
lset labels.Labels,
resolution int64,
acceptMalformedIndex bool,
enableVerticalCompaction bool,
compactions prometheus.Counter,
compactionRunsStarted prometheus.Counter,
compactionRunsCompleted prometheus.Counter,
compactionFailures prometheus.Counter,
verticalCompactions prometheus.Counter,
groupGarbageCollectedBlocks prometheus.Counter,
blocksMarkedForDeletion prometheus.Counter,
blocksMarkedForNoCompact prometheus.Counter,
hashFunc metadata.HashFunc,
blockFilesConcurrency int,
compactBlocksFetchConcurrency int,
) (*Group, error) {
if logger == nil {
logger = log.NewNopLogger()
}
if blockFilesConcurrency <= 0 {
return nil, errors.Errorf("invalid concurrency level (%d), blockFilesConcurrency level must be > 0", blockFilesConcurrency)
}
g := &Group{
logger: logger,
bkt: bkt,
key: key,
labels: lset,
resolution: resolution,
acceptMalformedIndex: acceptMalformedIndex,
enableVerticalCompaction: enableVerticalCompaction,
compactions: compactions,
compactionRunsStarted: compactionRunsStarted,
compactionRunsCompleted: compactionRunsCompleted,
compactionFailures: compactionFailures,
verticalCompactions: verticalCompactions,
groupGarbageCollectedBlocks: groupGarbageCollectedBlocks,
blocksMarkedForDeletion: blocksMarkedForDeletion,
blocksMarkedForNoCompact: blocksMarkedForNoCompact,
hashFunc: hashFunc,
blockFilesConcurrency: blockFilesConcurrency,
compactBlocksFetchConcurrency: compactBlocksFetchConcurrency,
}
return g, nil
}
// Key returns an identifier for the group.
func (cg *Group) Key() string {
return cg.key
}
func (cg *Group) deleteFromGroup(target map[ulid.ULID]struct{}) {
cg.mtx.Lock()
defer cg.mtx.Unlock()
var newGroupMeta []*metadata.Meta
for _, meta := range cg.metasByMinTime {
if _, found := target[meta.BlockMeta.ULID]; !found {
newGroupMeta = append(newGroupMeta, meta)
}
}
cg.metasByMinTime = newGroupMeta
}
// AppendMeta the block with the given meta to the group.
func (cg *Group) AppendMeta(meta *metadata.Meta) error {
cg.mtx.Lock()
defer cg.mtx.Unlock()
if !labels.Equal(cg.labels, labels.FromMap(meta.Thanos.Labels)) {
return errors.New("block and group labels do not match")
}
if cg.resolution != meta.Thanos.Downsample.Resolution {
return errors.New("block and group resolution do not match")
}
cg.metasByMinTime = append(cg.metasByMinTime, meta)
sort.Slice(cg.metasByMinTime, func(i, j int) bool {
return cg.metasByMinTime[i].MinTime < cg.metasByMinTime[j].MinTime
})
return nil
}
// IDs returns all sorted IDs of blocks in the group.
func (cg *Group) IDs() (ids []ulid.ULID) {
cg.mtx.Lock()
defer cg.mtx.Unlock()
for _, m := range cg.metasByMinTime {
ids = append(ids, m.ULID)
}
sort.Slice(ids, func(i, j int) bool {
return ids[i].Compare(ids[j]) < 0
})
return ids
}
// MinTime returns the min time across all group's blocks.
func (cg *Group) MinTime() int64 {
cg.mtx.Lock()
defer cg.mtx.Unlock()
if len(cg.metasByMinTime) > 0 {
return cg.metasByMinTime[0].MinTime
}
return math.MaxInt64
}
// MaxTime returns the max time across all group's blocks.
func (cg *Group) MaxTime() int64 {
cg.mtx.Lock()
defer cg.mtx.Unlock()
max := int64(math.MinInt64)
for _, m := range cg.metasByMinTime {
if m.MaxTime > max {
max = m.MaxTime
}
}
return max
}
// Labels returns the labels that all blocks in the group share.
func (cg *Group) Labels() labels.Labels {
return cg.labels
}
// Resolution returns the common downsampling resolution of blocks in the group.
func (cg *Group) Resolution() int64 {
return cg.resolution
}
func (cg *Group) Extensions() any {
return cg.extensions
}
func (cg *Group) SetExtensions(extensions any) {
cg.extensions = extensions
}
// CompactProgressMetrics contains Prometheus metrics related to compaction progress.
type CompactProgressMetrics struct {
NumberOfCompactionRuns prometheus.Gauge
NumberOfCompactionBlocks prometheus.Gauge
}
// ProgressCalculator calculates the progress of the compaction process for a given slice of Groups.
type ProgressCalculator interface {
ProgressCalculate(ctx context.Context, groups []*Group) error
}
// CompactionProgressCalculator contains a planner and ProgressMetrics, which are updated during the compaction simulation process.
type CompactionProgressCalculator struct {
planner Planner
*CompactProgressMetrics
}
// NewCompactProgressCalculator creates a new CompactionProgressCalculator.
func NewCompactionProgressCalculator(reg prometheus.Registerer, planner *tsdbBasedPlanner) *CompactionProgressCalculator {
return &CompactionProgressCalculator{
planner: planner,
CompactProgressMetrics: &CompactProgressMetrics{
NumberOfCompactionRuns: promauto.With(reg).NewGauge(prometheus.GaugeOpts{
Name: "thanos_compact_todo_compactions",
Help: "number of compactions to be done",
}),
NumberOfCompactionBlocks: promauto.With(reg).NewGauge(prometheus.GaugeOpts{
Name: "thanos_compact_todo_compaction_blocks",
Help: "number of blocks planned to be compacted",
}),
},
}
}
// ProgressCalculate calculates the number of blocks and compaction runs in the planning process of the given groups.
func (ps *CompactionProgressCalculator) ProgressCalculate(ctx context.Context, groups []*Group) error {
groupCompactions := make(map[string]int, len(groups))
groupBlocks := make(map[string]int, len(groups))
for len(groups) > 0 {
tmpGroups := make([]*Group, 0, len(groups))
for _, g := range groups {
if len(g.IDs()) == 1 {
continue
}
plan, err := ps.planner.Plan(ctx, g.metasByMinTime, nil, g.extensions)
if err != nil {
return errors.Wrapf(err, "could not plan")
}
if len(plan) == 0 {
continue
}
groupCompactions[g.key]++
toRemove := make(map[ulid.ULID]struct{}, len(plan))
metas := make([]*tsdb.BlockMeta, 0, len(plan))
for _, p := range plan {
metas = append(metas, &p.BlockMeta)
toRemove[p.BlockMeta.ULID] = struct{}{}
}
g.deleteFromGroup(toRemove)
groupBlocks[g.key] += len(plan)
if len(g.metasByMinTime) == 0 {
continue
}
newMeta := tsdb.CompactBlockMetas(ulid.MustNew(uint64(time.Now().Unix()), nil), metas...)
if err := g.AppendMeta(&metadata.Meta{BlockMeta: *newMeta, Thanos: metadata.Thanos{Downsample: metadata.ThanosDownsample{Resolution: g.Resolution()}, Labels: g.Labels().Map()}}); err != nil {
return errors.Wrapf(err, "append meta")
}
tmpGroups = append(tmpGroups, g)
}
groups = tmpGroups
}
ps.CompactProgressMetrics.NumberOfCompactionRuns.Set(0)
ps.CompactProgressMetrics.NumberOfCompactionBlocks.Set(0)
for key, iters := range groupCompactions {
ps.CompactProgressMetrics.NumberOfCompactionRuns.Add(float64(iters))
ps.CompactProgressMetrics.NumberOfCompactionBlocks.Add(float64(groupBlocks[key]))
}
return nil
}
// DownsampleProgressMetrics contains Prometheus metrics related to downsampling progress.
type DownsampleProgressMetrics struct {
NumberOfBlocksDownsampled prometheus.Gauge
}
// DownsampleProgressCalculator contains DownsampleMetrics, which are updated during the downsampling simulation process.
type DownsampleProgressCalculator struct {
*DownsampleProgressMetrics
}
// NewDownsampleProgressCalculator creates a new DownsampleProgressCalculator.
func NewDownsampleProgressCalculator(reg prometheus.Registerer) *DownsampleProgressCalculator {
return &DownsampleProgressCalculator{
DownsampleProgressMetrics: &DownsampleProgressMetrics{
NumberOfBlocksDownsampled: promauto.With(reg).NewGauge(prometheus.GaugeOpts{
Name: "thanos_compact_todo_downsample_blocks",
Help: "number of blocks to be downsampled",
}),
},
}
}
// ProgressCalculate calculates the number of blocks to be downsampled for the given groups.
func (ds *DownsampleProgressCalculator) ProgressCalculate(ctx context.Context, groups []*Group) error {
sources5m := map[ulid.ULID]struct{}{}
sources1h := map[ulid.ULID]struct{}{}
groupBlocks := make(map[string]int, len(groups))
for _, group := range groups {
for _, m := range group.metasByMinTime {
switch m.Thanos.Downsample.Resolution {
case downsample.ResLevel0:
continue
case downsample.ResLevel1:
for _, id := range m.Compaction.Sources {
sources5m[id] = struct{}{}
}
case downsample.ResLevel2:
for _, id := range m.Compaction.Sources {
sources1h[id] = struct{}{}
}
default:
return errors.Errorf("unexpected downsampling resolution %d", m.Thanos.Downsample.Resolution)
}
}
}
for _, group := range groups {
for _, m := range group.metasByMinTime {
switch m.Thanos.Downsample.Resolution {
case downsample.ResLevel0:
missing := false
for _, id := range m.Compaction.Sources {
if _, ok := sources5m[id]; !ok {
missing = true
break
}
}
if !missing {
continue
}
if m.MaxTime-m.MinTime < downsample.ResLevel1DownsampleRange {
continue
}
groupBlocks[group.key]++
case downsample.ResLevel1:
missing := false
for _, id := range m.Compaction.Sources {
if _, ok := sources1h[id]; !ok {
missing = true
break
}
}
if !missing {
continue
}
if m.MaxTime-m.MinTime < downsample.ResLevel2DownsampleRange {
continue
}
groupBlocks[group.key]++
}
}
}
ds.DownsampleProgressMetrics.NumberOfBlocksDownsampled.Set(0)
for _, blocks := range groupBlocks {
ds.DownsampleProgressMetrics.NumberOfBlocksDownsampled.Add(float64(blocks))
}
return nil
}
// RetentionProgressMetrics contains Prometheus metrics related to retention progress.
type RetentionProgressMetrics struct {
NumberOfBlocksToDelete prometheus.Gauge
}
// RetentionProgressCalculator contains RetentionProgressMetrics, which are updated during the retention simulation process.
type RetentionProgressCalculator struct {
*RetentionProgressMetrics
retentionByResolution map[ResolutionLevel]time.Duration
}
// NewRetentionProgressCalculator creates a new RetentionProgressCalculator.
func NewRetentionProgressCalculator(reg prometheus.Registerer, retentionByResolution map[ResolutionLevel]time.Duration) *RetentionProgressCalculator {
return &RetentionProgressCalculator{
retentionByResolution: retentionByResolution,
RetentionProgressMetrics: &RetentionProgressMetrics{
NumberOfBlocksToDelete: promauto.With(reg).NewGauge(prometheus.GaugeOpts{
Name: "thanos_compact_todo_deletion_blocks",
Help: "number of blocks that have crossed their retention period",
}),
},
}
}
// ProgressCalculate calculates the number of blocks to be retained for the given groups.
func (rs *RetentionProgressCalculator) ProgressCalculate(ctx context.Context, groups []*Group) error {
groupBlocks := make(map[string]int, len(groups))
for _, group := range groups {
for _, m := range group.metasByMinTime {
retentionDuration := rs.retentionByResolution[ResolutionLevel(m.Thanos.Downsample.Resolution)]
if retentionDuration.Seconds() == 0 {
continue
}
maxTime := time.Unix(m.MaxTime/1000, 0)
if time.Now().After(maxTime.Add(retentionDuration)) {
groupBlocks[group.key]++
}
}
}
rs.RetentionProgressMetrics.NumberOfBlocksToDelete.Set(0)
for _, blocks := range groupBlocks {
rs.RetentionProgressMetrics.NumberOfBlocksToDelete.Add(float64(blocks))
}
return nil
}
// Planner returns blocks to compact.
type Planner interface {
// Plan returns a list of blocks that should be compacted into single one.
// The blocks can be overlapping. The provided metadata has to be ordered by minTime.
Plan(ctx context.Context, metasByMinTime []*metadata.Meta, errChan chan error, extensions any) ([]*metadata.Meta, error)
}
type BlockDeletableChecker interface {
CanDelete(group *Group, blockID ulid.ULID) bool
}
type DefaultBlockDeletableChecker struct {
}
func (c DefaultBlockDeletableChecker) CanDelete(_ *Group, _ ulid.ULID) bool {
return true
}
type CompactionLifecycleCallback interface {
PreCompactionCallback(ctx context.Context, logger log.Logger, group *Group, toCompactBlocks []*metadata.Meta) error
PostCompactionCallback(ctx context.Context, logger log.Logger, group *Group, blockID ulid.ULID) error
GetBlockPopulator(ctx context.Context, logger log.Logger, group *Group) (tsdb.BlockPopulator, error)
}
type DefaultCompactionLifecycleCallback struct {
}
func (c DefaultCompactionLifecycleCallback) PreCompactionCallback(_ context.Context, logger log.Logger, cg *Group, toCompactBlocks []*metadata.Meta) error {
// Due to #183 we verify that none of the blocks in the plan have overlapping sources.
// This is one potential source of how we could end up with duplicated chunks.
uniqueSources := map[ulid.ULID]struct{}{}
for _, m := range toCompactBlocks {
for _, s := range m.Compaction.Sources {
if _, ok := uniqueSources[s]; ok {
if !cg.enableVerticalCompaction {
return halt(errors.Errorf("overlapping sources detected for plan %v", toCompactBlocks))
}
level.Warn(logger).Log("msg", "overlapping sources detected for plan", "duplicated_block", s, "to_compact_blocks", fmt.Sprintf("%v", toCompactBlocks))
}
uniqueSources[s] = struct{}{}
}
}
return nil
}
func (c DefaultCompactionLifecycleCallback) PostCompactionCallback(_ context.Context, _ log.Logger, _ *Group, _ ulid.ULID) error {
return nil
}
func (c DefaultCompactionLifecycleCallback) GetBlockPopulator(_ context.Context, _ log.Logger, _ *Group) (tsdb.BlockPopulator, error) {
return tsdb.DefaultBlockPopulator{}, nil
}
// Compactor provides compaction against an underlying storage of time series data.
// It is similar to tsdb.Compactor but only relevant methods are kept. Plan and Write are removed.
// TODO(bwplotka): Split the Planner from Compactor on upstream as well, so we can import it.
type Compactor interface {
// Compact runs compaction against the provided directories. Must
// only be called concurrently with results of Plan().
// Can optionally pass a list of already open blocks,
// to avoid having to reopen them.
// Prometheus always return one or no block. The interface allows returning more than one
// block for downstream users to experiment with compactor.
// When one resulting Block has 0 samples
// * No block is written.
// * The source dirs are marked Deletable.
// * Block is not included in the result.
Compact(dest string, dirs []string, open []*tsdb.Block) ([]ulid.ULID, error)
CompactWithBlockPopulator(dest string, dirs []string, open []*tsdb.Block, blockPopulator tsdb.BlockPopulator) ([]ulid.ULID, error)
}
// Compact plans and runs a single compaction against the group. The compacted result
// is uploaded into the bucket the blocks were retrieved from.
func (cg *Group) Compact(ctx context.Context, dir string, planner Planner, comp Compactor, blockDeletableChecker BlockDeletableChecker, compactionLifecycleCallback CompactionLifecycleCallback) (shouldRerun bool, compIDs []ulid.ULID, rerr error) {
cg.compactionRunsStarted.Inc()
subDir := filepath.Join(dir, cg.Key())
defer func() {
// Leave the compact directory for inspection if it is a halt error
// or if it is not then so that possibly we would not have to download everything again.
if rerr != nil {
return
}
if err := os.RemoveAll(subDir); err != nil {
level.Error(cg.logger).Log("msg", "failed to remove compaction group work directory", "path", subDir, "err", err)
}
}()
if err := os.MkdirAll(subDir, 0750); err != nil {
return false, nil, errors.Wrap(err, "create compaction group dir")
}
defer func() {
if p := recover(); p != nil {
var sb strings.Builder
cgIDs := cg.IDs()
for i, blid := range cgIDs {
_, _ = sb.WriteString(blid.String())
if i < len(cgIDs)-1 {
_, _ = sb.WriteString(",")
}
}
rerr = fmt.Errorf("panicked while compacting %s: %v", sb.String(), p)
}
}()
errChan := make(chan error, 1)
err := tracing.DoInSpanWithErr(ctx, "compaction_group", func(ctx context.Context) (err error) {
shouldRerun, compIDs, err = cg.compact(ctx, subDir, planner, comp, blockDeletableChecker, compactionLifecycleCallback, errChan)
return err
}, opentracing.Tags{"group.key": cg.Key()})
errChan <- err
close(errChan)
if err != nil {
cg.compactionFailures.Inc()
return false, nil, err
}
cg.compactionRunsCompleted.Inc()
return shouldRerun, compIDs, nil
}
// Issue347Error is a type wrapper for errors that should invoke repair process for broken block.
type Issue347Error struct {
err error
id ulid.ULID
}
func issue347Error(err error, brokenBlock ulid.ULID) Issue347Error {
return Issue347Error{err: err, id: brokenBlock}
}
func (e Issue347Error) Error() string {
return e.err.Error()
}
// IsIssue347Error returns true if the base error is a Issue347Error.
func IsIssue347Error(err error) bool {
_, ok := errors.Cause(err).(Issue347Error)
return ok
}
// OutOfOrderChunkError is a type wrapper for OOO chunk error from validating block index.
type OutOfOrderChunksError struct {
err error
id ulid.ULID
}
func (e OutOfOrderChunksError) Error() string {
return e.err.Error()
}
func outOfOrderChunkError(err error, brokenBlock ulid.ULID) OutOfOrderChunksError {
return OutOfOrderChunksError{err: err, id: brokenBlock}
}
// IsOutOfOrderChunkError returns true if the base error is a OutOfOrderChunkError.
func IsOutOfOrderChunkError(err error) bool {
_, ok := errors.Cause(err).(OutOfOrderChunksError)
return ok
}
// HaltError is a type wrapper for errors that should halt any further progress on compactions.
type HaltError struct {
err error
}
func halt(err error) HaltError {
return HaltError{err: err}
}
func (e HaltError) Error() string {
return e.err.Error()
}
func (e HaltError) Unwrap() error {
return errors.Cause(e.err)
}
// IsHaltError returns true if the base error is a HaltError.
// If a multierror is passed, any halt error will return true.
func IsHaltError(err error) bool {
if multiErr, ok := errors.Cause(err).(errutil.NonNilMultiRootError); ok {
for _, err := range multiErr {
if _, ok := errors.Cause(err).(HaltError); ok {
return true
}
}
return false
}