Debian Codegraph @

scraper/scraperhelper/controller.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package scraperhelper // import "go.opentelemetry.io/collector/scraper/scraperhelper"
5
6 import (
7 "context"
8 "sync"
9 "time"
10
11 "go.uber.org/multierr"
12
13 "go.opentelemetry.io/collector/component"
14 "go.opentelemetry.io/collector/consumer"
15 "go.opentelemetry.io/collector/pdata/plog"
16 "go.opentelemetry.io/collector/pdata/pmetric"
17 "go.opentelemetry.io/collector/receiver"
18 "go.opentelemetry.io/collector/receiver/receiverhelper"
19 "go.opentelemetry.io/collector/scraper"
20 "go.opentelemetry.io/collector/scraper/scrapererror"
21 )
22
23 // ControllerOption apply changes to internal options.
24 type ControllerOption interface {
25 apply(*controllerOptions)
26 }
27
28 type optionFunc func(*controllerOptions)
29
30 func (of optionFunc) apply(e *controllerOptions) {
31 of(e)
32 }
33
34 // AddScraper configures the scraper.Metrics to be called with the specified options,
35 // and at the specified collection interval.
36 //
37 // Observability information will be reported, and the scraped metrics
38 // will be passed to the next consumer.
39 func AddScraper(t component.Type, sc scraper.Metrics) ControllerOption {
40 f := scraper.NewFactory(t, nil,
41 scraper.WithMetrics(func(context.Context, scraper.Settings, component.Config) (scraper.Metrics, error) {
42 return sc, nil
43 }, component.StabilityLevelAlpha))
44 return AddFactoryWithConfig(f, nil)
45 }
46
47 // AddFactoryWithConfig configures the scraper.Factory and associated config that
48 // will be used to create a new scraper. The created scraper will be called with
49 // the specified options, and at the specified collection interval.
50 //
51 // Observability information will be reported, and the scraped metrics
52 // will be passed to the next consumer.
53 func AddFactoryWithConfig(f scraper.Factory, cfg component.Config) ControllerOption {
54 return optionFunc(func(o *controllerOptions) {
55 o.factoriesWithConfig = append(o.factoriesWithConfig, factoryWithConfig{f: f, cfg: cfg})
56 })
57 }
58
59 // WithTickerChannel allows you to override the scraper controller's ticker
60 // channel to specify when scrape is called. This is only expected to be
61 // used by tests.
62 func WithTickerChannel(tickerCh <-chan time.Time) ControllerOption {
63 return optionFunc(func(o *controllerOptions) {
64 o.tickerCh = tickerCh
65 })
66 }
67
68 type factoryWithConfig struct {
69 f scraper.Factory
70 cfg component.Config
71 }
72
73 type controllerOptions struct {
74 tickerCh <-chan time.Time
75 factoriesWithConfig []factoryWithConfig
76 }
77
78 type controller[T component.Component] struct {
79 collectionInterval time.Duration
80 initialDelay time.Duration
81 timeout time.Duration
82
83 scrapers []T
84 scrapeFunc func(*controller[T])
85 tickerCh <-chan time.Time
86
87 done chan struct{}
88 wg sync.WaitGroup
89
90 obsrecv *receiverhelper.ObsReport
91 }
92
93 func newController[T component.Component](
94 cfg *ControllerConfig,
95 rSet receiver.Settings,
96 scrapers []T,
97 scrapeFunc func(*controller[T]),
98 tickerCh <-chan time.Time,
99 ) (*controller[T], error) {
100 obsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{
101 ReceiverID: rSet.ID,
102 Transport: "",
103 ReceiverCreateSettings: rSet,
104 })
105 if err != nil {
106 return nil, err
107 }
108
109 cs := &controller[T]{
110 collectionInterval: cfg.CollectionInterval,
111 initialDelay: cfg.InitialDelay,
112 timeout: cfg.Timeout,
113 scrapers: scrapers,
114 scrapeFunc: scrapeFunc,
115 done: make(chan struct{}),
116 tickerCh: tickerCh,
117 obsrecv: obsrecv,
118 }
119
120 return cs, nil
121 }
122
123 // Start the receiver, invoked during service start.
124 func (sc *controller[T]) Start(ctx context.Context, host component.Host) error {
125 for _, scrp := range sc.scrapers {
126 if err := scrp.Start(ctx, host); err != nil {
127 return err
128 }
129 }
130
131 sc.startScraping()
132 return nil
133 }
134
135 // Shutdown the receiver, invoked during service shutdown.
136 func (sc *controller[T]) Shutdown(ctx context.Context) error {
137 // Signal the goroutine to stop.
138 close(sc.done)
139 sc.wg.Wait()
140 var errs error
141 for _, scrp := range sc.scrapers {
142 errs = multierr.Append(errs, scrp.Shutdown(ctx))
143 }
144
145 return errs
146 }
147
148 // startScraping initiates a ticker that calls Scrape based on the configured
149 // collection interval.
150 func (sc *controller[T]) startScraping() {
151 sc.wg.Add(1)
152 go func() {
153 defer sc.wg.Done()
154 if sc.initialDelay > 0 {
155 select {
156 case <-time.After(sc.initialDelay):
157 case <-sc.done:
158 return
159 }
160 }
161
162 if sc.tickerCh == nil {
163 ticker := time.NewTicker(sc.collectionInterval)
164 defer ticker.Stop()
165
166 sc.tickerCh = ticker.C
167 }
168 // Call scrape method during initialization to ensure
169 // that scrapers start from when the component starts
170 // instead of waiting for the full duration to start.
171 sc.scrapeFunc(sc)
172 for {
173 select {
174 case <-sc.tickerCh:
175 sc.scrapeFunc(sc)
176 case <-sc.done:
177 return
178 }
179 }
180 }()
181 }
182
183 // NewLogsController creates a receiver.Logs with the configured options, that can control multiple scraper.Logs.
184 func NewLogsController(cfg *ControllerConfig,
185 rSet receiver.Settings,
186 nextConsumer consumer.Logs,
187 options ...ControllerOption,
188 ) (receiver.Logs, error) {
189 co := getOptions(options)
190 scrapers := make([]scraper.Logs, 0, len(co.factoriesWithConfig))
191 for _, fwc := range co.factoriesWithConfig {
192 set := getSettings(fwc.f.Type(), rSet)
193 s, err := fwc.f.CreateLogs(context.Background(), set, fwc.cfg)
194 if err != nil {
195 return nil, err
196 }
197 s, err = wrapObsLogs(s, rSet.ID, set.ID, set.TelemetrySettings)
198 if err != nil {
199 return nil, err
200 }
201 scrapers = append(scrapers, s)
202 }
203 return newController[scraper.Logs](
204 cfg, rSet, scrapers, func(c *controller[scraper.Logs]) { scrapeLogs(c, nextConsumer) }, co.tickerCh)
205 }
206
207 // NewMetricsController creates a receiver.Metrics with the configured options, that can control multiple scraper.Metrics.
208 func NewMetricsController(cfg *ControllerConfig,
209 rSet receiver.Settings,
210 nextConsumer consumer.Metrics,
211 options ...ControllerOption,
212 ) (receiver.Metrics, error) {
213 co := getOptions(options)
214 scrapers := make([]scraper.Metrics, 0, len(co.factoriesWithConfig))
215 for _, fwc := range co.factoriesWithConfig {
216 set := getSettings(fwc.f.Type(), rSet)
217 s, err := fwc.f.CreateMetrics(context.Background(), set, fwc.cfg)
218 if err != nil {
219 return nil, err
220 }
221 s, err = wrapObsMetrics(s, rSet.ID, set.ID, set.TelemetrySettings)
222 if err != nil {
223 return nil, err
224 }
225 scrapers = append(scrapers, s)
226 }
227 return newController[scraper.Metrics](
228 cfg, rSet, scrapers, func(c *controller[scraper.Metrics]) { scrapeMetrics(c, nextConsumer) }, co.tickerCh)
229 }
230
231 func scrapeLogs(c *controller[scraper.Logs], nextConsumer consumer.Logs) {
232 ctx, done := withScrapeContext(c.timeout)
233 defer done()
234
235 logs := plog.NewLogs()
236 for i := range c.scrapers {
237 md, err := c.scrapers[i].ScrapeLogs(ctx)
238 if err != nil && !scrapererror.IsPartialScrapeError(err) {
239 continue
240 }
241 md.ResourceLogs().MoveAndAppendTo(logs.ResourceLogs())
242 }
243
244 logRecordCount := logs.LogRecordCount()
245 ctx = c.obsrecv.StartMetricsOp(ctx)
246 err := nextConsumer.ConsumeLogs(ctx, logs)
247 c.obsrecv.EndMetricsOp(ctx, "", logRecordCount, err)
248 }
249
250 func scrapeMetrics(c *controller[scraper.Metrics], nextConsumer consumer.Metrics) {
251 ctx, done := withScrapeContext(c.timeout)
252 defer done()
253
254 metrics := pmetric.NewMetrics()
255 for i := range c.scrapers {
256 md, err := c.scrapers[i].ScrapeMetrics(ctx)
257 if err != nil && !scrapererror.IsPartialScrapeError(err) {
258 continue
259 }
260 md.ResourceMetrics().MoveAndAppendTo(metrics.ResourceMetrics())
261 }
262
263 dataPointCount := metrics.DataPointCount()
264 ctx = c.obsrecv.StartMetricsOp(ctx)
265 err := nextConsumer.ConsumeMetrics(ctx, metrics)
266 c.obsrecv.EndMetricsOp(ctx, "", dataPointCount, err)
267 }
268
269 func getOptions(options []ControllerOption) controllerOptions {
270 co := controllerOptions{}
271 for _, op := range options {
272 op.apply(&co)
273 }
274 return co
275 }
276
277 func getSettings(sType component.Type, rSet receiver.Settings) scraper.Settings {
278 return scraper.Settings{
279 ID: component.NewID(sType),
280 TelemetrySettings: rSet.TelemetrySettings,
281 BuildInfo: rSet.BuildInfo,
282 }
283 }
284
285 // withScrapeContext will return a context that has no deadline if timeout is 0
286 // which implies no explicit timeout had occurred, otherwise, a context
287 // with a deadline of the provided timeout is returned.
288 func withScrapeContext(timeout time.Duration) (context.Context, context.CancelFunc) {
289 if timeout == 0 {
290 return context.WithCancel(context.Background())
291 }
292 return context.WithTimeout(context.Background(), timeout)
293 }