Debian Codegraph @

exporters/otlp/otlptrace/otlptracegrpc/internal/observ/instrumentation.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package observ // import "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ"
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "sync"
11 "time"
12
13 "google.golang.org/grpc/codes"
14
15 "go.opentelemetry.io/otel"
16 "go.opentelemetry.io/otel/attribute"
17 "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal"
18 "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/x"
19 "go.opentelemetry.io/otel/internal/global"
20 "go.opentelemetry.io/otel/metric"
21 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
22 "go.opentelemetry.io/otel/semconv/v1.40.0/otelconv"
23 )
24
25 const (
26 // ScopeName is the unique name of the meter used for instrumentation.
27 ScopeName = "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc/internal/observ"
28
29 // SchemaURL is the schema URL of the metrics produced by this
30 // instrumentation.
31 SchemaURL = semconv.SchemaURL
32
33 // Version is the current version of this instrumentation.
34 //
35 // This matches the version of the exporter.
36 Version = internal.Version
37 )
38
39 var (
40 measureAttrsPool = &sync.Pool{
41 New: func() any {
42 const n = 1 + // component.name
43 1 + // component.type
44 1 + // server.addr
45 1 + // server.port
46 1 + // error.type
47 1 // rpc.grpc.status_code
48 s := make([]attribute.KeyValue, 0, n)
49 // Return a pointer to a slice instead of a slice itself
50 // to avoid allocations on every call.
51 return &s
52 },
53 }
54
55 addOptPool = &sync.Pool{
56 New: func() any {
57 const n = 1 // WithAttributeSet
58 o := make([]metric.AddOption, 0, n)
59 return &o
60 },
61 }
62
63 recordOptPool = &sync.Pool{
64 New: func() any {
65 const n = 1 // WithAttributeSet
66 o := make([]metric.RecordOption, 0, n)
67 return &o
68 },
69 }
70 )
71
72 func get[T any](p *sync.Pool) *[]T { return p.Get().(*[]T) }
73
74 func put[T any](p *sync.Pool, s *[]T) {
75 *s = (*s)[:0] // Reset.
76 p.Put(s)
77 }
78
79 // ComponentName returns the component name for the exporter with the
80 // provided ID.
81 func ComponentName(id int64) string {
82 t := semconv.OTelComponentTypeOtlpGRPCSpanExporter.Value.AsString()
83 return fmt.Sprintf("%s/%d", t, id)
84 }
85
86 // Instrumentation is experimental instrumentation for the exporter.
87 type Instrumentation struct {
88 inflightSpans metric.Int64UpDownCounter
89 exportedSpans metric.Int64Counter
90 opDuration metric.Float64Histogram
91
92 attrs []attribute.KeyValue
93 addOpt metric.AddOption
94 recOpt metric.RecordOption
95 }
96
97 // NewInstrumentation returns instrumentation for an OTLP over gPRC trace
98 // exporter with the provided ID using the global MeterProvider.
99 //
100 // The id should be the unique exporter instance ID. It is used
101 // to set the "component.name" attribute.
102 //
103 // The target is the endpoint the exporter is exporting to.
104 //
105 // If the experimental observability is disabled, nil is returned.
106 func NewInstrumentation(id int64, target string) (*Instrumentation, error) {
107 if !x.Observability.Enabled() {
108 return nil, nil
109 }
110
111 attrs := BaseAttrs(id, target)
112 i := &Instrumentation{
113 attrs: attrs,
114 addOpt: metric.WithAttributeSet(attribute.NewSet(attrs...)),
115
116 // Do not modify attrs (NewSet sorts in-place), make a new slice.
117 recOpt: metric.WithAttributeSet(attribute.NewSet(append(
118 // Default to OK status code.
119 []attribute.KeyValue{
120 semconv.RPCResponseStatusCode(codes.OK.String()),
121 },
122 attrs...,
123 )...)),
124 }
125
126 mp := otel.GetMeterProvider()
127 m := mp.Meter(
128 ScopeName,
129 metric.WithInstrumentationVersion(Version),
130 metric.WithSchemaURL(SchemaURL),
131 )
132
133 var err error
134
135 inflightSpans, e := otelconv.NewSDKExporterSpanInflight(m)
136 if e != nil {
137 e = fmt.Errorf("failed to create span inflight metric: %w", e)
138 err = errors.Join(err, e)
139 }
140 i.inflightSpans = inflightSpans.Inst()
141
142 exportedSpans, e := otelconv.NewSDKExporterSpanExported(m)
143 if e != nil {
144 e = fmt.Errorf("failed to create span exported metric: %w", e)
145 err = errors.Join(err, e)
146 }
147 i.exportedSpans = exportedSpans.Inst()
148
149 opDuration, e := otelconv.NewSDKExporterOperationDuration(m)
150 if e != nil {
151 e = fmt.Errorf("failed to create operation duration metric: %w", e)
152 err = errors.Join(err, e)
153 }
154 i.opDuration = opDuration.Inst()
155
156 return i, err
157 }
158
159 // BaseAttrs returns the base attributes for the exporter with the provided ID
160 // and target.
161 //
162 // The id should be the unique exporter instance ID. It is used
163 // to set the "component.name" attribute.
164 //
165 // The target is the gRPC target the exporter is exporting to. It is expected
166 // to be the output of the Client's CanonicalTarget method.
167 func BaseAttrs(id int64, target string) []attribute.KeyValue {
168 host, port, err := ParseCanonicalTarget(target)
169 if err != nil || (host == "" && port < 0) {
170 if err != nil {
171 global.Debug("failed to parse target", "target", target, "error", err)
172 }
173 return []attribute.KeyValue{
174 semconv.OTelComponentName(ComponentName(id)),
175 semconv.OTelComponentTypeOtlpGRPCSpanExporter,
176 }
177 }
178
179 // Do not use append so the slice is exactly allocated.
180
181 if port < 0 {
182 return []attribute.KeyValue{
183 semconv.OTelComponentName(ComponentName(id)),
184 semconv.OTelComponentTypeOtlpGRPCSpanExporter,
185 semconv.ServerAddress(host),
186 }
187 }
188
189 if host == "" {
190 return []attribute.KeyValue{
191 semconv.OTelComponentName(ComponentName(id)),
192 semconv.OTelComponentTypeOtlpGRPCSpanExporter,
193 semconv.ServerPort(port),
194 }
195 }
196
197 return []attribute.KeyValue{
198 semconv.OTelComponentName(ComponentName(id)),
199 semconv.OTelComponentTypeOtlpGRPCSpanExporter,
200 semconv.ServerAddress(host),
201 semconv.ServerPort(port),
202 }
203 }
204
205 // ExportSpans instruments the ExportSpans method of the exporter. It returns
206 // an [ExportOp] that must have its [ExportOp.End] method called when the
207 // ExportSpans method returns.
208 func (i *Instrumentation) ExportSpans(ctx context.Context, nSpans int) ExportOp {
209 start := time.Now()
210
211 if i.inflightSpans.Enabled(ctx) {
212 addOpt := get[metric.AddOption](addOptPool)
213 defer put(addOptPool, addOpt)
214 *addOpt = append(*addOpt, i.addOpt)
215 i.inflightSpans.Add(ctx, int64(nSpans), *addOpt...)
216 }
217
218 return ExportOp{
219 ctx: ctx,
220 start: start,
221 nSpans: int64(nSpans),
222 inst: i,
223 }
224 }
225
226 // ExportOp tracks the operation being observed by [Instrumentation.ExportSpans].
227 type ExportOp struct {
228 ctx context.Context
229 start time.Time
230 nSpans int64
231
232 inst *Instrumentation
233 }
234
235 // End completes the observation of the operation being observed by a call to
236 // [Instrumentation.ExportSpans].
237 //
238 // Any error that is encountered is provided as err.
239 //
240 // If err is not nil, all spans will be recorded as failures unless error is of
241 // type [internal.PartialSuccess]. In the case of a PartialSuccess, the number
242 // of successfully exported spans will be determined by inspecting the
243 // RejectedItems field of the PartialSuccess.
244 func (e ExportOp) End(err error, code codes.Code) {
245 addOpt := get[metric.AddOption](addOptPool)
246 defer put(addOptPool, addOpt)
247 *addOpt = append(*addOpt, e.inst.addOpt)
248
249 if e.inst.inflightSpans.Enabled(e.ctx) {
250 e.inst.inflightSpans.Add(e.ctx, -e.nSpans, *addOpt...)
251 }
252
253 success := successful(e.nSpans, err)
254 // Record successfully exported spans, even if the value is 0 which are
255 // meaningful to distribution aggregations.
256 if e.inst.exportedSpans.Enabled(e.ctx) {
257 e.inst.exportedSpans.Add(e.ctx, success, *addOpt...)
258 }
259
260 if err != nil && e.inst.exportedSpans.Enabled(e.ctx) {
261 attrs := get[attribute.KeyValue](measureAttrsPool)
262 defer put(measureAttrsPool, attrs)
263 *attrs = append(*attrs, e.inst.attrs...)
264 *attrs = append(*attrs, semconv.ErrorType(err))
265
266 // Do not inefficiently make a copy of attrs by using
267 // WithAttributes instead of WithAttributeSet.
268 o := metric.WithAttributeSet(attribute.NewSet(*attrs...))
269 // Reset addOpt with new attribute set.
270 *addOpt = append((*addOpt)[:0], o)
271
272 e.inst.exportedSpans.Add(e.ctx, e.nSpans-success, *addOpt...)
273 }
274
275 if e.inst.opDuration.Enabled(e.ctx) {
276 recOpt := get[metric.RecordOption](recordOptPool)
277 defer put(recordOptPool, recOpt)
278 *recOpt = append(*recOpt, e.inst.recordOption(err, code))
279
280 d := time.Since(e.start).Seconds()
281 e.inst.opDuration.Record(e.ctx, d, *recOpt...)
282 }
283 }
284
285 // recordOption returns a RecordOption with attributes representing the
286 // outcome of the operation being recorded.
287 //
288 // If err is nil and code is codes.OK, the default recOpt of the
289 // Instrumentation is returned.
290 //
291 // If err is not nil or code is not codes.OK, a new RecordOption is returned
292 // with the base attributes of the Instrumentation plus the rpc.grpc.status_code
293 // attribute set to the provided code, and if err is not nil, the error.type
294 // attribute set to the type of the error.
295 func (i *Instrumentation) recordOption(err error, code codes.Code) metric.RecordOption {
296 if err == nil && code == codes.OK {
297 return i.recOpt
298 }
299
300 attrs := get[attribute.KeyValue](measureAttrsPool)
301 defer put(measureAttrsPool, attrs)
302 *attrs = append(*attrs, i.attrs...)
303
304 *attrs = append(*attrs, semconv.RPCResponseStatusCode(code.String()))
305 if err != nil {
306 *attrs = append(*attrs, semconv.ErrorType(err))
307 }
308
309 // Do not inefficiently make a copy of attrs by using WithAttributes
310 // instead of WithAttributeSet.
311 return metric.WithAttributeSet(attribute.NewSet(*attrs...))
312 }
313
314 // successful returns the number of successfully exported spans out of the n
315 // that were exported based on the provided error.
316 //
317 // If err is nil, n is returned. All spans were successfully exported.
318 //
319 // If err is not nil and not an [internal.PartialSuccess] error, 0 is returned.
320 // It is assumed all spans failed to be exported.
321 //
322 // If err is an [internal.PartialSuccess] error, the number of successfully
323 // exported spans is computed by subtracting the RejectedItems field from n. If
324 // RejectedItems is negative, n is returned. If RejectedItems is greater than
325 // n, 0 is returned.
326 func successful(n int64, err error) int64 {
327 if err == nil {
328 return n // All spans successfully exported.
329 }
330 // Split rejection calculation so successful is inlinable.
331 return n - rejected(n, err)
332 }
333
334 var errPartialPool = &sync.Pool{
335 New: func() any { return new(internal.PartialSuccess) },
336 }
337
338 // rejected returns how many out of the n spans exporter were rejected based on
339 // the provided non-nil err.
340 func rejected(n int64, err error) int64 {
341 ps := errPartialPool.Get().(*internal.PartialSuccess)
342 defer errPartialPool.Put(ps)
343 // Check for partial success.
344 if errors.As(err, ps) {
345 // Bound RejectedItems to [0, n]. This should not be needed,
346 // but be defensive as this is from an external source.
347 return min(max(ps.RejectedItems, 0), n)
348 }
349 return n // All spans rejected.
350 }