Path: blob/main/component/loki/process/internal/metric/histograms.go
4096 views
package metric12import (3"fmt"4"time"56"github.com/prometheus/client_golang/prometheus"7"github.com/prometheus/common/model"8)910// DefaultHistogramConfig sets the defaults for a Histogram.11var DefaultHistogramConfig = HistogramConfig{12MaxIdle: 5 * time.Minute,13}1415// HistogramConfig defines a histogram metric whose values are bucketed.16type HistogramConfig struct {17// Shared fields18Name string `river:"name,attr"`19Description string `river:"description,attr,optional"`20Source string `river:"source,attr,optional"`21Prefix string `river:"prefix,attr,optional"`22MaxIdle time.Duration `river:"max_idle_duration,attr,optional"`23Value string `river:"value,attr,optional"`2425// Histogram-specific fields26Buckets []float64 `river:"buckets,attr"`27}2829// UnmarshalRiver implements the unmarshaller30func (h *HistogramConfig) UnmarshalRiver(f func(v interface{}) error) error {31*h = DefaultHistogramConfig32type histogram HistogramConfig33err := f((*histogram)(h))34if err != nil {35return err36}3738if h.MaxIdle < 1*time.Second {39return fmt.Errorf("max_idle_duration must be greater or equal than 1s")40}4142if h.Source == "" {43h.Source = h.Name44}45return nil46}4748// Histograms is a vector of histograms for a log stream.49type Histograms struct {50*metricVec51Cfg *HistogramConfig52}5354// NewHistograms creates a new histogram vec.55func NewHistograms(name string, config *HistogramConfig) (*Histograms, error) {56return &Histograms{57metricVec: newMetricVec(func(labels map[string]string) prometheus.Metric {58return &expiringHistogram{prometheus.NewHistogram(prometheus.HistogramOpts{59Help: config.Description,60Name: name,61ConstLabels: labels,62Buckets: config.Buckets,63}),640,65}66}, int64(config.MaxIdle.Seconds())),67Cfg: config,68}, nil69}7071// With returns the histogram associated with a stream labelset.72func (h *Histograms) With(labels model.LabelSet) prometheus.Histogram {73return h.metricVec.With(labels).(prometheus.Histogram)74}7576type expiringHistogram struct {77prometheus.Histogram78lastModSec int6479}8081// Observe adds a single observation to the histogram.82func (h *expiringHistogram) Observe(val float64) {83h.Histogram.Observe(val)84h.lastModSec = time.Now().Unix()85}8687// HasExpired implements Expirable88func (h *expiringHistogram) HasExpired(currentTimeSec int64, maxAgeSec int64) bool {89return currentTimeSec-h.lastModSec >= maxAgeSec90}919293