Skip to content

confighttp: route-based span naming for ServeMux #12593

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .chloggen/confighttp-server-spanname.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: bug_fix

# The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver)
component: confighttp

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Use low-cardinality route pattern for confighttp server span names

# One or more tracking issues or pull requests related to the change
issues: [12468]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext: |
For components that route HTTP requests using a net/http.ServeMux, such as otlpreceiver,
server spans will now be given low-cardinality span names based on the route pattern.

# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [api, user]
43 changes: 39 additions & 4 deletions config/confighttp/confighttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,13 @@ func WithDecoder(key string, dec func(body io.ReadCloser) (io.ReadCloser, error)
})
}

// ToServer creates an http.Server from settings object.
// ToServer creates an http.Server, serving requests with the given handler.
//
// If handler is an *http.ServeMux, then its Handler method will be used to
// determine the matching route pattern to format the span name according to
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name. For
// backwards compatibility, if handler is NOT an *http.ServeMux, then the
// span name will be the URL path.
func (hss *ServerConfig) ToServer(_ context.Context, host component.Host, settings component.TelemetrySettings, handler http.Handler, opts ...ToServerOption) (*http.Server, error) {
serverOpts := &toServerOptions{}
serverOpts.Apply(opts...)
Expand All @@ -423,6 +429,7 @@ func (hss *ServerConfig) ToServer(_ context.Context, host component.Host, settin
hss.CompressionAlgorithms = defaultCompressionAlgorithms
}

mux, handlerIsMux := handler.(*http.ServeMux)
handler = httpContentDecompressor(
handler,
hss.MaxRequestBodySize,
Expand Down Expand Up @@ -461,20 +468,38 @@ func (hss *ServerConfig) ToServer(_ context.Context, host component.Host, settin
handler = responseHeadersHandler(handler, hss.ResponseHeaders)
}

spanNameFormatter := func(_ string, r *http.Request) string {
return r.URL.Path
}
if handlerIsMux {
spanNameFormatter = func(_ string, r *http.Request) string {
target := r.Pattern
if target == "" {
target = "unknown route"
}
return fmt.Sprintf("%s %s", r.Method, target)
}
}

otelOpts := append(
[]otelhttp.Option{
otelhttp.WithTracerProvider(settings.TracerProvider),
otelhttp.WithPropagators(otel.GetTextMapPropagator()),
otelhttp.WithSpanNameFormatter(func(_ string, r *http.Request) string {
return r.URL.Path
}),
otelhttp.WithSpanNameFormatter(spanNameFormatter),
otelhttp.WithMeterProvider(settings.MeterProvider),
},
serverOpts.OtelhttpOpts...)

// Enable OpenTelemetry observability plugin.
handler = otelhttp.NewHandler(handler, "", otelOpts...)

// We need to ensure Request.Pattern is set prior to instrumentation.
// This is set by ServeMux.ServeHTTP, but that won't be invoked until
// after the otelhttp instrumentation.
if handlerIsMux {
handler = &muxPatternHandler{next: handler, mux: mux}
}

// wrap the current handler in an interceptor that will add client.Info to the request's context
handler = &clientInfoHandler{
next: handler,
Expand All @@ -498,6 +523,16 @@ func (hss *ServerConfig) ToServer(_ context.Context, host component.Host, settin
return server, err
}

type muxPatternHandler struct {
next http.Handler
mux *http.ServeMux
}

func (h *muxPatternHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, r.Pattern = h.mux.Handler(r)
h.next.ServeHTTP(w, r)
}

func responseHeadersHandler(handler http.Handler, headers map[string]configopaque.String) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
Expand Down
73 changes: 73 additions & 0 deletions config/confighttp/confighttp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
"go.uber.org/zap"

"go.opentelemetry.io/collector/client"
Expand Down Expand Up @@ -1526,3 +1528,74 @@ func TestDefaultHTTPServerSettings(t *testing.T) {
assert.Equal(t, time.Duration(0), httpServerSettings.ReadTimeout)
assert.Equal(t, 1*time.Minute, httpServerSettings.ReadHeaderTimeout)
}

func TestServerTelemetry(t *testing.T) {
hss := ServerConfig{Endpoint: "localhost:0"}
exporter := tracetest.NewInMemoryExporter()
telemetry := componenttest.NewNopTelemetrySettings()
telemetry.TracerProvider = trace.NewTracerProvider(trace.WithSyncer(exporter))

nopHandler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})
muxHandler := http.NewServeMux()
muxHandler.Handle("/a/{pattern}", nopHandler)
sendRequest := func(t *testing.T, url string, expectedCode int) {
t.Helper()
resp, err := http.Get(url) //nolint:gosec
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
assert.Equal(t, expectedCode, resp.StatusCode)
}

t.Run("plain_handler", func(t *testing.T) {
withServer(t, hss, telemetry, nopHandler, func(_ *http.Server, url string) {
sendRequest(t, url+"/plain", http.StatusOK)
sendRequest(t, url+"/", http.StatusOK)
})
spans := exporter.GetSpans()
assert.Len(t, spans, 2)
assert.Equal(t, "/plain", spans[0].Name)
assert.Equal(t, "/", spans[1].Name)
exporter.Reset()
})
t.Run("mux", func(t *testing.T) {
withServer(t, hss, telemetry, muxHandler, func(_ *http.Server, url string) {
sendRequest(t, url+"/a/bc123", http.StatusOK)
sendRequest(t, url+"/", http.StatusNotFound)
})
spans := exporter.GetSpans()
assert.Len(t, spans, 2)
assert.Equal(t, "GET /a/{pattern}", spans[0].Name)
assert.Equal(t, "GET unknown route", spans[1].Name)
exporter.Reset()
})
}

func withServer(
t *testing.T,
cfg ServerConfig,
set component.TelemetrySettings,
h http.Handler,
f func(srv *http.Server, url string),
) {
srv, err := cfg.ToServer(context.Background(), componenttest.NewNopHost(), set, h)
require.NoError(t, err)
defer func() {
assert.NoError(t, srv.Close())
}()

lis, err := cfg.ToListener(context.Background())
require.NoError(t, err)
done := make(chan struct{})
go func() {
defer close(done)
_ = srv.Serve(lis)
}()
defer func() {
err := srv.Shutdown(context.Background())
assert.NoError(t, err)
<-done
}()

u := &url.URL{Scheme: "http", Host: lis.Addr().String()}
f(srv, u.String())
}
2 changes: 1 addition & 1 deletion config/confighttp/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ require (
go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest v0.121.0
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0
go.opentelemetry.io/otel v1.35.0
go.opentelemetry.io/otel/sdk v1.35.0
go.uber.org/goleak v1.3.0
go.uber.org/zap v1.27.0
golang.org/x/net v0.36.0
Expand All @@ -37,7 +38,6 @@ require (
go.opentelemetry.io/collector/extension v1.27.0 // indirect
go.opentelemetry.io/collector/pdata v1.27.0 // indirect
go.opentelemetry.io/otel/metric v1.35.0 // indirect
go.opentelemetry.io/otel/sdk v1.35.0 // indirect
go.opentelemetry.io/otel/sdk/metric v1.35.0 // indirect
go.opentelemetry.io/otel/trace v1.35.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
Expand Down
Loading