-
Notifications
You must be signed in to change notification settings - Fork 24
/
otel-config.go
291 lines (263 loc) · 9.77 KB
/
otel-config.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package agent
import (
"crypto/tls"
"fmt"
"path"
"sync"
promapi "github.com/prometheus/client_golang/api"
"go.opentelemetry.io/collector/receiver/otlpreceiver"
"go.uber.org/fx"
"k8s.io/client-go/rest"
policysyncv1 "github.com/fluxninja/aperture/api/v2/gen/proto/go/aperture/policy/sync/v1"
agentconfig "github.com/fluxninja/aperture/v2/cmd/aperture-agent/config"
agentinfo "github.com/fluxninja/aperture/v2/pkg/agent-info"
"github.com/fluxninja/aperture/v2/pkg/config"
etcdclient "github.com/fluxninja/aperture/v2/pkg/etcd/client"
etcdwatcher "github.com/fluxninja/aperture/v2/pkg/etcd/watcher"
"github.com/fluxninja/aperture/v2/pkg/info"
"github.com/fluxninja/aperture/v2/pkg/log"
"github.com/fluxninja/aperture/v2/pkg/net/listener"
"github.com/fluxninja/aperture/v2/pkg/notifiers"
otelconfig "github.com/fluxninja/aperture/v2/pkg/otelcollector/config"
otelconsts "github.com/fluxninja/aperture/v2/pkg/otelcollector/consts"
inframeter "github.com/fluxninja/aperture/v2/pkg/otelcollector/infra-meter"
"github.com/fluxninja/aperture/v2/pkg/policies/paths"
"github.com/fluxninja/aperture/v2/pkg/secretmanager"
"github.com/fluxninja/aperture/v2/pkg/utils"
)
type ProvideAgentIn struct {
fx.In
Unmarshaller config.Unmarshaller
Lis *listener.Listener
PromClient promapi.Client
TLSConfig *tls.Config
AI *agentinfo.AgentInfo
EtcdClient *etcdclient.Client
Lifecycle fx.Lifecycle
Shutdowner fx.Shutdowner
InstallationModeConfig *agentinfo.InstallationModeConfig `optional:"true"`
SecretManagetClient *secretmanager.SecretManagerClient `optional:"true"`
}
func provideAgent(
in ProvideAgentIn,
) (*otelconfig.Provider, error) {
var agentCfg agentconfig.AgentOTelConfig
if err := in.Unmarshaller.UnmarshalKey("otel", &agentCfg); err != nil {
return nil, fmt.Errorf("unmarshalling otel config: %w", err)
}
allInfraMeters := map[string]*policysyncv1.InfraMeterWrapper{}
var allInfraMetersMutex sync.Mutex
configProvider := otelconfig.NewProvider("service")
configProvider.AddMutatingHook(func(otelCfg *otelconfig.Config) {
otelCfg.SetDebugPort(&agentCfg.CommonOTelConfig)
otelCfg.AddDebugExtensions(&agentCfg.CommonOTelConfig)
addLogsPipeline(otelCfg, &agentCfg)
addTracesPipeline(otelCfg, in.Lis)
addMetricsPipeline(otelCfg, &agentCfg, in.TLSConfig, in.Lis, in.PromClient)
otelconfig.AddAlertsPipeline(otelCfg, agentCfg.CommonOTelConfig, otelconsts.ProcessorAgentResourceLabels)
installationMode := ""
if in.InstallationModeConfig != nil {
installationMode = in.InstallationModeConfig.InstallationMode
}
if err := inframeter.AddInfraMeters(
otelCfg, allInfraMeters, installationMode, in.SecretManagetClient); err != nil {
log.Error().Err(err).Msg("unable to add custom metrics pipelines")
utils.Shutdown(in.Shutdowner)
return
}
})
configProvider.UpdateConfig()
handleInfraMeterUpdate := func(event notifiers.Event, unmarshaller config.Unmarshaller) {
var err error //nolint:govet
log.Info().Str("event", event.String()).Msg("infra meter update")
im := &policysyncv1.InfraMeterWrapper{}
if err = unmarshaller.Unmarshal(im); err != nil {
log.Error().Err(err).Msg("unmarshalling infra meter")
return
}
key := string(event.Key)
allInfraMetersMutex.Lock()
defer allInfraMetersMutex.Unlock()
switch event.Type {
case notifiers.Write:
allInfraMeters[key] = im
case notifiers.Remove:
delete(allInfraMeters, key)
}
// trigger update
log.Info().Msgf("received infra meter update, hot re-loading OTel, total infra meters: %d", len(allInfraMeters))
configProvider.UpdateConfig()
}
// Get Agent Group from host info gatherer
agentGroupName := in.AI.GetAgentGroup()
// Scope the sync to the agent group.
etcdPath := path.Join(paths.InfraMeterConfigPath,
paths.AgentGroupPrefix(agentGroupName))
watcher, err := etcdwatcher.NewWatcher(in.EtcdClient, etcdPath)
if err != nil {
return nil, err
}
unmarshalNotifier, err := notifiers.NewUnmarshalPrefixNotifier("",
handleInfraMeterUpdate,
config.NewProtobufUnmarshaller,
)
if err != nil {
return nil, fmt.Errorf("creating unmarshal notifier: %w", err)
}
notifiers.WatcherLifecycle(in.Lifecycle, watcher, []notifiers.PrefixNotifier{unmarshalNotifier})
return configProvider, nil
}
func addLogsPipeline(
config *otelconfig.Config,
userConfig *agentconfig.AgentOTelConfig,
) {
// Common dependencies for pipelines
config.AddReceiver(otelconsts.ReceiverOTLP, otlpreceiver.Config{})
// Note: Passing map[string]interface{}{} instead of real config, so that
// processors' configs' default work.
config.AddProcessor(otelconsts.ProcessorMetrics, map[string]interface{}{})
config.AddBatchProcessor(
otelconsts.ProcessorBatchPrerollup,
userConfig.BatchPrerollup.Timeout.AsDuration(),
userConfig.BatchPrerollup.SendBatchSize,
userConfig.BatchPrerollup.SendBatchMaxSize,
)
config.AddProcessor(otelconsts.ProcessorRollup, map[string]interface{}{})
config.AddBatchProcessor(
otelconsts.ProcessorBatchPostrollup,
userConfig.BatchPostrollup.Timeout.AsDuration(),
userConfig.BatchPostrollup.SendBatchSize,
userConfig.BatchPostrollup.SendBatchMaxSize,
)
config.AddExporter(otelconsts.ExporterLogging, nil)
processors := []string{
otelconsts.ProcessorMetrics,
otelconsts.ProcessorBatchPrerollup,
otelconsts.ProcessorRollup,
otelconsts.ProcessorBatchPostrollup,
otelconsts.ProcessorAgentGroup,
}
config.Service.AddPipeline("logs", otelconfig.Pipeline{
Receivers: []string{otelconsts.ReceiverOTLP, otelconsts.ConnectorAdapter},
Processors: processors,
Exporters: []string{otelconsts.ExporterLogging},
})
}
func addTracesPipeline(config *otelconfig.Config, _ *listener.Listener) {
config.AddConnector(otelconsts.ConnectorAdapter, map[string]any{})
config.Service.AddPipeline("traces", otelconfig.Pipeline{
Receivers: []string{otelconsts.ReceiverOTLP},
Exporters: []string{otelconsts.ConnectorAdapter},
})
}
func addMetricsPipeline(
config *otelconfig.Config,
agentConfig *agentconfig.AgentOTelConfig,
tlsConfig *tls.Config,
lis *listener.Listener,
promClient promapi.Client,
) {
pipeline := otelconfig.Pipeline{}
addPrometheusReceiver(config, agentConfig, tlsConfig, lis)
if promClient != nil {
otelconfig.AddPrometheusRemoteWriteExporter(config, promClient)
pipeline.Exporters = []string{otelconsts.ExporterPrometheusRemoteWrite}
}
processors := []string{
otelconsts.ProcessorAgentGroup,
}
if !agentConfig.EnableHighCardinalityPlatformMetrics {
otelconfig.AddHighCardinalityMetricsFilterProcessor(config)
// Prepending processor so we drop metrics as soon as possible without any unnecessary operation on them.
processors = append([]string{otelconsts.ProcessorFilterHighCardinalityMetrics}, processors...)
}
pipeline.Processors = processors
pipeline.Receivers = []string{otelconsts.ReceiverPrometheus}
config.Service.AddPipeline("metrics/fast", pipeline)
}
func addPrometheusReceiver(
config *otelconfig.Config,
agentConfig *agentconfig.AgentOTelConfig,
tlsConfig *tls.Config,
lis *listener.Listener,
) {
scrapeConfigs := []map[string]any{
otelconfig.BuildApertureSelfScrapeConfig("aperture-self", tlsConfig, lis),
otelconfig.BuildOTelScrapeConfig("aperture-otel", agentConfig.CommonOTelConfig),
}
if !agentConfig.DisableKubernetesScraper {
_, err := rest.InClusterConfig()
if err == rest.ErrNotInCluster {
log.Debug().Msg("K8s environment not detected. Skipping K8s scrape configurations.")
} else if err != nil {
log.Warn().Err(err).Msg("Error when discovering k8s environment")
} else {
log.Debug().Msg("K8s environment detected. Adding K8s scrape configurations.")
scrapeConfigs = append(scrapeConfigs, buildKubernetesPodsScrapeConfig())
}
}
// Unfortunately prometheus config structs do not have proper `mapstructure`
// tags, so they are not properly read by OTel. Need to use bare maps instead.
config.AddReceiver(otelconsts.ReceiverPrometheus, map[string]any{
"config": map[string]any{
"global": map[string]any{
"scrape_interval": "10s",
"scrape_timeout": "1s",
"evaluation_interval": "1m",
},
"scrape_configs": scrapeConfigs,
},
})
}
func buildKubernetesPodsScrapeConfig() map[string]any {
return map[string]any{
"job_name": "kubernetes-pods",
"scheme": "http",
"metrics_path": "/metrics",
"kubernetes_sd_configs": []map[string]any{
{"role": "pod"},
},
"relabel_configs": []map[string]any{
// Scrape only the node on which this agent is running.
{
"source_labels": []string{"__meta_kubernetes_pod_node_name"},
"action": "keep",
"regex": info.Hostname,
},
// Scrape only pods which have github.com/fluxninja/scrape=true annotation.
{
"source_labels": []string{"__meta_kubernetes_pod_annotation_aperture_tech_scrape"},
"action": "keep",
"regex": "true",
},
// Allow rewrite of scheme, path and port where prometheus metrics are served.
{
"source_labels": []string{"__meta_kubernetes_pod_annotation_prometheus_io_scheme"},
"action": "replace",
"regex": "(https?)",
"target_label": "__scheme__",
},
{
"source_labels": []string{"__meta_kubernetes_pod_annotation_prometheus_io_path"},
"action": "replace",
"target_label": "__metrics_path__",
"regex": "(.+)",
},
{
"source_labels": []string{"__address__", "__meta_kubernetes_pod_annotation_prometheus_io_port"},
"action": "replace",
"regex": `([^:]+)(?::\d+)?;(\d+)`,
"replacement": "$$1:$$2",
"target_label": "__address__",
},
},
"metric_relabel_configs": []map[string]any{
// For now, dropping everything. In future, we'll want to filter in some
// metrics based on policies. See #4632.
{
"source_labels": []string{},
"action": "drop",
},
},
}
}