Debian Codegraph @

cmd/mdatagen/internal/metric.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package internal // import "go.opentelemetry.io/collector/cmd/mdatagen/internal"
5
6 import (
7 "errors"
8 "fmt"
9 "regexp"
10 "strings"
11
12 "golang.org/x/text/cases"
13 "golang.org/x/text/language"
14
15 "go.opentelemetry.io/collector/component"
16 "go.opentelemetry.io/collector/confmap"
17 "go.opentelemetry.io/collector/pdata/pmetric"
18 )
19
20 var reNonAlnum = regexp.MustCompile(`[^a-z0-9]+`)
21
22 type MetricName string
23
24 func (mn MetricName) Render() (string, error) {
25 return FormatIdentifier(string(mn), true)
26 }
27
28 func (mn MetricName) RenderUnexported() (string, error) {
29 return FormatIdentifier(string(mn), false)
30 }
31
32 type Metric struct {
33 Signal `mapstructure:",squash"`
34
35 // Optional can be used to specify metrics that may
36 // or may not be present in all cases, depending on configuration.
37 Optional bool `mapstructure:"optional"`
38
39 // Unit of the metric.
40 Unit *string `mapstructure:"unit"`
41
42 // Sum stores metadata for sum metric type
43 Sum *Sum `mapstructure:"sum,omitempty"`
44 // Gauge stores metadata for gauge metric type
45 Gauge *Gauge `mapstructure:"gauge,omitempty"`
46 // Histogram stores metadata for histogram metric type
47 Histogram *Histogram `mapstructure:"histogram,omitempty"`
48
49 // Override the default prefix for the metric name.
50 Prefix string `mapstructure:"prefix"`
51 }
52
53 type Stability struct {
54 Level component.StabilityLevel `mapstructure:"level"`
55 From string `mapstructure:"from"`
56 }
57
58 func (s Stability) String() string {
59 if s.Level == component.StabilityLevelUndefined ||
60 s.Level == component.StabilityLevelStable {
61 return ""
62 }
63 if s.From != "" {
64 return fmt.Sprintf(" [%s since %s]", s.Level.String(), s.From)
65 }
66 return fmt.Sprintf(" [%s]", s.Level.String())
67 }
68
69 func (s *Stability) Unmarshal(parser *confmap.Conf) error {
70 if !parser.IsSet("level") {
71 return errors.New("missing required field: `stability.level`")
72 }
73 return parser.Unmarshal(s)
74 }
75
76 func (m *Metric) validate(metricName MetricName, semConvVersion string) error {
77 var errs error
78 if m.Sum == nil && m.Gauge == nil && m.Histogram == nil {
79 errs = errors.Join(errs, errors.New("missing metric type key, "+
80 "one of the following has to be specified: sum, gauge, histogram"))
81 }
82 if (m.Sum != nil && m.Gauge != nil) || (m.Sum != nil && m.Histogram != nil) || (m.Gauge != nil && m.Histogram != nil) {
83 errs = errors.Join(errs, errors.New("more than one metric type keys, "+
84 "only one of the following has to be specified: sum, gauge, histogram"))
85 }
86 if m.Description == "" {
87 errs = errors.Join(errs, errors.New(`missing metric description`))
88 }
89 if m.Unit == nil {
90 errs = errors.Join(errs, errors.New(`missing metric unit`))
91 }
92 if m.Sum != nil {
93 errs = errors.Join(errs, m.Sum.Validate())
94 }
95 if m.Gauge != nil {
96 errs = errors.Join(errs, m.Gauge.Validate())
97 }
98 if m.SemanticConvention != nil {
99 if err := validateSemConvMetricURL(m.SemanticConvention.SemanticConventionRef, semConvVersion, string(metricName)); err != nil {
100 errs = errors.Join(errs, err)
101 }
102 }
103 return errs
104 }
105
106 func metricAnchor(metricName string) string {
107 m := strings.ToLower(strings.TrimSpace(metricName))
108 m = reNonAlnum.ReplaceAllString(m, "")
109 return "metric-" + m
110 }
111
112 // validateSemConvMetricURL verifies the URL matches exactly:
113 // https://github.com/open-telemetry/semantic-conventions/blob/<semConvVersion>/*#metric-<metricName>
114 func validateSemConvMetricURL(rawURL, semConvVersion, metricName string) error {
115 if strings.TrimSpace(rawURL) == "" {
116 return errors.New("url is empty")
117 }
118 if strings.TrimSpace(semConvVersion) == "" {
119 return errors.New("semConvVersion is empty")
120 }
121 if strings.TrimSpace(metricName) == "" {
122 return errors.New("metricName is empty")
123 }
124 semConvVersion = "v" + semConvVersion
125
126 anchor := metricAnchor(metricName)
127 // Build a strict regex that enforces https, repo, blob, given version, any doc path, and exact anchor.
128 pattern := fmt.Sprintf(`^https://github\.com/open-telemetry/semantic-conventions/blob/%s/[^#\s]+#%s$`,
129 semConvVersion,
130 anchor,
131 )
132 re := regexp.MustCompile(pattern)
133 if !re.MatchString(rawURL) {
134 return fmt.Errorf(
135 "invalid semantic-conventions URL: want https://github.com/open-telemetry/semantic-conventions/blob/%s/*#%s, got %q",
136 semConvVersion, anchor, rawURL)
137 }
138 return nil
139 }
140
141 func (m *Metric) Unmarshal(parser *confmap.Conf) error {
142 if !parser.IsSet("enabled") {
143 return errors.New("missing required field: `enabled`")
144 }
145 if !parser.IsSet("stability") {
146 return errors.New("missing required field: `stability`")
147 }
148 return parser.Unmarshal(m)
149 }
150
151 func (m Metric) Data() MetricData {
152 if m.Sum != nil {
153 return m.Sum
154 }
155 if m.Gauge != nil {
156 return m.Gauge
157 }
158 if m.Histogram != nil {
159 return m.Histogram
160 }
161 return nil
162 }
163
164 // MetricData is generic interface for all metric datatypes.
165 type MetricData interface {
166 Type() string
167 HasMonotonic() bool
168 HasAggregated() bool
169 HasMetricInputType() bool
170 Instrument() string
171 IsAsync() bool
172 }
173
174 // AggregationTemporality defines a metric aggregation type.
175 type AggregationTemporality struct {
176 // Aggregation describes if the aggregator reports delta changes
177 // since last report time, or cumulative changes since a fixed start time.
178 Aggregation pmetric.AggregationTemporality
179 }
180
181 // UnmarshalText implements the encoding.TextUnmarshaler interface.
182 func (agg *AggregationTemporality) UnmarshalText(text []byte) error {
183 switch vtStr := string(text); vtStr {
184 case "cumulative":
185 agg.Aggregation = pmetric.AggregationTemporalityCumulative
186 case "delta":
187 agg.Aggregation = pmetric.AggregationTemporalityDelta
188 default:
189 return fmt.Errorf("invalid aggregation: %q", vtStr)
190 }
191 return nil
192 }
193
194 // String returns string representation of the aggregation temporality.
195 func (agg *AggregationTemporality) String() string {
196 return agg.Aggregation.String()
197 }
198
199 // Mono defines the metric monotonicity.
200 type Mono struct {
201 // Monotonic is true if the sum is monotonic.
202 Monotonic bool `mapstructure:"monotonic"`
203 }
204
205 // MetricInputType defines the metric input value type
206 type MetricInputType struct {
207 // InputType is the type the metric needs to be parsed from, options are "string"
208 InputType string `mapstructure:"input_type"`
209 }
210
211 func (mit MetricInputType) HasMetricInputType() bool {
212 return mit.InputType != ""
213 }
214
215 // String returns name of the datapoint type.
216 func (mit MetricInputType) String() string {
217 return mit.InputType
218 }
219
220 func (mit MetricInputType) Validate() error {
221 if mit.InputType != "" && mit.InputType != "string" {
222 return fmt.Errorf("invalid `input_type` value \"%v\", must be \"\" or \"string\"", mit.InputType)
223 }
224 return nil
225 }
226
227 // MetricValueType defines the metric number type.
228 type MetricValueType struct {
229 // ValueType is type of the metric number, options are "double", "int".
230 ValueType pmetric.NumberDataPointValueType
231 }
232
233 func (mvt *MetricValueType) Unmarshal(parser *confmap.Conf) error {
234 if !parser.IsSet("value_type") {
235 return errors.New("missing required field: `value_type`")
236 }
237 return nil
238 }
239
240 // UnmarshalText implements the encoding.TextUnmarshaler interface.
241 func (mvt *MetricValueType) UnmarshalText(text []byte) error {
242 switch vtStr := string(text); vtStr {
243 case "int":
244 mvt.ValueType = pmetric.NumberDataPointValueTypeInt
245 case "double":
246 mvt.ValueType = pmetric.NumberDataPointValueTypeDouble
247 default:
248 return fmt.Errorf("invalid value_type: %q", vtStr)
249 }
250 return nil
251 }
252
253 // String returns name of the datapoint type.
254 func (mvt MetricValueType) String() string {
255 return mvt.ValueType.String()
256 }
257
258 // BasicType returns name of a golang basic type for the datapoint type.
259 func (mvt MetricValueType) BasicType() string {
260 switch mvt.ValueType {
261 case pmetric.NumberDataPointValueTypeInt:
262 return "int64"
263 case pmetric.NumberDataPointValueTypeDouble:
264 return "float64"
265 case pmetric.NumberDataPointValueTypeEmpty:
266 return ""
267 default:
268 return ""
269 }
270 }
271
272 var _ MetricData = (*Gauge)(nil)
273
274 type Gauge struct {
275 MetricValueType `mapstructure:"value_type"`
276 MetricInputType `mapstructure:",squash"`
277 Async bool `mapstructure:"async,omitempty"`
278 }
279
280 // Unmarshal is a custom unmarshaler for gauge. Needed mostly to avoid MetricValueType.Unmarshal inheritance.
281 func (d *Gauge) Unmarshal(parser *confmap.Conf) error {
282 if err := d.MetricValueType.Unmarshal(parser); err != nil {
283 return err
284 }
285 return parser.Unmarshal(d, confmap.WithIgnoreUnused())
286 }
287
288 func (d *Gauge) Type() string {
289 return "Gauge"
290 }
291
292 func (d *Gauge) HasMonotonic() bool {
293 return false
294 }
295
296 func (d *Gauge) HasAggregated() bool {
297 return false
298 }
299
300 func (d *Gauge) Instrument() string {
301 instrumentName := cases.Title(language.English).String(d.BasicType())
302
303 if d.Async {
304 instrumentName += "Observable"
305 }
306
307 instrumentName += "Gauge"
308 return instrumentName
309 }
310
311 func (d *Gauge) IsAsync() bool {
312 return d.Async
313 }
314
315 var _ MetricData = (*Sum)(nil)
316
317 type Sum struct {
318 AggregationTemporality `mapstructure:"aggregation_temporality"`
319 Mono `mapstructure:",squash"`
320 MetricValueType `mapstructure:"value_type"`
321 MetricInputType `mapstructure:",squash"`
322 Async bool `mapstructure:"async,omitempty"`
323 }
324
325 // Unmarshal is a custom unmarshaler for sum. Needed mostly to avoid MetricValueType.Unmarshal inheritance.
326 func (d *Sum) Unmarshal(parser *confmap.Conf) error {
327 if err := d.MetricValueType.Unmarshal(parser); err != nil {
328 return err
329 }
330 return parser.Unmarshal(d, confmap.WithIgnoreUnused())
331 }
332
333 // TODO: Currently, this func will not be called because of https://github.com/open-telemetry/opentelemetry-collector/issues/6671. Uncomment function and
334 // add a test case to Test_LoadMetadata for file no_monotonic.yaml once the issue is solved.
335 //
336 // Unmarshal is a custom unmarshaler for Mono.
337 // func (m *Mono) Unmarshal(parser *confmap.Conf) error {
338 // if !parser.IsSet("monotonic") {
339 // return errors.New("missing required field: `monotonic`")
340 // }
341 // return parser.Unmarshal(m)
342 // }
343
344 func (d *Sum) Type() string {
345 return "Sum"
346 }
347
348 func (d *Sum) HasMonotonic() bool {
349 return true
350 }
351
352 func (d *Sum) HasAggregated() bool {
353 return true
354 }
355
356 func (d *Sum) Instrument() string {
357 instrumentName := cases.Title(language.English).String(d.BasicType())
358
359 if d.Async {
360 instrumentName += "Observable"
361 }
362 if !d.Monotonic {
363 instrumentName += "UpDown"
364 }
365 instrumentName += "Counter"
366 return instrumentName
367 }
368
369 func (d *Sum) IsAsync() bool {
370 return d.Async
371 }
372
373 var _ MetricData = (*Histogram)(nil)
374
375 type Histogram struct {
376 AggregationTemporality `mapstructure:"aggregation_temporality"`
377 Mono `mapstructure:",squash"`
378 MetricValueType `mapstructure:"value_type"`
379 MetricInputType `mapstructure:",squash"`
380 Async bool `mapstructure:"async,omitempty"`
381 Boundaries []float64 `mapstructure:"bucket_boundaries"`
382 }
383
384 func (d *Histogram) Type() string {
385 return "Histogram"
386 }
387
388 func (d *Histogram) HasMonotonic() bool {
389 return false
390 }
391
392 func (d *Histogram) HasAggregated() bool {
393 return true
394 }
395
396 func (d *Histogram) Instrument() string {
397 instrumentName := cases.Title(language.English).String(d.BasicType())
398 return instrumentName + d.Type()
399 }
400
401 // Unmarshal is a custom unmarshaler for histogram. Needed mostly to avoid MetricValueType.Unmarshal inheritance.
402 func (d *Histogram) Unmarshal(parser *confmap.Conf) error {
403 if err := d.MetricValueType.Unmarshal(parser); err != nil {
404 return err
405 }
406 return parser.Unmarshal(d, confmap.WithIgnoreUnused())
407 }
408
409 func (d *Histogram) IsAsync() bool {
410 return d.Async
411 }