Debian Codegraph @

cmd/mdatagen/internal/metadata.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 "slices"
11 "strconv"
12 "strings"
13
14 "go.opentelemetry.io/collector/filter"
15 "go.opentelemetry.io/collector/pdata/pcommon"
16 )
17
18 type Metadata struct {
19 // Type of the component.
20 Type string `mapstructure:"type"`
21 // Type of the parent component (applicable to subcomponents).
22 Parent string `mapstructure:"parent"`
23 // Status information for the component.
24 Status *Status `mapstructure:"status"`
25 // The name of the package that will be generated.
26 GeneratedPackageName string `mapstructure:"generated_package_name"`
27 // Telemetry information for the component.
28 Telemetry Telemetry `mapstructure:"telemetry"`
29 // SemConvVersion is a version number of OpenTelemetry semantic conventions applied to the scraped metrics.
30 SemConvVersion string `mapstructure:"sem_conv_version"`
31 // ResourceAttributes that can be emitted by the component.
32 ResourceAttributes map[AttributeName]Attribute `mapstructure:"resource_attributes"`
33 // Entities organizes resource attributes into logical entities.
34 Entities []Entity `mapstructure:"entities"`
35 // Attributes emitted by one or more metrics.
36 Attributes map[AttributeName]Attribute `mapstructure:"attributes"`
37 // Metrics that can be emitted by the component.
38 Metrics map[MetricName]Metric `mapstructure:"metrics"`
39 // Events that can be emitted by the component.
40 Events map[EventName]Event `mapstructure:"events"`
41 // GithubProject is the project where the component README lives in the format of org/repo, defaults to open-telemetry/opentelemetry-collector-contrib
42 GithubProject string `mapstructure:"github_project"`
43 // ScopeName of the metrics emitted by the component.
44 ScopeName string `mapstructure:"scope_name"`
45 // ShortFolderName is the shortened folder name of the component, removing class if present
46 ShortFolderName string `mapstructure:"-"`
47 // Tests is the set of tests generated with the component
48 Tests Tests `mapstructure:"tests"`
49 // PackageName is the name of the package where the component is defined.
50 PackageName string `mapstructure:"package_name"`
51 }
52
53 func (md Metadata) GetCodeCovComponentID() string {
54 if md.Status.CodeCovComponentID != "" {
55 return md.Status.CodeCovComponentID
56 }
57
58 return strings.ReplaceAll(md.Status.Class+"_"+md.Type, "/", "_")
59 }
60
61 func (md Metadata) HasEntities() bool {
62 return len(md.Entities) > 0
63 }
64
65 func (md *Metadata) Validate() error {
66 var errs error
67 if err := md.validateType(); err != nil {
68 errs = errors.Join(errs, err)
69 }
70
71 if md.Parent != "" {
72 if md.Status != nil {
73 // status is not required for subcomponents.
74 errs = errors.Join(errs, errors.New("status must be empty for subcomponents"))
75 }
76 } else {
77 errs = errors.Join(errs, md.Status.Validate())
78 }
79
80 if err := md.validateResourceAttributes(); err != nil {
81 errs = errors.Join(errs, err)
82 }
83
84 if err := md.validateEntities(); err != nil {
85 errs = errors.Join(errs, err)
86 }
87
88 if err := md.validateMetricsAndEvents(); err != nil {
89 errs = errors.Join(errs, err)
90 }
91
92 return errs
93 }
94
95 // typeRegexp is used to validate the type of a component.
96 // A type must start with an ASCII alphabetic character and
97 // can only contain ASCII alphanumeric characters and '_'.
98 // We allow '/' for subcomponents.
99 // This must be kept in sync with the regex in component/config.go.
100 var typeRegexp = regexp.MustCompile(`^[a-zA-Z][0-9a-zA-Z_]{0,62}$`)
101
102 func (md *Metadata) validateType() error {
103 if md.Type == "" {
104 return errors.New("missing type")
105 }
106
107 if md.Parent != "" {
108 // subcomponents are allowed to have a '/' in their type.
109 return nil
110 }
111
112 if !typeRegexp.MatchString(md.Type) {
113 return fmt.Errorf("invalid character(s) in type %q", md.Type)
114 }
115 return nil
116 }
117
118 func (md *Metadata) validateResourceAttributes() error {
119 var errs error
120 for name, attr := range md.ResourceAttributes {
121 if attr.Description == "" {
122 errs = errors.Join(errs, fmt.Errorf("empty description for resource attribute: %v", name))
123 }
124 empty := ValueType{ValueType: pcommon.ValueTypeEmpty}
125 if attr.Type == empty {
126 errs = errors.Join(errs, fmt.Errorf("empty type for resource attribute: %v", name))
127 }
128 if attr.EnabledPtr == nil {
129 errs = errors.Join(errs, fmt.Errorf("enabled field is required for resource attribute: %v", name))
130 }
131 }
132 return errs
133 }
134
135 func (md *Metadata) validateEntities() error {
136 var errs error
137 usedAttrs := make(map[AttributeName]string)
138 seenTypes := make(map[string]bool)
139
140 for _, entity := range md.Entities {
141 if entity.Type == "" {
142 errs = errors.Join(errs, errors.New("entity type cannot be empty"))
143 continue
144 }
145 if seenTypes[entity.Type] {
146 errs = errors.Join(errs, fmt.Errorf(`duplicate entity type: %v`, entity.Type))
147 }
148 seenTypes[entity.Type] = true
149
150 if entity.Brief == "" {
151 errs = errors.Join(errs, fmt.Errorf(`entity "%v": brief is required`, entity.Type))
152 }
153 if len(entity.Identity) == 0 {
154 errs = errors.Join(errs, fmt.Errorf(`entity "%v": identity is required`, entity.Type))
155 }
156 for _, ref := range entity.Identity {
157 if _, ok := md.ResourceAttributes[ref.Ref]; !ok {
158 errs = errors.Join(errs, fmt.Errorf(`entity "%v": identity refers to undefined resource attribute: %v`, entity.Type, ref.Ref))
159 }
160 if otherEntity, used := usedAttrs[ref.Ref]; used {
161 errs = errors.Join(errs, fmt.Errorf(`entity "%v": attribute %v is already used by entity "%v"`, entity.Type, ref.Ref, otherEntity))
162 } else {
163 usedAttrs[ref.Ref] = entity.Type
164 }
165 }
166 for _, ref := range entity.Description {
167 if _, ok := md.ResourceAttributes[ref.Ref]; !ok {
168 errs = errors.Join(errs, fmt.Errorf(`entity "%v": description refers to undefined resource attribute: %v`, entity.Type, ref.Ref))
169 }
170 if otherEntity, used := usedAttrs[ref.Ref]; used {
171 errs = errors.Join(errs, fmt.Errorf(`entity "%v": attribute %v is already used by entity "%v"`, entity.Type, ref.Ref, otherEntity))
172 } else {
173 usedAttrs[ref.Ref] = entity.Type
174 }
175 }
176 }
177 return errs
178 }
179
180 func (md *Metadata) validateMetricsAndEvents() error {
181 var errs error
182 usedAttrs := map[AttributeName]bool{}
183 errs = errors.Join(errs,
184 validateMetrics(md.Metrics, md.Attributes, usedAttrs, md.SemConvVersion),
185 validateMetrics(md.Telemetry.Metrics, md.Attributes, usedAttrs, md.SemConvVersion),
186 validateEvents(md.Events, md.Attributes, usedAttrs),
187 md.validateAttributes(usedAttrs))
188 return errs
189 }
190
191 func (md *Metadata) validateAttributes(usedAttrs map[AttributeName]bool) error {
192 var errs error
193 unusedAttrs := make([]AttributeName, 0, len(md.Attributes))
194 for attrName, attr := range md.Attributes {
195 if attr.Description == "" {
196 errs = errors.Join(errs, fmt.Errorf(`missing attribute description for: %v`, attrName))
197 }
198 empty := ValueType{ValueType: pcommon.ValueTypeEmpty}
199 if attr.Type == empty {
200 errs = errors.Join(errs, fmt.Errorf("empty type for attribute: %v", attrName))
201 }
202 if attr.EnabledPtr != nil {
203 errs = errors.Join(errs, fmt.Errorf("enabled field is not allowed for regular attribute: %v", attrName))
204 }
205 if !usedAttrs[attrName] {
206 unusedAttrs = append(unusedAttrs, attrName)
207 }
208 }
209 if len(unusedAttrs) > 0 {
210 errs = errors.Join(errs, fmt.Errorf("unused attributes: %v", unusedAttrs))
211 }
212 return errs
213 }
214
215 func (md *Metadata) supportsSignal(signal string) bool {
216 if md.Status == nil {
217 return false
218 }
219
220 for _, signals := range md.Status.Stability {
221 if slices.Contains(signals, signal) {
222 return true
223 }
224 }
225
226 return false
227 }
228
229 func validateMetrics(metrics map[MetricName]Metric, attributes map[AttributeName]Attribute, usedAttrs map[AttributeName]bool, semConvVersion string) error {
230 var errs error
231 for mn, m := range metrics {
232 if err := m.validate(mn, semConvVersion); err != nil {
233 errs = errors.Join(errs, fmt.Errorf(`metric "%v": %w`, mn, err))
234 continue
235 }
236 unknownAttrs := make([]AttributeName, 0, len(m.Attributes))
237 for _, attr := range m.Attributes {
238 if _, ok := attributes[attr]; ok {
239 usedAttrs[attr] = true
240 } else {
241 unknownAttrs = append(unknownAttrs, attr)
242 }
243 }
244 if len(unknownAttrs) > 0 {
245 errs = errors.Join(errs, fmt.Errorf(`metric "%v" refers to undefined attributes: %v`, mn, unknownAttrs))
246 }
247 }
248 return errs
249 }
250
251 func validateEvents(events map[EventName]Event, attributes map[AttributeName]Attribute, usedAttrs map[AttributeName]bool) error {
252 var errs error
253 for en, e := range events {
254 if err := e.validate(); err != nil {
255 errs = errors.Join(errs, fmt.Errorf(`event "%v": %w`, en, err))
256 continue
257 }
258 unknownAttrs := make([]AttributeName, 0, len(e.Attributes))
259 for _, attr := range e.Attributes {
260 if _, ok := attributes[attr]; ok {
261 usedAttrs[attr] = true
262 } else {
263 unknownAttrs = append(unknownAttrs, attr)
264 }
265 }
266 if len(unknownAttrs) > 0 {
267 errs = errors.Join(errs, fmt.Errorf(`event "%v" refers to undefined attributes: %v`, en, unknownAttrs))
268 }
269 }
270 return errs
271 }
272
273 type AttributeName string
274
275 // AttributeRequirementLevel defines the requirement level of an attribute.
276 type AttributeRequirementLevel string
277
278 const (
279 // AttributeRequirementLevelRequired means the attribute is always included and cannot be excluded.
280 AttributeRequirementLevelRequired AttributeRequirementLevel = "required"
281 // AttributeRequirementLevelConditionallyRequired means the attribute is included by default when certain conditions are met.
282 AttributeRequirementLevelConditionallyRequired AttributeRequirementLevel = "conditionally_required"
283 // AttributeRequirementLevelRecommended means the attribute is included by default but can be disabled via configuration.
284 AttributeRequirementLevelRecommended AttributeRequirementLevel = "recommended"
285 // AttributeRequirementLevelOptIn means the attribute is not included unless explicitly enabled in user config.
286 AttributeRequirementLevelOptIn AttributeRequirementLevel = "opt_in"
287 )
288
289 // String returns capitalized display name of the requirement level for documentation.
290 func (rl AttributeRequirementLevel) String() string {
291 switch rl {
292 case AttributeRequirementLevelRequired:
293 return "Required"
294 case AttributeRequirementLevelConditionallyRequired:
295 return "Conditionally Required"
296 case AttributeRequirementLevelRecommended:
297 return "Recommended"
298 case AttributeRequirementLevelOptIn:
299 return "Opt-In"
300 }
301 return ""
302 }
303
304 func (mn AttributeName) Render() (string, error) {
305 return FormatIdentifier(string(mn), true)
306 }
307
308 func (mn AttributeName) RenderUnexported() (string, error) {
309 return FormatIdentifier(string(mn), false)
310 }
311
312 // ValueType defines an attribute value type.
313 type ValueType struct {
314 // ValueType is type of the attribute value.
315 ValueType pcommon.ValueType
316 }
317
318 // UnmarshalText implements the encoding.TextUnmarshaler interface.
319 func (mvt *ValueType) UnmarshalText(text []byte) error {
320 switch vtStr := string(text); vtStr {
321 case "string":
322 mvt.ValueType = pcommon.ValueTypeStr
323 case "int":
324 mvt.ValueType = pcommon.ValueTypeInt
325 case "double":
326 mvt.ValueType = pcommon.ValueTypeDouble
327 case "bool":
328 mvt.ValueType = pcommon.ValueTypeBool
329 case "bytes":
330 mvt.ValueType = pcommon.ValueTypeBytes
331 case "slice":
332 mvt.ValueType = pcommon.ValueTypeSlice
333 case "map":
334 mvt.ValueType = pcommon.ValueTypeMap
335 default:
336 return fmt.Errorf("invalid type: %q", vtStr)
337 }
338 return nil
339 }
340
341 // String returns capitalized name of the ValueType.
342 func (mvt ValueType) String() string {
343 return strings.Title(strings.ToLower(mvt.ValueType.String())) //nolint:staticcheck // SA1019
344 }
345
346 // Primitive returns name of primitive type for the ValueType.
347 func (mvt ValueType) Primitive() string {
348 switch mvt.ValueType {
349 case pcommon.ValueTypeStr:
350 return "string"
351 case pcommon.ValueTypeInt:
352 return "int64"
353 case pcommon.ValueTypeDouble:
354 return "float64"
355 case pcommon.ValueTypeBool:
356 return "bool"
357 case pcommon.ValueTypeBytes:
358 return "[]byte"
359 case pcommon.ValueTypeSlice:
360 return "[]any"
361 case pcommon.ValueTypeMap:
362 return "map[string]any"
363 case pcommon.ValueTypeEmpty:
364 return ""
365 default:
366 return ""
367 }
368 }
369
370 type SemanticConvention struct {
371 SemanticConventionRef string `mapstructure:"ref"`
372 }
373
374 type Warnings struct {
375 // A warning that will be displayed if the field is enabled in user config.
376 IfEnabled string `mapstructure:"if_enabled"`
377 // A warning that will be displayed if `enabled` field is not set explicitly in user config.
378 IfEnabledNotSet string `mapstructure:"if_enabled_not_set"`
379 // A warning that will be displayed if the field is configured by user in any way.
380 IfConfigured string `mapstructure:"if_configured"`
381 }
382
383 type Attribute struct {
384 // Description describes the purpose of the attribute.
385 Description string `mapstructure:"description"`
386 // NameOverride can be used to override the attribute name.
387 NameOverride string `mapstructure:"name_override"`
388 // EnabledPtr defines whether the attribute is enabled by default.
389 EnabledPtr *bool `mapstructure:"enabled"`
390 // Include can be used to filter attributes.
391 Include []filter.Config `mapstructure:"include"`
392 // Include can be used to filter attributes.
393 Exclude []filter.Config `mapstructure:"exclude"`
394 // Enum can optionally describe the set of values to which the attribute can belong.
395 Enum []string `mapstructure:"enum"`
396 // Type is an attribute type.
397 Type ValueType `mapstructure:"type"`
398 // FullName is the attribute name populated from the map key.
399 FullName AttributeName `mapstructure:"-"`
400 // Warnings that will be shown to user under specified conditions.
401 Warnings Warnings `mapstructure:"warnings"`
402 // RequirementLevel defines the requirement level of the attribute.
403 RequirementLevel AttributeRequirementLevel `mapstructure:"requirement_level"`
404 }
405
406 // IsConditional returns true if the attribute is conditionally required.
407 func (a Attribute) IsConditional() bool {
408 return a.RequirementLevel == AttributeRequirementLevelConditionallyRequired
409 }
410
411 // UnmarshalText implements the encoding.TextUnmarshaler interface.
412 func (rl *AttributeRequirementLevel) UnmarshalText(text []byte) error {
413 switch string(text) {
414 case "required":
415 *rl = AttributeRequirementLevelRequired
416 case "conditionally_required":
417 *rl = AttributeRequirementLevelConditionallyRequired
418 case "recommended":
419 *rl = AttributeRequirementLevelRecommended
420 case "opt_in":
421 *rl = AttributeRequirementLevelOptIn
422 case "":
423 *rl = AttributeRequirementLevelRecommended
424 default:
425 return fmt.Errorf("invalid requirement_level %q", string(text))
426 }
427 return nil
428 }
429
430 // Enabled returns the boolean value of EnabledPtr.
431 // This method is needed to differentiate between different types of attributes:
432 // - Resource attributes: EnabledPtr is always set (non-nil) due to validation
433 // - Regular attributes: EnabledPtr is always nil due to validation
434 // Panics if EnabledPtr is nil, indicating incorrect template usage.
435 func (a Attribute) Enabled() bool {
436 if a.EnabledPtr == nil {
437 panic("Enabled() must not be called on regular attributes, only on resource attributes")
438 }
439 return *a.EnabledPtr
440 }
441
442 // Name returns actual name of the attribute that is set on the metric after applying NameOverride.
443 func (a Attribute) Name() AttributeName {
444 if a.NameOverride != "" {
445 return AttributeName(a.NameOverride)
446 }
447 return a.FullName
448 }
449
450 func (a Attribute) TestValue() string {
451 if a.Enum != nil {
452 return fmt.Sprintf(`%q`, a.Enum[0])
453 }
454 switch a.Type.ValueType {
455 case pcommon.ValueTypeEmpty:
456 return ""
457 case pcommon.ValueTypeStr:
458 return fmt.Sprintf(`"%s-val"`, a.FullName)
459 case pcommon.ValueTypeInt:
460 return strconv.Itoa(len(a.FullName))
461 case pcommon.ValueTypeDouble:
462 return fmt.Sprintf("%f", 0.1+float64(len(a.FullName)))
463 case pcommon.ValueTypeBool:
464 return strconv.FormatBool(len(a.FullName)%2 == 0)
465 case pcommon.ValueTypeMap:
466 return fmt.Sprintf(`map[string]any{"key1": "%s-val1", "key2": "%s-val2"}`, a.FullName, a.FullName)
467 case pcommon.ValueTypeSlice:
468 return fmt.Sprintf(`[]any{"%s-item1", "%s-item2"}`, a.FullName, a.FullName)
469 case pcommon.ValueTypeBytes:
470 return fmt.Sprintf(`[]byte("%s-val")`, a.FullName)
471 }
472 return ""
473 }
474
475 type Signal struct {
476 // Enabled defines whether the signal is enabled by default.
477 Enabled bool `mapstructure:"enabled"`
478
479 // Warnings that will be shown to user under specified conditions.
480 Warnings Warnings `mapstructure:"warnings"`
481
482 // Description of the signal.
483 Description string `mapstructure:"description"`
484
485 // The semantic convention reference of the signal.
486 SemanticConvention *SemanticConvention `mapstructure:"semantic_convention"`
487
488 // The stability level of the signal.
489 Stability Stability `mapstructure:"stability"`
490
491 // Extended documentation of the signal. If specified, this will be appended to the description used in generated documentation.
492 ExtendedDocumentation string `mapstructure:"extended_documentation"`
493
494 // Attributes is the list of attributes that the signal emits.
495 Attributes []AttributeName `mapstructure:"attributes"`
496 }
497
498 func (s Signal) HasConditionalAttributes(attrs map[AttributeName]Attribute) bool {
499 for _, attr := range s.Attributes {
500 if v, exists := attrs[attr]; exists && v.IsConditional() {
501 return true
502 }
503 }
504 return false
505 }
506
507 type Entity struct {
508 // Type is the type of the entity.
509 Type string `mapstructure:"type"`
510 // Brief is a brief description of the entity.
511 Brief string `mapstructure:"brief"`
512 // Stability is the stability level of the entity.
513 Stability string `mapstructure:"stability"`
514 // Identity contains references to resource attributes that uniquely identify the entity.
515 Identity []EntityAttributeRef `mapstructure:"identity"`
516 // Description contains references to resource attributes that describe the entity.
517 Description []EntityAttributeRef `mapstructure:"description"`
518 }
519
520 type EntityAttributeRef struct {
521 // Ref is the reference to a resource attribute.
522 Ref AttributeName `mapstructure:"ref"`
523 }