| 352 | } |
| 353 | |
| 354 | func CreateBlock( |
| 355 | ctx context.Context, |
| 356 | rnd *rand.Rand, |
| 357 | dir string, |
| 358 | series []labels.Labels, |
| 359 | numSamples int, |
| 360 | mint, maxt int64, |
| 361 | scrapeInterval int64, |
| 362 | seriesSize int64, |
| 363 | ) (id ulid.ULID, err error) { |
| 364 | headOpts := tsdb.DefaultHeadOptions() |
| 365 | headOpts.ChunkDirRoot = filepath.Join(dir, "chunks") |
| 366 | headOpts.ChunkRange = 10000000000 |
| 367 | h, err := tsdb.NewHead(nil, nil, nil, nil, headOpts, nil) |
| 368 | if err != nil { |
| 369 | return id, errors.Wrap(err, "create head block") |
| 370 | } |
| 371 | defer func() { |
| 372 | runutil.CloseWithErrCapture(&err, h, "TSDB Head") |
| 373 | if e := os.RemoveAll(headOpts.ChunkDirRoot); e != nil { |
| 374 | err = errors.Wrap(e, "delete chunks dir") |
| 375 | } |
| 376 | }() |
| 377 | |
| 378 | app := h.Appender(ctx) |
| 379 | for i := range series { |
| 380 | |
| 381 | var ref storage.SeriesRef |
| 382 | start := RandRange(rnd, mint, maxt) |
| 383 | for j := range numSamples { |
| 384 | ref, err = app.Append(ref, series[i], start, float64(i+j)) |
| 385 | if err != nil { |
| 386 | if rerr := app.Rollback(); rerr != nil { |
| 387 | err = errors.Wrapf(err, "rollback failed: %v", rerr) |
| 388 | } |
| 389 | return id, errors.Wrap(err, "add sample") |
| 390 | } |
| 391 | start += scrapeInterval |
| 392 | if start > maxt { |
| 393 | break |
| 394 | } |
| 395 | } |
| 396 | } |
| 397 | if err := app.Commit(); err != nil { |
| 398 | return id, errors.Wrap(err, "commit") |
| 399 | } |
| 400 | |
| 401 | c, err := tsdb.NewLeveledCompactor(ctx, nil, promslog.NewNopLogger(), []int64{maxt - mint}, nil, nil) |
| 402 | if err != nil { |
| 403 | return id, errors.Wrap(err, "create compactor") |
| 404 | } |
| 405 | |
| 406 | ids, err := c.Write(dir, h, mint, maxt, nil) |
| 407 | if err != nil { |
| 408 | return id, errors.Wrap(err, "write block") |
| 409 | } |
| 410 | if len(ids) == 0 { |
| 411 | return id, errors.Errorf("nothing to write, asked for %d samples", numSamples) |