/
series.go
282 lines (240 loc) · 7.98 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
// 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/gogo/protobuf/types"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/tsdb"
"github.com/prometheus/prometheus/tsdb/chunks"
"github.com/prometheus/prometheus/tsdb/index"
"github.com/prometheus/prometheus/tsdb/wal"
"github.com/thanos-io/thanos/pkg/store/hintspb"
"github.com/thanos-io/thanos/pkg/store/labelpb"
"github.com/thanos-io/thanos/pkg/store/storepb"
"github.com/thanos-io/thanos/pkg/testutil"
)
const (
// LabelLongSuffix is a label with ~50B in size, to emulate real-world high cardinality.
LabelLongSuffix = "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd"
)
func allPostings(t testing.TB, ix tsdb.IndexReader) index.Postings {
k, v := index.AllPostingsKey()
p, err := ix.Postings(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!).
Random *rand.Rand
}
// 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
}
fmt.Printf(
"Creating %d %d-sample series with %s interval in %s\n",
opts.Series,
opts.SamplesPerSeries,
opts.ScrapeInterval.String(),
opts.TSDBDir,
)
var w *wal.WAL
var err error
if opts.WithWAL {
w, err = wal.New(nil, nil, filepath.Join(opts.TSDBDir, "wal"), true)
testutil.Ok(t, err)
} else {
testutil.Ok(t, os.MkdirAll(filepath.Join(opts.TSDBDir, "wal"), os.ModePerm))
}
headOpts := tsdb.DefaultHeadOptions()
headOpts.ChunkDirRoot = opts.TSDBDir
h, err := tsdb.NewHead(nil, nil, w, 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
ref, err := app.Append(
0,
labels.FromStrings("foo", "bar", "i", fmt.Sprintf("%07d%s", tsLabel, LabelLongSuffix)),
int64(tsLabel)*opts.ScrapeInterval.Milliseconds(),
opts.Random.Float64(),
)
testutil.Ok(t, err)
for is := 1; is < opts.SamplesPerSeries; is++ {
_, err := app.Append(ref, nil, int64(tsLabel+is)*opts.ScrapeInterval.Milliseconds(), opts.Random.Float64())
testutil.Ok(t, err)
}
}
testutil.Ok(t, app.Commit())
// 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 (
lset labels.Labels
chunkMetas []chunks.Meta
expected = make([]*storepb.Series, 0, opts.Series)
)
all := allPostings(t, ir)
for all.Next() {
testutil.Ok(t, ir.Series(all.At(), &lset, &chunkMetas))
expected = append(expected, &storepb.Series{Labels: labelpb.ZLabelsFromPromLabels(append(opts.PrependLabels.Copy(), lset...))})
if opts.SkipChunks {
continue
}
for _, c := range chunkMetas {
chEnc, err := chks.Chunk(c.Ref)
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{Type: storepb.Chunk_XOR, Data: chEnc.Bytes(), Hash: xxhash.Sum64(chEnc.Bytes())},
})
}
}
testutil.Ok(t, all.Err())
return h, expected
}
// 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
}
// 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)
}
testutil.Equals(t, c.ExpectedSeries[j].Chunks, srv.SeriesSet[j].Chunks, "%v series chunks mismatch", j)
}
}
} 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, c.ExpectedHints, actualHints)
}
}
})
}
}