/
receiver.go
272 lines (232 loc) · 8.28 KB
/
receiver.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
// Copyright 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 smartagentreceiver
import (
"context"
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"runtime"
"strings"
"sync"
"github.com/shirou/gopsutil/v3/common"
saconfig "github.com/signalfx/signalfx-agent/pkg/core/config"
"github.com/signalfx/signalfx-agent/pkg/monitors"
"github.com/signalfx/signalfx-agent/pkg/monitors/collectd"
"github.com/signalfx/signalfx-agent/pkg/monitors/types"
"github.com/signalfx/signalfx-agent/pkg/utils/hostfs"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer"
otelcolextension "go.opentelemetry.io/collector/extension"
otelcolreceiver "go.opentelemetry.io/collector/receiver"
"go.uber.org/zap"
"github.com/signalfx/splunk-otel-collector/pkg/extension/smartagentextension"
)
const setOutputErrMsg = "unable to set output field of monitor"
const systemTypeKey = "system.type"
type receiver struct {
monitor any
nextMetricsConsumer consumer.Metrics
nextLogsConsumer consumer.Logs
nextTracesConsumer consumer.Traces
logger *zap.Logger
config *Config
params otelcolreceiver.CreateSettings
sync.Mutex
}
var _ otelcolreceiver.Metrics = (*receiver)(nil)
var (
saConfig *saconfig.Config
nonWordCharacters = regexp.MustCompile(`[^\w]+`)
logrusShim *logrusToZap
configureCollectdOnce sync.Once
configureEnvironmentOnce sync.Once
configureLogrusOnce sync.Once
)
func newReceiver(params otelcolreceiver.CreateSettings, config Config) *receiver {
return &receiver{
logger: params.Logger,
params: params,
config: &config,
}
}
func (r *receiver) registerMetricsConsumer(metricsConsumer consumer.Metrics) {
r.Lock()
defer r.Unlock()
r.nextMetricsConsumer = metricsConsumer
}
func (r *receiver) registerLogsConsumer(logsConsumer consumer.Logs) {
r.Lock()
defer r.Unlock()
r.nextLogsConsumer = logsConsumer
}
func (r *receiver) registerTracesConsumer(tracesConsumer consumer.Traces) {
r.Lock()
defer r.Unlock()
r.nextTracesConsumer = tracesConsumer
}
func (r *receiver) Start(_ context.Context, host component.Host) error {
// subsequent Start() invocations should noop
if r.monitor != nil {
return nil
}
err := r.config.validate()
if err != nil {
return fmt.Errorf("config validation failed for %q: %w", r.params.ID.String(), err)
}
configCore := r.config.monitorConfig.MonitorConfigCore()
monitorType := configCore.Type
monitorID := nonWordCharacters.ReplaceAllString(r.params.ID.String(), "")
configCore.MonitorID = types.MonitorID(monitorID)
configureLogrusOnce.Do(func() {
// we need a default logger that doesn't tie to a particular receiver instance
// but still uses the underlying service TelemetrySettings.Logger:
logrusShim = newLogrusToZap(r.logger.With(zap.String("name", "default")))
})
// source logger set to the logrus StandardLogger because it is assumed that the monitor's is derived from it
logrusShim.redirect(monitorLogrus{
Logger: logrus.StandardLogger(),
monitorType: r.config.monitorConfig.MonitorConfigCore().Type,
monitorID: monitorID,
}, r.logger)
if !r.config.acceptsEndpoints {
r.logger.Debug("This Smart Agent monitor does not use Host/Port config fields. If either are set, they will be ignored.", zap.String("monitor_type", monitorType))
}
r.monitor, err = r.createMonitor(monitorType, host)
if err != nil {
return fmt.Errorf("failed creating monitor %q: %w", monitorType, err)
}
configCore.ProcPath = saConfig.ProcPath
configCore.BundleDir = saConfig.BundleDir
return saconfig.CallConfigure(r.monitor, r.config.monitorConfig)
}
func (r *receiver) Shutdown(context.Context) error {
if r.monitor == nil {
return fmt.Errorf("smartagentreceiver's Shutdown() called before Start() or with invalid monitor state")
}
shutdownable, ok := (r.monitor).(monitors.Shutdownable)
if !ok {
return fmt.Errorf("invalid monitor state at Shutdown(): %#v", r.monitor)
}
shutdownable.Shutdown()
return nil
}
func (r *receiver) createMonitor(monitorType string, host component.Host) (monitor any, err error) {
// retrieve registered MonitorFactory from agent's registration store
monitorFactory, ok := monitors.MonitorFactories[monitorType]
if !ok {
return nil, fmt.Errorf("unable to find MonitorFactory for %q", monitorType)
}
monitor = monitorFactory() // monitor is a pointer to a monitor struct
// Make metadata nil if we aren't using built in filtering and then none of
// the new filtering logic will apply.
metadata, ok := monitors.MonitorMetadatas[monitorType]
if !ok || metadata == nil {
// This indicates a programming error in not specifying metadata, not
// bad user input
return nil, fmt.Errorf("could not find monitor metadata of type %s", monitorType)
}
monitorFiltering, err := newMonitorFiltering(r.config.monitorConfig, metadata, r.logger)
if err != nil {
return nil, err
}
output, err := newOutput(
*r.config, monitorFiltering, r.nextMetricsConsumer, r.nextLogsConsumer, r.nextTracesConsumer, host, r.params,
)
if err != nil {
return nil, err
}
set, err := setStructFieldWithExplicitType(
monitor, "Output", output,
reflect.TypeOf((*types.Output)(nil)).Elem(),
reflect.TypeOf((*types.FilteringOutput)(nil)).Elem(),
)
if !set || err != nil {
if err != nil {
return nil, fmt.Errorf("%s: %w", setOutputErrMsg, err)
}
return nil, fmt.Errorf("%s", setOutputErrMsg)
}
for k, v := range r.config.monitorConfig.MonitorConfigCore().ExtraDimensions {
output.AddExtraDimension(k, v)
}
output.AddExtraDimension(systemTypeKey, stripMonitorTypePrefix(monitorType))
// Configure SmartAgentConfigProvider to gather any global config overrides and
// set required envs.
configureEnvironmentOnce.Do(func() {
r.setUpSmartAgentConfigProvider(host.GetExtensions())
setUpEnvironment()
})
if r.config.monitorConfig.MonitorConfigCore().IsCollectdBased() {
configureCollectdOnce.Do(func() {
r.logger.Info("Configuring collectd")
err = collectd.ConfigureMainCollectd(&saConfig.Collectd)
})
}
return monitor, err
}
func stripMonitorTypePrefix(s string) string {
idx := strings.Index(s, "/")
if idx == -1 {
return s
}
return s[idx+1:]
}
func (r *receiver) setUpSmartAgentConfigProvider(extensions map[component.ID]otelcolextension.Extension) {
// If smartagent extension is not configured, use the default config.
f := smartagentextension.NewFactory()
saConfig = &f.CreateDefaultConfig().(*smartagentextension.Config).Config
// Do a lookup for any smartagent extensions to pick up common collectd options
// to be applied across instances of the receiver.
var foundAtLeastOne bool
var multipleSAExtensions bool
var chosenExtension component.ID
for c, ext := range extensions {
if c.Type() != f.Type() {
continue
}
if foundAtLeastOne {
multipleSAExtensions = true
continue
}
var cfgProvider smartagentextension.SmartAgentConfigProvider
cfgProvider, foundAtLeastOne = ext.(smartagentextension.SmartAgentConfigProvider)
if !foundAtLeastOne {
continue
}
saConfig = cfgProvider.SmartAgentConfig()
chosenExtension = c
r.logger.Info("Smart Agent Config provider configured", zap.Stringer("extension_name", chosenExtension))
}
if multipleSAExtensions {
r.logger.Warn(fmt.Sprintf("multiple smartagent extensions found, using %v", chosenExtension))
}
}
func setUpEnvironment() {
if runtime.GOOS != "windows" { // Agent bundle doesn't include jre for Windows
if _, ok := os.LookupEnv("JAVA_HOME"); !ok {
os.Setenv("JAVA_HOME", filepath.Join(saConfig.BundleDir, "jre"))
}
}
hostfs.SetEnvMap(common.EnvMap{
common.HostProcEnvKey: saConfig.ProcPath,
common.HostEtcEnvKey: saConfig.EtcPath,
common.HostVarEnvKey: saConfig.VarPath,
common.HostRunEnvKey: saConfig.RunPath,
common.HostSysEnvKey: saConfig.SysPath,
})
}