|
| 1 | +package strategies |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "math" |
| 7 | + "sort" |
| 8 | + |
| 9 | + "github.com/dustin/go-humanize" |
| 10 | + "github.com/go-kit/log" |
| 11 | + "github.com/go-kit/log/level" |
| 12 | + "github.com/prometheus/common/model" |
| 13 | + "github.com/prometheus/prometheus/model/labels" |
| 14 | + |
| 15 | + "github.com/grafana/loki/v3/pkg/bloombuild/protos" |
| 16 | + iter "github.com/grafana/loki/v3/pkg/iter/v2" |
| 17 | + v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1" |
| 18 | + "github.com/grafana/loki/v3/pkg/storage/config" |
| 19 | + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/bloomshipper" |
| 20 | + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb" |
| 21 | + "github.com/grafana/loki/v3/pkg/storage/stores/shipper/indexshipper/tsdb/index" |
| 22 | +) |
| 23 | + |
| 24 | +type ChunkSizeStrategyLimits interface { |
| 25 | + BloomTaskTargetSeriesChunksSizeBytes(tenantID string) uint64 |
| 26 | +} |
| 27 | + |
| 28 | +type ChunkSizeStrategy struct { |
| 29 | + limits ChunkSizeStrategyLimits |
| 30 | + logger log.Logger |
| 31 | +} |
| 32 | + |
| 33 | +func NewChunkSizeStrategy( |
| 34 | + limits ChunkSizeStrategyLimits, |
| 35 | + logger log.Logger, |
| 36 | +) (*ChunkSizeStrategy, error) { |
| 37 | + return &ChunkSizeStrategy{ |
| 38 | + limits: limits, |
| 39 | + logger: logger, |
| 40 | + }, nil |
| 41 | +} |
| 42 | + |
| 43 | +func (s *ChunkSizeStrategy) Name() string { |
| 44 | + return SplitBySeriesChunkSizeStrategyName |
| 45 | +} |
| 46 | + |
| 47 | +func (s *ChunkSizeStrategy) Plan( |
| 48 | + ctx context.Context, |
| 49 | + table config.DayTable, |
| 50 | + tenant string, |
| 51 | + tsdbs TSDBSet, |
| 52 | + metas []bloomshipper.Meta, |
| 53 | +) ([]*protos.Task, error) { |
| 54 | + targetTaskSize := s.limits.BloomTaskTargetSeriesChunksSizeBytes(tenant) |
| 55 | + |
| 56 | + logger := log.With(s.logger, "table", table.Addr(), "tenant", tenant) |
| 57 | + level.Debug(s.logger).Log("msg", "loading work for tenant", "target task size", humanize.Bytes(targetTaskSize)) |
| 58 | + |
| 59 | + // Determine which TSDBs have gaps and need to be processed. |
| 60 | + tsdbsWithGaps, err := gapsBetweenTSDBsAndMetas(v1.NewBounds(0, math.MaxUint64), tsdbs, metas) |
| 61 | + if err != nil { |
| 62 | + level.Error(logger).Log("msg", "failed to find gaps", "err", err) |
| 63 | + return nil, fmt.Errorf("failed to find gaps: %w", err) |
| 64 | + } |
| 65 | + |
| 66 | + if len(tsdbsWithGaps) == 0 { |
| 67 | + level.Debug(logger).Log("msg", "blooms exist for all tsdbs") |
| 68 | + return nil, nil |
| 69 | + } |
| 70 | + |
| 71 | + sizedIter, iterSize, err := s.sizedSeriesIter(ctx, tenant, tsdbsWithGaps, targetTaskSize) |
| 72 | + if err != nil { |
| 73 | + return nil, fmt.Errorf("failed to get sized series iter: %w", err) |
| 74 | + } |
| 75 | + |
| 76 | + tasks := make([]*protos.Task, 0, iterSize) |
| 77 | + for sizedIter.Next() { |
| 78 | + series := sizedIter.At() |
| 79 | + if series.Len() == 0 { |
| 80 | + // This should never happen, but just in case. |
| 81 | + level.Warn(logger).Log("msg", "got empty series batch", "tsdb", series.TSDB().Name()) |
| 82 | + continue |
| 83 | + } |
| 84 | + |
| 85 | + bounds := series.Bounds() |
| 86 | + |
| 87 | + blocks, err := getBlocksMatchingBounds(metas, bounds) |
| 88 | + if err != nil { |
| 89 | + return nil, fmt.Errorf("failed to get blocks matching bounds: %w", err) |
| 90 | + } |
| 91 | + |
| 92 | + planGap := protos.Gap{ |
| 93 | + Bounds: bounds, |
| 94 | + Series: series.V1Series(), |
| 95 | + Blocks: blocks, |
| 96 | + } |
| 97 | + |
| 98 | + tasks = append(tasks, protos.NewTask(table, tenant, bounds, series.TSDB(), []protos.Gap{planGap})) |
| 99 | + } |
| 100 | + if err := sizedIter.Err(); err != nil { |
| 101 | + return nil, fmt.Errorf("failed to iterate over sized series: %w", err) |
| 102 | + } |
| 103 | + |
| 104 | + return tasks, nil |
| 105 | +} |
| 106 | + |
| 107 | +func getBlocksMatchingBounds(metas []bloomshipper.Meta, bounds v1.FingerprintBounds) ([]bloomshipper.BlockRef, error) { |
| 108 | + blocks := make([]bloomshipper.BlockRef, 0, 10) |
| 109 | + |
| 110 | + for _, meta := range metas { |
| 111 | + if meta.Bounds.Intersection(bounds) == nil { |
| 112 | + // this meta doesn't overlap the gap, skip |
| 113 | + continue |
| 114 | + } |
| 115 | + |
| 116 | + for _, block := range meta.Blocks { |
| 117 | + if block.Bounds.Intersection(bounds) == nil { |
| 118 | + // this block doesn't overlap the gap, skip |
| 119 | + continue |
| 120 | + } |
| 121 | + // this block overlaps the gap, add it to the plan |
| 122 | + // for this gap |
| 123 | + blocks = append(blocks, block) |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + // ensure we sort blocks so deduping iterator works as expected |
| 128 | + sort.Slice(blocks, func(i, j int) bool { |
| 129 | + return blocks[i].Bounds.Less(blocks[j].Bounds) |
| 130 | + }) |
| 131 | + |
| 132 | + peekingBlocks := iter.NewPeekIter( |
| 133 | + iter.NewSliceIter( |
| 134 | + blocks, |
| 135 | + ), |
| 136 | + ) |
| 137 | + |
| 138 | + // dedupe blocks which could be in multiple metas |
| 139 | + itr := iter.NewDedupingIter( |
| 140 | + func(a, b bloomshipper.BlockRef) bool { |
| 141 | + return a == b |
| 142 | + }, |
| 143 | + iter.Identity[bloomshipper.BlockRef], |
| 144 | + func(a, _ bloomshipper.BlockRef) bloomshipper.BlockRef { |
| 145 | + return a |
| 146 | + }, |
| 147 | + peekingBlocks, |
| 148 | + ) |
| 149 | + |
| 150 | + deduped, err := iter.Collect(itr) |
| 151 | + if err != nil { |
| 152 | + return nil, fmt.Errorf("failed to dedupe blocks: %w", err) |
| 153 | + } |
| 154 | + |
| 155 | + return deduped, nil |
| 156 | +} |
| 157 | + |
| 158 | +type seriesWithChunks struct { |
| 159 | + tsdb tsdb.SingleTenantTSDBIdentifier |
| 160 | + fp model.Fingerprint |
| 161 | + chunks []index.ChunkMeta |
| 162 | +} |
| 163 | + |
| 164 | +type seriesBatch struct { |
| 165 | + series []seriesWithChunks |
| 166 | + size uint64 |
| 167 | +} |
| 168 | + |
| 169 | +func newSeriesBatch() seriesBatch { |
| 170 | + return seriesBatch{ |
| 171 | + series: make([]seriesWithChunks, 0, 100), |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +func (b *seriesBatch) Bounds() v1.FingerprintBounds { |
| 176 | + if len(b.series) == 0 { |
| 177 | + return v1.NewBounds(0, 0) |
| 178 | + } |
| 179 | + |
| 180 | + // We assume that the series are sorted by fingerprint. |
| 181 | + // This is guaranteed since series are iterated in order by the TSDB. |
| 182 | + return v1.NewBounds(b.series[0].fp, b.series[len(b.series)-1].fp) |
| 183 | +} |
| 184 | + |
| 185 | +func (b *seriesBatch) V1Series() []*v1.Series { |
| 186 | + series := make([]*v1.Series, 0, len(b.series)) |
| 187 | + for _, s := range b.series { |
| 188 | + res := &v1.Series{ |
| 189 | + Fingerprint: s.fp, |
| 190 | + Chunks: make(v1.ChunkRefs, 0, len(s.chunks)), |
| 191 | + } |
| 192 | + for _, chk := range s.chunks { |
| 193 | + res.Chunks = append(res.Chunks, v1.ChunkRef{ |
| 194 | + From: model.Time(chk.MinTime), |
| 195 | + Through: model.Time(chk.MaxTime), |
| 196 | + Checksum: chk.Checksum, |
| 197 | + }) |
| 198 | + } |
| 199 | + |
| 200 | + series = append(series, res) |
| 201 | + } |
| 202 | + |
| 203 | + return series |
| 204 | +} |
| 205 | + |
| 206 | +func (b *seriesBatch) Append(s seriesWithChunks, size uint64) { |
| 207 | + b.series = append(b.series, s) |
| 208 | + b.size += size |
| 209 | +} |
| 210 | + |
| 211 | +func (b *seriesBatch) Len() int { |
| 212 | + return len(b.series) |
| 213 | +} |
| 214 | + |
| 215 | +func (b *seriesBatch) Size() uint64 { |
| 216 | + return b.size |
| 217 | +} |
| 218 | + |
| 219 | +func (b *seriesBatch) TSDB() tsdb.SingleTenantTSDBIdentifier { |
| 220 | + if len(b.series) == 0 { |
| 221 | + return tsdb.SingleTenantTSDBIdentifier{} |
| 222 | + } |
| 223 | + return b.series[0].tsdb |
| 224 | +} |
| 225 | + |
| 226 | +func (s *ChunkSizeStrategy) sizedSeriesIter( |
| 227 | + ctx context.Context, |
| 228 | + tenant string, |
| 229 | + tsdbsWithGaps []tsdbGaps, |
| 230 | + targetTaskSizeBytes uint64, |
| 231 | +) (iter.Iterator[seriesBatch], int, error) { |
| 232 | + batches := make([]seriesBatch, 0, 100) |
| 233 | + currentBatch := newSeriesBatch() |
| 234 | + |
| 235 | + for _, idx := range tsdbsWithGaps { |
| 236 | + for _, gap := range idx.gaps { |
| 237 | + if err := idx.tsdb.ForSeries( |
| 238 | + ctx, |
| 239 | + tenant, |
| 240 | + gap, |
| 241 | + 0, math.MaxInt64, |
| 242 | + func(_ labels.Labels, fp model.Fingerprint, chks []index.ChunkMeta) (stop bool) { |
| 243 | + select { |
| 244 | + case <-ctx.Done(): |
| 245 | + return true |
| 246 | + default: |
| 247 | + var seriesSize uint64 |
| 248 | + for _, chk := range chks { |
| 249 | + seriesSize += uint64(chk.KB * 1024) |
| 250 | + } |
| 251 | + |
| 252 | + // Cut a new batch IF the current batch is not empty (so we add at least one series to the batch) |
| 253 | + // AND Adding this series to the batch would exceed the target task size. |
| 254 | + if currentBatch.Len() > 0 && currentBatch.Size()+seriesSize > targetTaskSizeBytes { |
| 255 | + batches = append(batches, currentBatch) |
| 256 | + currentBatch = newSeriesBatch() |
| 257 | + } |
| 258 | + |
| 259 | + currentBatch.Append(seriesWithChunks{ |
| 260 | + tsdb: idx.tsdbIdentifier, |
| 261 | + fp: fp, |
| 262 | + chunks: chks, |
| 263 | + }, seriesSize) |
| 264 | + return false |
| 265 | + } |
| 266 | + }, |
| 267 | + labels.MustNewMatcher(labels.MatchEqual, "", ""), |
| 268 | + ); err != nil { |
| 269 | + return nil, 0, err |
| 270 | + } |
| 271 | + |
| 272 | + // Add the last batch for this TSDB if it's not empty. |
| 273 | + if currentBatch.Len() > 0 { |
| 274 | + batches = append(batches, currentBatch) |
| 275 | + currentBatch = newSeriesBatch() |
| 276 | + } |
| 277 | + } |
| 278 | + } |
| 279 | + |
| 280 | + select { |
| 281 | + case <-ctx.Done(): |
| 282 | + return iter.NewEmptyIter[seriesBatch](), 0, ctx.Err() |
| 283 | + default: |
| 284 | + return iter.NewCancelableIter[seriesBatch](ctx, iter.NewSliceIter[seriesBatch](batches)), len(batches), nil |
| 285 | + } |
| 286 | +} |
0 commit comments