-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathconfig.go
296 lines (264 loc) · 10 KB
/
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
292
293
294
295
296
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package proctelemetry // import "go.opentelemetry.io/collector/service/internal/proctelemetry"
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/config"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/bridge/opencensus"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
otelprom "go.opentelemetry.io/otel/exporters/prometheus"
"go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
"go.opentelemetry.io/otel/sdk/instrumentation"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/collector/processor/processorhelper"
semconv "go.opentelemetry.io/collector/semconv/v1.18.0"
)
const (
// gRPC Instrumentation Name
GRPCInstrumentation = "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
// http Instrumentation Name
HTTPInstrumentation = "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
// supported protocols
protocolProtobufHTTP = "http/protobuf"
protocolProtobufGRPC = "grpc/protobuf"
)
var (
// GRPCUnacceptableKeyValues is a list of high cardinality grpc attributes that should be filtered out.
GRPCUnacceptableKeyValues = []attribute.KeyValue{
attribute.String(semconv.AttributeNetSockPeerAddr, ""),
attribute.String(semconv.AttributeNetSockPeerPort, ""),
attribute.String(semconv.AttributeNetSockPeerName, ""),
}
// HTTPUnacceptableKeyValues is a list of high cardinality http attributes that should be filtered out.
HTTPUnacceptableKeyValues = []attribute.KeyValue{
attribute.String(semconv.AttributeNetHostName, ""),
attribute.String(semconv.AttributeNetHostPort, ""),
}
errNoValidMetricExporter = errors.New("no valid metric exporter")
)
func InitMetricReader(ctx context.Context, reader config.MetricReader, asyncErrorChannel chan error) (sdkmetric.Reader, *http.Server, error) {
if reader.Pull != nil {
return initPullExporter(reader.Pull.Exporter, asyncErrorChannel)
}
if reader.Periodic != nil {
opts := []sdkmetric.PeriodicReaderOption{
sdkmetric.WithProducer(opencensus.NewMetricProducer()),
}
if reader.Periodic.Interval != nil {
opts = append(opts, sdkmetric.WithInterval(time.Duration(*reader.Periodic.Interval)*time.Millisecond))
}
if reader.Periodic.Timeout != nil {
opts = append(opts, sdkmetric.WithTimeout(time.Duration(*reader.Periodic.Timeout)*time.Millisecond))
}
return initPeriodicExporter(ctx, reader.Periodic.Exporter, opts...)
}
return nil, nil, fmt.Errorf("unsupported metric reader type %v", reader)
}
func InitOpenTelemetry(res *resource.Resource, options []sdkmetric.Option, disableHighCardinality bool) (*sdkmetric.MeterProvider, error) {
opts := []sdkmetric.Option{
sdkmetric.WithResource(res),
sdkmetric.WithView(batchViews(disableHighCardinality)...),
}
opts = append(opts, options...)
return sdkmetric.NewMeterProvider(
opts...,
), nil
}
func InitPrometheusServer(registry *prometheus.Registry, address string, asyncErrorChannel chan error) *http.Server {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
server := &http.Server{
Addr: address,
Handler: mux,
}
go func() {
if serveErr := server.ListenAndServe(); serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) {
asyncErrorChannel <- serveErr
}
}()
return server
}
func batchViews(disableHighCardinality bool) []sdkmetric.View {
views := []sdkmetric.View{
sdkmetric.NewView(
sdkmetric.Instrument{Name: processorhelper.BuildCustomMetricName("batch", "batch_send_size")},
sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{
Boundaries: []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000},
}},
),
sdkmetric.NewView(
sdkmetric.Instrument{Name: processorhelper.BuildCustomMetricName("batch", "batch_send_size_bytes")},
sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{
Boundaries: []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000,
100_000, 200_000, 300_000, 400_000, 500_000, 600_000, 700_000, 800_000, 900_000,
1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000},
}},
),
}
if disableHighCardinality {
views = append(views, sdkmetric.NewView(sdkmetric.Instrument{
Scope: instrumentation.Scope{
Name: GRPCInstrumentation,
},
}, sdkmetric.Stream{
AttributeFilter: cardinalityFilter(GRPCUnacceptableKeyValues...),
}))
views = append(views, sdkmetric.NewView(sdkmetric.Instrument{
Scope: instrumentation.Scope{
Name: HTTPInstrumentation,
},
}, sdkmetric.Stream{
AttributeFilter: cardinalityFilter(HTTPUnacceptableKeyValues...),
}))
}
return views
}
func cardinalityFilter(kvs ...attribute.KeyValue) attribute.Filter {
filter := attribute.NewSet(kvs...)
return func(kv attribute.KeyValue) bool {
return !filter.HasValue(kv.Key)
}
}
func initPrometheusExporter(prometheusConfig *config.Prometheus, asyncErrorChannel chan error) (sdkmetric.Reader, *http.Server, error) {
promRegistry := prometheus.NewRegistry()
if prometheusConfig.Host == nil {
return nil, nil, fmt.Errorf("host must be specified")
}
if prometheusConfig.Port == nil {
return nil, nil, fmt.Errorf("port must be specified")
}
exporter, err := otelprom.New(
otelprom.WithRegisterer(promRegistry),
// https://github.com/open-telemetry/opentelemetry-collector/issues/8043
otelprom.WithoutUnits(),
// Disabled for the moment until this becomes stable, and we are ready to break backwards compatibility.
otelprom.WithoutScopeInfo(),
otelprom.WithProducer(opencensus.NewMetricProducer()),
// This allows us to produce metrics that are backwards compatible w/ opencensus
otelprom.WithoutCounterSuffixes(),
otelprom.WithNamespace("otelcol"),
otelprom.WithResourceAsConstantLabels(attribute.NewDenyKeysFilter()),
)
if err != nil {
return nil, nil, fmt.Errorf("error creating otel prometheus exporter: %w", err)
}
return exporter, InitPrometheusServer(promRegistry, fmt.Sprintf("%s:%d", *prometheusConfig.Host, *prometheusConfig.Port), asyncErrorChannel), nil
}
func initPullExporter(exporter config.MetricExporter, asyncErrorChannel chan error) (sdkmetric.Reader, *http.Server, error) {
if exporter.Prometheus != nil {
return initPrometheusExporter(exporter.Prometheus, asyncErrorChannel)
}
return nil, nil, errNoValidMetricExporter
}
func initPeriodicExporter(ctx context.Context, exporter config.MetricExporter, opts ...sdkmetric.PeriodicReaderOption) (sdkmetric.Reader, *http.Server, error) {
if exporter.Console != nil {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
exp, err := stdoutmetric.New(
stdoutmetric.WithEncoder(enc),
)
if err != nil {
return nil, nil, err
}
return sdkmetric.NewPeriodicReader(exp, opts...), nil, nil
}
if exporter.OTLP != nil {
var err error
var exp sdkmetric.Exporter
switch exporter.OTLP.Protocol {
case protocolProtobufHTTP:
exp, err = initOTLPHTTPExporter(ctx, exporter.OTLP)
case protocolProtobufGRPC:
exp, err = initOTLPgRPCExporter(ctx, exporter.OTLP)
default:
return nil, nil, fmt.Errorf("unsupported protocol %s", exporter.OTLP.Protocol)
}
if err != nil {
return nil, nil, err
}
return sdkmetric.NewPeriodicReader(exp, opts...), nil, nil
}
return nil, nil, errNoValidMetricExporter
}
func normalizeEndpoint(endpoint string) string {
if !strings.HasPrefix(endpoint, "https://") && !strings.HasPrefix(endpoint, "http://") {
return fmt.Sprintf("http://%s", endpoint)
}
return endpoint
}
func initOTLPgRPCExporter(ctx context.Context, otlpConfig *config.OTLPMetric) (sdkmetric.Exporter, error) {
opts := []otlpmetricgrpc.Option{}
if len(otlpConfig.Endpoint) > 0 {
u, err := url.ParseRequestURI(normalizeEndpoint(otlpConfig.Endpoint))
if err != nil {
return nil, err
}
opts = append(opts, otlpmetricgrpc.WithEndpoint(u.Host))
if u.Scheme == "http" {
opts = append(opts, otlpmetricgrpc.WithInsecure())
}
}
if otlpConfig.Compression != nil {
switch *otlpConfig.Compression {
case "gzip":
opts = append(opts, otlpmetricgrpc.WithCompressor(*otlpConfig.Compression))
case "none":
break
default:
return nil, fmt.Errorf("unsupported compression %q", *otlpConfig.Compression)
}
}
if otlpConfig.Timeout != nil {
opts = append(opts, otlpmetricgrpc.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
}
if len(otlpConfig.Headers) > 0 {
opts = append(opts, otlpmetricgrpc.WithHeaders(otlpConfig.Headers))
}
return otlpmetricgrpc.New(ctx, opts...)
}
func initOTLPHTTPExporter(ctx context.Context, otlpConfig *config.OTLPMetric) (sdkmetric.Exporter, error) {
opts := []otlpmetrichttp.Option{}
if len(otlpConfig.Endpoint) > 0 {
u, err := url.ParseRequestURI(normalizeEndpoint(otlpConfig.Endpoint))
if err != nil {
return nil, err
}
opts = append(opts, otlpmetrichttp.WithEndpoint(u.Host))
if u.Scheme == "http" {
opts = append(opts, otlpmetrichttp.WithInsecure())
}
if len(u.Path) > 0 {
opts = append(opts, otlpmetrichttp.WithURLPath(u.Path))
}
}
if otlpConfig.Compression != nil {
switch *otlpConfig.Compression {
case "gzip":
opts = append(opts, otlpmetrichttp.WithCompression(otlpmetrichttp.GzipCompression))
case "none":
opts = append(opts, otlpmetrichttp.WithCompression(otlpmetrichttp.NoCompression))
default:
return nil, fmt.Errorf("unsupported compression %q", *otlpConfig.Compression)
}
}
if otlpConfig.Timeout != nil {
opts = append(opts, otlpmetrichttp.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
}
if len(otlpConfig.Headers) > 0 {
opts = append(opts, otlpmetrichttp.WithHeaders(otlpConfig.Headers))
}
return otlpmetrichttp.New(ctx, opts...)
}