2022-07-21 16:49:52 +00:00
package pushmetrics
import (
2024-01-15 11:37:02 +00:00
"context"
2022-07-21 16:49:52 +00:00
"flag"
"strings"
2024-01-15 11:37:02 +00:00
"sync"
2022-07-21 16:49:52 +00:00
"time"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/appmetrics"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/flagutil"
2022-07-22 10:35:58 +00:00
"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
2022-07-21 16:49:52 +00:00
"github.com/VictoriaMetrics/metrics"
)
var (
2022-10-01 15:26:05 +00:00
pushURL = flagutil . NewArrayString ( "pushmetrics.url" , "Optional URL to push metrics exposed at /metrics page. See https://docs.victoriametrics.com/#push-metrics . " +
2023-05-10 07:50:41 +00:00
"By default, metrics exposed at /metrics page aren't pushed to any remote storage" )
2022-07-26 17:40:19 +00:00
pushInterval = flag . Duration ( "pushmetrics.interval" , 10 * time . Second , "Interval for pushing metrics to -pushmetrics.url" )
2022-10-01 15:26:05 +00:00
pushExtraLabel = flagutil . NewArrayString ( "pushmetrics.extraLabel" , "Optional labels to add to metrics pushed to -pushmetrics.url . " +
2022-07-26 16:24:24 +00:00
` For example, -pushmetrics.extraLabel='instance="foo"' adds instance="foo" label to all the metrics pushed to -pushmetrics.url ` )
2022-07-21 16:49:52 +00:00
)
func init ( ) {
// The -pushmetrics.url flag can contain basic auth creds, so it mustn't be visible when exposing the flags.
flagutil . RegisterSecretFlag ( "pushmetrics.url" )
}
2024-01-09 12:01:03 +00:00
var (
2024-01-09 12:17:09 +00:00
pushCtx , cancelPushCtx = context . WithCancel ( context . Background ( ) )
2024-01-15 11:37:02 +00:00
wgDone sync . WaitGroup
2024-01-09 12:01:03 +00:00
)
2022-07-22 10:35:58 +00:00
// Init must be called after logger.Init
2022-07-21 16:49:52 +00:00
func Init ( ) {
2022-07-26 16:24:24 +00:00
extraLabels := strings . Join ( * pushExtraLabel , "," )
2022-07-21 16:49:52 +00:00
for _ , pu := range * pushURL {
2024-01-09 12:01:03 +00:00
opts := & metrics . PushOptions {
ExtraLabels : extraLabels ,
2024-01-15 11:37:02 +00:00
WaitGroup : & wgDone ,
2024-01-09 12:01:03 +00:00
}
2024-01-09 12:17:09 +00:00
if err := metrics . InitPushExtWithOptions ( pushCtx , pu , * pushInterval , appmetrics . WritePrometheusMetrics , opts ) ; err != nil {
2022-07-22 10:35:58 +00:00
logger . Fatalf ( "cannot initialize pushmetrics: %s" , err )
}
2022-07-21 16:49:52 +00:00
}
}
2024-01-09 12:01:03 +00:00
2024-01-09 12:17:09 +00:00
// Stop stops the periodic push of metrics.
// It is important to stop the push of metrics before disposing resources
// these metrics attached to. See related https://github.com/VictoriaMetrics/VictoriaMetrics/issues/5548
//
// Stop must be called after Init.
func Stop ( ) {
cancelPushCtx ( )
2024-01-15 11:37:02 +00:00
wgDone . Wait ( )
2024-01-09 12:01:03 +00:00
}