Debian Codegraph @

instrumentation/net/http/otelhttp/transport.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
5
6 import (
7 "context"
8 "io"
9 "net/http"
10 "net/http/httptrace"
11 "sync/atomic"
12 "time"
13
14 "go.opentelemetry.io/otel"
15 "go.opentelemetry.io/otel/attribute"
16 "go.opentelemetry.io/otel/codes"
17 "go.opentelemetry.io/otel/propagation"
18 otelsemconv "go.opentelemetry.io/otel/semconv/v1.40.0"
19 "go.opentelemetry.io/otel/trace"
20
21 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request"
22 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv"
23 )
24
25 // Transport implements the http.RoundTripper interface and wraps
26 // outbound HTTP(S) requests with a span and enriches it with metrics.
27 type Transport struct {
28 rt http.RoundTripper
29
30 tracer trace.Tracer
31 propagators propagation.TextMapPropagator
32 spanStartOptions []trace.SpanStartOption
33 filters []Filter
34 spanNameFormatter func(string, *http.Request) string
35 clientTrace func(context.Context) *httptrace.ClientTrace
36 metricAttributesFn func(*http.Request) []attribute.KeyValue
37
38 semconv semconv.HTTPClient
39 }
40
41 var _ http.RoundTripper = &Transport{}
42
43 // NewTransport wraps the provided http.RoundTripper with one that
44 // starts a span, injects the span context into the outbound request headers,
45 // and enriches it with metrics.
46 //
47 // If the provided http.RoundTripper is nil, http.DefaultTransport will be used
48 // as the base http.RoundTripper.
49 func NewTransport(base http.RoundTripper, opts ...Option) *Transport {
50 if base == nil {
51 base = http.DefaultTransport
52 }
53
54 t := Transport{
55 rt: base,
56 }
57
58 defaultOpts := []Option{
59 WithSpanOptions(trace.WithSpanKind(trace.SpanKindClient)),
60 WithSpanNameFormatter(defaultTransportFormatter),
61 }
62
63 c := newConfig(append(defaultOpts, opts...)...)
64 t.applyConfig(c)
65
66 return &t
67 }
68
69 func (t *Transport) applyConfig(c *config) {
70 t.tracer = c.Tracer
71 t.propagators = c.Propagators
72 t.spanStartOptions = c.SpanStartOptions
73 t.filters = c.Filters
74 t.spanNameFormatter = c.SpanNameFormatter
75 t.clientTrace = c.ClientTrace
76 t.semconv = semconv.NewHTTPClient(c.Meter)
77 t.metricAttributesFn = c.MetricAttributesFn
78 }
79
80 func defaultTransportFormatter(_ string, r *http.Request) string {
81 return "HTTP " + r.Method
82 }
83
84 // RoundTrip creates a Span and propagates its context via the provided request's headers
85 // before handing the request to the configured base RoundTripper. The created span will
86 // end when the response body is closed or when a read from the body returns io.EOF.
87 func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) {
88 requestStartTime := time.Now()
89 for _, f := range t.filters {
90 if !f(r) {
91 // Simply pass through to the base RoundTripper if a filter rejects the request
92 return t.rt.RoundTrip(r)
93 }
94 }
95
96 tracer := t.tracer
97
98 if tracer == nil {
99 if span := trace.SpanFromContext(r.Context()); span.SpanContext().IsValid() {
100 tracer = newTracer(span.TracerProvider())
101 } else {
102 tracer = newTracer(otel.GetTracerProvider())
103 }
104 }
105
106 ctx, span := tracer.Start(r.Context(), t.spanNameFormatter("", r), t.spanStartOptions...)
107
108 if t.clientTrace != nil {
109 ctx = httptrace.WithClientTrace(ctx, t.clientTrace(ctx))
110 }
111
112 labeler, found := LabelerFromContext(ctx)
113 if !found {
114 ctx = ContextWithLabeler(ctx, labeler)
115 }
116
117 r = r.Clone(ctx) // According to RoundTripper spec, we shouldn't modify the origin request.
118
119 var lastBW *request.BodyWrapper // Records the last body wrapper. Can be nil.
120 maybeWrapBody := func(body io.ReadCloser) io.ReadCloser {
121 if body == nil || body == http.NoBody {
122 return body
123 }
124 bw := request.NewBodyWrapper(body, func(int64) {})
125 lastBW = bw
126 return bw
127 }
128 r.Body = maybeWrapBody(r.Body)
129 if r.GetBody != nil {
130 originalGetBody := r.GetBody
131 r.GetBody = func() (io.ReadCloser, error) {
132 b, err := originalGetBody()
133 if err != nil {
134 lastBW = nil // The underlying transport will fail to make a retry request, hence, record no data.
135 return nil, err
136 }
137 return maybeWrapBody(b), nil
138 }
139 }
140
141 span.SetAttributes(t.semconv.RequestTraceAttrs(r)...)
142 t.propagators.Inject(ctx, propagation.HeaderCarrier(r.Header))
143
144 res, err := t.rt.RoundTrip(r)
145
146 // Record the metrics on error or no error.
147 statusCode := 0
148 if err == nil {
149 statusCode = res.StatusCode
150 }
151 var requestSize int64
152 if lastBW != nil {
153 requestSize = lastBW.BytesRead()
154 }
155 t.semconv.RecordMetrics(
156 ctx,
157 semconv.MetricData{
158 RequestSize: requestSize,
159 RequestDuration: time.Since(requestStartTime),
160 },
161 t.semconv.MetricOptions(semconv.MetricAttributes{
162 Req: r,
163 StatusCode: statusCode,
164 AdditionalAttributes: append(labeler.Get(), t.metricAttributesFromRequest(r)...),
165 }),
166 )
167
168 if err != nil {
169 span.SetAttributes(otelsemconv.ErrorType(err))
170 span.SetStatus(codes.Error, err.Error())
171 span.End()
172
173 return res, err
174 }
175
176 readRecordFunc := func(int64) {}
177 res.Body = newWrappedBody(span, readRecordFunc, res.Body)
178 // traces
179 span.SetAttributes(t.semconv.ResponseTraceAttrs(res)...)
180 span.SetStatus(t.semconv.Status(res.StatusCode))
181
182 return res, nil
183 }
184
185 func (t *Transport) metricAttributesFromRequest(r *http.Request) []attribute.KeyValue {
186 var attributeForRequest []attribute.KeyValue
187 if t.metricAttributesFn != nil {
188 attributeForRequest = t.metricAttributesFn(r)
189 }
190 return attributeForRequest
191 }
192
193 // newWrappedBody returns a new and appropriately scoped *wrappedBody as an
194 // io.ReadCloser. If the passed body implements io.Writer, the returned value
195 // will implement io.ReadWriteCloser.
196 func newWrappedBody(span trace.Span, record func(n int64), body io.ReadCloser) io.ReadCloser {
197 // The successful protocol switch responses will have a body that
198 // implement an io.ReadWriteCloser. Ensure this interface type continues
199 // to be satisfied if that is the case.
200 if _, ok := body.(io.ReadWriteCloser); ok {
201 return &wrappedBody{span: span, record: record, body: body}
202 }
203
204 // Remove the implementation of the io.ReadWriteCloser and only implement
205 // the io.ReadCloser.
206 return struct{ io.ReadCloser }{&wrappedBody{span: span, record: record, body: body}}
207 }
208
209 // wrappedBody is the response body type returned by the transport
210 // instrumentation to complete a span. Errors encountered when using the
211 // response body are recorded in span tracking the response.
212 //
213 // The span tracking the response is ended when this body is closed.
214 //
215 // If the response body implements the io.Writer interface (i.e. for
216 // successful protocol switches), the wrapped body also will.
217 type wrappedBody struct {
218 span trace.Span
219 recorded atomic.Bool
220 record func(n int64)
221 body io.ReadCloser
222 read atomic.Int64
223 }
224
225 var _ io.ReadWriteCloser = &wrappedBody{}
226
227 func (wb *wrappedBody) Write(p []byte) (int, error) {
228 // This will not panic given the guard in newWrappedBody.
229 n, err := wb.body.(io.Writer).Write(p)
230 if err != nil {
231 wb.span.SetAttributes(otelsemconv.ErrorType(err))
232 wb.span.SetStatus(codes.Error, err.Error())
233 }
234 return n, err
235 }
236
237 func (wb *wrappedBody) Read(b []byte) (int, error) {
238 n, err := wb.body.Read(b)
239 // Record the number of bytes read
240 wb.read.Add(int64(n))
241
242 switch err {
243 case nil:
244 // nothing to do here but fall through to the return
245 case io.EOF:
246 wb.recordBytesRead()
247 wb.span.End()
248 default:
249 wb.span.SetAttributes(otelsemconv.ErrorType(err))
250 wb.span.SetStatus(codes.Error, err.Error())
251 }
252 return n, err
253 }
254
255 // recordBytesRead is a function that ensures the number of bytes read is recorded once and only once.
256 func (wb *wrappedBody) recordBytesRead() {
257 // note: it is more performant (and equally correct) to use atomic.Bool over sync.Once here. In the event that
258 // two goroutines are racing to call this method, the number of bytes read will no longer increase. Using
259 // CompareAndSwap allows later goroutines to return quickly and not block waiting for the race winner to finish
260 // calling wb.record(wb.read.Load()).
261 if wb.recorded.CompareAndSwap(false, true) {
262 // Record the total number of bytes read
263 wb.record(wb.read.Load())
264 }
265 }
266
267 func (wb *wrappedBody) Close() error {
268 wb.recordBytesRead()
269 wb.span.End()
270 if wb.body != nil {
271 return wb.body.Close()
272 }
273 return nil
274 }