Debian Codegraph @

instrumentation/github.com/emicklei/go-restful/otelrestful/restful.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelrestful // import "go.opentelemetry.io/contrib/instrumentation/github.com/emicklei/go-restful/otelrestful"
5
6 import (
7 "github.com/emicklei/go-restful/v3"
8 "go.opentelemetry.io/otel"
9 "go.opentelemetry.io/otel/propagation"
10 oteltrace "go.opentelemetry.io/otel/trace"
11
12 "go.opentelemetry.io/contrib/instrumentation/github.com/emicklei/go-restful/otelrestful/internal/semconv"
13 )
14
15 // ScopeName is the instrumentation scope name.
16 const ScopeName = "go.opentelemetry.io/contrib/instrumentation/github.com/emicklei/go-restful/otelrestful"
17
18 // OTelFilter returns a restful.FilterFunction which will trace an incoming request.
19 //
20 // The service parameter should describe the name of the (virtual) server handling
21 // the request. Options can be applied to configure the tracer and propagators
22 // used for this filter.
23 func OTelFilter(service string, opts ...Option) restful.FilterFunction {
24 cfg := config{}
25 for _, opt := range opts {
26 opt.apply(&cfg)
27 }
28 if cfg.TracerProvider == nil {
29 cfg.TracerProvider = otel.GetTracerProvider()
30 }
31 tracer := cfg.TracerProvider.Tracer(
32 ScopeName,
33 oteltrace.WithInstrumentationVersion(Version),
34 )
35 if cfg.Propagators == nil {
36 cfg.Propagators = otel.GetTextMapPropagator()
37 }
38 semconvServer := semconv.NewHTTPServer(nil)
39
40 return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
41 r := req.Request
42 ctx := cfg.Propagators.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
43 route := req.SelectedRoutePath()
44 spanName := route
45
46 opts := []oteltrace.SpanStartOption{
47 oteltrace.WithAttributes(semconvServer.RequestTraceAttrs(service, r, semconv.RequestTraceAttrsOpts{})...),
48 oteltrace.WithSpanKind(oteltrace.SpanKindServer),
49 }
50 if route != "" {
51 rAttr := semconvServer.Route(route)
52 opts = append(opts, oteltrace.WithAttributes(rAttr))
53 }
54
55 if cfg.PublicEndpoint || (cfg.PublicEndpointFn != nil && cfg.PublicEndpointFn(r.WithContext(ctx))) {
56 opts = append(opts, oteltrace.WithNewRoot())
57 // Linking incoming span context if any for public endpoint.
58 if s := oteltrace.SpanContextFromContext(ctx); s.IsValid() && s.IsRemote() {
59 opts = append(opts, oteltrace.WithLinks(oteltrace.Link{SpanContext: s}))
60 }
61 }
62
63 ctx, span := tracer.Start(ctx, spanName, opts...)
64 defer span.End()
65
66 // pass the span through the request context
67 req.Request = req.Request.WithContext(ctx)
68
69 chain.ProcessFilter(req, resp)
70
71 status := resp.StatusCode()
72 span.SetStatus(semconvServer.Status(status))
73 span.SetAttributes(semconvServer.ResponseTraceAttrs(semconv.ResponseTelemetry{
74 StatusCode: status,
75 })...)
76 }
77 }