prometheus.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package datasenders // import "github.com/open-telemetry/opentelemetry-collector-contrib/testbed/datasenders"
  4. import (
  5. "context"
  6. "fmt"
  7. "go.opentelemetry.io/collector/component/componenttest"
  8. "go.opentelemetry.io/collector/consumer"
  9. "go.opentelemetry.io/collector/exporter/exportertest"
  10. "go.uber.org/zap"
  11. "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/prometheusexporter"
  12. "github.com/open-telemetry/opentelemetry-collector-contrib/testbed/testbed"
  13. )
  14. type prometheusDataSender struct {
  15. testbed.DataSenderBase
  16. consumer.Metrics
  17. namespace string
  18. }
  19. // NewPrometheusDataSender creates a new Prometheus sender that will expose data
  20. // on the specified port after Start is called.
  21. func NewPrometheusDataSender(host string, port int) testbed.MetricDataSender {
  22. return &prometheusDataSender{
  23. DataSenderBase: testbed.DataSenderBase{
  24. Port: port,
  25. Host: host,
  26. },
  27. }
  28. }
  29. func (pds *prometheusDataSender) Start() error {
  30. factory := prometheusexporter.NewFactory()
  31. cfg := factory.CreateDefaultConfig().(*prometheusexporter.Config)
  32. cfg.Endpoint = pds.GetEndpoint().String()
  33. cfg.Namespace = pds.namespace
  34. params := exportertest.NewNopCreateSettings()
  35. params.Logger = zap.L()
  36. exp, err := factory.CreateMetricsExporter(context.Background(), params, cfg)
  37. if err != nil {
  38. return err
  39. }
  40. pds.Metrics = exp
  41. return exp.Start(context.Background(), componenttest.NewNopHost())
  42. }
  43. func (pds *prometheusDataSender) GenConfigYAMLStr() string {
  44. format := `
  45. prometheus:
  46. config:
  47. scrape_configs:
  48. - job_name: 'testbed'
  49. scrape_interval: 100ms
  50. static_configs:
  51. - targets: ['%s']
  52. `
  53. return fmt.Sprintf(format, pds.GetEndpoint())
  54. }
  55. func (pds *prometheusDataSender) ProtocolName() string {
  56. return "prometheus"
  57. }