Debian Codegraph @

sdk/metric/config.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 "os"
10 "strconv"
11 "strings"
12 "sync"
13
14 "go.opentelemetry.io/otel"
15 "go.opentelemetry.io/otel/sdk/metric/exemplar"
16 "go.opentelemetry.io/otel/sdk/resource"
17 )
18
19 // config contains configuration options for a MeterProvider.
20 type config struct {
21 res *resource.Resource
22 readers []Reader
23 views []View
24 exemplarFilter exemplar.Filter
25 cardinalityLimit int
26 }
27
28 const defaultCardinalityLimit = 0
29
30 // readerSignals returns a force-flush and shutdown function for a
31 // MeterProvider to call in their respective options. All Readers c contains
32 // will have their force-flush and shutdown methods unified into returned
33 // single functions.
34 func (c config) readerSignals() (forceFlush, shutdown func(context.Context) error) {
35 var fFuncs, sFuncs []func(context.Context) error
36 for _, r := range c.readers {
37 sFuncs = append(sFuncs, r.Shutdown)
38 if f, ok := r.(interface{ ForceFlush(context.Context) error }); ok {
39 fFuncs = append(fFuncs, f.ForceFlush)
40 }
41 }
42
43 return unify(fFuncs), unifyShutdown(sFuncs)
44 }
45
46 // unify unifies calling all of funcs into a single function call. All errors
47 // returned from calls to funcs will be unify into a single error return
48 // value.
49 func unify(funcs []func(context.Context) error) func(context.Context) error {
50 return func(ctx context.Context) error {
51 var err error
52 for _, f := range funcs {
53 if e := f(ctx); e != nil {
54 err = errors.Join(err, e)
55 }
56 }
57 return err
58 }
59 }
60
61 // unifyShutdown unifies calling all of funcs once for a shutdown. If called
62 // more than once, an ErrReaderShutdown error is returned.
63 func unifyShutdown(funcs []func(context.Context) error) func(context.Context) error {
64 f := unify(funcs)
65 var once sync.Once
66 return func(ctx context.Context) error {
67 err := ErrReaderShutdown
68 once.Do(func() { err = f(ctx) })
69 return err
70 }
71 }
72
73 // newConfig returns a config configured with options.
74 func newConfig(options []Option) config {
75 conf := config{
76 res: resource.Default(),
77 exemplarFilter: exemplar.TraceBasedFilter,
78 cardinalityLimit: cardinalityLimitFromEnv(),
79 }
80 for _, o := range meterProviderOptionsFromEnv() {
81 conf = o.apply(conf)
82 }
83 for _, o := range options {
84 conf = o.apply(conf)
85 }
86 return conf
87 }
88
89 // Option applies a configuration option value to a MeterProvider.
90 type Option interface {
91 apply(config) config
92 }
93
94 // optionFunc applies a set of options to a config.
95 type optionFunc func(config) config
96
97 // apply returns a config with option(s) applied.
98 func (o optionFunc) apply(conf config) config {
99 return o(conf)
100 }
101
102 // WithResource associates a Resource with a MeterProvider. This Resource
103 // represents the entity producing telemetry and is associated with all Meters
104 // the MeterProvider will create.
105 //
106 // By default, if this Option is not used, the default Resource from the
107 // go.opentelemetry.io/otel/sdk/resource package will be used.
108 func WithResource(res *resource.Resource) Option {
109 return optionFunc(func(conf config) config {
110 var err error
111 conf.res, err = resource.Merge(resource.Environment(), res)
112 if err != nil {
113 otel.Handle(err)
114 }
115 return conf
116 })
117 }
118
119 // WithReader associates Reader r with a MeterProvider.
120 //
121 // By default, if this option is not used, the MeterProvider will perform no
122 // operations; no data will be exported without a Reader.
123 func WithReader(r Reader) Option {
124 return optionFunc(func(cfg config) config {
125 if r == nil {
126 return cfg
127 }
128 cfg.readers = append(cfg.readers, r)
129 return cfg
130 })
131 }
132
133 // WithView associates views with a MeterProvider.
134 //
135 // Views are appended to existing ones in a MeterProvider if this option is
136 // used multiple times.
137 //
138 // By default, if this option is not used, the MeterProvider will use the
139 // default view.
140 func WithView(views ...View) Option {
141 return optionFunc(func(cfg config) config {
142 cfg.views = append(cfg.views, views...)
143 return cfg
144 })
145 }
146
147 // WithExemplarFilter configures the exemplar filter.
148 //
149 // The exemplar filter determines which measurements are offered to the
150 // exemplar reservoir, but the exemplar reservoir makes the final decision of
151 // whether to store an exemplar.
152 //
153 // By default, the [exemplar.SampledFilter]
154 // is used. Exemplars can be entirely disabled by providing the
155 // [exemplar.AlwaysOffFilter].
156 func WithExemplarFilter(filter exemplar.Filter) Option {
157 return optionFunc(func(cfg config) config {
158 cfg.exemplarFilter = filter
159 return cfg
160 })
161 }
162
163 // WithCardinalityLimit sets the global cardinality limit for the MeterProvider.
164 //
165 // The cardinality limit is the hard limit on the number of metric datapoints
166 // that can be collected for a single instrument in a single collect cycle.
167 //
168 // Setting this to a zero or negative value means no limit is applied.
169 // This value applies to all instrument kinds, but can be overridden per kind by
170 // the reader's cardinality limit selector (see [WithCardinalityLimitSelector]).
171 func WithCardinalityLimit(limit int) Option {
172 // For backward compatibility, the environment variable `OTEL_GO_X_CARDINALITY_LIMIT`
173 // can also be used to set this value.
174 return optionFunc(func(cfg config) config {
175 cfg.cardinalityLimit = limit
176 return cfg
177 })
178 }
179
180 func meterProviderOptionsFromEnv() []Option {
181 var opts []Option
182 // https://github.com/open-telemetry/opentelemetry-specification/blob/d4b241f451674e8f611bb589477680341006ad2b/specification/configuration/sdk-environment-variables.md#exemplar
183 const filterEnvKey = "OTEL_METRICS_EXEMPLAR_FILTER"
184
185 switch strings.ToLower(strings.TrimSpace(os.Getenv(filterEnvKey))) {
186 case "always_on":
187 opts = append(opts, WithExemplarFilter(exemplar.AlwaysOnFilter))
188 case "always_off":
189 opts = append(opts, WithExemplarFilter(exemplar.AlwaysOffFilter))
190 case "trace_based":
191 opts = append(opts, WithExemplarFilter(exemplar.TraceBasedFilter))
192 }
193 return opts
194 }
195
196 func cardinalityLimitFromEnv() int {
197 const cardinalityLimitKey = "OTEL_GO_X_CARDINALITY_LIMIT"
198 v := strings.TrimSpace(os.Getenv(cardinalityLimitKey))
199 if v == "" {
200 return defaultCardinalityLimit
201 }
202 n, err := strconv.Atoi(v)
203 if err != nil {
204 otel.Handle(err)
205 return defaultCardinalityLimit
206 }
207 return n
208 }