metadata.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package consul // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/metadataproviders/consul"
  4. import (
  5. "context"
  6. "fmt"
  7. "github.com/hashicorp/consul/api"
  8. )
  9. type Provider interface {
  10. Metadata(context.Context) (*Metadata, error)
  11. }
  12. type consulMetadataImpl struct {
  13. consulClient *api.Client
  14. allowedLabels map[string]any
  15. }
  16. type Metadata struct {
  17. NodeID string
  18. Hostname string
  19. Datacenter string
  20. HostMetadata map[string]string
  21. }
  22. func NewProvider(client *api.Client, allowedLabels map[string]any) Provider {
  23. return &consulMetadataImpl{consulClient: client, allowedLabels: allowedLabels}
  24. }
  25. func (d *consulMetadataImpl) Metadata(_ context.Context) (*Metadata, error) {
  26. var metadata Metadata
  27. self, err := d.consulClient.Agent().Self()
  28. if err != nil {
  29. return nil, fmt.Errorf("failed to get local agent information: %w", err)
  30. }
  31. config := self["Config"]
  32. if config == nil {
  33. return nil, fmt.Errorf("failed getting consul agent configuration. was 'Config' returned by consul?. resp: %+v", self)
  34. }
  35. hostname, ok := config["NodeName"].(string)
  36. if !ok {
  37. return nil, fmt.Errorf("failed getting consul hostname. was 'NodeName' returned by consul? resp: %+v", config)
  38. }
  39. metadata.Hostname = hostname
  40. datacenter, ok := config["Datacenter"].(string)
  41. if !ok {
  42. return nil, fmt.Errorf("failed getting consul datacenter. was 'Datacenter' returned by consul? resp: %+v", config)
  43. }
  44. metadata.Datacenter = datacenter
  45. nodeID, ok := config["NodeID"].(string)
  46. if !ok {
  47. return nil, fmt.Errorf("failed getting node ID. was 'NodeID' returned by consul? resp: %+v", config)
  48. }
  49. metadata.NodeID = nodeID
  50. meta := self["Meta"]
  51. if meta == nil {
  52. return &metadata, nil
  53. }
  54. metaMap := make(map[string]string)
  55. for k, v := range meta {
  56. if _, ok := d.allowedLabels[k]; ok {
  57. metaMap[k] = v.(string)
  58. }
  59. }
  60. metadata.HostMetadata = metaMap
  61. return &metadata, nil
  62. }