lib/httpserver: cache /metrics output for a second

This should reduce CPU load when `/metrics` output is scraped with a frequency exceeding a request per second
This commit is contained in:
Aliaksandr Valialkin 2021-02-16 14:54:34 +02:00
parent 7869d38043
commit 18305caadb

View file

@ -6,9 +6,12 @@ import (
"io"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/buildinfo"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/bytesutil"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/flagutil"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/memory"
"github.com/VictoriaMetrics/metrics"
@ -18,6 +21,27 @@ var versionRe = regexp.MustCompile(`v\d+\.\d+\.\d+`)
// WritePrometheusMetrics writes all the registered metrics to w in Prometheus exposition format.
func WritePrometheusMetrics(w io.Writer) {
currentTime := time.Now()
metricsCacheLock.Lock()
if currentTime.Sub(metricsCacheLastUpdateTime) > time.Second {
var bb bytesutil.ByteBuffer
writePrometheusMetrics(&bb)
metricsCache.Store(&bb)
metricsCacheLastUpdateTime = currentTime
}
metricsCacheLock.Unlock()
bb := metricsCache.Load().(*bytesutil.ByteBuffer)
w.Write(bb.B)
}
var (
metricsCacheLock sync.Mutex
metricsCacheLastUpdateTime time.Time
metricsCache atomic.Value
)
func writePrometheusMetrics(w io.Writer) {
metrics.WritePrometheus(w, true)
metrics.WriteFDMetrics(w)