| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package configunmarshaler |
| 5 |
|
| 6 |
import ( |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
|
| 10 |
"golang.org/x/exp/maps" |
| 11 |
|
| 12 |
"go.opentelemetry.io/collector/component" |
| 13 |
"go.opentelemetry.io/collector/confmap" |
| 14 |
) |
| 15 |
|
| 16 |
type Configs[F component.Factory] struct { |
| 17 |
cfgs map[component.ID]component.Config |
| 18 |
|
| 19 |
factories map[component.Type]F |
| 20 |
} |
| 21 |
|
| 22 |
func NewConfigs[F component.Factory](factories map[component.Type]F) *Configs[F] { |
| 23 |
return &Configs[F]{factories: factories} |
| 24 |
} |
| 25 |
|
| 26 |
func (c *Configs[F]) Unmarshal(conf *confmap.Conf) error { |
| 27 |
rawCfgs := make(map[component.ID]map[string]any) |
| 28 |
if err := conf.Unmarshal(&rawCfgs); err != nil { |
| 29 |
return err |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
c.cfgs = make(map[component.ID]component.Config) |
| 34 |
|
| 35 |
for id := range rawCfgs { |
| 36 |
|
| 37 |
factory, ok := c.factories[id.Type()] |
| 38 |
if !ok { |
| 39 |
return errorUnknownType(id, maps.Keys(c.factories)) |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
sub, err := conf.Sub(id.String()) |
| 44 |
if err != nil { |
| 45 |
return errorUnmarshalError(id, err) |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
cfg := factory.CreateDefaultConfig() |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
if err := sub.Unmarshal(&cfg); err != nil { |
| 54 |
return errorUnmarshalError(id, err) |
| 55 |
} |
| 56 |
|
| 57 |
c.cfgs[id] = cfg |
| 58 |
} |
| 59 |
|
| 60 |
return nil |
| 61 |
} |
| 62 |
|
| 63 |
func (c *Configs[F]) Configs() map[component.ID]component.Config { |
| 64 |
return c.cfgs |
| 65 |
} |
| 66 |
|
| 67 |
func errorUnknownType(id component.ID, factories []component.Type) error { |
| 68 |
if id.Type().String() == "logging" { |
| 69 |
return errors.New("the logging exporter has been deprecated, use the debug exporter instead") |
| 70 |
} |
| 71 |
return fmt.Errorf("unknown type: %q for id: %q (valid values: %v)", id.Type(), id, factories) |
| 72 |
} |
| 73 |
|
| 74 |
func errorUnmarshalError(id component.ID, err error) error { |
| 75 |
return fmt.Errorf("error reading configuration for %q: %w", id, err) |
| 76 |
} |