-
Notifications
You must be signed in to change notification settings - Fork 548
/
Copy pathbackfill_test.go
408 lines (329 loc) · 13.1 KB
/
backfill_test.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
// SPDX-License-Identifier: AGPL-3.0-only
//go:build requires_docker
package integration
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path"
"path/filepath"
"testing"
"time"
"github.com/go-kit/log"
"github.com/grafana/dskit/flagext"
"github.com/grafana/dskit/runutil"
"github.com/grafana/dskit/test"
"github.com/grafana/e2e"
e2edb "github.com/grafana/e2e/db"
"github.com/oklog/ulid"
"github.com/prometheus/prometheus/model/labels"
"github.com/stretchr/testify/require"
"github.com/thanos-io/objstore"
"golang.org/x/time/rate"
"github.com/grafana/mimir/integration/e2emimir"
"github.com/grafana/mimir/pkg/mimirtool/client"
"github.com/grafana/mimir/pkg/storage/bucket"
"github.com/grafana/mimir/pkg/storage/bucket/s3"
"github.com/grafana/mimir/pkg/storage/tsdb/block"
)
func TestMimirtoolBackfill(t *testing.T) {
const (
overridesFile = "overrides.yaml"
)
tmpDir := t.TempDir()
blockEnd := time.Now().Truncate(2 * time.Hour)
block1, err := block.CreateBlock(
context.Background(), tmpDir,
[]labels.Labels{
labels.FromStrings("test", "test1", "a", "1"),
labels.FromStrings("test", "test1", "a", "2"),
labels.FromStrings("test", "test1", "a", "3"),
},
100, blockEnd.Add(-2*time.Hour).UnixMilli(), blockEnd.UnixMilli(), labels.EmptyLabels())
require.NoError(t, err)
block2, err := block.CreateBlock(
context.Background(), tmpDir,
[]labels.Labels{
labels.FromStrings("test", "test2", "a", "1"),
labels.FromStrings("test", "test2", "a", "2"),
labels.FromStrings("test", "test2", "a", "3"),
},
100, blockEnd.Add(-2*time.Hour).UnixMilli(), blockEnd.UnixMilli(), labels.EmptyLabels())
require.NoError(t, err)
s, err := e2e.NewScenario(networkName)
require.NoError(t, err)
defer s.Close()
// Write blank overrides file, so we can check if they are updated later
require.NoError(t, writeFileToSharedDir(s, overridesFile, []byte{}))
// Start dependencies.
consul := e2edb.NewConsul()
minio := e2edb.NewMinio(9000, mimirBucketName)
require.NoError(t, s.StartAndWaitReady(consul, minio))
dataDir := filepath.Join(s.SharedDir(), "data")
err = os.Mkdir(dataDir, os.ModePerm)
require.NoError(t, err)
// Configure the compactor with a data directory and runtime config (for overrides)
flags := mergeFlags(CommonStorageBackendFlags(), BlocksStorageFlags(), map[string]string{
"-compactor.data-dir": filepath.Join(e2e.ContainerSharedDir, "data"),
"-runtime-config.reload-period": "100ms",
"-runtime-config.file": filepath.Join(e2e.ContainerSharedDir, overridesFile),
})
// Start Mimir compactor.
compactor := e2emimir.NewCompactor("compactor", consul.NetworkHTTPEndpoint(), flags)
require.NoError(t, s.StartAndWaitReady(compactor))
{
// Try to upload block using mimirtool. Should fail because upload is not enabled for user.
output, err := runMimirtoolBackfill(tmpDir, compactor, block1)
require.Contains(t, output, "400 Bad Request")
require.Contains(t, output, "block upload is disabled")
require.Error(t, err)
}
{
runtimeConfigURL := fmt.Sprintf("http://%s/runtime_config?mode=diff", compactor.HTTPEndpoint())
out, err := getURL(runtimeConfigURL)
require.NoError(t, err)
// Enable block upload for anonymous.
require.NoError(t, writeFileToSharedDir(s, overridesFile, []byte(`
overrides:
anonymous:
compactor_block_upload_enabled: true
`)))
// Wait until compactor has reloaded runtime config.
test.Poll(t, 1*time.Second, true, func() interface{} {
newOut, err := getURL(runtimeConfigURL)
require.NoError(t, err)
return out != newOut
})
// Upload block using mimirtool, should work since upload is enabled for user.
output, err := runMimirtoolBackfill(tmpDir, compactor, block1)
require.Contains(t, output, fmt.Sprintf("msg=\"block uploaded successfully\" block=%s", block1))
require.NoError(t, err)
}
{
// Upload block1 and block2. Block 1 already exists, but block2 should be uploaded without problems.
output, err := runMimirtoolBackfill(tmpDir, compactor, block1, block2)
require.Contains(t, output, fmt.Sprintf("msg=\"block already exists on the server\" path=%s", path.Join(e2e.ContainerSharedDir, block1.String())))
require.Contains(t, output, fmt.Sprintf("msg=\"block uploaded successfully\" block=%s", block2))
// If blocks exist, it's not an error.
require.NoError(t, err)
}
{
// Verify that blocks exist in the bucket.
client, err := s3.NewBucketClient(s3.Config{
Endpoint: minio.HTTPEndpoint(),
Insecure: true,
BucketName: mimirBucketName,
AccessKeyID: e2edb.MinioAccessKey,
SecretAccessKey: flagext.SecretWithValue(e2edb.MinioSecretKey),
}, "test", log.NewNopLogger())
require.NoError(t, err)
verifyBlock(t, client, block1, filepath.Join(tmpDir, block1.String()))
verifyBlock(t, client, block2, filepath.Join(tmpDir, block2.String()))
}
{
// Let's try to upload a block without meta.json.
b, err := block.CreateBlock(
context.Background(), tmpDir,
[]labels.Labels{
labels.FromStrings("test", "bad", "a", "1"),
labels.FromStrings("test", "bad", "a", "2"),
labels.FromStrings("test", "bad", "a", "3"),
},
100, blockEnd.Add(-2*time.Hour).UnixMilli(), blockEnd.UnixMilli(), labels.EmptyLabels())
require.NoError(t, err)
require.NoError(t, os.Remove(filepath.Join(tmpDir, b.String(), block.MetaFilename)))
output, err := runMimirtoolBackfill(tmpDir, compactor, b)
require.Regexp(t, fmt.Sprintf("msg=\"failed uploading block\"[^\n]+path=%s", path.Join(e2e.ContainerSharedDir, b.String())), output)
require.Error(t, err)
}
{
// Let's try block with external labels. Mimir currently rejects those.
extLabels := labels.FromStrings("ext", "labels")
b, err := block.CreateBlock(
context.Background(), tmpDir,
[]labels.Labels{
labels.FromStrings("test", "bad", "a", "1"),
labels.FromStrings("test", "bad", "a", "2"),
labels.FromStrings("test", "bad", "a", "3"),
},
100, blockEnd.Add(-2*time.Hour).UnixMilli(), blockEnd.UnixMilli(), extLabels)
require.NoError(t, err)
output, err := runMimirtoolBackfill(tmpDir, compactor, b)
require.Contains(t, output, "unsupported external label: ext")
require.Error(t, err)
}
}
func TestBackfillSlowUploadSpeed(t *testing.T) {
s, err := e2e.NewScenario(networkName)
require.NoError(t, err)
defer s.Close()
// Start dependencies.
consul := e2edb.NewConsul()
minio := e2edb.NewMinio(9000, mimirBucketName)
require.NoError(t, s.StartAndWaitReady(consul, minio))
dataDir := filepath.Join(s.SharedDir(), "data")
require.NoError(t, os.Mkdir(dataDir, os.ModePerm))
const httpServerTimeout = 2 * time.Second
flags := mergeFlags(CommonStorageBackendFlags(), BlocksStorageFlags(), map[string]string{
"-compactor.data-dir": filepath.Join(e2e.ContainerSharedDir, "data"),
// Enable uploads for all tenants
"-compactor.block-upload-enabled": "true",
// Use short timeouts for HTTP endpoints.
// This timeout will not be applied to file upload endpoint.
"-server.http-read-timeout": httpServerTimeout.String(),
"-server.http-write-timeout": httpServerTimeout.String(),
"-querier.timeout": httpServerTimeout.String(), // must be set too, otherwise validation check fails because default value is too high compared to -server.http-write-timeout.
"-log.level": "debug",
})
// Start Mimir compactor.
compactor := e2emimir.NewCompactor("compactor", consul.NetworkHTTPEndpoint(), flags)
require.NoError(t, s.StartAndWaitReady(compactor))
// Create block that we will try to upload.
tmpDir := t.TempDir()
blockEnd := time.Now().Truncate(2 * time.Hour)
block, err := block.CreateBlock(
context.Background(), tmpDir,
[]labels.Labels{
labels.FromStrings("test", "test1", "a", "1"),
labels.FromStrings("test", "test1", "a", "2"),
labels.FromStrings("test", "test1", "a", "3"),
},
100, blockEnd.Add(-2*time.Hour).UnixMilli(), blockEnd.UnixMilli(), labels.EmptyLabels())
require.NoError(t, err)
httpClient := &http.Client{}
// Initiate new block upload.
{
// client.GetBlockMeta will generate correct meta.json file ready for initiating upload of our block.
meta, err := client.GetBlockMeta(fmt.Sprintf("%s/%s", tmpDir, block.String()))
require.NoError(t, err)
buf := bytes.NewBuffer(nil)
require.NoError(t, json.NewEncoder(buf).Encode(meta))
req, err := http.NewRequest("POST", fmt.Sprintf("http://%s/api/v1/upload/block/%s/start", compactor.HTTPEndpoint(), block.String()), buf)
req.Header.Set("X-Scope-OrgID", userID)
require.NoError(t, err)
resp, err := httpClient.Do(req)
require.NoError(t, err)
body := readAndCloseBody(t, resp.Body)
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
}
// Now start uploading block data, slowly, so that it takes longer than http server timeout.
// This will only succeed if timeout is overridden for the endpoint.
{
const targetDuration = httpServerTimeout * 2
chunksFilename := fmt.Sprintf("%s/%s/chunks/000001", tmpDir, block.String())
chunksFiledata, err := os.ReadFile(chunksFilename)
require.NoError(t, err)
// We add one second, because rate-limited reader already allows reading in time 0.
rateLimit := float64(len(chunksFiledata)) / (targetDuration.Seconds() + 1)
require.True(t, rateLimit > 0) // sanity check
rr := newRateLimitedReader(bytes.NewReader(chunksFiledata), rateLimit, int(rateLimit))
req, err := http.NewRequest("POST", fmt.Sprintf("http://%s/api/v1/upload/block/%s/files?path=chunks/000001", compactor.HTTPEndpoint(), block.String()), rr)
req.Header.Set("X-Scope-OrgID", userID)
require.NoError(t, err)
start := time.Now()
resp, err := httpClient.Do(req)
elapsed := time.Since(start)
require.NoError(t, err)
body := readAndCloseBody(t, resp.Body)
require.Equal(t, http.StatusOK, resp.StatusCode, string(body))
// Verify that it actually took as long as we expected.
require.True(t, elapsed > targetDuration)
}
}
func readAndCloseBody(t *testing.T, r io.ReadCloser) []byte {
b, err := io.ReadAll(r)
require.NoError(t, err)
require.NoError(t, r.Close())
return b
}
func verifyBlock(t *testing.T, client objstore.Bucket, ulid ulid.ULID, localPath string) {
for _, fn := range []string{"index", "chunks/000001"} {
a, err := client.Attributes(context.Background(), path.Join("blocks/anonymous", ulid.String(), fn))
require.NoError(t, err)
fi, err := os.Stat(filepath.Join(localPath, filepath.FromSlash(fn)))
require.NoError(t, err)
require.Equal(t, fi.Size(), a.Size)
}
localMeta, err := block.ReadMetaFromDir(localPath)
require.NoError(t, err)
remoteMeta, err := block.DownloadMeta(context.Background(), log.NewNopLogger(), bucket.NewPrefixedBucketClient(client, "blocks/anonymous"), ulid)
require.NoError(t, err)
require.Equal(t, localMeta.ULID, remoteMeta.ULID)
require.Equal(t, localMeta.Stats, remoteMeta.Stats)
}
func runMimirtoolBackfill(sharedDir string, compactor *e2emimir.MimirService, blocksToUpload ...ulid.ULID) (string, error) {
dockerArgs := []string{
"run",
"--rm",
"--net=" + networkName,
"--name=" + networkName + "-mimirtool-backfill",
}
dockerArgs = append(dockerArgs, "--volume", fmt.Sprintf("%s:%s:z", sharedDir, e2e.ContainerSharedDir))
dockerArgs = append(dockerArgs, e2emimir.GetMimirtoolImage())
// Mimirtool args.
dockerArgs = append(dockerArgs, "backfill")
dockerArgs = append(dockerArgs, "--address", fmt.Sprintf("http://%s:%d/", compactor.Name(), compactor.HTTPPort()))
dockerArgs = append(dockerArgs, "--id", "anonymous")
for _, b := range blocksToUpload {
dockerArgs = append(dockerArgs, path.Join(e2e.ContainerSharedDir, b.String()))
}
out, err := e2e.RunCommandAndGetOutput("docker", dockerArgs...)
return string(out), err
}
func getURL(url string) (string, error) {
res, err := e2e.DoGet(url)
if err != nil {
return "", err
}
// Check the status code.
if res.StatusCode < 200 || res.StatusCode >= 300 {
return "", fmt.Errorf("unexpected status code %d %s", res.StatusCode, res.Status)
}
defer runutil.ExhaustCloseWithErrCapture(&err, res.Body, "reading body")
body, err := io.ReadAll(res.Body)
return string(body), err
}
func newRateLimitedReader(r io.Reader, bytesPerSec float64, burst int) io.Reader {
return &rateLimitedReader{
r: r,
burst: burst,
bucket: rate.NewLimiter(rate.Limit(bytesPerSec), burst),
}
}
type rateLimitedReader struct {
r io.Reader
burst int
bucket *rate.Limiter
}
func (r *rateLimitedReader) Read(buf []byte) (int, error) {
// We can't wait for more bytes than our burst size.
if len(buf) > r.burst {
buf = buf[:r.burst]
}
n, err := r.r.Read(buf)
if n <= 0 {
return n, err
}
err1 := r.bucket.WaitN(context.Background(), n)
if err == nil {
err = err1
}
return n, err
}
func TestRateLimitedReader(t *testing.T) {
t.Skip("slow test, checking implementation of rate-limited reader.")
const dataLen = 16384
const dataRate = 4096
data := make([]byte, dataLen)
start := time.Now()
n, err := io.Copy(io.Discard, newRateLimitedReader(bytes.NewReader(data), dataRate, dataRate))
elapsed := time.Since(start)
require.NoError(t, err)
require.Equal(t, int64(len(data)), n)
// rate limiter starts "full", hence "dataLen - dataRate".
require.InDelta(t, elapsed.Seconds(), (dataLen-dataRate)/dataRate, 1)
}