zipkin.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // Copyright The OpenTelemetry Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package zipkin // import "go.opentelemetry.io/otel/exporters/zipkin"
  15. import (
  16. "bytes"
  17. "context"
  18. "encoding/json"
  19. "fmt"
  20. "io"
  21. "log"
  22. "net/http"
  23. "net/url"
  24. "sync"
  25. "github.com/go-logr/logr"
  26. "github.com/go-logr/stdr"
  27. sdktrace "go.opentelemetry.io/otel/sdk/trace"
  28. )
  29. const (
  30. defaultCollectorURL = "http://localhost:9411/api/v2/spans"
  31. )
  32. // Exporter exports spans to the zipkin collector.
  33. type Exporter struct {
  34. url string
  35. client *http.Client
  36. logger logr.Logger
  37. stoppedMu sync.RWMutex
  38. stopped bool
  39. }
  40. var _ sdktrace.SpanExporter = &Exporter{}
  41. var emptyLogger = logr.Logger{}
  42. // Options contains configuration for the exporter.
  43. type config struct {
  44. client *http.Client
  45. logger logr.Logger
  46. }
  47. // Option defines a function that configures the exporter.
  48. type Option interface {
  49. apply(config) config
  50. }
  51. type optionFunc func(config) config
  52. func (fn optionFunc) apply(cfg config) config {
  53. return fn(cfg)
  54. }
  55. // WithLogger configures the exporter to use the passed logger.
  56. // WithLogger and WithLogr will overwrite each other.
  57. func WithLogger(logger *log.Logger) Option {
  58. return WithLogr(stdr.New(logger))
  59. }
  60. // WithLogr configures the exporter to use the passed logr.Logger.
  61. // WithLogr and WithLogger will overwrite each other.
  62. func WithLogr(logger logr.Logger) Option {
  63. return optionFunc(func(cfg config) config {
  64. cfg.logger = logger
  65. return cfg
  66. })
  67. }
  68. // WithClient configures the exporter to use the passed HTTP client.
  69. func WithClient(client *http.Client) Option {
  70. return optionFunc(func(cfg config) config {
  71. cfg.client = client
  72. return cfg
  73. })
  74. }
  75. // New creates a new Zipkin exporter.
  76. func New(collectorURL string, opts ...Option) (*Exporter, error) {
  77. if collectorURL == "" {
  78. // Use endpoint from env var or default collector URL.
  79. collectorURL = envOr(envEndpoint, defaultCollectorURL)
  80. }
  81. u, err := url.Parse(collectorURL)
  82. if err != nil {
  83. return nil, fmt.Errorf("invalid collector URL %q: %v", collectorURL, err)
  84. }
  85. if u.Scheme == "" || u.Host == "" {
  86. return nil, fmt.Errorf("invalid collector URL %q: no scheme or host", collectorURL)
  87. }
  88. cfg := config{}
  89. for _, opt := range opts {
  90. cfg = opt.apply(cfg)
  91. }
  92. if cfg.client == nil {
  93. cfg.client = http.DefaultClient
  94. }
  95. return &Exporter{
  96. url: collectorURL,
  97. client: cfg.client,
  98. logger: cfg.logger,
  99. }, nil
  100. }
  101. // ExportSpans exports spans to a Zipkin receiver.
  102. func (e *Exporter) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error {
  103. e.stoppedMu.RLock()
  104. stopped := e.stopped
  105. e.stoppedMu.RUnlock()
  106. if stopped {
  107. e.logf("exporter stopped, not exporting span batch")
  108. return nil
  109. }
  110. if len(spans) == 0 {
  111. e.logf("no spans to export")
  112. return nil
  113. }
  114. models := SpanModels(spans)
  115. body, err := json.Marshal(models)
  116. if err != nil {
  117. return e.errf("failed to serialize zipkin models to JSON: %v", err)
  118. }
  119. e.logf("about to send a POST request to %s with body %s", e.url, body)
  120. req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.url, bytes.NewBuffer(body))
  121. if err != nil {
  122. return e.errf("failed to create request to %s: %v", e.url, err)
  123. }
  124. req.Header.Set("Content-Type", "application/json")
  125. resp, err := e.client.Do(req)
  126. if err != nil {
  127. return e.errf("request to %s failed: %v", e.url, err)
  128. }
  129. defer resp.Body.Close()
  130. // Zipkin API returns a 202 on success and the content of the body isn't interesting
  131. // but it is still being read because according to https://golang.org/pkg/net/http/#Response
  132. // > The default HTTP client's Transport may not reuse HTTP/1.x "keep-alive" TCP connections
  133. // > if the Body is not read to completion and closed.
  134. _, err = io.Copy(io.Discard, resp.Body)
  135. if err != nil {
  136. return e.errf("failed to read response body: %v", err)
  137. }
  138. if resp.StatusCode != http.StatusAccepted {
  139. return e.errf("failed to send spans to zipkin server with status %d", resp.StatusCode)
  140. }
  141. return nil
  142. }
  143. // Shutdown stops the exporter flushing any pending exports.
  144. func (e *Exporter) Shutdown(ctx context.Context) error {
  145. e.stoppedMu.Lock()
  146. e.stopped = true
  147. e.stoppedMu.Unlock()
  148. select {
  149. case <-ctx.Done():
  150. return ctx.Err()
  151. default:
  152. }
  153. return nil
  154. }
  155. func (e *Exporter) logf(format string, args ...interface{}) {
  156. if e.logger != emptyLogger {
  157. e.logger.Info(fmt.Sprintf(format, args...))
  158. }
  159. }
  160. func (e *Exporter) errf(format string, args ...interface{}) error {
  161. e.logf(format, args...)
  162. return fmt.Errorf(format, args...)
  163. }
  164. // MarshalLog is the marshaling function used by the logging system to represent this exporter.
  165. func (e *Exporter) MarshalLog() interface{} {
  166. return struct {
  167. Type string
  168. URL string
  169. }{
  170. Type: "zipkin",
  171. URL: e.url,
  172. }
  173. }