Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/component/loki/process/internal/metric/histograms.go
4096 views
1
package metric
2
3
import (
4
"fmt"
5
"time"
6
7
"github.com/prometheus/client_golang/prometheus"
8
"github.com/prometheus/common/model"
9
)
10
11
// DefaultHistogramConfig sets the defaults for a Histogram.
12
var DefaultHistogramConfig = HistogramConfig{
13
MaxIdle: 5 * time.Minute,
14
}
15
16
// HistogramConfig defines a histogram metric whose values are bucketed.
17
type HistogramConfig struct {
18
// Shared fields
19
Name string `river:"name,attr"`
20
Description string `river:"description,attr,optional"`
21
Source string `river:"source,attr,optional"`
22
Prefix string `river:"prefix,attr,optional"`
23
MaxIdle time.Duration `river:"max_idle_duration,attr,optional"`
24
Value string `river:"value,attr,optional"`
25
26
// Histogram-specific fields
27
Buckets []float64 `river:"buckets,attr"`
28
}
29
30
// UnmarshalRiver implements the unmarshaller
31
func (h *HistogramConfig) UnmarshalRiver(f func(v interface{}) error) error {
32
*h = DefaultHistogramConfig
33
type histogram HistogramConfig
34
err := f((*histogram)(h))
35
if err != nil {
36
return err
37
}
38
39
if h.MaxIdle < 1*time.Second {
40
return fmt.Errorf("max_idle_duration must be greater or equal than 1s")
41
}
42
43
if h.Source == "" {
44
h.Source = h.Name
45
}
46
return nil
47
}
48
49
// Histograms is a vector of histograms for a log stream.
50
type Histograms struct {
51
*metricVec
52
Cfg *HistogramConfig
53
}
54
55
// NewHistograms creates a new histogram vec.
56
func NewHistograms(name string, config *HistogramConfig) (*Histograms, error) {
57
return &Histograms{
58
metricVec: newMetricVec(func(labels map[string]string) prometheus.Metric {
59
return &expiringHistogram{prometheus.NewHistogram(prometheus.HistogramOpts{
60
Help: config.Description,
61
Name: name,
62
ConstLabels: labels,
63
Buckets: config.Buckets,
64
}),
65
0,
66
}
67
}, int64(config.MaxIdle.Seconds())),
68
Cfg: config,
69
}, nil
70
}
71
72
// With returns the histogram associated with a stream labelset.
73
func (h *Histograms) With(labels model.LabelSet) prometheus.Histogram {
74
return h.metricVec.With(labels).(prometheus.Histogram)
75
}
76
77
type expiringHistogram struct {
78
prometheus.Histogram
79
lastModSec int64
80
}
81
82
// Observe adds a single observation to the histogram.
83
func (h *expiringHistogram) Observe(val float64) {
84
h.Histogram.Observe(val)
85
h.lastModSec = time.Now().Unix()
86
}
87
88
// HasExpired implements Expirable
89
func (h *expiringHistogram) HasExpired(currentTimeSec int64, maxAgeSec int64) bool {
90
return currentTimeSec-h.lastModSec >= maxAgeSec
91
}
92
93