Debian Codegraph @

exporters/stdout/stdoutmetric/internal/observ/instrumentation.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package observ provides observability for stdout metric exporter.
5 // This is an experimental feature controlled by the x.Observability feature flag.
6 package observ // import "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric/internal/observ"
7
8 import (
9 "context"
10 "errors"
11 "fmt"
12 "sync"
13 "time"
14
15 "go.opentelemetry.io/otel"
16 "go.opentelemetry.io/otel/attribute"
17 "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric/internal"
18 "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric/internal/x"
19 "go.opentelemetry.io/otel/metric"
20 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
21 "go.opentelemetry.io/otel/semconv/v1.40.0/otelconv"
22 )
23
24 const (
25 scope = "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric/internal/observ"
26
27 // ComponentType is a name identifying the type of the OpenTelemetry
28 // component. It is not a standardized OTel component type, so it uses the
29 // Go package prefixed type name to ensure uniqueness and identity.
30 ComponentType = "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric.exporter"
31
32 // Version is the current version of this instrumentation.
33 //
34 // This matches the version of the exporter.
35 Version = internal.Version
36 )
37
38 var (
39 measureAttrsPool = &sync.Pool{
40 New: func() any {
41 // "component.name" + "component.type" + "error.type"
42 const n = 1 + 1 + 1
43 s := make([]attribute.KeyValue, 0, n)
44 // Return a pointer to a slice instead of a slice itself
45 // to avoid allocations on every call.
46 return &s
47 },
48 }
49
50 addOptsPool = &sync.Pool{
51 New: func() any {
52 const n = 1 // WithAttributeSet
53 s := make([]metric.AddOption, 0, n)
54 return &s
55 },
56 }
57
58 recordOptsPool = &sync.Pool{
59 New: func() any {
60 const n = 1 // WithAttributeSet
61 s := make([]metric.RecordOption, 0, n)
62 return &s
63 },
64 }
65 )
66
67 func get[T any](p *sync.Pool) *[]T { return p.Get().(*[]T) }
68
69 func put[T any](p *sync.Pool, s *[]T) {
70 *s = (*s)[:0] // Reset.
71 p.Put(s)
72 }
73
74 // Instrumentation is the instrumentation for stdout metric exporter.
75 type Instrumentation struct {
76 inflight metric.Int64UpDownCounter
77 exported otelconv.SDKExporterMetricDataPointExported
78 duration otelconv.SDKExporterOperationDuration
79
80 attrs []attribute.KeyValue
81 addOpts []metric.AddOption
82 recordOpts []metric.RecordOption
83 }
84
85 // ExporterComponentName returns the component name attribute for the exporter
86 // with the provided ID.
87 func ExporterComponentName(id int64) attribute.KeyValue {
88 componentName := fmt.Sprintf("%s/%d", ComponentType, id)
89 return semconv.OTelComponentName(componentName)
90 }
91
92 // NewInstrumentation returns a new Instrumentation for the stdout metric exporter
93 // with the provided ID.
94 //
95 // If the experimental observability is disabled, nil is returned.
96 func NewInstrumentation(id int64) (*Instrumentation, error) {
97 if !x.Observability.Enabled() {
98 return nil, nil
99 }
100 attrs := []attribute.KeyValue{
101 ExporterComponentName(id),
102 semconv.OTelComponentTypeKey.String(ComponentType),
103 }
104 attrOpts := metric.WithAttributeSet(attribute.NewSet(attrs...))
105 addOpts := []metric.AddOption{attrOpts}
106 recordOpts := []metric.RecordOption{attrOpts}
107 em := &Instrumentation{
108 attrs: attrs,
109 addOpts: addOpts,
110 recordOpts: recordOpts,
111 }
112 mp := otel.GetMeterProvider()
113 m := mp.Meter(
114 scope,
115 metric.WithInstrumentationVersion(Version),
116 metric.WithSchemaURL(semconv.SchemaURL),
117 )
118
119 var err error
120 inflightMetric, e := otelconv.NewSDKExporterMetricDataPointInflight(m)
121 if e != nil {
122 e = fmt.Errorf("failed to create metric_data_point inflight metric: %w", e)
123 err = errors.Join(err, e)
124 }
125 em.inflight = inflightMetric.Inst()
126 if em.exported, e = otelconv.NewSDKExporterMetricDataPointExported(m); e != nil {
127 e = fmt.Errorf("failed to create metric_data_point exported metric: %w", e)
128 err = errors.Join(err, e)
129 }
130 if em.duration, e = otelconv.NewSDKExporterOperationDuration(m); e != nil {
131 e = fmt.Errorf("failed to create operation duration metric: %w", e)
132 err = errors.Join(err, e)
133 }
134 return em, err
135 }
136
137 // ExportMetrics instruments the Export method of the exporter. It returns an
138 // ExportOp that needs to be ended with End() when the export operation completes.
139 func (i *Instrumentation) ExportMetrics(ctx context.Context, count int64) ExportOp {
140 start := time.Now()
141
142 // Avoid work when observability is disabled.
143 if i.inflight.Enabled(ctx) {
144 i.inflight.Add(ctx, count, i.addOpts...)
145 }
146 return ExportOp{
147 ctx: ctx,
148 start: start,
149 nTraces: count,
150 inst: i,
151 }
152 }
153
154 // ExportOp is an in-progress ExportMetrics operation.
155 type ExportOp struct {
156 ctx context.Context
157 start time.Time
158 nTraces int64
159 inst *Instrumentation
160 }
161
162 // End ends the ExportMetrics operation, recording its duration.
163 //
164 // The err parameter indicates whether the operation failed. If err is not nil,
165 // it is added to metrics as attribute.
166 func (e ExportOp) End(err error) {
167 inflightEnabled := e.inst.inflight.Enabled(e.ctx)
168 exportedEnabled := e.inst.exported.Enabled(e.ctx)
169 durationEnabled := e.inst.duration.Enabled(e.ctx)
170
171 if !inflightEnabled && !exportedEnabled && !durationEnabled {
172 return
173 }
174
175 var durationSeconds float64
176 if durationEnabled {
177 durationSeconds = time.Since(e.start).Seconds()
178 }
179 if inflightEnabled {
180 e.inst.inflight.Add(e.ctx, -e.nTraces, e.inst.addOpts...)
181 }
182 if err == nil { // short circuit in case of success to avoid allocations
183 if exportedEnabled {
184 e.inst.exported.Inst().Add(e.ctx, e.nTraces, e.inst.addOpts...)
185 }
186 if durationEnabled {
187 e.inst.duration.Inst().Record(e.ctx, durationSeconds, e.inst.recordOpts...)
188 }
189 return
190 }
191
192 if !exportedEnabled && !durationEnabled {
193 return
194 }
195
196 attrs := get[attribute.KeyValue](measureAttrsPool)
197 defer func() {
198 put(measureAttrsPool, attrs)
199 }()
200 *attrs = append(*attrs, e.inst.attrs...)
201 *attrs = append(*attrs, semconv.ErrorType(err))
202
203 set := attribute.NewSet(*attrs...)
204 attrOpt := metric.WithAttributeSet(set)
205
206 if exportedEnabled {
207 addOpts := get[metric.AddOption](addOptsPool)
208 defer put(addOptsPool, addOpts)
209
210 *addOpts = append(*addOpts, attrOpt)
211 e.inst.exported.Inst().Add(e.ctx, e.nTraces, *addOpts...)
212 }
213 if durationEnabled {
214 recordOpts := get[metric.RecordOption](recordOptsPool)
215 defer put(recordOptsPool, recordOpts)
216
217 *recordOpts = append(*recordOpts, attrOpt)
218 e.inst.duration.Inst().Record(e.ctx, durationSeconds, *recordOpts...)
219 }
220 }