Debian Codegraph @

otelconf/x/config_common.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package x // import "go.opentelemetry.io/contrib/otelconf/x"
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "reflect"
11
12 "go.opentelemetry.io/otel/baggage"
13 sdklog "go.opentelemetry.io/otel/sdk/log"
14 sdkmetric "go.opentelemetry.io/otel/sdk/metric"
15 sdktrace "go.opentelemetry.io/otel/sdk/trace"
16 )
17
18 const (
19 compressionGzip = "gzip"
20 compressionNone = "none"
21 )
22
23 var enumValuesAttributeType = []any{
24 nil,
25 "string",
26 "bool",
27 "int",
28 "double",
29 "string_array",
30 "bool_array",
31 "int_array",
32 "double_array",
33 }
34
35 var enumValuesViewSelectorInstrumentType = []any{
36 "counter",
37 "gauge",
38 "histogram",
39 "observable_counter",
40 "observable_gauge",
41 "observable_up_down_counter",
42 "up_down_counter",
43 }
44
45 var enumValuesOTLPMetricDefaultHistogramAggregation = []any{
46 "explicit_bucket_histogram",
47 "base2_exponential_bucket_histogram",
48 }
49
50 type configOptions struct {
51 ctx context.Context
52 opentelemetryConfig OpenTelemetryConfiguration
53 loggerProviderOptions []sdklog.LoggerProviderOption
54 meterProviderOptions []sdkmetric.Option
55 tracerProviderOptions []sdktrace.TracerProviderOption
56 }
57
58 type shutdownFunc func(context.Context) error
59
60 func noopShutdown(context.Context) error {
61 return nil
62 }
63
64 type errBound struct {
65 Field string
66 Bound int
67 Op string
68 }
69
70 func (e *errBound) Error() string {
71 return fmt.Sprintf("field %s: must be %s %d", e.Field, e.Op, e.Bound)
72 }
73
74 func (e *errBound) Is(target error) bool {
75 t, ok := target.(*errBound)
76 if !ok {
77 return false
78 }
79 return e.Field == t.Field && e.Bound == t.Bound && e.Op == t.Op
80 }
81
82 type errRequired struct {
83 Object any
84 Field string
85 }
86
87 func (e *errRequired) Error() string {
88 return fmt.Sprintf("field %s in %s: required", e.Field, reflect.TypeOf(e.Object))
89 }
90
91 func (e *errRequired) Is(target error) bool {
92 t, ok := target.(*errRequired)
93 if !ok {
94 return false
95 }
96 return reflect.TypeOf(e.Object) == reflect.TypeOf(t.Object) && e.Field == t.Field
97 }
98
99 type errUnmarshal struct {
100 Object any
101 }
102
103 func (e *errUnmarshal) Error() string {
104 return fmt.Sprintf("unmarshal error in %T", e.Object)
105 }
106
107 func (e *errUnmarshal) Is(target error) bool {
108 t, ok := target.(*errUnmarshal)
109 if !ok {
110 return false
111 }
112 return reflect.TypeOf(e.Object) == reflect.TypeOf(t.Object)
113 }
114
115 // newErrGreaterOrEqualZero creates a new error indicating that the field must be greater than
116 // or equal to zero.
117 func newErrGreaterOrEqualZero(field string) error {
118 return &errBound{Field: field, Bound: 0, Op: ">="}
119 }
120
121 // newErrGreaterThanZero creates a new error indicating that the field must be greater
122 // than zero.
123 func newErrGreaterThanZero(field string) error {
124 return &errBound{Field: field, Bound: 0, Op: ">"}
125 }
126
127 // newErrRequired creates a new error indicating that the exporter field is required.
128 func newErrRequired(object any, field string) error {
129 return &errRequired{Object: object, Field: field}
130 }
131
132 // newErrUnmarshal creates a new error indicating that an error occurred during unmarshaling.
133 func newErrUnmarshal(object any) error {
134 return &errUnmarshal{Object: object}
135 }
136
137 type errInvalid struct {
138 Identifier string
139 }
140
141 func (e *errInvalid) Error() string {
142 return "invalid config: " + e.Identifier
143 }
144
145 func (*errInvalid) Is(target error) bool {
146 _, ok := target.(*errInvalid)
147 return ok
148 }
149
150 // newErrInvalid creates a new error indicating that an error occurred due to misconfiguration.
151 func newErrInvalid(id string) error {
152 return &errInvalid{Identifier: id}
153 }
154
155 // unmarshalSamplerTypes handles always_on and always_off sampler unmarshaling.
156 func unmarshalSamplerTypes(raw map[string]any, plain *Sampler) {
157 // always_on can be nil, must check and set here
158 if _, ok := raw["always_on"]; ok {
159 plain.AlwaysOn = AlwaysOnSampler{}
160 }
161 // always_off can be nil, must check and set here
162 if _, ok := raw["always_off"]; ok {
163 plain.AlwaysOff = AlwaysOffSampler{}
164 }
165 }
166
167 // unmarshalMetricProducer handles opencensus metric producer unmarshaling.
168 func unmarshalMetricProducer(raw map[string]any, plain *MetricProducer) {
169 // opencensus can be nil, must check and set here
170 if v, ok := raw["opencensus"]; ok && v == nil {
171 delete(raw, "opencensus")
172 plain.Opencensus = OpenCensusMetricProducer{}
173 }
174 if len(raw) > 0 {
175 plain.AdditionalProperties = raw
176 }
177 }
178
179 // validatePeriodicMetricReader handles validation for PeriodicMetricReader.
180 func validatePeriodicMetricReader(plain *PeriodicMetricReader) error {
181 if plain.Timeout != nil && 0 > *plain.Timeout {
182 return newErrGreaterOrEqualZero("timeout")
183 }
184 if plain.Interval != nil && 0 > *plain.Interval {
185 return newErrGreaterOrEqualZero("interval")
186 }
187 return nil
188 }
189
190 // validateBatchLogRecordProcessor handles validation for BatchLogRecordProcessor.
191 func validateBatchLogRecordProcessor(plain *BatchLogRecordProcessor) error {
192 if plain.ExportTimeout != nil && 0 > *plain.ExportTimeout {
193 return newErrGreaterOrEqualZero("export_timeout")
194 }
195 if plain.MaxExportBatchSize != nil && 0 >= *plain.MaxExportBatchSize {
196 return newErrGreaterThanZero("max_export_batch_size")
197 }
198 if plain.MaxQueueSize != nil && 0 >= *plain.MaxQueueSize {
199 return newErrGreaterThanZero("max_queue_size")
200 }
201 if plain.ScheduleDelay != nil && 0 > *plain.ScheduleDelay {
202 return newErrGreaterOrEqualZero("schedule_delay")
203 }
204 return nil
205 }
206
207 // validateBatchSpanProcessor handles validation for BatchSpanProcessor.
208 func validateBatchSpanProcessor(plain *BatchSpanProcessor) error {
209 if plain.ExportTimeout != nil && 0 > *plain.ExportTimeout {
210 return newErrGreaterOrEqualZero("export_timeout")
211 }
212 if plain.MaxExportBatchSize != nil && 0 >= *plain.MaxExportBatchSize {
213 return newErrGreaterThanZero("max_export_batch_size")
214 }
215 if plain.MaxQueueSize != nil && 0 >= *plain.MaxQueueSize {
216 return newErrGreaterThanZero("max_queue_size")
217 }
218 if plain.ScheduleDelay != nil && 0 > *plain.ScheduleDelay {
219 return newErrGreaterOrEqualZero("schedule_delay")
220 }
221 return nil
222 }
223
224 // validateCardinalityLimits handles validation for CardinalityLimits.
225 func validateCardinalityLimits(plain *CardinalityLimits) error {
226 if plain.Counter != nil && 0 >= *plain.Counter {
227 return newErrGreaterThanZero("counter")
228 }
229 if plain.Default != nil && 0 >= *plain.Default {
230 return newErrGreaterThanZero("default")
231 }
232 if plain.Gauge != nil && 0 >= *plain.Gauge {
233 return newErrGreaterThanZero("gauge")
234 }
235 if plain.Histogram != nil && 0 >= *plain.Histogram {
236 return newErrGreaterThanZero("histogram")
237 }
238 if plain.ObservableCounter != nil && 0 >= *plain.ObservableCounter {
239 return newErrGreaterThanZero("observable_counter")
240 }
241 if plain.ObservableGauge != nil && 0 >= *plain.ObservableGauge {
242 return newErrGreaterThanZero("observable_gauge")
243 }
244 if plain.ObservableUpDownCounter != nil && 0 >= *plain.ObservableUpDownCounter {
245 return newErrGreaterThanZero("observable_up_down_counter")
246 }
247 if plain.UpDownCounter != nil && 0 >= *plain.UpDownCounter {
248 return newErrGreaterThanZero("up_down_counter")
249 }
250 return nil
251 }
252
253 // validateSpanLimits handles validation for SpanLimits.
254 func validateSpanLimits(plain *SpanLimits) error {
255 if plain.AttributeCountLimit != nil && 0 > *plain.AttributeCountLimit {
256 return newErrGreaterOrEqualZero("attribute_count_limit")
257 }
258 if plain.AttributeValueLengthLimit != nil && 0 > *plain.AttributeValueLengthLimit {
259 return newErrGreaterOrEqualZero("attribute_value_length_limit")
260 }
261 if plain.EventAttributeCountLimit != nil && 0 > *plain.EventAttributeCountLimit {
262 return newErrGreaterOrEqualZero("event_attribute_count_limit")
263 }
264 if plain.EventCountLimit != nil && 0 > *plain.EventCountLimit {
265 return newErrGreaterOrEqualZero("event_count_limit")
266 }
267 if plain.LinkAttributeCountLimit != nil && 0 > *plain.LinkAttributeCountLimit {
268 return newErrGreaterOrEqualZero("link_attribute_count_limit")
269 }
270 if plain.LinkCountLimit != nil && 0 > *plain.LinkCountLimit {
271 return newErrGreaterOrEqualZero("link_count_limit")
272 }
273 return nil
274 }
275
276 func ptr[T any](v T) *T {
277 return &v
278 }
279
280 // createHeadersConfig combines the two header config fields. Headers take precedence over headersList.
281 func createHeadersConfig(headers []NameStringValuePair, headersList *string) (map[string]string, error) {
282 result := make(map[string]string)
283 if headersList != nil {
284 // Parsing follows https://github.com/open-telemetry/opentelemetry-configuration/blob/568e5080816d40d75792eb754fc96bde09654159/schema/type_descriptions.yaml#L584.
285 headerslist, err := baggage.Parse(*headersList)
286 if err != nil {
287 return nil, errors.Join(newErrInvalid("invalid headers_list"), err)
288 }
289 for _, kv := range headerslist.Members() {
290 result[kv.Key()] = kv.Value()
291 }
292 }
293 // Headers take precedence over HeadersList, so this has to be after HeadersList is processed.
294 for _, kv := range headers {
295 if kv.Value != nil {
296 result[kv.Name] = *kv.Value
297 }
298 }
299 return result, nil
300 }
301
302 // supportedInstrumentType return an error if the instrument type is not supported.
303 func supportedInstrumentType(in InstrumentType) error {
304 for _, expected := range enumValuesViewSelectorInstrumentType {
305 if string(in) == fmt.Sprintf("%s", expected) {
306 return nil
307 }
308 }
309 return newErrInvalid(fmt.Sprintf("invalid selector (expected one of %#v): %#v", enumValuesViewSelectorInstrumentType, in))
310 }
311
312 // supportedHistogramAggregation return an error if the histogram aggregation is not supported.
313 func supportedHistogramAggregation(in ExporterDefaultHistogramAggregation) error {
314 for _, expected := range enumValuesOTLPMetricDefaultHistogramAggregation {
315 if string(in) == fmt.Sprintf("%s", expected) {
316 return nil
317 }
318 }
319 return newErrInvalid(fmt.Sprintf("invalid histogram aggregation (expected one of %#v): %#v", enumValuesOTLPMetricDefaultHistogramAggregation, in))
320 }