Debian Codegraph @

sdk/metric/reader.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package metric // import "go.opentelemetry.io/otel/sdk/metric"
5
6 import (
7 "context"
8 "errors"
9
10 "go.opentelemetry.io/otel/sdk/metric/metricdata"
11 )
12
13 // errDuplicateRegister is logged by a Reader when an attempt to registered it
14 // more than once occurs.
15 var errDuplicateRegister = errors.New("duplicate reader registration")
16
17 // ErrReaderNotRegistered is returned if Collect or Shutdown are called before
18 // the reader is registered with a MeterProvider.
19 var ErrReaderNotRegistered = errors.New("reader is not registered")
20
21 // ErrReaderShutdown is returned if Collect or Shutdown are called after a
22 // reader has been Shutdown once.
23 var ErrReaderShutdown = errors.New("reader is shutdown")
24
25 // errNonPositiveDuration is logged when an environmental variable
26 // has non-positive value.
27 var errNonPositiveDuration = errors.New("non-positive duration")
28
29 // Reader is the interface used between the SDK and an
30 // exporter. Control flow is bi-directional through the
31 // Reader, since the SDK initiates ForceFlush and Shutdown
32 // while the exporter initiates collection. The Register() method here
33 // informs the Reader that it can begin reading, signaling the
34 // start of bi-directional control flow.
35 //
36 // Typically, push-based exporters that are periodic will
37 // implement PeriodicExporter themselves and construct a
38 // PeriodicReader to satisfy this interface.
39 //
40 // Pull-based exporters will typically implement Register
41 // themselves, since they read on demand.
42 //
43 // Warning: methods may be added to this interface in minor releases.
44 type Reader interface {
45 // register registers a Reader with a MeterProvider.
46 // The producer argument allows the Reader to signal the sdk to collect
47 // and send aggregated metric measurements.
48 register(sdkProducer)
49
50 // temporality reports the Temporality for the instrument kind provided.
51 //
52 // This method needs to be concurrent safe with itself and all the other
53 // Reader methods.
54 temporality(InstrumentKind) metricdata.Temporality
55
56 // aggregation returns what Aggregation to use for an instrument kind.
57 //
58 // This method needs to be concurrent safe with itself and all the other
59 // Reader methods.
60 aggregation(InstrumentKind) Aggregation // nolint:revive // import-shadow for method scoped by type.
61
62 // cardinalityLimit returns the cardinality limit for an instrument kind.
63 // When fallback is true, the pipeline falls back to the provider's global limit.
64 // When fallback is false, limit is used: 0 or less means no limit (unlimited),
65 // and a positive value is the limit for that kind.
66 //
67 // This method needs to be concurrent safe with itself and all the other
68 // Reader methods.
69 cardinalityLimit(InstrumentKind) (limit int, fallback bool)
70
71 // Collect gathers and returns all metric data related to the Reader from
72 // the SDK and stores it in rm. An error is returned if this is called
73 // after Shutdown or if rm is nil.
74 //
75 // This method needs to be concurrent safe, and the cancellation of the
76 // passed context is expected to be honored.
77 Collect(ctx context.Context, rm *metricdata.ResourceMetrics) error
78 // DO NOT CHANGE: any modification will not be backwards compatible and
79 // must never be done outside of a new major release.
80
81 // Shutdown flushes all metric measurements held in an export pipeline and releases any
82 // held computational resources.
83 //
84 // This deadline or cancellation of the passed context are honored. An appropriate
85 // error will be returned in these situations. There is no guaranteed that all
86 // telemetry be flushed or all resources have been released in these
87 // situations.
88 //
89 // After Shutdown is called, calls to Collect will perform no operation and instead will return
90 // an error indicating the shutdown state.
91 //
92 // This method needs to be concurrent safe.
93 Shutdown(context.Context) error
94 // DO NOT CHANGE: any modification will not be backwards compatible and
95 // must never be done outside of a new major release.
96 }
97
98 // sdkProducer produces metrics for a Reader.
99 type sdkProducer interface {
100 // produce returns aggregated metrics from a single collection.
101 //
102 // This method is safe to call concurrently.
103 produce(context.Context, *metricdata.ResourceMetrics) error
104 }
105
106 // Producer produces metrics for a Reader from an external source.
107 type Producer interface {
108 // DO NOT CHANGE: any modification will not be backwards compatible and
109 // must never be done outside of a new major release.
110
111 // Produce returns aggregated metrics from an external source.
112 //
113 // This method should be safe to call concurrently.
114 Produce(context.Context) ([]metricdata.ScopeMetrics, error)
115 // DO NOT CHANGE: any modification will not be backwards compatible and
116 // must never be done outside of a new major release.
117 }
118
119 // produceHolder is used as an atomic.Value to wrap the non-concrete producer
120 // type.
121 type produceHolder struct {
122 produce func(context.Context, *metricdata.ResourceMetrics) error
123 }
124
125 // shutdownProducer produces an ErrReaderShutdown error always.
126 type shutdownProducer struct{}
127
128 // produce returns an ErrReaderShutdown error.
129 func (shutdownProducer) produce(context.Context, *metricdata.ResourceMetrics) error {
130 return ErrReaderShutdown
131 }
132
133 // TemporalitySelector selects the temporality to use based on the InstrumentKind.
134 type TemporalitySelector func(InstrumentKind) metricdata.Temporality
135
136 // DefaultTemporalitySelector is the default TemporalitySelector used if
137 // WithTemporalitySelector is not provided. CumulativeTemporality will be used
138 // for all instrument kinds if this TemporalitySelector is used.
139 func DefaultTemporalitySelector(k InstrumentKind) metricdata.Temporality {
140 return CumulativeTemporalitySelector(k)
141 }
142
143 // CumulativeTemporalitySelector is the TemporalitySelector that uses
144 // a cumulative temporality for all instrument kinds.
145 func CumulativeTemporalitySelector(InstrumentKind) metricdata.Temporality {
146 return metricdata.CumulativeTemporality
147 }
148
149 // DeltaTemporalitySelector is the TemporalitySelector that uses
150 // a delta temporality for instrument kinds: counter, histogram, observable counter
151 // All other instruments use cumulative temporality.
152 func DeltaTemporalitySelector(k InstrumentKind) metricdata.Temporality {
153 switch k {
154 case InstrumentKindCounter, InstrumentKindHistogram, InstrumentKindObservableCounter:
155 return metricdata.DeltaTemporality
156 default:
157 return metricdata.CumulativeTemporality
158 }
159 }
160
161 // LowMemoryTemporalitySelector is the TemporalitySelector that uses
162 // delta temporality for counters and histograms. All other instruments use
163 // cumulative temporality.
164 func LowMemoryTemporalitySelector(k InstrumentKind) metricdata.Temporality {
165 switch k {
166 case InstrumentKindCounter, InstrumentKindHistogram:
167 return metricdata.DeltaTemporality
168 default:
169 return metricdata.CumulativeTemporality
170 }
171 }
172
173 // AggregationSelector selects the aggregation and the parameters to use for
174 // that aggregation based on the InstrumentKind.
175 //
176 // If the Aggregation returned is nil or DefaultAggregation, the selection from
177 // DefaultAggregationSelector will be used.
178 type AggregationSelector func(InstrumentKind) Aggregation
179
180 // DefaultAggregationSelector returns the default aggregation and parameters
181 // that will be used to summarize measurement made from an instrument of
182 // InstrumentKind. This AggregationSelector using the following selection
183 // mapping: Counter ⇨ Sum, Observable Counter ⇨ Sum, UpDownCounter ⇨ Sum,
184 // Observable UpDownCounter ⇨ Sum, Observable Gauge ⇨ LastValue,
185 // Histogram ⇨ ExplicitBucketHistogram.
186 func DefaultAggregationSelector(ik InstrumentKind) Aggregation {
187 switch ik {
188 case InstrumentKindCounter,
189 InstrumentKindUpDownCounter,
190 InstrumentKindObservableCounter,
191 InstrumentKindObservableUpDownCounter:
192 return AggregationSum{}
193 case InstrumentKindObservableGauge, InstrumentKindGauge:
194 return AggregationLastValue{}
195 case InstrumentKindHistogram:
196 return AggregationExplicitBucketHistogram{
197 Boundaries: []float64{0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000},
198 NoMinMax: false,
199 }
200 }
201 panic("unknown instrument kind")
202 }
203
204 // CardinalityLimitSelector selects the cardinality limit to use based on the
205 // InstrumentKind. The cardinality limit is the maximum number of distinct
206 // attribute sets that can be recorded for a single instrument.
207 //
208 // The selector returns (limit, fallback). When fallback is true, the pipeline
209 // falls back to the provider's global cardinality limit.
210 // When fallback is false, the limit is applied: a value of 0 or less means
211 // no limit, and a positive value is the limit for that kind.
212 // To avoid overriding the provider's global limit, return (0, true).
213 type CardinalityLimitSelector func(InstrumentKind) (limit int, fallback bool)
214
215 // defaultCardinalityLimitSelector is the default CardinalityLimitSelector used
216 // if WithCardinalityLimitSelector is not provided. It returns (0, true) for all
217 // instrument kinds, allowing the pipeline to fall back to the provider's global
218 // limit.
219 func defaultCardinalityLimitSelector(_ InstrumentKind) (int, bool) {
220 return 0, true
221 }
222
223 // ReaderOption is an option which can be applied to manual or Periodic
224 // readers.
225 type ReaderOption interface {
226 PeriodicReaderOption
227 ManualReaderOption
228 }
229
230 // WithProducer registers producers as an external Producer of metric data
231 // for this Reader.
232 func WithProducer(p Producer) ReaderOption {
233 return producerOption{p: p}
234 }
235
236 type producerOption struct {
237 p Producer
238 }
239
240 // applyManual returns a manualReaderConfig with option applied.
241 func (o producerOption) applyManual(c manualReaderConfig) manualReaderConfig {
242 c.producers = append(c.producers, o.p)
243 return c
244 }
245
246 // applyPeriodic returns a periodicReaderConfig with option applied.
247 func (o producerOption) applyPeriodic(c periodicReaderConfig) periodicReaderConfig {
248 c.producers = append(c.producers, o.p)
249 return c
250 }
251
252 // WithCardinalityLimitSelector sets the CardinalityLimitSelector a reader will
253 // use to determine the cardinality limit for an instrument based on its kind.
254 // If this option is not used, the reader will use the
255 // defaultCardinalityLimitSelector.
256 //
257 // The selector should return (limit, false) to set a positive limit,
258 // (0, false) to explicitly specify unlimited, or
259 // (0, true) to fall back to the provider's global limit.
260 //
261 // See [CardinalityLimitSelector] for more details.
262 func WithCardinalityLimitSelector(selector CardinalityLimitSelector) ReaderOption {
263 return cardinalityLimitSelectorOption{selector: selector}
264 }
265
266 type cardinalityLimitSelectorOption struct {
267 selector CardinalityLimitSelector
268 }
269
270 // applyManual returns a manualReaderConfig with option applied.
271 func (o cardinalityLimitSelectorOption) applyManual(c manualReaderConfig) manualReaderConfig {
272 c.cardinalityLimitSelector = o.selector
273 return c
274 }
275
276 // applyPeriodic returns a periodicReaderConfig with option applied.
277 func (o cardinalityLimitSelectorOption) applyPeriodic(c periodicReaderConfig) periodicReaderConfig {
278 c.cardinalityLimitSelector = o.selector
279 return c
280 }