Debian Codegraph @

otelcol/collector.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package otelcol handles the command-line, configuration, and runs the OpenTelemetry Collector.
5 // It contains the main [Collector] struct and its constructor [NewCollector].
6 // [Collector.Run] starts the Collector and then blocks until it shuts down.
7 package otelcol // import "go.opentelemetry.io/collector/otelcol"
8
9 import (
10 "context"
11 "errors"
12 "fmt"
13 "os"
14 "os/signal"
15 "sync"
16 "sync/atomic"
17 "syscall"
18
19 "go.uber.org/multierr"
20 "go.uber.org/zap"
21 "go.uber.org/zap/zapcore"
22
23 "go.opentelemetry.io/collector/component"
24 "go.opentelemetry.io/collector/confmap"
25 "go.opentelemetry.io/collector/confmap/xconfmap"
26 "go.opentelemetry.io/collector/otelcol/internal/grpclog"
27 "go.opentelemetry.io/collector/service"
28 )
29
30 // State defines Collector's state.
31 type State int
32
33 const (
34 StateStarting State = iota
35 StateRunning
36 StateClosing
37 StateClosed
38 )
39
40 func (s State) String() string {
41 switch s {
42 case StateStarting:
43 return "Starting"
44 case StateRunning:
45 return "Running"
46 case StateClosing:
47 return "Closing"
48 case StateClosed:
49 return "Closed"
50 }
51 return "UNKNOWN"
52 }
53
54 // CollectorSettings holds configuration for creating a new Collector.
55 type CollectorSettings struct {
56 // Factories returns component factories for the collector.
57 //
58 // TODO(13263) This is a dangerous "bare" function value, should define an interface
59 // following style guidelines.
60 Factories func() (Factories, error)
61
62 // BuildInfo provides collector start information.
63 BuildInfo component.BuildInfo
64
65 // DisableGracefulShutdown disables the automatic graceful shutdown
66 // of the collector on SIGINT or SIGTERM.
67 // Users who want to handle signals themselves can disable this behavior
68 // and manually handle the signals to shutdown the collector.
69 DisableGracefulShutdown bool
70
71 // ConfigProviderSettings allows configuring the way the Collector retrieves its configuration
72 // The Collector will reload based on configuration changes from the ConfigProvider if any
73 // confmap.Providers watch for configuration changes.
74 ConfigProviderSettings ConfigProviderSettings
75
76 // ProviderModules maps provider schemes to their respective go modules.
77 ProviderModules map[string]string
78
79 // ConverterModules maps converter names to their respective go modules.
80 ConverterModules []string
81
82 // LoggingOptions provides a way to change behavior of zap logging.
83 LoggingOptions []zap.Option
84
85 // SkipSettingGRPCLogger avoids setting the grpc logger
86 SkipSettingGRPCLogger bool
87 }
88
89 // (Internal note) Collector Lifecycle:
90 // - New constructs a new Collector.
91 // - Run starts the collector.
92 // - Run calls setupConfigurationComponents to handle configuration.
93 // If configuration parser fails, collector's config can be reloaded.
94 // Collector can be shutdown if parser gets a shutdown error.
95 // - Run runs runAndWaitForShutdownEvent and waits for a shutdown event.
96 // SIGINT and SIGTERM, errors, and (*Collector).Shutdown can trigger the shutdown events.
97 // - Upon shutdown, pipelines are notified, then pipelines and extensions are shut down.
98 // - Users can call (*Collector).Shutdown anytime to shut down the collector.
99
100 // Collector represents a server providing the OpenTelemetry Collector service.
101 type Collector struct {
102 set CollectorSettings
103
104 configProvider *ConfigProvider
105
106 serviceConfig *service.Config
107 service *service.Service
108 state *atomic.Int64
109
110 // shutdownChan is used to terminate the collector.
111 shutdownChan chan struct{}
112 shutdownOnce sync.Once
113
114 // signalsChannel is used to receive termination signals from the OS.
115 signalsChannel chan os.Signal
116 // asyncErrorChannel is used to signal a fatal error from any component.
117 asyncErrorChannel chan error
118 bc *bufferedCore
119 updateConfigProviderLogger func(core zapcore.Core)
120 }
121
122 // NewCollector creates and returns a new instance of Collector.
123 func NewCollector(set CollectorSettings) (*Collector, error) {
124 bc := newBufferedCore(zapcore.DebugLevel)
125 cc := newCollectorCore(bc)
126 options := append([]zap.Option{zap.WithCaller(true)}, set.LoggingOptions...)
127 logger := zap.New(cc, options...)
128 set.ConfigProviderSettings.ResolverSettings.ProviderSettings = confmap.ProviderSettings{Logger: logger}
129 set.ConfigProviderSettings.ResolverSettings.ConverterSettings = confmap.ConverterSettings{Logger: logger}
130
131 configProvider, err := NewConfigProvider(set.ConfigProviderSettings)
132 if err != nil {
133 return nil, err
134 }
135
136 state := new(atomic.Int64)
137 state.Store(int64(StateStarting))
138 return &Collector{
139 set: set,
140 state: state,
141 shutdownChan: make(chan struct{}),
142 // Per signal.Notify documentation, a size of the channel equaled with
143 // the number of signals getting notified on is recommended.
144 signalsChannel: make(chan os.Signal, 3),
145 asyncErrorChannel: make(chan error),
146 configProvider: configProvider,
147 bc: bc,
148 updateConfigProviderLogger: cc.SetCore,
149 }, nil
150 }
151
152 // GetState returns current state of the collector server.
153 func (col *Collector) GetState() State {
154 return State(col.state.Load())
155 }
156
157 // Shutdown shuts down the collector server.
158 func (col *Collector) Shutdown() {
159 col.shutdownOnce.Do(func() {
160 close(col.shutdownChan)
161 })
162 }
163
164 func buildModuleInfo(m map[component.Type]string) map[component.Type]service.ModuleInfo {
165 moduleInfo := make(map[component.Type]service.ModuleInfo)
166 for k, v := range m {
167 moduleInfo[k] = service.ModuleInfo{BuilderRef: v}
168 }
169 return moduleInfo
170 }
171
172 // setupConfigurationComponents loads the config, creates the graph, and starts the components. If all the steps succeeds it
173 // sets the col.service with the service currently running.
174 func (col *Collector) setupConfigurationComponents(ctx context.Context) error {
175 col.setCollectorState(StateStarting)
176
177 factories, err := col.set.Factories()
178 if err != nil {
179 return fmt.Errorf("failed to initialize factories: %w", err)
180 }
181
182 cfg, err := col.configProvider.Get(ctx, factories)
183 if err != nil {
184 return fmt.Errorf("failed to get config: %w", err)
185 }
186
187 if err = xconfmap.Validate(cfg); err != nil {
188 return fmt.Errorf("invalid configuration: %w", err)
189 }
190
191 col.serviceConfig = &cfg.Service
192
193 conf := confmap.New()
194
195 if err = conf.Marshal(cfg); err != nil {
196 return fmt.Errorf("could not marshal configuration: %w", err)
197 }
198
199 col.service, err = service.New(ctx, service.Settings{
200 BuildInfo: col.set.BuildInfo,
201 CollectorConf: conf,
202
203 ReceiversConfigs: cfg.Receivers,
204 ReceiversFactories: factories.Receivers,
205 ProcessorsConfigs: cfg.Processors,
206 ProcessorsFactories: factories.Processors,
207 ExportersConfigs: cfg.Exporters,
208 ExportersFactories: factories.Exporters,
209 ConnectorsConfigs: cfg.Connectors,
210 ConnectorsFactories: factories.Connectors,
211 ExtensionsConfigs: cfg.Extensions,
212 ExtensionsFactories: factories.Extensions,
213
214 ModuleInfos: service.ModuleInfos{
215 Receiver: buildModuleInfo(factories.ReceiverModules),
216 Processor: buildModuleInfo(factories.ProcessorModules),
217 Exporter: buildModuleInfo(factories.ExporterModules),
218 Extension: buildModuleInfo(factories.ExtensionModules),
219 Connector: buildModuleInfo(factories.ConnectorModules),
220 },
221 AsyncErrorChannel: col.asyncErrorChannel,
222 LoggingOptions: col.set.LoggingOptions,
223 TelemetryFactory: factories.Telemetry,
224 }, cfg.Service)
225 if err != nil {
226 return err
227 }
228 if col.updateConfigProviderLogger != nil {
229 col.updateConfigProviderLogger(col.service.Logger().Core())
230 }
231 if col.bc != nil {
232 x := col.bc.TakeLogs()
233 for _, log := range x {
234 ce := col.service.Logger().Core().Check(log.Entry, nil)
235 if ce != nil {
236 ce.Write(log.Context...)
237 }
238 }
239 }
240
241 if !col.set.SkipSettingGRPCLogger {
242 grpclog.SetLogger(col.service.Logger())
243 }
244
245 if err = col.service.Start(ctx); err != nil {
246 return multierr.Combine(err, col.service.Shutdown(ctx))
247 }
248 col.setCollectorState(StateRunning)
249
250 return nil
251 }
252
253 func (col *Collector) reloadConfiguration(ctx context.Context) error {
254 col.service.Logger().Warn("Config updated, restart service")
255 col.setCollectorState(StateClosing)
256
257 if err := col.service.Shutdown(ctx); err != nil {
258 return fmt.Errorf("failed to shutdown the retiring config: %w", err)
259 }
260
261 if err := col.setupConfigurationComponents(ctx); err != nil {
262 return fmt.Errorf("failed to setup configuration components: %w", err)
263 }
264
265 return nil
266 }
267
268 func (col *Collector) DryRun(ctx context.Context) error {
269 factories, err := col.set.Factories()
270 if err != nil {
271 return fmt.Errorf("failed to initialize factories: %w", err)
272 }
273
274 cfg, err := col.configProvider.Get(ctx, factories)
275 if err != nil {
276 return fmt.Errorf("failed to get config: %w", err)
277 }
278
279 if err := xconfmap.Validate(cfg); err != nil {
280 return err
281 }
282
283 return service.Validate(ctx, service.Settings{
284 BuildInfo: col.set.BuildInfo,
285 ReceiversConfigs: cfg.Receivers,
286 ReceiversFactories: factories.Receivers,
287 ProcessorsConfigs: cfg.Processors,
288 ProcessorsFactories: factories.Processors,
289 ExportersConfigs: cfg.Exporters,
290 ExportersFactories: factories.Exporters,
291 ConnectorsConfigs: cfg.Connectors,
292 ConnectorsFactories: factories.Connectors,
293 TelemetryFactory: factories.Telemetry,
294 }, service.Config{
295 Pipelines: cfg.Service.Pipelines,
296 })
297 }
298
299 func newFallbackLogger(options []zap.Option) (*zap.Logger, error) {
300 ec := zap.NewProductionEncoderConfig()
301 ec.EncodeTime = zapcore.ISO8601TimeEncoder
302 zapCfg := &zap.Config{
303 Level: zap.NewAtomicLevelAt(zapcore.DebugLevel),
304 Encoding: "console",
305 EncoderConfig: ec,
306 OutputPaths: []string{"stderr"},
307 ErrorOutputPaths: []string{"stderr"},
308 }
309 return zapCfg.Build(options...)
310 }
311
312 // Run starts the collector according to the given configuration, and waits for it to complete.
313 // Consecutive calls to Run are not allowed, Run shouldn't be called once a collector is shut down.
314 // Sets up the control logic for config reloading and shutdown.
315 func (col *Collector) Run(ctx context.Context) error {
316 // setupConfigurationComponents is the "main" function responsible for startup
317 if err := col.setupConfigurationComponents(ctx); err != nil {
318 col.setCollectorState(StateClosed)
319 logger, loggerErr := newFallbackLogger(col.set.LoggingOptions)
320 if loggerErr != nil {
321 return errors.Join(err, fmt.Errorf("unable to create fallback logger: %w", loggerErr))
322 }
323
324 if col.bc != nil {
325 x := col.bc.TakeLogs()
326 for _, log := range x {
327 ce := logger.Core().Check(log.Entry, nil)
328 if ce != nil {
329 ce.Write(log.Context...)
330 }
331 }
332 }
333
334 return err
335 }
336
337 // Always notify with SIGHUP for configuration reloading.
338 signal.Notify(col.signalsChannel, syscall.SIGHUP)
339 defer signal.Stop(col.signalsChannel)
340
341 // Only notify with SIGTERM and SIGINT if graceful shutdown is enabled.
342 if !col.set.DisableGracefulShutdown {
343 signal.Notify(col.signalsChannel, os.Interrupt, syscall.SIGTERM)
344 }
345
346 // Control loop: selects between channels for various interrupts - when this loop is broken, the collector exits.
347 // If a configuration reload fails, we return without waiting for graceful shutdown.
348 LOOP:
349 for {
350 select {
351 case err := <-col.configProvider.Watch():
352 if err != nil {
353 col.service.Logger().Error("Config watch failed", zap.Error(err))
354 break LOOP
355 }
356 if err := col.reloadConfiguration(ctx); err != nil {
357 return err
358 }
359 case err := <-col.asyncErrorChannel:
360 col.service.Logger().Error("Asynchronous error received, terminating process", zap.Error(err))
361 break LOOP
362 case s := <-col.signalsChannel:
363 col.service.Logger().Info("Received signal from OS", zap.String("signal", s.String()))
364 if s != syscall.SIGHUP {
365 break LOOP
366 }
367 if err := col.reloadConfiguration(ctx); err != nil {
368 return err
369 }
370 case <-col.shutdownChan:
371 col.service.Logger().Info("Received shutdown request")
372 break LOOP
373 case <-ctx.Done():
374 col.service.Logger().Info("Context done, terminating process", zap.Error(ctx.Err()))
375 // Call shutdown with background context as the passed in context has been canceled
376 return col.shutdown(context.Background()) //nolint:contextcheck
377 }
378 }
379 return col.shutdown(ctx)
380 }
381
382 func (col *Collector) shutdown(ctx context.Context) error {
383 col.setCollectorState(StateClosing)
384
385 // Accumulate errors and proceed with shutting down remaining components.
386 var errs error
387
388 if err := col.configProvider.Shutdown(ctx); err != nil {
389 errs = multierr.Append(errs, fmt.Errorf("failed to shutdown config provider: %w", err))
390 }
391
392 // shutdown service
393 if err := col.service.Shutdown(ctx); err != nil {
394 errs = multierr.Append(errs, fmt.Errorf("failed to shutdown service after error: %w", err))
395 }
396
397 col.setCollectorState(StateClosed)
398
399 return errs
400 }
401
402 // setCollectorState provides current state of the collector
403 func (col *Collector) setCollectorState(state State) {
404 col.state.Store(int64(state))
405 }