-
Notifications
You must be signed in to change notification settings - Fork 482
/
relabel.go
308 lines (266 loc) · 9.03 KB
/
relabel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package relabel
import (
"context"
"fmt"
"sync"
"go.uber.org/atomic"
"github.com/prometheus/prometheus/storage"
"github.com/grafana/agent/component"
flow_relabel "github.com/grafana/agent/component/common/relabel"
"github.com/grafana/agent/component/prometheus"
"github.com/grafana/agent/service/labelstore"
lru "github.com/hashicorp/golang-lru/v2"
prometheus_client "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/prometheus/model/exemplar"
"github.com/prometheus/prometheus/model/histogram"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/metadata"
"github.com/prometheus/prometheus/model/relabel"
"github.com/prometheus/prometheus/model/value"
)
func init() {
component.Register(component.Registration{
Name: "prometheus.relabel",
Args: Arguments{},
Exports: Exports{},
Build: func(opts component.Options, args component.Arguments) (component.Component, error) {
return New(opts, args.(Arguments))
},
})
}
// Arguments holds values which are used to configure the prometheus.relabel
// component.
type Arguments struct {
// Where the relabelled metrics should be forwarded to.
ForwardTo []storage.Appendable `river:"forward_to,attr"`
// The relabelling rules to apply to each metric before it's forwarded.
MetricRelabelConfigs []*flow_relabel.Config `river:"rule,block,optional"`
// Cache size to use for LRU cache.
CacheSize int `river:"max_cache_size,attr,optional"`
}
// SetToDefault implements river.Defaulter.
func (arg *Arguments) SetToDefault() {
*arg = Arguments{
CacheSize: 100_000,
}
}
// Validate implements river.Validator.
func (arg *Arguments) Validate() error {
if arg.CacheSize <= 0 {
return fmt.Errorf("max_cache_size must be greater than 0 and is %d", arg.CacheSize)
}
return nil
}
// Exports holds values which are exported by the prometheus.relabel component.
type Exports struct {
Receiver storage.Appendable `river:"receiver,attr"`
Rules flow_relabel.Rules `river:"rules,attr"`
}
// Component implements the prometheus.relabel component.
type Component struct {
mut sync.RWMutex
opts component.Options
mrc []*relabel.Config
receiver *prometheus.Interceptor
metricsProcessed prometheus_client.Counter
metricsOutgoing prometheus_client.Counter
cacheHits prometheus_client.Counter
cacheMisses prometheus_client.Counter
cacheSize prometheus_client.Gauge
cacheDeletes prometheus_client.Counter
fanout *prometheus.Fanout
exited atomic.Bool
ls labelstore.LabelStore
cacheMut sync.RWMutex
cache *lru.Cache[uint64, *labelAndID]
}
var (
_ component.Component = (*Component)(nil)
)
// New creates a new prometheus.relabel component.
func New(o component.Options, args Arguments) (*Component, error) {
cache, err := lru.New[uint64, *labelAndID](args.CacheSize)
if err != nil {
return nil, err
}
data, err := o.GetServiceData(labelstore.ServiceName)
if err != nil {
return nil, err
}
c := &Component{
opts: o,
cache: cache,
ls: data.(labelstore.LabelStore),
}
c.metricsProcessed = prometheus_client.NewCounter(prometheus_client.CounterOpts{
Name: "agent_prometheus_relabel_metrics_processed",
Help: "Total number of metrics processed",
})
c.metricsOutgoing = prometheus_client.NewCounter(prometheus_client.CounterOpts{
Name: "agent_prometheus_relabel_metrics_written",
Help: "Total number of metrics written",
})
c.cacheMisses = prometheus_client.NewCounter(prometheus_client.CounterOpts{
Name: "agent_prometheus_relabel_cache_misses",
Help: "Total number of cache misses",
})
c.cacheHits = prometheus_client.NewCounter(prometheus_client.CounterOpts{
Name: "agent_prometheus_relabel_cache_hits",
Help: "Total number of cache hits",
})
c.cacheSize = prometheus_client.NewGauge(prometheus_client.GaugeOpts{
Name: "agent_prometheus_relabel_cache_size",
Help: "Total size of relabel cache",
})
c.cacheDeletes = prometheus_client.NewCounter(prometheus_client.CounterOpts{
Name: "agent_prometheus_relabel_cache_deletes",
Help: "Total number of cache deletes",
})
for _, metric := range []prometheus_client.Collector{c.metricsProcessed, c.metricsOutgoing, c.cacheMisses, c.cacheHits, c.cacheSize, c.cacheDeletes} {
err = o.Registerer.Register(metric)
if err != nil {
return nil, err
}
}
c.fanout = prometheus.NewFanout(args.ForwardTo, o.ID, o.Registerer, c.ls)
c.receiver = prometheus.NewInterceptor(
c.fanout,
c.ls,
prometheus.WithAppendHook(func(_ storage.SeriesRef, l labels.Labels, t int64, v float64, next storage.Appender) (storage.SeriesRef, error) {
if c.exited.Load() {
return 0, fmt.Errorf("%s has exited", o.ID)
}
newLbl := c.relabel(v, l)
if newLbl.IsEmpty() {
return 0, nil
}
c.metricsOutgoing.Inc()
return next.Append(0, newLbl, t, v)
}),
prometheus.WithExemplarHook(func(_ storage.SeriesRef, l labels.Labels, e exemplar.Exemplar, next storage.Appender) (storage.SeriesRef, error) {
if c.exited.Load() {
return 0, fmt.Errorf("%s has exited", o.ID)
}
newLbl := c.relabel(0, l)
if newLbl.IsEmpty() {
return 0, nil
}
return next.AppendExemplar(0, newLbl, e)
}),
prometheus.WithMetadataHook(func(_ storage.SeriesRef, l labels.Labels, m metadata.Metadata, next storage.Appender) (storage.SeriesRef, error) {
if c.exited.Load() {
return 0, fmt.Errorf("%s has exited", o.ID)
}
newLbl := c.relabel(0, l)
if newLbl.IsEmpty() {
return 0, nil
}
return next.UpdateMetadata(0, newLbl, m)
}),
prometheus.WithHistogramHook(func(_ storage.SeriesRef, l labels.Labels, t int64, h *histogram.Histogram, fh *histogram.FloatHistogram, next storage.Appender) (storage.SeriesRef, error) {
if c.exited.Load() {
return 0, fmt.Errorf("%s has exited", o.ID)
}
newLbl := c.relabel(0, l)
if newLbl.IsEmpty() {
return 0, nil
}
return next.AppendHistogram(0, newLbl, t, h, fh)
}),
)
// Immediately export the receiver which remains the same for the component
// lifetime.
o.OnStateChange(Exports{Receiver: c.receiver, Rules: args.MetricRelabelConfigs})
// Call to Update() to set the relabelling rules once at the start.
if err = c.Update(args); err != nil {
return nil, err
}
return c, nil
}
// Run implements component.Component.
func (c *Component) Run(ctx context.Context) error {
defer c.exited.Store(true)
<-ctx.Done()
return nil
}
// Update implements component.Component.
func (c *Component) Update(args component.Arguments) error {
c.mut.Lock()
defer c.mut.Unlock()
newArgs := args.(Arguments)
c.clearCache(newArgs.CacheSize)
c.mrc = flow_relabel.ComponentToPromRelabelConfigs(newArgs.MetricRelabelConfigs)
c.fanout.UpdateChildren(newArgs.ForwardTo)
c.opts.OnStateChange(Exports{Receiver: c.receiver, Rules: newArgs.MetricRelabelConfigs})
return nil
}
func (c *Component) relabel(val float64, lbls labels.Labels) labels.Labels {
c.mut.RLock()
defer c.mut.RUnlock()
globalRef := c.ls.GetOrAddGlobalRefID(lbls)
var (
relabelled labels.Labels
keep bool
)
newLbls, found := c.getFromCache(globalRef)
if found {
c.cacheHits.Inc()
// If newLbls is nil but cache entry was found then we want to keep the value nil, if it's not we want to reuse the labels
if newLbls != nil {
relabelled = newLbls.labels
}
} else {
// Relabel against a copy of the labels to prevent modifying the original
// slice.
relabelled, keep = relabel.Process(lbls.Copy(), c.mrc...)
c.cacheMisses.Inc()
c.addToCache(globalRef, relabelled, keep)
}
// If stale remove from the cache, the reason we don't exit early is so the stale value can propagate.
// TODO: (@mattdurham) This caching can leak and likely needs a timed eviction at some point, but this is simple.
// In the future the global ref cache may have some hooks to allow notification of when caches should be evicted.
if value.IsStaleNaN(val) {
c.deleteFromCache(globalRef)
}
// Set the cache size to the cache.len
// TODO(@mattdurham): Instead of setting this each time could collect on demand for better performance.
c.cacheSize.Set(float64(c.cache.Len()))
return relabelled
}
func (c *Component) getFromCache(id uint64) (*labelAndID, bool) {
c.cacheMut.RLock()
defer c.cacheMut.RUnlock()
fm, found := c.cache.Get(id)
return fm, found
}
func (c *Component) deleteFromCache(id uint64) {
c.cacheMut.Lock()
defer c.cacheMut.Unlock()
c.cacheDeletes.Inc()
c.cache.Remove(id)
}
func (c *Component) clearCache(cacheSize int) {
c.cacheMut.Lock()
defer c.cacheMut.Unlock()
cache, _ := lru.New[uint64, *labelAndID](cacheSize)
c.cache = cache
}
func (c *Component) addToCache(originalID uint64, lbls labels.Labels, keep bool) {
c.cacheMut.Lock()
defer c.cacheMut.Unlock()
if !keep {
c.cache.Add(originalID, nil)
return
}
newGlobal := c.ls.GetOrAddGlobalRefID(lbls)
c.cache.Add(originalID, &labelAndID{
labels: lbls,
id: newGlobal,
})
}
// labelAndID stores both the globalrefid for the label and the id itself. We store the id so that it doesn't have
// to be recalculated again.
type labelAndID struct {
labels labels.Labels
id uint64
}