| 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 |
"net/http" |
| 8 |
"time" |
| 9 |
|
| 10 |
"github.com/felixge/httpsnoop" |
| 11 |
"go.opentelemetry.io/otel" |
| 12 |
"go.opentelemetry.io/otel/attribute" |
| 13 |
"go.opentelemetry.io/otel/propagation" |
| 14 |
"go.opentelemetry.io/otel/trace" |
| 15 |
|
| 16 |
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request" |
| 17 |
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv" |
| 18 |
) |
| 19 |
|
| 20 |
// middleware is an http middleware which wraps the next handler in a span. |
| 21 |
type middleware struct { |
| 22 |
operation string |
| 23 |
server string |
| 24 |
|
| 25 |
tracer trace.Tracer |
| 26 |
propagators propagation.TextMapPropagator |
| 27 |
spanStartOptions []trace.SpanStartOption |
| 28 |
readEvent bool |
| 29 |
writeEvent bool |
| 30 |
filters []Filter |
| 31 |
spanNameFormatter func(string, *http.Request) string |
| 32 |
publicEndpointFn func(*http.Request) bool |
| 33 |
metricAttributesFn func(*http.Request) []attribute.KeyValue |
| 34 |
|
| 35 |
semconv semconv.HTTPServer |
| 36 |
} |
| 37 |
|
| 38 |
func defaultHandlerFormatter(operation string, _ *http.Request) string { |
| 39 |
return operation |
| 40 |
} |
| 41 |
|
| 42 |
// NewHandler wraps the passed handler in a span named after the operation and |
| 43 |
// enriches it with metrics. |
| 44 |
func NewHandler(handler http.Handler, operation string, opts ...Option) http.Handler { |
| 45 |
return NewMiddleware(operation, opts...)(handler) |
| 46 |
} |
| 47 |
|
| 48 |
// NewMiddleware returns a tracing and metrics instrumentation middleware. |
| 49 |
// The handler returned by the middleware wraps a handler |
| 50 |
// in a span named after the operation and enriches it with metrics. |
| 51 |
func NewMiddleware(operation string, opts ...Option) func(http.Handler) http.Handler { |
| 52 |
h := middleware{ |
| 53 |
operation: operation, |
| 54 |
} |
| 55 |
|
| 56 |
defaultOpts := []Option{ |
| 57 |
WithSpanOptions(trace.WithSpanKind(trace.SpanKindServer)), |
| 58 |
WithSpanNameFormatter(defaultHandlerFormatter), |
| 59 |
} |
| 60 |
|
| 61 |
c := newConfig(append(defaultOpts, opts...)...) |
| 62 |
h.configure(c) |
| 63 |
|
| 64 |
return func(next http.Handler) http.Handler { |
| 65 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 66 |
h.serveHTTP(w, r, next) |
| 67 |
}) |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
func (h *middleware) configure(c *config) { |
| 72 |
h.tracer = c.Tracer |
| 73 |
h.propagators = c.Propagators |
| 74 |
h.spanStartOptions = c.SpanStartOptions |
| 75 |
h.readEvent = c.ReadEvent |
| 76 |
h.writeEvent = c.WriteEvent |
| 77 |
h.filters = c.Filters |
| 78 |
h.spanNameFormatter = c.SpanNameFormatter |
| 79 |
h.publicEndpointFn = c.PublicEndpointFn |
| 80 |
h.server = c.ServerName |
| 81 |
h.semconv = semconv.NewHTTPServer(c.Meter) |
| 82 |
h.metricAttributesFn = c.MetricAttributesFn |
| 83 |
} |
| 84 |
|
| 85 |
// serveHTTP sets up tracing and calls the given next http.Handler with the span |
| 86 |
// context injected into the request context. |
| 87 |
func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http.Handler) { |
| 88 |
requestStartTime := time.Now() |
| 89 |
for _, f := range h.filters { |
| 90 |
if !f(r) { |
| 91 |
// Simply pass through to the handler if a filter rejects the request |
| 92 |
next.ServeHTTP(w, r) |
| 93 |
return |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
ctx := h.propagators.Extract(r.Context(), propagation.HeaderCarrier(r.Header)) |
| 98 |
opts := []trace.SpanStartOption{ |
| 99 |
trace.WithAttributes(h.semconv.RequestTraceAttrs(h.server, r, semconv.RequestTraceAttrsOpts{})...), |
| 100 |
} |
| 101 |
|
| 102 |
opts = append(opts, h.spanStartOptions...) |
| 103 |
if h.publicEndpointFn != nil && h.publicEndpointFn(r.WithContext(ctx)) { |
| 104 |
opts = append(opts, trace.WithNewRoot()) |
| 105 |
// Linking incoming span context if any for public endpoint. |
| 106 |
if s := trace.SpanContextFromContext(ctx); s.IsValid() && s.IsRemote() { |
| 107 |
opts = append(opts, trace.WithLinks(trace.Link{SpanContext: s})) |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
tracer := h.tracer |
| 112 |
|
| 113 |
if tracer == nil { |
| 114 |
if span := trace.SpanFromContext(r.Context()); span.SpanContext().IsValid() { |
| 115 |
tracer = newTracer(span.TracerProvider()) |
| 116 |
} else { |
| 117 |
tracer = newTracer(otel.GetTracerProvider()) |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
if startTime := StartTimeFromContext(ctx); !startTime.IsZero() { |
| 122 |
opts = append(opts, trace.WithTimestamp(startTime)) |
| 123 |
requestStartTime = startTime |
| 124 |
} |
| 125 |
|
| 126 |
ctx, span := tracer.Start(ctx, h.spanNameFormatter(h.operation, r), opts...) |
| 127 |
defer span.End() |
| 128 |
|
| 129 |
readRecordFunc := func(int64) {} |
| 130 |
if h.readEvent { |
| 131 |
readRecordFunc = func(n int64) { |
| 132 |
span.AddEvent("read", trace.WithAttributes(ReadBytesKey.Int64(n))) |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
// if request body is nil or NoBody, we don't want to mutate the body as it |
| 137 |
// will affect the identity of it in an unforeseeable way because we assert |
| 138 |
// ReadCloser fulfills a certain interface and it is indeed nil or NoBody. |
| 139 |
bw := request.NewBodyWrapper(r.Body, readRecordFunc) |
| 140 |
if r.Body != nil && r.Body != http.NoBody { |
| 141 |
r.Body = bw |
| 142 |
} |
| 143 |
|
| 144 |
writeRecordFunc := func(int64) {} |
| 145 |
if h.writeEvent { |
| 146 |
writeRecordFunc = func(n int64) { |
| 147 |
span.AddEvent("write", trace.WithAttributes(WroteBytesKey.Int64(n))) |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
rww := request.NewRespWriterWrapper(w, writeRecordFunc) |
| 152 |
|
| 153 |
// Wrap w to use our ResponseWriter methods while also exposing |
| 154 |
// other interfaces that w may implement (http.CloseNotifier, |
| 155 |
// http.Flusher, http.Hijacker, http.Pusher, io.ReaderFrom). |
| 156 |
|
| 157 |
w = httpsnoop.Wrap(w, httpsnoop.Hooks{ |
| 158 |
Header: func(httpsnoop.HeaderFunc) httpsnoop.HeaderFunc { |
| 159 |
return rww.Header |
| 160 |
}, |
| 161 |
Write: func(httpsnoop.WriteFunc) httpsnoop.WriteFunc { |
| 162 |
return rww.Write |
| 163 |
}, |
| 164 |
WriteHeader: func(httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc { |
| 165 |
return rww.WriteHeader |
| 166 |
}, |
| 167 |
Flush: func(httpsnoop.FlushFunc) httpsnoop.FlushFunc { |
| 168 |
return rww.Flush |
| 169 |
}, |
| 170 |
}) |
| 171 |
|
| 172 |
labeler, found := LabelerFromContext(ctx) |
| 173 |
if !found { |
| 174 |
ctx = ContextWithLabeler(ctx, labeler) |
| 175 |
} |
| 176 |
|
| 177 |
r = r.WithContext(ctx) |
| 178 |
next.ServeHTTP(w, r) |
| 179 |
|
| 180 |
if r.Pattern != "" { |
| 181 |
span.SetName(h.spanNameFormatter(h.operation, r)) |
| 182 |
} |
| 183 |
|
| 184 |
statusCode := rww.StatusCode() |
| 185 |
bytesWritten := rww.BytesWritten() |
| 186 |
span.SetStatus(h.semconv.Status(statusCode)) |
| 187 |
bytesRead := bw.BytesRead() |
| 188 |
span.SetAttributes(h.semconv.ResponseTraceAttrs(semconv.ResponseTelemetry{ |
| 189 |
StatusCode: statusCode, |
| 190 |
ReadBytes: bytesRead, |
| 191 |
ReadError: bw.Error(), |
| 192 |
WriteBytes: bytesWritten, |
| 193 |
WriteError: rww.Error(), |
| 194 |
})...) |
| 195 |
|
| 196 |
h.semconv.RecordMetrics(ctx, semconv.ServerMetricData{ |
| 197 |
ServerName: h.server, |
| 198 |
ResponseSize: bytesWritten, |
| 199 |
MetricAttributes: semconv.MetricAttributes{ |
| 200 |
Req: r, |
| 201 |
StatusCode: statusCode, |
| 202 |
AdditionalAttributes: append(labeler.Get(), h.metricAttributesFromRequest(r)...), |
| 203 |
}, |
| 204 |
MetricData: semconv.MetricData{ |
| 205 |
RequestSize: bytesRead, |
| 206 |
RequestDuration: time.Since(requestStartTime), |
| 207 |
}, |
| 208 |
}) |
| 209 |
} |
| 210 |
|
| 211 |
func (h *middleware) metricAttributesFromRequest(r *http.Request) []attribute.KeyValue { |
| 212 |
var attributeForRequest []attribute.KeyValue |
| 213 |
if h.metricAttributesFn != nil { |
| 214 |
attributeForRequest = h.metricAttributesFn(r) |
| 215 |
} |
| 216 |
return attributeForRequest |
| 217 |
} |