Debian Codegraph @

instrumentation/net/http/httptrace/otelhttptrace/clienttrace.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelhttptrace // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
5
6 import (
7 "context"
8 "crypto/tls"
9 "net/http/httptrace"
10 "net/textproto"
11 "strings"
12 "sync"
13
14 "go.opentelemetry.io/otel"
15 "go.opentelemetry.io/otel/attribute"
16 "go.opentelemetry.io/otel/codes"
17 "go.opentelemetry.io/otel/trace"
18
19 "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv"
20 )
21
22 // ScopeName is the instrumentation scope name.
23 const ScopeName = "go.opentelemetry.io/otel/instrumentation/httptrace"
24
25 // HTTP attributes.
26 var (
27 HTTPStatus = attribute.Key("http.status")
28 HTTPHeaderMIME = attribute.Key("http.mime")
29 HTTPRemoteAddr = attribute.Key("http.remote")
30 HTTPLocalAddr = attribute.Key("http.local")
31 HTTPConnectionReused = attribute.Key("http.conn.reused")
32 HTTPConnectionWasIdle = attribute.Key("http.conn.wasidle")
33 HTTPConnectionIdleTime = attribute.Key("http.conn.idletime")
34 HTTPConnectionStartNetwork = attribute.Key("http.conn.start.network")
35 HTTPConnectionDoneNetwork = attribute.Key("http.conn.done.network")
36 HTTPConnectionDoneAddr = attribute.Key("http.conn.done.addr")
37 HTTPDNSAddrs = attribute.Key("http.dns.addrs")
38 )
39
40 var hookMap = map[string]string{
41 "http.dns": "http.getconn",
42 "http.connect": "http.getconn",
43 "http.tls": "http.getconn",
44 }
45
46 func parentHook(hook string) string {
47 if strings.HasPrefix(hook, "http.connect") {
48 return hookMap["http.connect"]
49 }
50 return hookMap[hook]
51 }
52
53 // ClientTraceOption allows customizations to how the httptrace.Client
54 // collects information.
55 type ClientTraceOption interface {
56 apply(*clientTracer)
57 }
58
59 type clientTraceOptionFunc func(*clientTracer)
60
61 func (fn clientTraceOptionFunc) apply(c *clientTracer) {
62 fn(c)
63 }
64
65 // WithoutSubSpans will modify the httptrace.ClientTrace to only collect data
66 // as Events and Attributes on a span found in the context. By default
67 // sub-spans will be generated.
68 func WithoutSubSpans() ClientTraceOption {
69 return clientTraceOptionFunc(func(ct *clientTracer) {
70 ct.useSpans = false
71 })
72 }
73
74 // WithRedactedHeaders will be replaced by fixed '****' values for the header
75 // names provided. These are in addition to the sensitive headers already
76 // redacted by default: Authorization, WWW-Authenticate, Proxy-Authenticate
77 // Proxy-Authorization, Cookie, Set-Cookie.
78 func WithRedactedHeaders(headers ...string) ClientTraceOption {
79 return clientTraceOptionFunc(func(ct *clientTracer) {
80 for _, header := range headers {
81 ct.redactedHeaders[strings.ToLower(header)] = struct{}{}
82 }
83 })
84 }
85
86 // WithoutHeaders will disable adding span attributes for the http headers
87 // and values.
88 func WithoutHeaders() ClientTraceOption {
89 return clientTraceOptionFunc(func(ct *clientTracer) {
90 ct.addHeaders = false
91 })
92 }
93
94 // WithInsecureHeaders will add span attributes for all http headers *INCLUDING*
95 // the sensitive headers that are redacted by default. The attribute values
96 // will include the raw un-redacted text. This might be useful for
97 // debugging authentication related issues, but should not be used for
98 // production deployments.
99 func WithInsecureHeaders() ClientTraceOption {
100 return clientTraceOptionFunc(func(ct *clientTracer) {
101 ct.addHeaders = true
102 ct.redactedHeaders = nil
103 })
104 }
105
106 // WithTracerProvider specifies a tracer provider for creating a tracer.
107 // The global provider is used if none is specified.
108 func WithTracerProvider(provider trace.TracerProvider) ClientTraceOption {
109 return clientTraceOptionFunc(func(ct *clientTracer) {
110 if provider != nil {
111 ct.tracerProvider = provider
112 }
113 })
114 }
115
116 type clientTracer struct {
117 context.Context
118
119 tracerProvider trace.TracerProvider
120
121 tr trace.Tracer
122
123 activeHooks map[string]context.Context
124 root trace.Span
125 mtx sync.Mutex
126 redactedHeaders map[string]struct{}
127 addHeaders bool
128 useSpans bool
129 semconv semconv.HTTPClient
130 }
131
132 // NewClientTrace returns an httptrace.ClientTrace implementation that will
133 // record OpenTelemetry spans for requests made by an http.Client. By default
134 // several spans will be added to the trace for various stages of a request
135 // (dns, connection, tls, etc). Also by default, all HTTP headers will be
136 // added as attributes to spans, although several headers will be automatically
137 // redacted: Authorization, WWW-Authenticate, Proxy-Authenticate,
138 // Proxy-Authorization, Cookie, and Set-Cookie.
139 func NewClientTrace(ctx context.Context, opts ...ClientTraceOption) *httptrace.ClientTrace {
140 ct := &clientTracer{
141 Context: ctx,
142 activeHooks: make(map[string]context.Context),
143 redactedHeaders: map[string]struct{}{
144 "authorization": {},
145 "www-authenticate": {},
146 "proxy-authenticate": {},
147 "proxy-authorization": {},
148 "cookie": {},
149 "set-cookie": {},
150 },
151 addHeaders: true,
152 useSpans: true,
153 semconv: semconv.NewHTTPClient(nil),
154 }
155
156 if span := trace.SpanFromContext(ctx); span.SpanContext().IsValid() {
157 ct.tracerProvider = span.TracerProvider()
158 } else {
159 ct.tracerProvider = otel.GetTracerProvider()
160 }
161
162 for _, opt := range opts {
163 opt.apply(ct)
164 }
165
166 ct.tr = ct.tracerProvider.Tracer(
167 ScopeName,
168 trace.WithInstrumentationVersion(Version),
169 )
170
171 return &httptrace.ClientTrace{
172 GetConn: ct.getConn,
173 GotConn: ct.gotConn,
174 PutIdleConn: ct.putIdleConn,
175 GotFirstResponseByte: ct.gotFirstResponseByte,
176 Got100Continue: ct.got100Continue,
177 Got1xxResponse: ct.got1xxResponse,
178 DNSStart: ct.dnsStart,
179 DNSDone: ct.dnsDone,
180 ConnectStart: ct.connectStart,
181 ConnectDone: ct.connectDone,
182 TLSHandshakeStart: ct.tlsHandshakeStart,
183 TLSHandshakeDone: ct.tlsHandshakeDone,
184 WroteHeaderField: ct.wroteHeaderField,
185 WroteHeaders: ct.wroteHeaders,
186 Wait100Continue: ct.wait100Continue,
187 WroteRequest: ct.wroteRequest,
188 }
189 }
190
191 func (ct *clientTracer) start(hook, spanName string, attrs ...attribute.KeyValue) {
192 if !ct.useSpans {
193 if ct.root == nil {
194 ct.root = trace.SpanFromContext(ct.Context)
195 }
196 ct.root.AddEvent(hook+".start", trace.WithAttributes(attrs...))
197 return
198 }
199
200 ct.mtx.Lock()
201 defer ct.mtx.Unlock()
202
203 if hookCtx, found := ct.activeHooks[hook]; !found {
204 var sp trace.Span
205 ct.activeHooks[hook], sp = ct.tr.Start(ct.getParentContext(hook), spanName, trace.WithAttributes(attrs...), trace.WithSpanKind(trace.SpanKindClient))
206 if ct.root == nil {
207 ct.root = sp
208 }
209 } else {
210 // end was called before start finished, add the start attributes and end the span here
211 span := trace.SpanFromContext(hookCtx)
212 span.SetAttributes(attrs...)
213 span.End()
214
215 delete(ct.activeHooks, hook)
216 }
217 }
218
219 func (ct *clientTracer) end(hook string, err error, attrs ...attribute.KeyValue) {
220 if !ct.useSpans {
221 // sometimes end may be called without previous start
222 if ct.root == nil {
223 ct.root = trace.SpanFromContext(ct.Context)
224 }
225 if err != nil {
226 attrs = append(attrs, attribute.String(hook+".error", err.Error()))
227 }
228 ct.root.AddEvent(hook+".done", trace.WithAttributes(attrs...))
229 return
230 }
231
232 ct.mtx.Lock()
233 defer ct.mtx.Unlock()
234 if ctx, ok := ct.activeHooks[hook]; ok {
235 span := trace.SpanFromContext(ctx)
236 if err != nil {
237 span.SetStatus(codes.Error, err.Error())
238 }
239 span.SetAttributes(attrs...)
240 span.End()
241 delete(ct.activeHooks, hook)
242 } else {
243 // start is not finished before end is called.
244 // Start a span here with the ending attributes that will be finished when start finishes.
245 // Yes, it's backwards. v0v
246 ctx, span := ct.tr.Start(ct.getParentContext(hook), hook, trace.WithAttributes(attrs...), trace.WithSpanKind(trace.SpanKindClient))
247 if err != nil {
248 span.SetStatus(codes.Error, err.Error())
249 }
250 ct.activeHooks[hook] = ctx
251 }
252 }
253
254 func (ct *clientTracer) getParentContext(hook string) context.Context {
255 ctx, ok := ct.activeHooks[parentHook(hook)]
256 if !ok {
257 return ct.Context
258 }
259 return ctx
260 }
261
262 func (ct *clientTracer) span(hook string) trace.Span {
263 ct.mtx.Lock()
264 defer ct.mtx.Unlock()
265 if ctx, ok := ct.activeHooks[hook]; ok {
266 return trace.SpanFromContext(ctx)
267 }
268 return nil
269 }
270
271 func (ct *clientTracer) getConn(host string) {
272 ct.start("http.getconn", "http.getconn", ct.semconv.TraceAttributes(host)...)
273 }
274
275 func (ct *clientTracer) gotConn(info httptrace.GotConnInfo) {
276 attrs := []attribute.KeyValue{
277 HTTPRemoteAddr.String(info.Conn.RemoteAddr().String()),
278 HTTPLocalAddr.String(info.Conn.LocalAddr().String()),
279 HTTPConnectionReused.Bool(info.Reused),
280 HTTPConnectionWasIdle.Bool(info.WasIdle),
281 }
282 if info.WasIdle {
283 attrs = append(attrs, HTTPConnectionIdleTime.String(info.IdleTime.String()))
284 }
285 ct.end("http.getconn", nil, attrs...)
286 }
287
288 func (ct *clientTracer) putIdleConn(err error) {
289 ct.end("http.receive", err)
290 }
291
292 func (ct *clientTracer) gotFirstResponseByte() {
293 ct.start("http.receive", "http.receive")
294 }
295
296 func (ct *clientTracer) dnsStart(info httptrace.DNSStartInfo) {
297 ct.start("http.dns", "http.dns", ct.semconv.TraceAttributes(info.Host)...)
298 }
299
300 func (ct *clientTracer) dnsDone(info httptrace.DNSDoneInfo) {
301 addrs := make([]string, 0, len(info.Addrs))
302 for _, netAddr := range info.Addrs {
303 addrs = append(addrs, netAddr.String())
304 }
305 ct.end("http.dns", info.Err, HTTPDNSAddrs.String(sliceToString(addrs)))
306 }
307
308 func (ct *clientTracer) connectStart(network, addr string) {
309 ct.start("http.connect."+addr, "http.connect",
310 HTTPRemoteAddr.String(addr),
311 HTTPConnectionStartNetwork.String(network),
312 )
313 }
314
315 func (ct *clientTracer) connectDone(network, addr string, err error) {
316 ct.end("http.connect."+addr, err,
317 HTTPConnectionDoneAddr.String(addr),
318 HTTPConnectionDoneNetwork.String(network),
319 )
320 }
321
322 func (ct *clientTracer) tlsHandshakeStart() {
323 ct.start("http.tls", "http.tls")
324 }
325
326 func (ct *clientTracer) tlsHandshakeDone(_ tls.ConnectionState, err error) {
327 ct.end("http.tls", err)
328 }
329
330 func (ct *clientTracer) wroteHeaderField(k string, v []string) {
331 if ct.useSpans && ct.span("http.headers") == nil {
332 ct.start("http.headers", "http.headers")
333 }
334 if !ct.addHeaders {
335 return
336 }
337 k = strings.ToLower(k)
338 value := sliceToString(v)
339 if _, ok := ct.redactedHeaders[k]; ok {
340 value = "****"
341 }
342 ct.root.SetAttributes(attribute.String("http.request.header."+k, value))
343 }
344
345 func (ct *clientTracer) wroteHeaders() {
346 if ct.useSpans && ct.span("http.headers") != nil {
347 ct.end("http.headers", nil)
348 }
349 ct.start("http.send", "http.send")
350 }
351
352 func (ct *clientTracer) wroteRequest(info httptrace.WroteRequestInfo) {
353 if info.Err != nil {
354 ct.root.SetStatus(codes.Error, info.Err.Error())
355 }
356 ct.end("http.send", info.Err)
357 }
358
359 func (ct *clientTracer) got100Continue() {
360 span := ct.root
361 if ct.useSpans {
362 span = ct.span("http.receive")
363 }
364 // It's possible that Got100Continue is called before GotFirstResponseByte at which point span can be `nil`.
365 if span != nil {
366 span.AddEvent("GOT 100 - Continue")
367 }
368 }
369
370 func (ct *clientTracer) wait100Continue() {
371 span := ct.root
372 if ct.useSpans {
373 span = ct.span("http.send")
374 }
375 // It's possible that Wait100Continue is called before GotFirstResponseByte at which point span can be `nil`.
376 if span != nil {
377 span.AddEvent("GOT 100 - Wait")
378 }
379 }
380
381 func (ct *clientTracer) got1xxResponse(code int, header textproto.MIMEHeader) error {
382 span := ct.root
383 if ct.useSpans {
384 span = ct.span("http.receive")
385 }
386 // It's possible that Got1xxResponse is called before GotFirstResponseByte at which point span can be `nil`.
387 if span != nil {
388 span.AddEvent("GOT 1xx", trace.WithAttributes(
389 HTTPStatus.Int(code),
390 HTTPHeaderMIME.String(sm2s(header)),
391 ))
392 }
393 return nil
394 }
395
396 func sliceToString(value []string) string {
397 if len(value) == 0 {
398 return "undefined"
399 }
400 return strings.Join(value, ",")
401 }
402
403 func sm2s(value map[string][]string) string {
404 var buf strings.Builder
405 for k, v := range value {
406 if buf.Len() != 0 {
407 _, _ = buf.WriteString(",")
408 }
409 _, _ = buf.WriteString(k)
410 _, _ = buf.WriteString("=")
411 _, _ = buf.WriteString(sliceToString(v))
412 }
413 return buf.String()
414 }