2021-02-01 00:10:16 +01:00
|
|
|
package vm
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"compress/gzip"
|
2023-02-22 13:06:55 +01:00
|
|
|
"context"
|
2021-02-01 00:10:16 +01:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2023-02-22 13:06:55 +01:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/app/vmctl/backoff"
|
2022-05-02 09:06:34 +02:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/app/vmctl/barpool"
|
2021-12-24 11:18:07 +01:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/app/vmctl/limiter"
|
2021-02-01 00:10:16 +01:00
|
|
|
"github.com/VictoriaMetrics/VictoriaMetrics/lib/decimal"
|
2022-09-21 10:08:33 +02:00
|
|
|
"github.com/cheggaaa/pb/v3"
|
2021-02-01 00:10:16 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// Config contains list of params to configure
|
|
|
|
// the Importer
|
|
|
|
type Config struct {
|
|
|
|
// VictoriaMetrics address to perform import requests
|
|
|
|
// --httpListenAddr value for single node version
|
2021-04-20 10:42:17 +02:00
|
|
|
// --httpListenAddr value of vmselect component for cluster version
|
2021-02-01 00:10:16 +01:00
|
|
|
Addr string
|
|
|
|
// Concurrency defines number of worker
|
|
|
|
// performing the import requests concurrently
|
|
|
|
Concurrency uint8
|
|
|
|
// Whether to apply gzip compression
|
|
|
|
Compress bool
|
|
|
|
// AccountID for cluster version.
|
|
|
|
// Empty value assumes it is a single node version
|
|
|
|
AccountID string
|
|
|
|
// BatchSize defines how many samples
|
|
|
|
// importer collects before sending the import request
|
|
|
|
BatchSize int
|
|
|
|
// User name for basic auth
|
|
|
|
User string
|
|
|
|
// Password for basic auth
|
|
|
|
Password string
|
|
|
|
// SignificantFigures defines the number of significant figures to leave
|
|
|
|
// in metric values before importing.
|
|
|
|
// Zero value saves all the significant decimal places
|
|
|
|
SignificantFigures int
|
2021-02-01 13:27:05 +01:00
|
|
|
// RoundDigits defines the number of decimal digits after the point that must be left
|
|
|
|
// in metric values before importing.
|
|
|
|
RoundDigits int
|
2021-02-01 00:10:16 +01:00
|
|
|
// ExtraLabels that will be added to all imported series. Must be in label=value format.
|
|
|
|
ExtraLabels []string
|
2021-12-24 11:18:07 +01:00
|
|
|
// RateLimit defines a data transfer speed in bytes per second.
|
|
|
|
// Is applied to each worker (see Concurrency) independently.
|
|
|
|
RateLimit int64
|
2022-05-02 09:06:34 +02:00
|
|
|
// Whether to disable progress bar per VM worker
|
|
|
|
DisableProgressBar bool
|
2021-02-01 00:10:16 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Importer performs insertion of timeseries
|
|
|
|
// via VictoriaMetrics import protocol
|
2021-04-20 19:16:17 +02:00
|
|
|
// see https://docs.victoriametrics.com/#how-to-import-time-series-data
|
2021-02-01 00:10:16 +01:00
|
|
|
type Importer struct {
|
|
|
|
addr string
|
|
|
|
importPath string
|
|
|
|
compress bool
|
|
|
|
user string
|
|
|
|
password string
|
|
|
|
|
|
|
|
close chan struct{}
|
|
|
|
input chan *TimeSeries
|
|
|
|
errors chan *ImportError
|
|
|
|
|
2021-12-24 11:18:07 +01:00
|
|
|
rl *limiter.Limiter
|
|
|
|
|
2021-02-01 00:10:16 +01:00
|
|
|
wg sync.WaitGroup
|
|
|
|
once sync.Once
|
|
|
|
|
2023-02-22 13:06:55 +01:00
|
|
|
s *stats
|
|
|
|
backoff *backoff.Backoff
|
2021-02-01 00:10:16 +01:00
|
|
|
}
|
|
|
|
|
2021-02-01 00:31:25 +01:00
|
|
|
// ResetStats resets im stats.
|
2021-02-01 00:10:16 +01:00
|
|
|
func (im *Importer) ResetStats() {
|
|
|
|
im.s = &stats{
|
|
|
|
startTime: time.Now(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-01 00:31:25 +01:00
|
|
|
// Stats returns im stats.
|
2021-02-01 00:10:16 +01:00
|
|
|
func (im *Importer) Stats() string {
|
|
|
|
return im.s.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddExtraLabelsToImportPath - adds extra labels query params to given url path.
|
|
|
|
func AddExtraLabelsToImportPath(path string, extraLabels []string) (string, error) {
|
|
|
|
dst := path
|
|
|
|
separator := "?"
|
|
|
|
for _, extraLabel := range extraLabels {
|
|
|
|
if !strings.Contains(extraLabel, "=") {
|
|
|
|
return path, fmt.Errorf("bad format for extra_label flag, it must be `key=value`, got: %q", extraLabel)
|
|
|
|
}
|
|
|
|
if strings.Contains(dst, "?") {
|
|
|
|
separator = "&"
|
|
|
|
}
|
|
|
|
dst += fmt.Sprintf("%sextra_label=%s", separator, extraLabel)
|
|
|
|
}
|
|
|
|
return dst, nil
|
|
|
|
}
|
|
|
|
|
2021-02-01 00:31:25 +01:00
|
|
|
// NewImporter creates new Importer for the given cfg.
|
2023-02-22 13:06:55 +01:00
|
|
|
func NewImporter(ctx context.Context, cfg Config) (*Importer, error) {
|
2021-02-01 00:10:16 +01:00
|
|
|
if cfg.Concurrency < 1 {
|
|
|
|
return nil, fmt.Errorf("concurrency can't be lower than 1")
|
|
|
|
}
|
|
|
|
|
|
|
|
addr := strings.TrimRight(cfg.Addr, "/")
|
|
|
|
// if single version
|
2021-04-20 19:16:17 +02:00
|
|
|
// see https://docs.victoriametrics.com/#how-to-import-time-series-data
|
2021-02-01 00:10:16 +01:00
|
|
|
importPath := addr + "/api/v1/import"
|
|
|
|
if cfg.AccountID != "" {
|
|
|
|
// if cluster version
|
2021-04-20 19:16:17 +02:00
|
|
|
// see https://docs.victoriametrics.com/Cluster-VictoriaMetrics.html#url-format
|
2021-02-01 00:10:16 +01:00
|
|
|
importPath = fmt.Sprintf("%s/insert/%s/prometheus/api/v1/import", addr, cfg.AccountID)
|
|
|
|
}
|
|
|
|
importPath, err := AddExtraLabelsToImportPath(importPath, cfg.ExtraLabels)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
im := &Importer{
|
|
|
|
addr: addr,
|
|
|
|
importPath: importPath,
|
|
|
|
compress: cfg.Compress,
|
|
|
|
user: cfg.User,
|
|
|
|
password: cfg.Password,
|
2021-12-24 11:18:07 +01:00
|
|
|
rl: limiter.NewLimiter(cfg.RateLimit),
|
2021-02-01 00:10:16 +01:00
|
|
|
close: make(chan struct{}),
|
|
|
|
input: make(chan *TimeSeries, cfg.Concurrency*4),
|
|
|
|
errors: make(chan *ImportError, cfg.Concurrency),
|
2023-02-22 13:06:55 +01:00
|
|
|
backoff: backoff.New(),
|
2021-02-01 00:10:16 +01:00
|
|
|
}
|
|
|
|
if err := im.Ping(); err != nil {
|
|
|
|
return nil, fmt.Errorf("ping to %q failed: %s", addr, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if cfg.BatchSize < 1 {
|
|
|
|
cfg.BatchSize = 1e5
|
|
|
|
}
|
|
|
|
|
|
|
|
im.wg.Add(int(cfg.Concurrency))
|
|
|
|
for i := 0; i < int(cfg.Concurrency); i++ {
|
2022-05-02 09:06:34 +02:00
|
|
|
var bar *pb.ProgressBar
|
|
|
|
if !cfg.DisableProgressBar {
|
|
|
|
pbPrefix := fmt.Sprintf(`{{ green "VM worker %d:" }}`, i)
|
|
|
|
bar = barpool.AddWithTemplate(pbPrefix+pbTpl, 0)
|
|
|
|
}
|
|
|
|
go func(bar *pb.ProgressBar) {
|
2021-02-01 00:10:16 +01:00
|
|
|
defer im.wg.Done()
|
2023-02-22 13:06:55 +01:00
|
|
|
im.startWorker(ctx, bar, cfg.BatchSize, cfg.SignificantFigures, cfg.RoundDigits)
|
2022-05-02 09:06:34 +02:00
|
|
|
}(bar)
|
2021-02-01 00:10:16 +01:00
|
|
|
}
|
|
|
|
im.ResetStats()
|
|
|
|
return im, nil
|
|
|
|
}
|
|
|
|
|
2022-05-02 09:06:34 +02:00
|
|
|
const pbTpl = `{{ (cycle . "←" "↖" "↑" "↗" "→" "↘" "↓" "↙" ) }} {{speed . "%s samples/s"}}`
|
|
|
|
|
2021-02-01 00:10:16 +01:00
|
|
|
// ImportError is type of error generated
|
|
|
|
// in case of unsuccessful import request
|
|
|
|
type ImportError struct {
|
2022-01-03 20:12:01 +01:00
|
|
|
// The batch of timeseries processed by importer at the moment
|
2021-02-01 00:10:16 +01:00
|
|
|
Batch []*TimeSeries
|
|
|
|
// The error that appeared during insert
|
2022-01-03 20:12:01 +01:00
|
|
|
// If err is nil - no error happened and Batch
|
|
|
|
// Is the latest delivered Batch.
|
2021-02-01 00:10:16 +01:00
|
|
|
Err error
|
|
|
|
}
|
|
|
|
|
|
|
|
// Errors returns a channel for receiving
|
|
|
|
// import errors if any
|
|
|
|
func (im *Importer) Errors() chan *ImportError { return im.errors }
|
|
|
|
|
|
|
|
// Input returns a channel for sending timeseries
|
|
|
|
// that need to be imported
|
2022-05-03 07:03:41 +02:00
|
|
|
func (im *Importer) Input(ts *TimeSeries) error {
|
|
|
|
select {
|
2022-11-29 22:53:28 +01:00
|
|
|
case <-im.close:
|
|
|
|
return fmt.Errorf("importer is closed")
|
2022-05-03 07:03:41 +02:00
|
|
|
case im.input <- ts:
|
|
|
|
return nil
|
|
|
|
case err := <-im.errors:
|
|
|
|
if err != nil && err.Err != nil {
|
|
|
|
return err.Err
|
|
|
|
}
|
|
|
|
return fmt.Errorf("process aborted")
|
|
|
|
}
|
|
|
|
}
|
2021-02-01 00:10:16 +01:00
|
|
|
|
|
|
|
// Close sends signal to all goroutines to exit
|
|
|
|
// and waits until they are finished
|
|
|
|
func (im *Importer) Close() {
|
|
|
|
im.once.Do(func() {
|
|
|
|
close(im.close)
|
2022-11-29 22:53:28 +01:00
|
|
|
close(im.input)
|
2021-02-01 00:10:16 +01:00
|
|
|
im.wg.Wait()
|
|
|
|
close(im.errors)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-02-22 13:06:55 +01:00
|
|
|
func (im *Importer) startWorker(ctx context.Context, bar *pb.ProgressBar, batchSize, significantFigures, roundDigits int) {
|
2021-02-01 00:10:16 +01:00
|
|
|
var batch []*TimeSeries
|
|
|
|
var dataPoints int
|
|
|
|
var waitForBatch time.Time
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-im.close:
|
2022-11-29 22:53:28 +01:00
|
|
|
for ts := range im.input {
|
|
|
|
ts = roundTimeseriesValue(ts, significantFigures, roundDigits)
|
|
|
|
batch = append(batch, ts)
|
|
|
|
}
|
2022-01-03 20:12:01 +01:00
|
|
|
exitErr := &ImportError{
|
|
|
|
Batch: batch,
|
|
|
|
}
|
2023-02-22 13:06:55 +01:00
|
|
|
retryableFunc := func() error { return im.Import(batch) }
|
|
|
|
_, err := im.backoff.Retry(ctx, retryableFunc)
|
|
|
|
if err != nil {
|
2022-01-03 20:12:01 +01:00
|
|
|
exitErr.Err = err
|
2021-02-01 00:10:16 +01:00
|
|
|
}
|
2022-01-03 20:12:01 +01:00
|
|
|
im.errors <- exitErr
|
2021-02-01 00:10:16 +01:00
|
|
|
return
|
2022-11-29 22:53:28 +01:00
|
|
|
case ts, ok := <-im.input:
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
2021-02-01 00:10:16 +01:00
|
|
|
// init waitForBatch when first
|
|
|
|
// value was received
|
|
|
|
if waitForBatch.IsZero() {
|
|
|
|
waitForBatch = time.Now()
|
|
|
|
}
|
|
|
|
|
2022-11-29 22:53:28 +01:00
|
|
|
ts = roundTimeseriesValue(ts, significantFigures, roundDigits)
|
2021-02-01 00:10:16 +01:00
|
|
|
batch = append(batch, ts)
|
|
|
|
dataPoints += len(ts.Values)
|
2022-05-02 09:06:34 +02:00
|
|
|
|
|
|
|
if bar != nil {
|
|
|
|
bar.Add(len(ts.Values))
|
|
|
|
}
|
|
|
|
|
2021-02-01 00:10:16 +01:00
|
|
|
if dataPoints < batchSize {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
im.s.Lock()
|
|
|
|
im.s.idleDuration += time.Since(waitForBatch)
|
|
|
|
im.s.Unlock()
|
|
|
|
|
2023-02-22 13:06:55 +01:00
|
|
|
if err := im.flush(ctx, batch); err != nil {
|
2021-02-01 00:10:16 +01:00
|
|
|
im.errors <- &ImportError{
|
|
|
|
Batch: batch,
|
|
|
|
Err: err,
|
|
|
|
}
|
|
|
|
// make a new batch, since old one was referenced as err
|
|
|
|
batch = make([]*TimeSeries, len(batch))
|
|
|
|
}
|
|
|
|
dataPoints = 0
|
2022-05-02 09:06:34 +02:00
|
|
|
batch = batch[:0]
|
2021-02-01 00:10:16 +01:00
|
|
|
waitForBatch = time.Now()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-22 13:06:55 +01:00
|
|
|
func (im *Importer) flush(ctx context.Context, b []*TimeSeries) error {
|
|
|
|
retryableFunc := func() error { return im.Import(b) }
|
|
|
|
attempts, err := im.backoff.Retry(ctx, retryableFunc)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("import failed with %d retries: %s", attempts, err)
|
2021-02-01 00:10:16 +01:00
|
|
|
}
|
2023-02-22 13:06:55 +01:00
|
|
|
im.s.Lock()
|
|
|
|
im.s.retries = attempts
|
|
|
|
im.s.Unlock()
|
|
|
|
return nil
|
2021-02-01 00:10:16 +01:00
|
|
|
}
|
|
|
|
|
2021-02-01 00:31:25 +01:00
|
|
|
// Ping sends a ping to im.addr.
|
2021-02-01 00:10:16 +01:00
|
|
|
func (im *Importer) Ping() error {
|
|
|
|
url := fmt.Sprintf("%s/health", im.addr)
|
2023-02-23 03:53:05 +01:00
|
|
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
2021-02-01 00:10:16 +01:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot create request to %q: %s", im.addr, err)
|
|
|
|
}
|
|
|
|
if im.user != "" {
|
|
|
|
req.SetBasicAuth(im.user, im.password)
|
|
|
|
}
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
|
|
return fmt.Errorf("bad status code: %d", resp.StatusCode)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-01 00:31:25 +01:00
|
|
|
// Import imports tsBatch.
|
2021-02-01 00:10:16 +01:00
|
|
|
func (im *Importer) Import(tsBatch []*TimeSeries) error {
|
|
|
|
if len(tsBatch) < 1 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
pr, pw := io.Pipe()
|
2023-02-23 03:53:05 +01:00
|
|
|
req, err := http.NewRequest(http.MethodPost, im.importPath, pr)
|
2021-02-01 00:10:16 +01:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cannot create request to %q: %s", im.addr, err)
|
|
|
|
}
|
|
|
|
if im.user != "" {
|
|
|
|
req.SetBasicAuth(im.user, im.password)
|
|
|
|
}
|
|
|
|
if im.compress {
|
|
|
|
req.Header.Set("Content-Encoding", "gzip")
|
|
|
|
}
|
|
|
|
|
|
|
|
errCh := make(chan error)
|
|
|
|
go func() {
|
|
|
|
errCh <- do(req)
|
|
|
|
close(errCh)
|
|
|
|
}()
|
|
|
|
|
|
|
|
w := io.Writer(pw)
|
|
|
|
if im.compress {
|
2021-12-24 11:18:07 +01:00
|
|
|
zw, err := gzip.NewWriterLevel(w, 1)
|
2021-02-01 00:10:16 +01:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unexpected error when creating gzip writer: %s", err)
|
|
|
|
}
|
|
|
|
w = zw
|
|
|
|
}
|
2021-12-24 11:18:07 +01:00
|
|
|
w = limiter.NewWriteLimiter(w, im.rl)
|
2021-02-01 00:10:16 +01:00
|
|
|
bw := bufio.NewWriterSize(w, 16*1024)
|
|
|
|
|
|
|
|
var totalSamples, totalBytes int
|
|
|
|
for _, ts := range tsBatch {
|
|
|
|
n, err := ts.write(bw)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("write err: %w", err)
|
|
|
|
}
|
|
|
|
totalBytes += n
|
|
|
|
totalSamples += len(ts.Values)
|
|
|
|
}
|
|
|
|
if err := bw.Flush(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-12-24 11:18:07 +01:00
|
|
|
if closer, ok := w.(io.Closer); ok {
|
|
|
|
err := closer.Close()
|
2021-02-01 00:10:16 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := pw.Close(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
requestErr := <-errCh
|
|
|
|
if requestErr != nil {
|
|
|
|
return fmt.Errorf("import request error for %q: %w", im.addr, requestErr)
|
|
|
|
}
|
|
|
|
|
|
|
|
im.s.Lock()
|
|
|
|
im.s.bytes += uint64(totalBytes)
|
|
|
|
im.s.samples += uint64(totalSamples)
|
|
|
|
im.s.requests++
|
|
|
|
im.s.Unlock()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-02-01 00:31:25 +01:00
|
|
|
// ErrBadRequest represents bad request error.
|
2021-02-01 00:10:16 +01:00
|
|
|
var ErrBadRequest = errors.New("bad request")
|
|
|
|
|
|
|
|
func do(req *http.Request) error {
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unexpected error when performing request: %s", err)
|
|
|
|
}
|
2021-02-01 00:31:25 +01:00
|
|
|
defer func() {
|
|
|
|
_ = resp.Body.Close()
|
|
|
|
}()
|
2021-02-01 00:10:16 +01:00
|
|
|
if resp.StatusCode != http.StatusNoContent {
|
2022-08-21 23:13:44 +02:00
|
|
|
body, err := io.ReadAll(resp.Body)
|
2021-02-01 00:10:16 +01:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to read response body for status code %d: %s", resp.StatusCode, err)
|
|
|
|
}
|
|
|
|
if resp.StatusCode == http.StatusBadRequest {
|
|
|
|
return fmt.Errorf("%w: unexpected response code %d: %s", ErrBadRequest, resp.StatusCode, string(body))
|
|
|
|
}
|
|
|
|
return fmt.Errorf("unexpected response code %d: %s", resp.StatusCode, string(body))
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func byteCountSI(b int64) string {
|
|
|
|
const unit = 1000
|
|
|
|
if b < unit {
|
|
|
|
return fmt.Sprintf("%d B", b)
|
|
|
|
}
|
|
|
|
div, exp := int64(unit), 0
|
|
|
|
for n := b / unit; n >= unit; n /= unit {
|
|
|
|
div *= unit
|
|
|
|
exp++
|
|
|
|
}
|
|
|
|
return fmt.Sprintf("%.1f %cB",
|
|
|
|
float64(b)/float64(div), "kMGTPE"[exp])
|
|
|
|
}
|
2022-11-29 22:53:28 +01:00
|
|
|
|
|
|
|
func roundTimeseriesValue(ts *TimeSeries, significantFigures, roundDigits int) *TimeSeries {
|
|
|
|
if significantFigures > 0 {
|
|
|
|
for i, v := range ts.Values {
|
|
|
|
ts.Values[i] = decimal.RoundToSignificantFigures(v, significantFigures)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if roundDigits < 100 {
|
|
|
|
for i, v := range ts.Values {
|
|
|
|
ts.Values[i] = decimal.RoundToDecimalDigits(v, roundDigits)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return ts
|
|
|
|
}
|