forked from thanos-io/thanos
/
series.go
399 lines (346 loc) · 11.9 KB
/
series.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
// Copyright (c) The Thanos Authors.
// Licensed under the Apache License 2.0.
package storetestutil
import (
"context"
"fmt"
"math"
"math/rand"
"os"
"path/filepath"
"runtime"
"sort"
"testing"
"time"
"github.com/cespare/xxhash"
"github.com/efficientgo/core/testutil"
"github.com/go-kit/log"
"github.com/gogo/protobuf/types"
"github.com/oklog/ulid"
"github.com/prometheus/prometheus/model/histogram"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb"
"github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/chunks"
"github.com/prometheus/prometheus/tsdb/index"
"github.com/prometheus/prometheus/tsdb/wlog"
"go.uber.org/atomic"
"github.com/thanos-io/thanos/pkg/store/hintspb"
"github.com/thanos-io/thanos/pkg/store/labelpb"
"github.com/thanos-io/thanos/pkg/store/storepb"
)
const (
// LabelLongSuffix is a label with ~50B in size, to emulate real-world high cardinality.
LabelLongSuffix = "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd"
)
func allPostings(ctx context.Context, t testing.TB, ix tsdb.IndexReader) index.Postings {
k, v := index.AllPostingsKey()
p, err := ix.Postings(ctx, k, v)
testutil.Ok(t, err)
return p
}
type HeadGenOptions struct {
TSDBDir string
SamplesPerSeries, Series int
ScrapeInterval time.Duration
WithWAL bool
PrependLabels labels.Labels
SkipChunks bool // Skips chunks in returned slice (not in generated head!).
SampleType chunkenc.ValueType
Random *rand.Rand
}
func CreateBlockFromHead(t testing.TB, dir string, head *tsdb.Head) ulid.ULID {
compactor, err := tsdb.NewLeveledCompactor(context.Background(), nil, log.NewNopLogger(), []int64{1000000}, nil, nil)
testutil.Ok(t, err)
testutil.Ok(t, os.MkdirAll(dir, 0777))
// Add +1 millisecond to block maxt because block intervals are half-open: [b.MinTime, b.MaxTime).
// Because of this block intervals are always +1 than the total samples it includes.
ulid, err := compactor.Write(dir, head, head.MinTime(), head.MaxTime()+1, nil)
testutil.Ok(t, err)
return ulid
}
// CreateHeadWithSeries returns head filled with given samples and same series returned in separate list for assertion purposes.
// Returned series list has "ext1"="1" prepended. Each series looks as follows:
// {foo=bar,i=000001aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd} <random value> where number indicate sample number from 0.
// Returned series are framed in the same way as remote read would frame them.
func CreateHeadWithSeries(t testing.TB, j int, opts HeadGenOptions) (*tsdb.Head, []*storepb.Series) {
if opts.SamplesPerSeries < 1 || opts.Series < 1 {
t.Fatal("samples and series has to be 1 or more")
}
if opts.ScrapeInterval == 0 {
opts.ScrapeInterval = 1 * time.Millisecond
}
// Use float type if sample type is not set.
if opts.SampleType == chunkenc.ValNone {
opts.SampleType = chunkenc.ValFloat
}
fmt.Printf(
"Creating %d %d-sample series with %s interval in %s\n",
opts.Series,
opts.SamplesPerSeries,
opts.ScrapeInterval.String(),
opts.TSDBDir,
)
var w *wlog.WL
var err error
if opts.WithWAL {
w, err = wlog.New(nil, nil, filepath.Join(opts.TSDBDir, "wal"), wlog.ParseCompressionType(true, string(wlog.CompressionSnappy)))
testutil.Ok(t, err)
} else {
testutil.Ok(t, os.MkdirAll(filepath.Join(opts.TSDBDir, "wal"), os.ModePerm))
}
headOpts := tsdb.DefaultHeadOptions()
headOpts.ChunkDirRoot = opts.TSDBDir
headOpts.EnableNativeHistograms = *atomic.NewBool(true)
h, err := tsdb.NewHead(nil, nil, w, nil, headOpts, nil)
testutil.Ok(t, err)
app := h.Appender(context.Background())
for i := 0; i < opts.Series; i++ {
tsLabel := j*opts.Series*opts.SamplesPerSeries + i*opts.SamplesPerSeries
switch opts.SampleType {
case chunkenc.ValFloat:
appendFloatSamples(t, app, tsLabel, opts)
case chunkenc.ValHistogram:
appendHistogramSamples(t, app, tsLabel, opts)
case chunkenc.ValFloatHistogram:
appendFloatHistogramSamples(t, app, tsLabel, opts)
}
}
testutil.Ok(t, app.Commit())
return h, ReadSeriesFromBlock(t, h, opts.PrependLabels, opts.SkipChunks)
}
func ReadSeriesFromBlock(t testing.TB, h tsdb.BlockReader, extLabels labels.Labels, skipChunks bool) []*storepb.Series {
// Use TSDB and get all series for assertion.
chks, err := h.Chunks()
testutil.Ok(t, err)
defer func() { testutil.Ok(t, chks.Close()) }()
ir, err := h.Index()
testutil.Ok(t, err)
defer func() { testutil.Ok(t, ir.Close()) }()
var (
chunkMetas []chunks.Meta
expected = make([]*storepb.Series, 0)
)
var builder labels.ScratchBuilder
all := allPostings(context.TODO(), t, ir)
for all.Next() {
testutil.Ok(t, ir.Series(all.At(), &builder, &chunkMetas))
lset := labelpb.ExtendSortedLabels(builder.Labels(), extLabels)
expected = append(expected, &storepb.Series{Labels: labelpb.ZLabelsFromPromLabels(lset)})
if skipChunks {
continue
}
for _, c := range chunkMetas {
chEnc, err := chks.Chunk(c)
testutil.Ok(t, err)
// Open Chunk.
if c.MaxTime == math.MaxInt64 {
c.MaxTime = c.MinTime + int64(chEnc.NumSamples()) - 1
}
expected[len(expected)-1].Chunks = append(expected[len(expected)-1].Chunks, storepb.AggrChunk{
MinTime: c.MinTime,
MaxTime: c.MaxTime,
Raw: &storepb.Chunk{
Data: chEnc.Bytes(),
Type: storepb.Chunk_Encoding(chEnc.Encoding() - 1),
Hash: xxhash.Sum64(chEnc.Bytes()),
},
})
}
}
testutil.Ok(t, all.Err())
return expected
}
func appendFloatSamples(t testing.TB, app storage.Appender, tsLabel int, opts HeadGenOptions) {
ref, err := app.Append(
0,
labels.FromStrings("foo", "bar", "i", fmt.Sprintf("%07d%s", tsLabel, LabelLongSuffix), "j", fmt.Sprintf("%v", tsLabel)),
int64(tsLabel)*opts.ScrapeInterval.Milliseconds(),
opts.Random.Float64(),
)
testutil.Ok(t, err)
for is := 1; is < opts.SamplesPerSeries; is++ {
_, err := app.Append(ref, labels.EmptyLabels(), int64(tsLabel+is)*opts.ScrapeInterval.Milliseconds(), opts.Random.Float64())
testutil.Ok(t, err)
}
}
func appendHistogramSamples(t testing.TB, app storage.Appender, tsLabel int, opts HeadGenOptions) {
sample := &histogram.Histogram{
Schema: 0,
Count: 20,
Sum: -3.1415,
ZeroCount: 12,
ZeroThreshold: 0.001,
NegativeSpans: []histogram.Span{
{Offset: 0, Length: 4},
{Offset: 1, Length: 1},
},
NegativeBuckets: []int64{1, 2, -2, 1, -1},
}
ref, err := app.AppendHistogram(
0,
labels.FromStrings("foo", "bar", "i", fmt.Sprintf("%07d%s", tsLabel, LabelLongSuffix), "j", fmt.Sprintf("%v", tsLabel)),
int64(tsLabel)*opts.ScrapeInterval.Milliseconds(),
sample,
nil,
)
testutil.Ok(t, err)
for is := 1; is < opts.SamplesPerSeries; is++ {
_, err := app.AppendHistogram(ref, labels.EmptyLabels(), int64(tsLabel+is)*opts.ScrapeInterval.Milliseconds(), sample, nil)
testutil.Ok(t, err)
}
}
func appendFloatHistogramSamples(t testing.TB, app storage.Appender, tsLabel int, opts HeadGenOptions) {
sample := &histogram.FloatHistogram{
ZeroThreshold: 0.01,
ZeroCount: 5.5,
Count: 15,
Sum: 11.5,
PositiveSpans: []histogram.Span{
{Offset: -2, Length: 2},
{Offset: 1, Length: 3},
},
PositiveBuckets: []float64{0.5, 0, 1.5, 2, 3.5},
NegativeSpans: []histogram.Span{
{Offset: 3, Length: 2},
{Offset: 3, Length: 2},
},
NegativeBuckets: []float64{1.5, 0.5, 2.5, 3},
}
ref, err := app.AppendHistogram(
0,
labels.FromStrings("foo", "bar", "i", fmt.Sprintf("%07d%s", tsLabel, LabelLongSuffix), "j", fmt.Sprintf("%v", tsLabel)),
int64(tsLabel)*opts.ScrapeInterval.Milliseconds(),
nil,
sample,
)
testutil.Ok(t, err)
for is := 1; is < opts.SamplesPerSeries; is++ {
_, err := app.AppendHistogram(ref, labels.EmptyLabels(), int64(tsLabel+is)*opts.ScrapeInterval.Milliseconds(), nil, sample)
testutil.Ok(t, err)
}
}
// SeriesServer is test gRPC storeAPI series server.
type SeriesServer struct {
// This field just exist to pseudo-implement the unused methods of the interface.
storepb.Store_SeriesServer
ctx context.Context
SeriesSet []*storepb.Series
Warnings []string
HintsSet []*types.Any
Size int64
}
func NewSeriesServer(ctx context.Context) *SeriesServer {
return &SeriesServer{ctx: ctx}
}
func (s *SeriesServer) Send(r *storepb.SeriesResponse) error {
s.Size += int64(r.Size())
if r.GetWarning() != "" {
s.Warnings = append(s.Warnings, r.GetWarning())
return nil
}
if r.GetSeries() != nil {
s.SeriesSet = append(s.SeriesSet, r.GetSeries())
return nil
}
if r.GetHints() != nil {
s.HintsSet = append(s.HintsSet, r.GetHints())
return nil
}
// Unsupported field, skip.
return nil
}
func (s *SeriesServer) Context() context.Context {
return s.ctx
}
func RunSeriesInterestingCases(t testutil.TB, maxSamples, maxSeries int, f func(t testutil.TB, samplesPerSeries, series int)) {
for _, tc := range []struct {
samplesPerSeries int
series int
}{
{
samplesPerSeries: 1,
series: maxSeries,
},
{
samplesPerSeries: maxSamples / (maxSeries / 10),
series: maxSeries / 10,
},
{
samplesPerSeries: maxSamples,
series: 1,
},
} {
if ok := t.Run(fmt.Sprintf("%dSeriesWith%dSamples", tc.series, tc.samplesPerSeries), func(t testutil.TB) {
f(t, tc.samplesPerSeries, tc.series)
}); !ok {
return
}
runtime.GC()
}
}
// SeriesCase represents single test/benchmark case for testing storepb series.
type SeriesCase struct {
Name string
Req *storepb.SeriesRequest
// Exact expectations are checked only for tests. For benchmarks only length is assured.
ExpectedSeries []*storepb.Series
ExpectedWarnings []string
ExpectedHints []hintspb.SeriesResponseHints
HintsCompareFunc func(t testutil.TB, expected, actual hintspb.SeriesResponseHints)
}
// TestServerSeries runs tests against given cases.
func TestServerSeries(t testutil.TB, store storepb.StoreServer, cases ...*SeriesCase) {
for _, c := range cases {
t.Run(c.Name, func(t testutil.TB) {
t.ResetTimer()
for i := 0; i < t.N(); i++ {
srv := NewSeriesServer(context.Background())
testutil.Ok(t, store.Series(c.Req, srv))
testutil.Equals(t, len(c.ExpectedWarnings), len(srv.Warnings), "%v", srv.Warnings)
testutil.Equals(t, len(c.ExpectedSeries), len(srv.SeriesSet))
testutil.Equals(t, len(c.ExpectedHints), len(srv.HintsSet))
if !t.IsBenchmark() {
if len(c.ExpectedSeries) == 1 {
// For bucketStoreAPI chunks are not sorted within response. TODO: Investigate: Is this fine?
sort.Slice(srv.SeriesSet[0].Chunks, func(i, j int) bool {
return srv.SeriesSet[0].Chunks[i].MinTime < srv.SeriesSet[0].Chunks[j].MinTime
})
}
// Huge responses can produce unreadable diffs - make it more human readable.
if len(c.ExpectedSeries) > 4 {
for j := range c.ExpectedSeries {
testutil.Equals(t, c.ExpectedSeries[j].Labels, srv.SeriesSet[j].Labels, "%v series chunks mismatch", j)
// Check chunks when it is not a skip chunk query
if !c.Req.SkipChunks {
if len(c.ExpectedSeries[j].Chunks) > 20 {
testutil.Equals(t, len(c.ExpectedSeries[j].Chunks), len(srv.SeriesSet[j].Chunks), "%v series chunks number mismatch", j)
}
for ci := range c.ExpectedSeries[j].Chunks {
testutil.Equals(t, c.ExpectedSeries[j].Chunks[ci], srv.SeriesSet[j].Chunks[ci], "%v series chunks mismatch %v", j, ci)
}
}
}
} else {
testutil.Equals(t, c.ExpectedSeries, srv.SeriesSet)
}
var actualHints []hintspb.SeriesResponseHints
for _, anyHints := range srv.HintsSet {
hints := hintspb.SeriesResponseHints{}
testutil.Ok(t, types.UnmarshalAny(anyHints, &hints))
actualHints = append(actualHints, hints)
}
testutil.Equals(t, len(c.ExpectedHints), len(actualHints))
for i, hint := range actualHints {
if c.HintsCompareFunc == nil {
testutil.Equals(t, c.ExpectedHints[i], hint)
} else {
c.HintsCompareFunc(t, c.ExpectedHints[i], hint)
}
}
}
}
})
}
}