-
Notifications
You must be signed in to change notification settings - Fork 455
/
block_generator.go
298 lines (255 loc) · 7.3 KB
/
block_generator.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
// SPDX-License-Identifier: AGPL-3.0-only
// Provenance-includes-location: https://github.com/thanos-io/thanos/blob/main/pkg/testutil/e2eutil/prometheus.go
// Provenance-includes-license: Apache-2.0
// Provenance-includes-copyright: The Thanos Authors.
package block
import (
"context"
crypto_rand "crypto/rand"
"math"
"math/rand"
"os"
"path/filepath"
"runtime"
"sort"
"github.com/go-kit/log"
"github.com/grafana/dskit/runutil"
"github.com/oklog/ulid"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb"
"github.com/prometheus/prometheus/tsdb/chunks"
"github.com/prometheus/prometheus/tsdb/index"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup"
"github.com/grafana/mimir/pkg/util/test"
)
type SeriesSpec struct {
Labels labels.Labels
Chunks []chunks.Meta
}
type SeriesSpecs []*SeriesSpec
func (s SeriesSpecs) MinTime() int64 {
minTime := int64(math.MaxInt64)
for _, series := range s {
for _, c := range series.Chunks {
if c.MinTime < minTime {
minTime = c.MinTime
}
}
}
return minTime
}
func (s SeriesSpecs) MaxTime() int64 {
maxTime := int64(math.MinInt64)
for _, series := range s {
for _, c := range series.Chunks {
if c.MaxTime > maxTime {
maxTime = c.MaxTime
}
}
}
return maxTime
}
// GenerateBlockFromSpec generates a TSDB block with series and chunks provided by the input specs.
// This utility is intended just to be used for testing. Do not use it for any production code.
func GenerateBlockFromSpec(storageDir string, specs SeriesSpecs) (_ *Meta, returnErr error) {
blockID := ulid.MustNew(ulid.Now(), crypto_rand.Reader)
blockDir := filepath.Join(storageDir, blockID.String())
// Ensure series are sorted.
sort.Slice(specs, func(i, j int) bool {
return labels.Compare(specs[i].Labels, specs[j].Labels) < 0
})
// Build symbols.
uniqueSymbols := map[string]struct{}{}
for _, series := range specs {
series.Labels.Range(func(l labels.Label) {
uniqueSymbols[l.Name] = struct{}{}
uniqueSymbols[l.Value] = struct{}{}
})
}
symbols := []string{}
for s := range uniqueSymbols {
symbols = append(symbols, s)
}
slices.Sort(symbols)
// Write all chunks to segment files.
chunkw, err := chunks.NewWriter(filepath.Join(blockDir, "chunks"))
if err != nil {
return nil, err
}
// Ensure the chunk writer is always closed (even on error).
chunkwClosed := false
defer func() {
if !chunkwClosed {
if err := chunkw.Close(); err != nil && returnErr == nil {
returnErr = err
}
}
}()
// Updates the Ref on each chunk.
for _, series := range specs {
// Ensure every chunk meta has chunk data.
for _, c := range series.Chunks {
if c.Chunk == nil {
return nil, errors.Errorf("missing chunk data for series %s", series.Labels.String())
}
}
if err := chunkw.WriteChunks(series.Chunks...); err != nil {
return nil, err
}
}
chunkwClosed = true
if err := chunkw.Close(); err != nil {
return nil, err
}
// Write index.
indexw, err := index.NewWriter(context.Background(), filepath.Join(blockDir, "index"))
if err != nil {
return nil, err
}
// Ensure the index writer is always closed (even on error).
indexwClosed := false
defer func() {
if !indexwClosed {
if err := indexw.Close(); err != nil && returnErr == nil {
returnErr = err
}
}
}()
// Add symbols.
for _, s := range symbols {
if err := indexw.AddSymbol(s); err != nil {
return nil, err
}
}
// Add series.
for i, series := range specs {
if err := indexw.AddSeries(storage.SeriesRef(i), series.Labels, series.Chunks...); err != nil {
return nil, err
}
}
indexwClosed = true
if err := indexw.Close(); err != nil {
return nil, err
}
// Generate the meta.json file.
meta := &Meta{
BlockMeta: tsdb.BlockMeta{
ULID: blockID,
MinTime: specs.MinTime(),
MaxTime: specs.MaxTime() + 1, // Not included.
Compaction: tsdb.BlockMetaCompaction{
Level: 1,
Sources: []ulid.ULID{blockID},
},
Version: 1,
},
Thanos: ThanosMeta{
Version: ThanosVersion1,
},
}
return meta, meta.WriteToDir(log.NewNopLogger(), blockDir)
}
// CreateBlock writes a block with the given series and numSamples samples each.
// Timeseries i%3==0 will contain floats, i%3==1 will contain histograms and i%3==2 will contain float histograms
// Samples will be in the time range [mint, maxt).
func CreateBlock(
ctx context.Context,
dir string,
series []labels.Labels,
numSamples int,
mint, maxt int64,
extLset labels.Labels,
) (id ulid.ULID, err error) {
if len(series) < 3 {
return id, errors.Errorf("not enough series to test different value types: floats, histograms, float histograms")
}
headOpts := tsdb.DefaultHeadOptions()
headOpts.ChunkDirRoot = filepath.Join(dir, "chunks")
headOpts.ChunkRange = math.MaxInt64
headOpts.EnableNativeHistograms.Store(true)
h, err := tsdb.NewHead(nil, nil, nil, nil, headOpts, nil)
if err != nil {
return id, errors.Wrap(err, "create head block")
}
defer func() {
runutil.CloseWithErrCapture(&err, h, "TSDB Head")
if e := os.RemoveAll(headOpts.ChunkDirRoot); e != nil {
err = errors.Wrap(e, "delete chunks dir")
}
}()
var g errgroup.Group
var timeStepSize = (maxt - mint) / int64(numSamples+1)
var batchSize = len(series) / runtime.GOMAXPROCS(0)
// For calculating the next series value type (float, histogram, etc)
batchOffset := 0
// prep some histogram test data
testHistograms := test.GenerateTestHistograms(numSamples)
testFloatHistograms := test.GenerateTestFloatHistograms(numSamples)
for len(series) > 0 {
l := batchSize
if len(series) < 1000 {
l = len(series)
}
batch := series[:l]
batchValueTypeOffset := batchOffset
batchOffset += batchSize
series = series[l:]
g.Go(func() error {
t := mint
for i := 0; i < numSamples; i++ {
app := h.Appender(ctx)
for j, lset := range batch {
var err error
switch (batchValueTypeOffset + j) % 3 {
case 0:
_, err = app.Append(0, lset, t, rand.Float64())
case 1:
_, err = app.AppendHistogram(0, lset, t, testHistograms[i], nil)
case 2:
_, err = app.AppendHistogram(0, lset, t, nil, testFloatHistograms[i])
}
if err != nil {
if rerr := app.Rollback(); rerr != nil {
err = errors.Wrapf(err, "rollback failed: %v", rerr)
}
return errors.Wrap(err, "add sample")
}
}
if err := app.Commit(); err != nil {
return errors.Wrap(err, "commit")
}
t += timeStepSize
}
return nil
})
}
if err := g.Wait(); err != nil {
return id, err
}
c, err := tsdb.NewLeveledCompactor(ctx, nil, log.NewNopLogger(), []int64{maxt - mint}, nil, nil)
if err != nil {
return id, errors.Wrap(err, "create compactor")
}
id, err = c.Write(dir, h, mint, maxt, nil)
if err != nil {
return id, errors.Wrap(err, "write block")
}
if id.Compare(ulid.ULID{}) == 0 {
return id, errors.Errorf("nothing to write, asked for %d samples", numSamples)
}
blockDir := filepath.Join(dir, id.String())
if _, err = InjectThanosMeta(log.NewNopLogger(), blockDir, ThanosMeta{
Labels: extLset.Map(),
Source: TestSource,
Files: []File{},
}, nil); err != nil {
return id, errors.Wrap(err, "finalize block")
}
if err = os.Remove(filepath.Join(dir, id.String(), "tombstones")); err != nil {
return id, errors.Wrap(err, "remove tombstones")
}
return id, nil
}