-
Notifications
You must be signed in to change notification settings - Fork 486
/
Copy pathinstance.go
251 lines (212 loc) · 7.1 KB
/
instance.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
package traces
import (
"context"
"fmt"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.opencensus.io/stats/view"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/config"
"go.opentelemetry.io/collector/service/extensions"
"go.opentelemetry.io/collector/service/external/pipelines"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
"github.com/grafana/agent/pkg/build"
"github.com/grafana/agent/pkg/logs"
"github.com/grafana/agent/pkg/metrics/instance"
"github.com/grafana/agent/pkg/traces/automaticloggingprocessor"
"github.com/grafana/agent/pkg/traces/contextkeys"
"github.com/grafana/agent/pkg/util"
)
// Instance wraps the OpenTelemetry collector to enable tracing pipelines
type Instance struct {
mut sync.Mutex
cfg InstanceConfig
logger *zap.Logger
metricViews []*view.View
extensions *extensions.Extensions
pipelines *pipelines.Pipelines
factories component.Factories
}
var _ component.Host = (*Instance)(nil)
// NewInstance creates and starts an instance of tracing pipelines.
func NewInstance(logsSubsystem *logs.Logs, reg prometheus.Registerer, cfg InstanceConfig, logger *zap.Logger, promInstanceManager instance.Manager) (*Instance, error) {
var err error
instance := &Instance{}
instance.logger = logger
instance.metricViews, err = newMetricViews(reg)
if err != nil {
return nil, fmt.Errorf("failed to create metric views: %w", err)
}
if err := instance.ApplyConfig(logsSubsystem, promInstanceManager, reg, cfg); err != nil {
return nil, err
}
return instance, nil
}
// ApplyConfig updates the configuration of the Instance.
func (i *Instance) ApplyConfig(logsSubsystem *logs.Logs, promInstanceManager instance.Manager, reg prometheus.Registerer, cfg InstanceConfig) error {
i.mut.Lock()
defer i.mut.Unlock()
if util.CompareYAML(cfg, i.cfg) {
// No config change
return nil
}
i.cfg = cfg
// Shut down any existing pipeline
i.stop()
err := i.buildAndStartPipeline(context.Background(), cfg, logsSubsystem, promInstanceManager, reg)
if err != nil {
return fmt.Errorf("failed to create pipeline: %w", err)
}
return nil
}
// Stop stops the OpenTelemetry collector subsystem
func (i *Instance) Stop() {
i.mut.Lock()
defer i.mut.Unlock()
i.stop()
view.Unregister(i.metricViews...)
}
func (i *Instance) stop() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if i.extensions != nil {
err := i.extensions.NotifyPipelineNotReady()
if err != nil {
i.logger.Error("failed to notify extension of pipeline shutdown", zap.Error(err))
}
}
dependencies := []struct {
name string
shutdown func() error
}{
{
name: "pipelines",
shutdown: func() error {
if i.pipelines == nil {
return nil
}
return i.pipelines.ShutdownAll(shutdownCtx)
},
},
{
name: "extensions",
shutdown: func() error {
if i.extensions == nil {
return nil
}
return i.extensions.Shutdown(shutdownCtx)
},
},
}
for _, dep := range dependencies {
i.logger.Info(fmt.Sprintf("shutting down %s", dep.name))
if err := dep.shutdown(); err != nil {
i.logger.Error(fmt.Sprintf("failed to shutdown %s", dep.name), zap.Error(err))
}
}
i.pipelines = nil
i.extensions = nil
}
func (i *Instance) buildAndStartPipeline(ctx context.Context, cfg InstanceConfig, logs *logs.Logs, instManager instance.Manager, reg prometheus.Registerer) error {
// create component factories
otelConfig, err := cfg.otelConfig()
if err != nil {
return fmt.Errorf("failed to load otelConfig from agent traces config: %w", err)
}
for _, rw := range cfg.RemoteWrite {
if rw.InsecureSkipVerify {
i.logger.Warn("Configuring TLS with insecure_skip_verify. Use tls_config.insecure_skip_verify instead")
}
if rw.TLSConfig != nil && rw.TLSConfig.ServerName != "" {
i.logger.Warn("Configuring unsupported tls_config.server_name")
}
}
if cfg.SpanMetrics != nil && len(cfg.SpanMetrics.MetricsInstance) != 0 {
ctx = context.WithValue(ctx, contextkeys.Metrics, instManager)
}
if cfg.LoadBalancing == nil && (cfg.TailSampling != nil || cfg.ServiceGraphs != nil) {
i.logger.Warn("Configuring tail_sampling and/or service_graphs without load_balance." +
"Load balancing is required for those features to properly work in multi agent deployments")
}
if cfg.AutomaticLogging != nil && cfg.AutomaticLogging.Backend != automaticloggingprocessor.BackendStdout {
ctx = context.WithValue(ctx, contextkeys.Logs, logs)
}
if cfg.ServiceGraphs != nil {
ctx = context.WithValue(ctx, contextkeys.PrometheusRegisterer, reg)
}
factories, err := tracingFactories()
if err != nil {
return fmt.Errorf("failed to load tracing factories: %w", err)
}
i.factories = factories
appinfo := component.BuildInfo{
Command: "agent",
Description: "agent",
Version: build.Version,
}
settings := component.TelemetrySettings{
Logger: i.logger,
TracerProvider: trace.NewNoopTracerProvider(),
MeterProvider: metric.NewNoopMeterProvider(),
}
// start extensions
i.extensions, err = extensions.New(ctx, extensions.Settings{
Telemetry: settings,
BuildInfo: appinfo,
Factories: factories.Extensions,
Configs: otelConfig.Extensions,
}, otelConfig.Service.Extensions)
if err != nil {
i.logger.Error(fmt.Sprintf("failed to build extensions: %s", err.Error()))
return fmt.Errorf("failed to create extensions builder: %w", err)
}
err = i.extensions.Start(ctx, i)
if err != nil {
i.logger.Error(fmt.Sprintf("failed to start extensions: %s", err.Error()))
return fmt.Errorf("failed to start extensions: %w", err)
}
i.pipelines, err = pipelines.Build(ctx, pipelines.Settings{
Telemetry: settings,
BuildInfo: appinfo,
ReceiverFactories: factories.Receivers,
ReceiverConfigs: otelConfig.Receivers,
ProcessorFactories: factories.Processors,
ProcessorConfigs: otelConfig.Processors,
ExporterFactories: factories.Exporters,
ExporterConfigs: otelConfig.Exporters,
PipelineConfigs: otelConfig.Pipelines,
})
if err != nil {
return fmt.Errorf("failed to create pipelines: %w", err)
}
if err := i.pipelines.StartAll(ctx, i); err != nil {
i.logger.Error(fmt.Sprintf("failed to start pipelines: %s", err.Error()))
return fmt.Errorf("failed to start pipelines: %w", err)
}
return i.extensions.NotifyPipelineReady()
}
// ReportFatalError implements component.Host
func (i *Instance) ReportFatalError(err error) {
i.logger.Error("fatal error reported", zap.Error(err))
}
// GetFactory implements component.Host
func (i *Instance) GetFactory(kind component.Kind, componentType config.Type) component.Factory {
switch kind {
case component.KindReceiver:
return i.factories.Receivers[componentType]
default:
return nil
}
}
// GetExtensions implements component.Host
func (i *Instance) GetExtensions() map[config.ComponentID]component.Extension {
return i.extensions.GetExtensions()
}
// GetExporters implements component.Host
func (i *Instance) GetExporters() map[config.DataType]map[config.ComponentID]component.Exporter {
// SpanMetricsProcessor needs to get the configured exporters.
return i.pipelines.GetExporters()
}