-
Notifications
You must be signed in to change notification settings - Fork 485
/
scrape.go
391 lines (335 loc) · 11.5 KB
/
scrape.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package scrape
import (
"context"
"fmt"
"net/url"
"sync"
"time"
"github.com/go-kit/log/level"
"github.com/grafana/agent/component/pyroscope"
"github.com/grafana/agent/service/cluster"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/discovery/targetgroup"
"github.com/grafana/agent/component"
component_config "github.com/grafana/agent/component/common/config"
"github.com/grafana/agent/component/discovery"
"github.com/grafana/agent/component/prometheus/scrape"
)
const (
pprofMemory string = "memory"
pprofBlock string = "block"
pprofGoroutine string = "goroutine"
pprofMutex string = "mutex"
pprofProcessCPU string = "process_cpu"
pprofFgprof string = "fgprof"
pprofGoDeltaProfMemory string = "godeltaprof_memory"
pprofGoDeltaProfBlock string = "godeltaprof_block"
pprofGoDeltaProfMutex string = "godeltaprof_mutex"
)
func init() {
component.Register(component.Registration{
Name: "pyroscope.scrape",
Args: Arguments{},
NeedsServices: []string{cluster.ServiceName},
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 pprof.scrape
// component.
type Arguments struct {
Targets []discovery.Target `river:"targets,attr"`
ForwardTo []pyroscope.Appendable `river:"forward_to,attr"`
// The job name to override the job label with.
JobName string `river:"job_name,attr,optional"`
// A set of query parameters with which the target is scraped.
Params url.Values `river:"params,attr,optional"`
// How frequently to scrape the targets of this scrape config.
ScrapeInterval time.Duration `river:"scrape_interval,attr,optional"`
// The timeout for scraping targets of this config.
ScrapeTimeout time.Duration `river:"scrape_timeout,attr,optional"`
// The URL scheme with which to fetch metrics from targets.
Scheme string `river:"scheme,attr,optional"`
// todo(ctovena): add support for limits.
// // An uncompressed response body larger than this many bytes will cause the
// // scrape to fail. 0 means no limit.
// BodySizeLimit units.Base2Bytes `river:"body_size_limit,attr,optional"`
// // More than this many targets after the target relabeling will cause the
// // scrapes to fail.
// TargetLimit uint `river:"target_limit,attr,optional"`
// // More than this many labels post metric-relabeling will cause the scrape
// // to fail.
// LabelLimit uint `river:"label_limit,attr,optional"`
// // More than this label name length post metric-relabeling will cause the
// // scrape to fail.
// LabelNameLengthLimit uint `river:"label_name_length_limit,attr,optional"`
// // More than this label value length post metric-relabeling will cause the
// // scrape to fail.
// LabelValueLengthLimit uint `river:"label_value_length_limit,attr,optional"`
HTTPClientConfig component_config.HTTPClientConfig `river:",squash"`
ProfilingConfig ProfilingConfig `river:"profiling_config,block,optional"`
Clustering scrape.Clustering `river:"clustering,block,optional"`
}
type ProfilingConfig struct {
Memory ProfilingTarget `river:"profile.memory,block,optional"`
Block ProfilingTarget `river:"profile.block,block,optional"`
Goroutine ProfilingTarget `river:"profile.goroutine,block,optional"`
Mutex ProfilingTarget `river:"profile.mutex,block,optional"`
ProcessCPU ProfilingTarget `river:"profile.process_cpu,block,optional"`
FGProf ProfilingTarget `river:"profile.fgprof,block,optional"`
GoDeltaProfMemory ProfilingTarget `river:"profile.godeltaprof_memory,block,optional"`
GoDeltaProfMutex ProfilingTarget `river:"profile.godeltaprof_mutex,block,optional"`
GoDeltaProfBlock ProfilingTarget `river:"profile.godeltaprof_block,block,optional"`
Custom []CustomProfilingTarget `river:"profile.custom,block,optional"`
PprofPrefix string `river:"path_prefix,attr,optional"`
}
// AllTargets returns the set of all standard and custom profiling targets,
// regardless of whether they're enabled. The key in the map indicates the name
// of the target.
func (cfg ProfilingConfig) AllTargets() map[string]ProfilingTarget {
targets := map[string]ProfilingTarget{
pprofMemory: cfg.Memory,
pprofBlock: cfg.Block,
pprofGoroutine: cfg.Goroutine,
pprofMutex: cfg.Mutex,
pprofProcessCPU: cfg.ProcessCPU,
pprofFgprof: cfg.FGProf,
pprofGoDeltaProfMemory: cfg.GoDeltaProfMemory,
pprofGoDeltaProfMutex: cfg.GoDeltaProfMutex,
pprofGoDeltaProfBlock: cfg.GoDeltaProfBlock,
}
for _, custom := range cfg.Custom {
targets[custom.Name] = ProfilingTarget{
Enabled: custom.Enabled,
Path: custom.Path,
Delta: custom.Delta,
}
}
return targets
}
var DefaultProfilingConfig = ProfilingConfig{
Memory: ProfilingTarget{
Enabled: true,
Path: "/debug/pprof/allocs",
},
Block: ProfilingTarget{
Enabled: true,
Path: "/debug/pprof/block",
},
Goroutine: ProfilingTarget{
Enabled: true,
Path: "/debug/pprof/goroutine",
},
Mutex: ProfilingTarget{
Enabled: true,
Path: "/debug/pprof/mutex",
},
ProcessCPU: ProfilingTarget{
Enabled: true,
Path: "/debug/pprof/profile",
Delta: true,
},
FGProf: ProfilingTarget{
Enabled: false,
Path: "/debug/fgprof",
Delta: true,
},
// https://github.com/grafana/godeltaprof/blob/main/http/pprof/pprof.go#L21
GoDeltaProfMemory: ProfilingTarget{
Enabled: false,
Path: "/debug/pprof/delta_heap",
},
GoDeltaProfMutex: ProfilingTarget{
Enabled: false,
Path: "/debug/pprof/delta_mutex",
},
GoDeltaProfBlock: ProfilingTarget{
Enabled: false,
Path: "/debug/pprof/delta_block",
},
}
// SetToDefault implements river.Defaulter.
func (cfg *ProfilingConfig) SetToDefault() {
*cfg = DefaultProfilingConfig
}
type ProfilingTarget struct {
Enabled bool `river:"enabled,attr,optional"`
Path string `river:"path,attr,optional"`
Delta bool `river:"delta,attr,optional"`
}
type CustomProfilingTarget struct {
Enabled bool `river:"enabled,attr"`
Path string `river:"path,attr"`
Delta bool `river:"delta,attr,optional"`
Name string `river:",label"`
}
var DefaultArguments = NewDefaultArguments()
// NewDefaultArguments create the default settings for a scrape job.
func NewDefaultArguments() Arguments {
return Arguments{
Scheme: "http",
HTTPClientConfig: component_config.DefaultHTTPClientConfig,
ScrapeInterval: 15 * time.Second,
ScrapeTimeout: 15*time.Second + (3 * time.Second),
ProfilingConfig: DefaultProfilingConfig,
}
}
// SetToDefault implements river.Defaulter.
func (arg *Arguments) SetToDefault() {
*arg = NewDefaultArguments()
}
// Validate implements river.Validator.
func (arg *Arguments) Validate() error {
if arg.ScrapeTimeout <= 0 {
return fmt.Errorf("scrape_timeout must be greater than 0")
}
if arg.ScrapeTimeout <= arg.ScrapeInterval {
return fmt.Errorf("scrape_timeout must be greater than scrape_interval")
}
if cfg, ok := arg.ProfilingConfig.ProcessCPU, true; ok {
if cfg.Enabled && arg.ScrapeTimeout < time.Second*2 {
return fmt.Errorf("%v scrape_timeout must be at least 2 seconds", pprofProcessCPU)
}
}
// We must explicitly Validate because HTTPClientConfig is squashed and it won't run otherwise
return arg.HTTPClientConfig.Validate()
}
// Component implements the pprof.scrape component.
type Component struct {
opts component.Options
cluster cluster.Cluster
reloadTargets chan struct{}
mut sync.RWMutex
args Arguments
scraper *Manager
appendable *pyroscope.Fanout
}
var _ component.Component = (*Component)(nil)
// New creates a new pprof.scrape component.
func New(o component.Options, args Arguments) (*Component, error) {
data, err := o.GetServiceData(cluster.ServiceName)
if err != nil {
return nil, fmt.Errorf("failed to get info about cluster service: %w", err)
}
clusterData := data.(cluster.Cluster)
flowAppendable := pyroscope.NewFanout(args.ForwardTo, o.ID, o.Registerer)
scraper := NewManager(flowAppendable, o.Logger)
c := &Component{
opts: o,
cluster: clusterData,
reloadTargets: make(chan struct{}, 1),
scraper: scraper,
appendable: flowAppendable,
}
// Call to Update() to set the receivers and targets 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.scraper.Stop()
targetSetsChan := make(chan map[string][]*targetgroup.Group)
go func() {
c.scraper.Run(targetSetsChan)
level.Info(c.opts.Logger).Log("msg", "scrape manager stopped")
}()
for {
select {
case <-ctx.Done():
return nil
case <-c.reloadTargets:
c.mut.RLock()
var (
tgs = c.args.Targets
jobName = c.opts.ID
clustering = c.args.Clustering.Enabled
)
if c.args.JobName != "" {
jobName = c.args.JobName
}
c.mut.RUnlock()
// NOTE(@tpaschalis) First approach, manually building the
// 'clustered' targets implementation every time.
ct := discovery.NewDistributedTargets(clustering, c.cluster, tgs)
promTargets := c.componentTargetsToProm(jobName, ct.Get())
select {
case targetSetsChan <- promTargets:
level.Debug(c.opts.Logger).Log("msg", "passed new targets to scrape manager")
case <-ctx.Done():
return nil
}
}
}
}
// Update implements component.Component.
func (c *Component) Update(args component.Arguments) error {
newArgs := args.(Arguments)
c.mut.Lock()
defer c.mut.Unlock()
c.args = newArgs
c.appendable.UpdateChildren(newArgs.ForwardTo)
err := c.scraper.ApplyConfig(newArgs)
if err != nil {
return fmt.Errorf("error applying scrape configs: %w", err)
}
level.Debug(c.opts.Logger).Log("msg", "scrape config was updated")
select {
case c.reloadTargets <- struct{}{}:
default:
}
return nil
}
// NotifyClusterChange implements component.ClusterComponent.
func (c *Component) NotifyClusterChange() {
c.mut.RLock()
defer c.mut.RUnlock()
if !c.args.Clustering.Enabled {
return // no-op
}
// Schedule a reload so targets get redistributed.
select {
case c.reloadTargets <- struct{}{}:
default:
}
}
func (c *Component) componentTargetsToProm(jobName string, tgs []discovery.Target) map[string][]*targetgroup.Group {
promGroup := &targetgroup.Group{Source: jobName}
for _, tg := range tgs {
promGroup.Targets = append(promGroup.Targets, convertLabelSet(tg))
}
return map[string][]*targetgroup.Group{jobName: {promGroup}}
}
func convertLabelSet(tg discovery.Target) model.LabelSet {
lset := make(model.LabelSet, len(tg))
for k, v := range tg {
lset[model.LabelName(k)] = model.LabelValue(v)
}
return lset
}
// DebugInfo implements component.DebugComponent.
func (c *Component) DebugInfo() interface{} {
var res []scrape.TargetStatus
for job, stt := range c.scraper.TargetsActive() {
for _, st := range stt {
var lastError string
if st.LastError() != nil {
lastError = st.LastError().Error()
}
if st != nil {
res = append(res, scrape.TargetStatus{
JobName: job,
URL: st.URL().String(),
Health: string(st.Health()),
Labels: st.discoveredLabels.Map(),
LastError: lastError,
LastScrape: st.LastScrape(),
LastScrapeDuration: st.LastScrapeDuration(),
})
}
}
}
return scrape.ScraperStatus{TargetStatus: res}
}