Debian Codegraph @

otelconf/x/trace.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package x // import "go.opentelemetry.io/contrib/otelconf/x"
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "net/url"
11 "time"
12
13 "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
14 "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
15 "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
16 "go.opentelemetry.io/otel/sdk/resource"
17 sdktrace "go.opentelemetry.io/otel/sdk/trace"
18 "go.opentelemetry.io/otel/trace"
19 "go.opentelemetry.io/otel/trace/noop"
20 "google.golang.org/grpc/credentials"
21
22 "go.opentelemetry.io/contrib/otelconf/internal/tls"
23 )
24
25 var errInvalidSamplerConfiguration = newErrInvalid("sampler configuration")
26
27 func tracerProvider(cfg configOptions, res *resource.Resource) (trace.TracerProvider, shutdownFunc, error) {
28 if cfg.opentelemetryConfig.TracerProvider == nil {
29 return noop.NewTracerProvider(), noopShutdown, nil
30 }
31
32 opts := append(cfg.tracerProviderOptions, sdktrace.WithResource(res))
33
34 var errs []error
35 for _, processor := range cfg.opentelemetryConfig.TracerProvider.Processors {
36 sp, err := spanProcessor(cfg.ctx, processor)
37 if err == nil {
38 opts = append(opts, sdktrace.WithSpanProcessor(sp))
39 } else {
40 errs = append(errs, err)
41 }
42 }
43 if s, err := sampler(cfg.opentelemetryConfig.TracerProvider.Sampler); err == nil {
44 opts = append(opts, sdktrace.WithSampler(s))
45 } else {
46 errs = append(errs, err)
47 }
48 if len(errs) > 0 {
49 return noop.NewTracerProvider(), noopShutdown, errors.Join(errs...)
50 }
51 tp := sdktrace.NewTracerProvider(opts...)
52 return tp, tp.Shutdown, nil
53 }
54
55 func parentBasedSampler(s *ParentBasedSampler) (sdktrace.Sampler, error) {
56 var rootSampler sdktrace.Sampler
57 var opts []sdktrace.ParentBasedSamplerOption
58 var errs []error
59 var err error
60
61 if s.Root == nil {
62 rootSampler = sdktrace.AlwaysSample()
63 } else {
64 rootSampler, err = sampler(s.Root)
65 if err != nil {
66 errs = append(errs, err)
67 }
68 }
69 if s.RemoteParentSampled != nil {
70 remoteParentSampler, err := sampler(s.RemoteParentSampled)
71 if err != nil {
72 errs = append(errs, err)
73 } else {
74 opts = append(opts, sdktrace.WithRemoteParentSampled(remoteParentSampler))
75 }
76 }
77 if s.RemoteParentNotSampled != nil {
78 remoteParentNotSampler, err := sampler(s.RemoteParentNotSampled)
79 if err != nil {
80 errs = append(errs, err)
81 } else {
82 opts = append(opts, sdktrace.WithRemoteParentNotSampled(remoteParentNotSampler))
83 }
84 }
85 if s.LocalParentSampled != nil {
86 localParentSampler, err := sampler(s.LocalParentSampled)
87 if err != nil {
88 errs = append(errs, err)
89 } else {
90 opts = append(opts, sdktrace.WithLocalParentSampled(localParentSampler))
91 }
92 }
93 if s.LocalParentNotSampled != nil {
94 localParentNotSampler, err := sampler(s.LocalParentNotSampled)
95 if err != nil {
96 errs = append(errs, err)
97 } else {
98 opts = append(opts, sdktrace.WithLocalParentNotSampled(localParentNotSampler))
99 }
100 }
101 if len(errs) > 0 {
102 return nil, errors.Join(errs...)
103 }
104 return sdktrace.ParentBased(rootSampler, opts...), nil
105 }
106
107 func sampler(s *Sampler) (sdktrace.Sampler, error) {
108 if s == nil {
109 // If omitted, parent based sampler with a root of always_on is used.
110 return sdktrace.ParentBased(sdktrace.AlwaysSample()), nil
111 }
112 if s.ParentBased != nil {
113 return parentBasedSampler(s.ParentBased)
114 }
115 if s.AlwaysOff != nil {
116 return sdktrace.NeverSample(), nil
117 }
118 if s.AlwaysOn != nil {
119 return sdktrace.AlwaysSample(), nil
120 }
121 if s.TraceIDRatioBased != nil {
122 if s.TraceIDRatioBased.Ratio == nil {
123 return sdktrace.TraceIDRatioBased(1), nil
124 }
125 return sdktrace.TraceIDRatioBased(*s.TraceIDRatioBased.Ratio), nil
126 }
127 return nil, errInvalidSamplerConfiguration
128 }
129
130 func spanExporter(ctx context.Context, exporter SpanExporter) (sdktrace.SpanExporter, error) {
131 exportersConfigured := 0
132 var exportFunc func() (sdktrace.SpanExporter, error)
133
134 if exporter.Console != nil {
135 exportersConfigured++
136 exportFunc = func() (sdktrace.SpanExporter, error) {
137 return stdouttrace.New(
138 stdouttrace.WithPrettyPrint(),
139 )
140 }
141 }
142 if exporter.OTLPHttp != nil {
143 exportersConfigured++
144 exportFunc = func() (sdktrace.SpanExporter, error) {
145 return otlpHTTPSpanExporter(ctx, exporter.OTLPHttp)
146 }
147 }
148 if exporter.OTLPGrpc != nil {
149 exportersConfigured++
150 exportFunc = func() (sdktrace.SpanExporter, error) {
151 return otlpGRPCSpanExporter(ctx, exporter.OTLPGrpc)
152 }
153 }
154 if exporter.OTLPFileDevelopment != nil {
155 // TODO: implement file exporter https://github.com/open-telemetry/opentelemetry-go/issues/5408
156 return nil, newErrInvalid("otlp_file/development")
157 }
158
159 if exportersConfigured > 1 {
160 return nil, newErrInvalid("must not specify multiple exporters")
161 }
162
163 if exportFunc != nil {
164 return exportFunc()
165 }
166 return nil, newErrInvalid("no valid span exporter")
167 }
168
169 func spanProcessor(ctx context.Context, processor SpanProcessor) (sdktrace.SpanProcessor, error) {
170 if processor.Batch != nil && processor.Simple != nil {
171 return nil, newErrInvalid("must not specify multiple span processor type")
172 }
173 if processor.Batch != nil {
174 exp, err := spanExporter(ctx, processor.Batch.Exporter)
175 if err != nil {
176 return nil, err
177 }
178 return batchSpanProcessor(processor.Batch, exp)
179 }
180 if processor.Simple != nil {
181 exp, err := spanExporter(ctx, processor.Simple.Exporter)
182 if err != nil {
183 return nil, err
184 }
185 return sdktrace.NewSimpleSpanProcessor(exp), nil
186 }
187 return nil, newErrInvalid("unsupported span processor type, must be one of simple or batch")
188 }
189
190 func otlpGRPCSpanExporter(ctx context.Context, otlpConfig *OTLPGrpcExporter) (sdktrace.SpanExporter, error) {
191 var opts []otlptracegrpc.Option
192
193 if otlpConfig.Endpoint != nil {
194 u, err := url.ParseRequestURI(*otlpConfig.Endpoint)
195 if err != nil {
196 return nil, errors.Join(newErrInvalid("endpoint parsing failed"), err)
197 }
198 // ParseRequestURI leaves the Host field empty when no
199 // scheme is specified (i.e. localhost:4317). This check is
200 // here to support the case where a user may not specify a
201 // scheme. The code does its best effort here by using
202 // otlpConfig.Endpoint as-is in that case.
203 if u.Host != "" {
204 opts = append(opts, otlptracegrpc.WithEndpoint(u.Host))
205 } else {
206 opts = append(opts, otlptracegrpc.WithEndpoint(*otlpConfig.Endpoint))
207 }
208
209 if u.Scheme == "http" || (u.Scheme != "https" && otlpConfig.Tls != nil && otlpConfig.Tls.Insecure != nil && *otlpConfig.Tls.Insecure) {
210 opts = append(opts, otlptracegrpc.WithInsecure())
211 }
212 }
213
214 if otlpConfig.Compression != nil {
215 switch *otlpConfig.Compression {
216 case compressionGzip:
217 opts = append(opts, otlptracegrpc.WithCompressor(*otlpConfig.Compression))
218 case compressionNone:
219 // none requires no options
220 default:
221 return nil, newErrInvalid(fmt.Sprintf("unsupported compression %q", *otlpConfig.Compression))
222 }
223 }
224 if otlpConfig.Timeout != nil && *otlpConfig.Timeout > 0 {
225 opts = append(opts, otlptracegrpc.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
226 }
227 headersConfig, err := createHeadersConfig(otlpConfig.Headers, otlpConfig.HeadersList)
228 if err != nil {
229 return nil, err
230 }
231 if len(headersConfig) > 0 {
232 opts = append(opts, otlptracegrpc.WithHeaders(headersConfig))
233 }
234
235 if otlpConfig.Tls != nil && (otlpConfig.Tls.CaFile != nil || otlpConfig.Tls.CertFile != nil || otlpConfig.Tls.KeyFile != nil) {
236 tlsConfig, err := tls.CreateConfig(otlpConfig.Tls.CaFile, otlpConfig.Tls.CertFile, otlpConfig.Tls.KeyFile)
237 if err != nil {
238 return nil, errors.Join(newErrInvalid("tls configuration"), err)
239 }
240 opts = append(opts, otlptracegrpc.WithTLSCredentials(credentials.NewTLS(tlsConfig)))
241 }
242
243 return otlptracegrpc.New(ctx, opts...)
244 }
245
246 func otlpHTTPSpanExporter(ctx context.Context, otlpConfig *OTLPHttpExporter) (sdktrace.SpanExporter, error) {
247 var opts []otlptracehttp.Option
248
249 if otlpConfig.Endpoint != nil {
250 u, err := url.ParseRequestURI(*otlpConfig.Endpoint)
251 if err != nil {
252 return nil, errors.Join(newErrInvalid("endpoint parsing failed"), err)
253 }
254 opts = append(opts, otlptracehttp.WithEndpoint(u.Host))
255
256 if u.Scheme == "http" {
257 opts = append(opts, otlptracehttp.WithInsecure())
258 }
259 if u.Path != "" {
260 opts = append(opts, otlptracehttp.WithURLPath(u.Path))
261 }
262 }
263 if otlpConfig.Compression != nil {
264 switch *otlpConfig.Compression {
265 case compressionGzip:
266 opts = append(opts, otlptracehttp.WithCompression(otlptracehttp.GzipCompression))
267 case compressionNone:
268 opts = append(opts, otlptracehttp.WithCompression(otlptracehttp.NoCompression))
269 default:
270 return nil, newErrInvalid(fmt.Sprintf("unsupported compression %q", *otlpConfig.Compression))
271 }
272 }
273 if otlpConfig.Timeout != nil && *otlpConfig.Timeout > 0 {
274 opts = append(opts, otlptracehttp.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
275 }
276 headersConfig, err := createHeadersConfig(otlpConfig.Headers, otlpConfig.HeadersList)
277 if err != nil {
278 return nil, err
279 }
280 if len(headersConfig) > 0 {
281 opts = append(opts, otlptracehttp.WithHeaders(headersConfig))
282 }
283
284 if otlpConfig.Tls != nil {
285 tlsConfig, err := tls.CreateConfig(otlpConfig.Tls.CaFile, otlpConfig.Tls.CertFile, otlpConfig.Tls.KeyFile)
286 if err != nil {
287 return nil, errors.Join(newErrInvalid("tls configuration"), err)
288 }
289 opts = append(opts, otlptracehttp.WithTLSClientConfig(tlsConfig))
290 }
291
292 return otlptracehttp.New(ctx, opts...)
293 }
294
295 func batchSpanProcessor(bsp *BatchSpanProcessor, exp sdktrace.SpanExporter) (sdktrace.SpanProcessor, error) {
296 var opts []sdktrace.BatchSpanProcessorOption
297 if err := validateBatchSpanProcessor(bsp); err != nil {
298 return nil, err
299 }
300 if bsp.ExportTimeout != nil {
301 opts = append(opts, sdktrace.WithExportTimeout(time.Millisecond*time.Duration(*bsp.ExportTimeout)))
302 }
303 if bsp.MaxExportBatchSize != nil {
304 opts = append(opts, sdktrace.WithMaxExportBatchSize(*bsp.MaxExportBatchSize))
305 }
306 if bsp.MaxQueueSize != nil {
307 opts = append(opts, sdktrace.WithMaxQueueSize(*bsp.MaxQueueSize))
308 }
309 if bsp.ScheduleDelay != nil {
310 opts = append(opts, sdktrace.WithBatchTimeout(time.Millisecond*time.Duration(*bsp.ScheduleDelay)))
311 }
312 return sdktrace.NewBatchSpanProcessor(exp, opts...), nil
313 }