Debian Codegraph @

instrumentation/github.com/gorilla/mux/otelmux/mux.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelmux // import "go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux"
5
6 import (
7 "fmt"
8 "net/http"
9 "time"
10
11 "github.com/felixge/httpsnoop"
12 "github.com/gorilla/mux"
13 "go.opentelemetry.io/otel"
14 "go.opentelemetry.io/otel/attribute"
15 "go.opentelemetry.io/otel/metric"
16 "go.opentelemetry.io/otel/propagation"
17 "go.opentelemetry.io/otel/trace"
18
19 "go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux/internal/request"
20 "go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux/internal/semconv"
21 )
22
23 const (
24 // ScopeName is the instrumentation scope name.
25 ScopeName = "go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux"
26 )
27
28 // Middleware sets up a handler to start tracing the incoming
29 // requests. The service parameter should describe the name of the
30 // (virtual) server handling the request.
31 func Middleware(service string, opts ...Option) mux.MiddlewareFunc {
32 cfg := config{}
33 for _, opt := range opts {
34 opt.apply(&cfg)
35 }
36 if cfg.TracerProvider == nil {
37 cfg.TracerProvider = otel.GetTracerProvider()
38 }
39 tracer := cfg.TracerProvider.Tracer(
40 ScopeName,
41 trace.WithInstrumentationVersion(Version()),
42 )
43 if cfg.Propagators == nil {
44 cfg.Propagators = otel.GetTextMapPropagator()
45 }
46 if cfg.spanNameFormatter == nil {
47 cfg.spanNameFormatter = defaultSpanNameFunc
48 }
49 if cfg.MeterProvider == nil {
50 cfg.MeterProvider = otel.GetMeterProvider()
51 }
52 meter := cfg.MeterProvider.Meter(
53 ScopeName,
54 metric.WithInstrumentationVersion(Version()),
55 )
56 return func(handler http.Handler) http.Handler {
57 return traceware{
58 service: service,
59 tracer: tracer,
60 propagators: cfg.Propagators,
61 handler: handler,
62 spanNameFormatter: cfg.spanNameFormatter,
63 publicEndpoint: cfg.PublicEndpoint,
64 publicEndpointFn: cfg.PublicEndpointFn,
65 filters: cfg.Filters,
66 meter: meter,
67 semconv: semconv.NewHTTPServer(meter),
68 metricAttributesFn: cfg.MetricAttributesFn,
69 }
70 }
71 }
72
73 type traceware struct {
74 service string
75 tracer trace.Tracer
76 propagators propagation.TextMapPropagator
77 handler http.Handler
78 spanNameFormatter func(string, *http.Request) string
79 publicEndpoint bool
80 publicEndpointFn func(*http.Request) bool
81 filters []Filter
82 meter metric.Meter
83 semconv semconv.HTTPServer
84 metricAttributesFn func(*http.Request) []attribute.KeyValue
85 }
86
87 // validMethods are all the OTel recognized HTTP methods.
88 var validMethods = map[string]struct{}{
89 http.MethodGet: {},
90 http.MethodHead: {},
91 http.MethodPost: {},
92 http.MethodPut: {},
93 http.MethodPatch: {},
94 http.MethodDelete: {},
95 http.MethodConnect: {},
96 http.MethodOptions: {},
97 http.MethodTrace: {},
98 }
99
100 // defaultSpanNameFunc returns the semconv based default span name.
101 func defaultSpanNameFunc(routeName string, r *http.Request) string {
102 method := r.Method
103 if _, ok := validMethods[method]; !ok {
104 method = "HTTP"
105 }
106 return method + " " + routeName
107 }
108
109 // ServeHTTP implements the http.Handler interface. It does the actual
110 // tracing of the request.
111 func (tw traceware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
112 requestStartTime := time.Now()
113 for _, f := range tw.filters {
114 if !f(r) {
115 // Simply pass through to the handler if a filter rejects the request
116 tw.handler.ServeHTTP(w, r)
117 return
118 }
119 }
120
121 ctx := tw.propagators.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
122 opts := []trace.SpanStartOption{
123 trace.WithAttributes(tw.semconv.RequestTraceAttrs(tw.service, r, semconv.RequestTraceAttrsOpts{})...),
124 trace.WithSpanKind(trace.SpanKindServer),
125 }
126
127 if tw.publicEndpoint || (tw.publicEndpointFn != nil && tw.publicEndpointFn(r.WithContext(ctx))) {
128 opts = append(opts, trace.WithNewRoot())
129 // Linking incoming span context if any for public endpoint.
130 if s := trace.SpanContextFromContext(ctx); s.IsValid() && s.IsRemote() {
131 opts = append(opts, trace.WithLinks(trace.Link{SpanContext: s}))
132 }
133 }
134
135 routeStr := extractRoute(r)
136
137 if routeStr == "" {
138 routeStr = fmt.Sprintf("HTTP %s route not found", r.Method)
139 } else {
140 rAttr := tw.semconv.Route(routeStr)
141 opts = append(opts, trace.WithAttributes(rAttr))
142 }
143 ctx, span := tw.tracer.Start(ctx, tw.spanNameFormatter(routeStr, r), opts...)
144 defer span.End()
145
146 readRecordFunc := func(int64) {}
147 // if request body is nil or NoBody, we don't want to mutate the body as it
148 // will affect the identity of it in an unforeseeable way because we assert
149 // ReadCloser fulfills a certain interface and it is indeed nil or NoBody.
150 bw := request.NewBodyWrapper(r.Body, readRecordFunc)
151 if r.Body != nil && r.Body != http.NoBody {
152 r.Body = bw
153 }
154
155 writeRecordFunc := func(int64) {}
156 rww := request.NewRespWriterWrapper(w, writeRecordFunc)
157
158 // Wrap w to use our ResponseWriter methods while also exposing
159 // other interfaces that w may implement (http.CloseNotifier,
160 // http.Flusher, http.Hijacker, http.Pusher, io.ReaderFrom).
161 w = httpsnoop.Wrap(w, httpsnoop.Hooks{
162 Header: func(httpsnoop.HeaderFunc) httpsnoop.HeaderFunc {
163 return rww.Header
164 },
165 Write: func(httpsnoop.WriteFunc) httpsnoop.WriteFunc {
166 return rww.Write
167 },
168 WriteHeader: func(httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
169 return rww.WriteHeader
170 },
171 Flush: func(httpsnoop.FlushFunc) httpsnoop.FlushFunc {
172 return rww.Flush
173 },
174 })
175
176 tw.handler.ServeHTTP(w, r.WithContext(ctx))
177 statusCode := rww.StatusCode()
178 span.SetStatus(tw.semconv.Status(statusCode))
179 span.SetAttributes(tw.semconv.ResponseTraceAttrs(semconv.ResponseTelemetry{
180 StatusCode: statusCode,
181 ReadBytes: bw.BytesRead(),
182 ReadError: bw.Error(),
183 WriteBytes: rww.BytesWritten(),
184 WriteError: rww.Error(),
185 })...)
186
187 metricAttributes := semconv.MetricAttributes{
188 Req: r,
189 StatusCode: statusCode,
190 Route: routeStr,
191 AdditionalAttributes: tw.metricAttributesFromRequest(r),
192 }
193
194 tw.semconv.RecordMetrics(ctx, semconv.ServerMetricData{
195 ServerName: tw.service,
196 ResponseSize: rww.BytesWritten(),
197 MetricAttributes: metricAttributes,
198 MetricData: semconv.MetricData{
199 RequestSize: bw.BytesRead(),
200 RequestDuration: time.Since(requestStartTime),
201 },
202 })
203 }
204
205 func (tw traceware) metricAttributesFromRequest(r *http.Request) []attribute.KeyValue {
206 var attributeForRequest []attribute.KeyValue
207 if tw.metricAttributesFn != nil {
208 attributeForRequest = tw.metricAttributesFn(r)
209 }
210 return attributeForRequest
211 }
212
213 func extractRoute(r *http.Request) string {
214 routeStr := r.Pattern
215
216 if routeStr == "" {
217 route := mux.CurrentRoute(r)
218 if route != nil {
219 routeStr, _ = route.GetPathTemplate()
220 }
221 }
222 return routeStr
223 }