config.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package skywalkingreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/skywalkingreceiver"
  4. import (
  5. "fmt"
  6. "go.opentelemetry.io/collector/component"
  7. "go.opentelemetry.io/collector/config/configgrpc"
  8. "go.opentelemetry.io/collector/config/confighttp"
  9. "go.opentelemetry.io/collector/confmap"
  10. )
  11. const (
  12. // The config field id to load the protocol map from
  13. protocolsFieldName = "protocols"
  14. )
  15. // Protocols is the configuration for the supported protocols.
  16. type Protocols struct {
  17. GRPC *configgrpc.GRPCServerSettings `mapstructure:"grpc"`
  18. HTTP *confighttp.HTTPServerSettings `mapstructure:"http"`
  19. }
  20. // Config defines configuration for skywalking receiver.
  21. type Config struct {
  22. Protocols `mapstructure:"protocols"`
  23. }
  24. var _ component.Config = (*Config)(nil)
  25. var _ confmap.Unmarshaler = (*Config)(nil)
  26. // Validate checks the receiver configuration is valid
  27. func (cfg *Config) Validate() error {
  28. if cfg.GRPC == nil && cfg.HTTP == nil {
  29. return fmt.Errorf("must specify at least one protocol when using the Skywalking receiver")
  30. }
  31. if cfg.GRPC != nil {
  32. var err error
  33. if _, err = extractPortFromEndpoint(cfg.GRPC.NetAddr.Endpoint); err != nil {
  34. return fmt.Errorf("unable to extract port for the gRPC endpoint: %w", err)
  35. }
  36. }
  37. if cfg.HTTP != nil {
  38. if _, err := extractPortFromEndpoint(cfg.HTTP.Endpoint); err != nil {
  39. return fmt.Errorf("unable to extract port for the HTTP endpoint: %w", err)
  40. }
  41. }
  42. return nil
  43. }
  44. // Unmarshal a config.Parser into the config struct.
  45. func (cfg *Config) Unmarshal(componentParser *confmap.Conf) error {
  46. if componentParser == nil || len(componentParser.AllKeys()) == 0 {
  47. return fmt.Errorf("empty config for Skywalking receiver")
  48. }
  49. // UnmarshalExact will not set struct properties to nil even if no key is provided,
  50. // so set the protocol structs to nil where the keys were omitted.
  51. err := componentParser.Unmarshal(cfg, confmap.WithErrorUnused())
  52. if err != nil {
  53. return err
  54. }
  55. protocols, err := componentParser.Sub(protocolsFieldName)
  56. if err != nil {
  57. return err
  58. }
  59. if !protocols.IsSet(protoGRPC) {
  60. cfg.GRPC = nil
  61. }
  62. if !protocols.IsSet(protoHTTP) {
  63. cfg.HTTP = nil
  64. }
  65. return nil
  66. }