-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
collector.go
246 lines (208 loc) · 7.31 KB
/
collector.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
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package service handles the command-line, configuration, and runs the
// OpenTelemetry Collector.
package service // import "go.opentelemetry.io/collector/service"
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
"syscall"
"go.uber.org/atomic"
"go.uber.org/multierr"
"go.uber.org/zap"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/extension/ballastextension"
"go.opentelemetry.io/collector/service/internal/telemetrylogs"
)
// State defines Collector's state.
type State int
const (
Starting State = iota
Running
Closing
Closed
)
func (s State) String() string {
switch s {
case Starting:
return "Starting"
case Running:
return "Running"
case Closing:
return "Closing"
case Closed:
return "Closed"
}
return "UNKNOWN"
}
// (Internal note) Collector Lifecycle:
// - New constructs a new Collector.
// - Run starts the collector.
// - Run calls setupConfigurationComponents to handle configuration.
// If configuration parser fails, collector's config can be reloaded.
// Collector can be shutdown if parser gets a shutdown error.
// - Run runs runAndWaitForShutdownEvent and waits for a shutdown event.
// SIGINT and SIGTERM, errors, and (*Collector).Shutdown can trigger the shutdown events.
// - Upon shutdown, pipelines are notified, then pipelines and extensions are shut down.
// - Users can call (*Collector).Shutdown anytime to shut down the collector.
// Collector represents a server providing the OpenTelemetry Collector service.
type Collector struct {
set CollectorSettings
service *service
state *atomic.Int32
// shutdownChan is used to terminate the collector.
shutdownChan chan struct{}
// signalsChannel is used to receive termination signals from the OS.
signalsChannel chan os.Signal
// asyncErrorChannel is used to signal a fatal error from any component.
asyncErrorChannel chan error
}
// New creates and returns a new instance of Collector.
func New(set CollectorSettings) (*Collector, error) {
if set.ConfigProvider == nil {
return nil, errors.New("invalid nil config provider")
}
if set.telemetry == nil {
set.telemetry = collectorTelemetry
}
return &Collector{
set: set,
state: atomic.NewInt32(int32(Starting)),
shutdownChan: make(chan struct{}),
signalsChannel: make(chan os.Signal, 1),
asyncErrorChannel: make(chan error),
}, nil
}
// GetState returns current state of the collector server.
func (col *Collector) GetState() State {
return State(col.state.Load())
}
// Shutdown shuts down the collector server.
func (col *Collector) Shutdown() {
// Only shutdown if we're in a Running or Starting State else noop
state := col.GetState()
if state == Running || state == Starting {
defer func() {
recover() // nolint:errcheck
}()
close(col.shutdownChan)
}
}
// setupConfigurationComponents loads the config and starts the components. If all the steps succeeds it
// sets the col.service with the service currently running.
func (col *Collector) setupConfigurationComponents(ctx context.Context) error {
col.setCollectorState(Starting)
cfg, err := col.set.ConfigProvider.Get(ctx, col.set.Factories)
if err != nil {
return fmt.Errorf("failed to get config: %w", err)
}
col.service, err = newService(&settings{
BuildInfo: col.set.BuildInfo,
Factories: col.set.Factories,
Config: cfg,
AsyncErrorChannel: col.asyncErrorChannel,
LoggingOptions: col.set.LoggingOptions,
telemetry: col.set.telemetry,
})
if err != nil {
return err
}
if !col.set.SkipSettingGRPCLogger {
telemetrylogs.SetColGRPCLogger(col.service.telemetrySettings.Logger, cfg.Service.Telemetry.Logs.Level)
}
if err = col.service.Start(ctx); err != nil {
return err
}
col.setCollectorState(Running)
return nil
}
// Run starts the collector according to the given configuration, and waits for it to complete.
// Consecutive calls to Run are not allowed, Run shouldn't be called once a collector is shut down.
func (col *Collector) Run(ctx context.Context) error {
if err := col.setupConfigurationComponents(ctx); err != nil {
col.setCollectorState(Closed)
return err
}
// Only notify with SIGTERM and SIGINT if graceful shutdown is enabled.
if !col.set.DisableGracefulShutdown {
signal.Notify(col.signalsChannel, os.Interrupt, syscall.SIGTERM)
}
LOOP:
for {
select {
case err := <-col.set.ConfigProvider.Watch():
if err != nil {
col.service.telemetrySettings.Logger.Error("Config watch failed", zap.Error(err))
break LOOP
}
col.service.telemetrySettings.Logger.Warn("Config updated, restart service")
col.setCollectorState(Closing)
if err = col.service.Shutdown(ctx); err != nil {
return fmt.Errorf("failed to shutdown the retiring config: %w", err)
}
if err = col.setupConfigurationComponents(ctx); err != nil {
return fmt.Errorf("failed to setup configuration components: %w", err)
}
case err := <-col.asyncErrorChannel:
col.service.telemetrySettings.Logger.Error("Asynchronous error received, terminating process", zap.Error(err))
break LOOP
case s := <-col.signalsChannel:
col.service.telemetrySettings.Logger.Info("Received signal from OS", zap.String("signal", s.String()))
break LOOP
case <-col.shutdownChan:
col.service.telemetrySettings.Logger.Info("Received shutdown request")
break LOOP
case <-ctx.Done():
col.service.telemetrySettings.Logger.Info("Context done, terminating process", zap.Error(ctx.Err()))
// Call shutdown with background context as the passed in context has been canceled
return col.shutdown(context.Background())
}
}
return col.shutdown(ctx)
}
func (col *Collector) shutdown(ctx context.Context) error {
col.setCollectorState(Closing)
// Accumulate errors and proceed with shutting down remaining components.
var errs error
if err := col.set.ConfigProvider.Shutdown(ctx); err != nil {
errs = multierr.Append(errs, fmt.Errorf("failed to shutdown config provider: %w", err))
}
if err := col.service.Shutdown(ctx); err != nil {
errs = multierr.Append(errs, fmt.Errorf("failed to shutdown service: %w", err))
}
// TODO: Move this as part of the service shutdown.
if err := col.service.telemetryInitializer.shutdown(); err != nil {
errs = multierr.Append(errs, fmt.Errorf("failed to shutdown collector telemetry: %w", err))
}
col.setCollectorState(Closed)
return errs
}
// setCollectorState provides current state of the collector
func (col *Collector) setCollectorState(state State) {
col.state.Store(int32(state))
}
func getBallastSize(host component.Host) uint64 {
var ballastSize uint64
extensions := host.GetExtensions()
for _, extension := range extensions {
if ext, ok := extension.(*ballastextension.MemoryBallast); ok {
ballastSize = ext.GetBallastSize()
break
}
}
return ballastSize
}