Debian Codegraph @

sdk/metric/manual_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 "fmt"
10 "sync"
11 "sync/atomic"
12
13 "go.opentelemetry.io/otel"
14 "go.opentelemetry.io/otel/internal/global"
15 "go.opentelemetry.io/otel/sdk/metric/internal/observ"
16 "go.opentelemetry.io/otel/sdk/metric/metricdata"
17 )
18
19 const (
20 // ManualReaderType uniquely identifies the OpenTelemetry Metric Reader component
21 // being instrumented.
22 manualReaderType = "go.opentelemetry.io/otel/sdk/metric/metric.ManualReader"
23 )
24
25 // ManualReader is a simple Reader that allows an application to
26 // read metrics on demand.
27 type ManualReader struct {
28 sdkProducer atomic.Value
29 shutdownOnce sync.Once
30
31 mu sync.Mutex
32 isShutdown bool
33 externalProducers atomic.Value
34
35 temporalitySelector TemporalitySelector
36 aggregationSelector AggregationSelector
37 cardinalityLimitSelector CardinalityLimitSelector
38
39 inst *observ.Instrumentation
40 }
41
42 // Compile time check the manualReader implements Reader and is comparable.
43 var _ = map[Reader]struct{}{&ManualReader{}: {}}
44
45 // NewManualReader returns a Reader which is directly called to collect metrics.
46 func NewManualReader(opts ...ManualReaderOption) *ManualReader {
47 cfg := newManualReaderConfig(opts)
48 r := &ManualReader{
49 temporalitySelector: cfg.temporalitySelector,
50 aggregationSelector: cfg.aggregationSelector,
51 cardinalityLimitSelector: cfg.cardinalityLimitSelector,
52 }
53 r.externalProducers.Store(cfg.producers)
54
55 var err error
56 r.inst, err = observ.NewInstrumentation(manualReaderType, nextManualReaderID())
57 if err != nil {
58 otel.Handle(err)
59 }
60
61 return r
62 }
63
64 var manualReaderIDCounter atomic.Int64
65
66 // nextManualReaderID returns an identifier for this manual reader,
67 // starting with 0 and incrementing by 1 each time it is called.
68 func nextManualReaderID() int64 {
69 return manualReaderIDCounter.Add(1) - 1
70 }
71
72 // register stores the sdkProducer which enables the caller
73 // to read metrics from the SDK on demand.
74 func (mr *ManualReader) register(p sdkProducer) {
75 // Only register once. If producer is already set, do nothing.
76 if !mr.sdkProducer.CompareAndSwap(nil, produceHolder{produce: p.produce}) {
77 msg := "did not register manual reader"
78 global.Error(errDuplicateRegister, msg)
79 }
80 }
81
82 // temporality reports the Temporality for the instrument kind provided.
83 func (mr *ManualReader) temporality(kind InstrumentKind) metricdata.Temporality {
84 return mr.temporalitySelector(kind)
85 }
86
87 // aggregation returns what Aggregation to use for kind.
88 func (mr *ManualReader) aggregation(
89 kind InstrumentKind,
90 ) Aggregation { // nolint:revive // import-shadow for method scoped by type.
91 return mr.aggregationSelector(kind)
92 }
93
94 // cardinalityLimit returns the cardinality limit for kind.
95 func (mr *ManualReader) cardinalityLimit(kind InstrumentKind) (int, bool) {
96 return mr.cardinalityLimitSelector(kind)
97 }
98
99 // Shutdown closes any connections and frees any resources used by the reader.
100 //
101 // This method is safe to call concurrently.
102 func (mr *ManualReader) Shutdown(context.Context) error {
103 err := ErrReaderShutdown
104 mr.shutdownOnce.Do(func() {
105 // Any future call to Collect will now return ErrReaderShutdown.
106 mr.sdkProducer.Store(produceHolder{
107 produce: shutdownProducer{}.produce,
108 })
109 mr.mu.Lock()
110 defer mr.mu.Unlock()
111 mr.isShutdown = true
112 // release references to Producer(s)
113 mr.externalProducers.Store([]Producer{})
114 err = nil
115 })
116 return err
117 }
118
119 // Collect gathers all metric data related to the Reader from
120 // the SDK and other Producers and stores the result in rm.
121 //
122 // Collect will return an error if called after shutdown.
123 // Collect will return an error if rm is a nil ResourceMetrics.
124 // Collect will return an error if the context's Done channel is closed.
125 //
126 // This method is safe to call concurrently.
127 func (mr *ManualReader) Collect(ctx context.Context, rm *metricdata.ResourceMetrics) error {
128 var err error
129 if mr.inst != nil {
130 cp := mr.inst.CollectMetrics(ctx)
131 defer func() { cp.End(err) }()
132 }
133
134 if rm == nil {
135 err = errors.New("manual reader: *metricdata.ResourceMetrics is nil")
136 return err
137 }
138 p := mr.sdkProducer.Load()
139 if p == nil {
140 err = ErrReaderNotRegistered
141 return err
142 }
143
144 ph, ok := p.(produceHolder)
145 if !ok {
146 // The atomic.Value is entirely in the periodicReader's control so
147 // this should never happen. In the unforeseen case that this does
148 // happen, return an error instead of panicking so a users code does
149 // not halt in the processes.
150 err = fmt.Errorf("manual reader: invalid producer: %T", p)
151 return err
152 }
153
154 err = ph.produce(ctx, rm)
155 if err != nil {
156 return err
157 }
158 for _, producer := range mr.externalProducers.Load().([]Producer) {
159 externalMetrics, e := producer.Produce(ctx)
160 if e != nil {
161 err = errors.Join(err, e)
162 }
163 rm.ScopeMetrics = append(rm.ScopeMetrics, externalMetrics...)
164 }
165
166 global.Debug("ManualReader collection", "Data", rm)
167
168 return err
169 }
170
171 // MarshalLog returns logging data about the ManualReader.
172 func (r *ManualReader) MarshalLog() any {
173 r.mu.Lock()
174 down := r.isShutdown
175 r.mu.Unlock()
176 return struct {
177 Type string
178 Registered bool
179 Shutdown bool
180 }{
181 Type: "ManualReader",
182 Registered: r.sdkProducer.Load() != nil,
183 Shutdown: down,
184 }
185 }
186
187 // manualReaderConfig contains configuration options for a ManualReader.
188 type manualReaderConfig struct {
189 temporalitySelector TemporalitySelector
190 aggregationSelector AggregationSelector
191 cardinalityLimitSelector CardinalityLimitSelector
192 producers []Producer
193 }
194
195 // newManualReaderConfig returns a manualReaderConfig configured with options.
196 func newManualReaderConfig(opts []ManualReaderOption) manualReaderConfig {
197 cfg := manualReaderConfig{
198 temporalitySelector: DefaultTemporalitySelector,
199 aggregationSelector: DefaultAggregationSelector,
200 cardinalityLimitSelector: defaultCardinalityLimitSelector,
201 }
202 for _, opt := range opts {
203 cfg = opt.applyManual(cfg)
204 }
205 return cfg
206 }
207
208 // ManualReaderOption applies a configuration option value to a ManualReader.
209 type ManualReaderOption interface {
210 applyManual(manualReaderConfig) manualReaderConfig
211 }
212
213 // WithTemporalitySelector sets the TemporalitySelector a reader will use to
214 // determine the Temporality of an instrument based on its kind. If this
215 // option is not used, the reader will use the DefaultTemporalitySelector.
216 func WithTemporalitySelector(selector TemporalitySelector) ManualReaderOption {
217 return temporalitySelectorOption{selector: selector}
218 }
219
220 type temporalitySelectorOption struct {
221 selector func(instrument InstrumentKind) metricdata.Temporality
222 }
223
224 // applyManual returns a manualReaderConfig with option applied.
225 func (t temporalitySelectorOption) applyManual(mrc manualReaderConfig) manualReaderConfig {
226 mrc.temporalitySelector = t.selector
227 return mrc
228 }
229
230 // WithAggregationSelector sets the AggregationSelector a reader will use to
231 // determine the aggregation to use for an instrument based on its kind. If
232 // this option is not used, the reader will use the DefaultAggregationSelector
233 // or the aggregation explicitly passed for a view matching an instrument.
234 func WithAggregationSelector(selector AggregationSelector) ManualReaderOption {
235 return aggregationSelectorOption{selector: selector}
236 }
237
238 type aggregationSelectorOption struct {
239 selector AggregationSelector
240 }
241
242 // applyManual returns a manualReaderConfig with option applied.
243 func (t aggregationSelectorOption) applyManual(c manualReaderConfig) manualReaderConfig {
244 c.aggregationSelector = t.selector
245 return c
246 }