Debian Codegraph @

exporters/zipkin/zipkin.go

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