Skip to content
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

[query] Use OTEL's helpers for http server #6121

Merged
merged 23 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from 20 commits
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
18 changes: 12 additions & 6 deletions cmd/query/app/apiv3/http_gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,18 +60,16 @@ func (h *HTTPGateway) RegisterRoutes(router *mux.Router) {

// addRoute adds a new endpoint to the router with given path and handler function.
// This code is mostly copied from ../http_handler.
func (h *HTTPGateway) addRoute(
func (*HTTPGateway) addRoute(
router *mux.Router,
f func(http.ResponseWriter, *http.Request),
route string,
_ ...any, /* args */
) *mux.Route {
var handler http.Handler = http.HandlerFunc(f)
traceMiddleware := otelhttp.NewHandler(
otelhttp.WithRouteTag(route, handler),
route,
otelhttp.WithTracerProvider(h.Tracer))
return router.HandleFunc(route, traceMiddleware.ServeHTTP)
handler = otelhttp.WithRouteTag(route, handler)
handler = spanNameHandler(route, handler)
return router.HandleFunc(route, handler.ServeHTTP)
}

// tryHandleError checks if the passed error is not nil and handles it by writing
Expand Down Expand Up @@ -242,3 +240,11 @@ func (h *HTTPGateway) getOperations(w http.ResponseWriter, r *http.Request) {
}
h.marshalResponse(&api_v3.GetOperationsResponse{Operations: apiOperations}, w)
}

func spanNameHandler(spanName string, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
span := trace.SpanFromContext(r.Context())
span.SetName(spanName)
handler.ServeHTTP(w, r)
})
}
17 changes: 12 additions & 5 deletions cmd/query/app/http_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,10 @@ func (aH *APIHandler) handleFunc(
) *mux.Route {
route := aH.formatRoute(routeFmt, args...)
var handler http.Handler = http.HandlerFunc(f)
traceMiddleware := otelhttp.NewHandler(
otelhttp.WithRouteTag(route, traceResponseHandler(handler)),
route,
otelhttp.WithTracerProvider(aH.tracer))
return router.HandleFunc(route, traceMiddleware.ServeHTTP)
handler = traceResponseHandler(handler)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO traceResponseHandler should be moved to initRouter, it can apply to the whole server, not just API handler

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yurishkuro do we want to do that in this PR or a different one?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably another, already too many changes here to keep track of

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

handler = otelhttp.WithRouteTag(route, handler)
handler = spanNameHandler(route, handler)
return router.HandleFunc(route, handler.ServeHTTP)
}

func (aH *APIHandler) formatRoute(route string, args ...any) string {
Expand Down Expand Up @@ -532,3 +531,11 @@ func traceResponseHandler(handler http.Handler) http.Handler {
handler.ServeHTTP(w, r)
})
}

func spanNameHandler(spanName string, handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
span := trace.SpanFromContext(r.Context())
span.SetName(spanName)
handler.ServeHTTP(w, r)
})
}
3 changes: 0 additions & 3 deletions cmd/query/app/http_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,6 @@ func TestGetTrace(t *testing.T) {
require.NoError(t, err)
assert.Empty(t, response.Errors)

assert.Len(t, exporter.GetSpans(), 1, "HTTP request was traced and span reported")
assert.Equal(t, "/api/traces/{traceID}", exporter.GetSpans()[0].Name)
yurishkuro marked this conversation as resolved.
Show resolved Hide resolved
yurishkuro marked this conversation as resolved.
Show resolved Hide resolved

traces := extractTraces(t, &response)
assert.Len(t, traces[0].Spans, 2)
assert.Len(t, traces[0].Spans[1].References, testCase.numSpanRefs)
Expand Down
58 changes: 51 additions & 7 deletions cmd/query/app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,12 @@
return nil, err
}
registerGRPCHandlers(grpcServer, querySvc, metricsQuerySvc, telset)

httpServer, err := createHTTPServer(ctx, querySvc, metricsQuerySvc, options, tm, telset)
var httpServer *httpServer
if !separatePorts {
httpServer, err = createHTTPServerLegacy(ctx, querySvc, metricsQuerySvc, options, tm, telset)
} else {
httpServer, err = createHTTPServerOTEL(ctx, querySvc, metricsQuerySvc, options, tm, telset)
}
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -243,7 +247,7 @@
return handler, staticHandlerCloser
}

func createHTTPServer(
func createHTTPServerLegacy(
ctx context.Context,
querySvc *querysvc.QueryService,
metricsQuerySvc querysvc.MetricsQueryService,
Expand All @@ -254,18 +258,58 @@
handler, staticHandlerCloser := initRouter(querySvc, metricsQuerySvc, queryOpts, tm, telset)
handler = responseHeadersHandler(handler, queryOpts.HTTP.ResponseHeaders)
handler = handlers.CompressHandler(handler)
yurishkuro marked this conversation as resolved.
Show resolved Hide resolved
recoveryHandler := recoveryhandler.NewRecoveryHandler(telset.Logger, true)

handler = recoveryhandler.NewRecoveryHandler(telset.Logger, true)(handler)
errorLog, _ := zap.NewStdLogAt(telset.Logger, zapcore.ErrorLevel)
server := &httpServer{
Server: &http.Server{
Handler: recoveryHandler(handler),
Handler: handler,
ErrorLog: errorLog,
ReadHeaderTimeout: 2 * time.Second,
},
staticHandlerCloser: staticHandlerCloser,
}

if queryOpts.HTTP.TLSSetting != nil {
tlsCfg, err := queryOpts.HTTP.TLSSetting.LoadTLSConfig(ctx) // This checks if the certificates are correctly provided
if err != nil {
return nil, errors.Join(err, staticHandlerCloser.Close())
}
server.TLSConfig = tlsCfg

Check warning on line 277 in cmd/query/app/server.go

View check run for this annotation

Codecov / codecov/patch

cmd/query/app/server.go#L273-L277

Added lines #L273 - L277 were not covered by tests
}
return server, nil
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

misleading diff display by GH - this part above did not actually change


func createHTTPServerOTEL(
ctx context.Context,
querySvc *querysvc.QueryService,
metricsQuerySvc querysvc.MetricsQueryService,
queryOpts *QueryOptions,
tm *tenancy.Manager,
telset telemetery.Setting,
) (*httpServer, error) {
handler, staticHandlerCloser := initRouter(querySvc, metricsQuerySvc, queryOpts, tm, telset)
handler = recoveryhandler.NewRecoveryHandler(telset.Logger, true)(handler)
hs, err := queryOpts.HTTP.ToServer(
ctx,
telset.Host,
component.TelemetrySettings{
Logger: telset.Logger,
TracerProvider: telset.TracerProvider,
LeveledMeterProvider: func(_ configtelemetry.Level) metric.MeterProvider {
return noop.NewMeterProvider()
},
},
handler,
)
if err != nil {
return nil, errors.Join(err, staticHandlerCloser.Close())
}

Check warning on line 306 in cmd/query/app/server.go

View check run for this annotation

Codecov / codecov/patch

cmd/query/app/server.go#L305-L306

Added lines #L305 - L306 were not covered by tests
server := &httpServer{
Server: hs,
staticHandlerCloser: staticHandlerCloser,
}

// TODO why doesn't OTEL helper do that already?
if queryOpts.HTTP.TLSSetting != nil {
tlsCfg, err := queryOpts.HTTP.TLSSetting.LoadTLSConfig(ctx) // This checks if the certificates are correctly provided
if err != nil {
Expand Down Expand Up @@ -293,7 +337,7 @@
return nil, err
}

s.httpConn, err = net.Listen("tcp", s.queryOptions.HTTP.Endpoint)
s.httpConn, err = s.queryOptions.HTTP.ToListener(ctx)
if err != nil {
return nil, err
}
Expand Down
22 changes: 10 additions & 12 deletions cmd/query/app/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -881,32 +881,30 @@ func TestServerHTTP_TracesRequest(t *testing.T) {
expectedTrace string
}{
{
name: "different ports",
name: "different ports (OTEL implementation)",
httpEndpoint: ":8080",
grpcEndpoint: ":8081",
queryString: "/api/traces/123456aBC",
expectedTrace: "/api/traces/{traceID}",
},
{
name: "different ports for v3 api",
name: "different ports (OTEL implementation) for v3 api",
httpEndpoint: ":8080",
grpcEndpoint: ":8081",
queryString: "/api/v3/traces/123456aBC",
expectedTrace: "/api/v3/traces/{trace_id}",
},
{
name: "same port",
httpEndpoint: ":8080",
grpcEndpoint: ":8080",
queryString: "/api/traces/123456aBC",
expectedTrace: "/api/traces/{traceID}",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are we loosing this trace? That was my point of adding the test to main first - it should not change in this PR.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yurishkuro We're losing this trace at the moment because removed the call to otelhttp.NewHandler which was taking a tracer. If we don't remove that call then we run into the issue of double instrumentation that we were seeing earlier.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so how do we explain that? The OTEL helper is supposed to add tracing middleware, why is it not working?

Copy link
Collaborator Author

@mahadzaryab1 mahadzaryab1 Oct 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yurishkuro The OTEL helper does add tracing. However, when the ports are the same, we're not using the OTEL helper to initialize the server and are our falling back to our custom implementation. We were previously using otelhttp.NewHandler in http_handler.go and http_gateway.go which was previously rendering this trace. We removed it from there because then we were running into the case of double instrumentation when the ports were different and we were using the OTEL helpers.

Copy link
Collaborator Author

@mahadzaryab1 mahadzaryab1 Oct 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking more about this - is there a reason why we can't just use OTEL's helper to create the server even if the ports are the same? We can still use a different flow when we start the listener.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yurishkuro I was actually wondering why we can't just use the server created by ToServer for the legacy flow as well?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How would we co-locate http and grpc servers on the same port in that case? We could if the listener is still done separately by our code.

Copy link
Collaborator Author

@mahadzaryab1 mahadzaryab1 Oct 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yurishkuro The listener is initialized separately and it already has a check for separate ports (see https://github.com/jaegertracing/jaeger/blob/main/cmd/query/app/server.go#L289). So can we just simplify the logic of creating the server to always create it using ToServer and then we can handle the legacy behaviour inside ToListener.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

give it a try. Or just add tracing handler to Legacy function and we can merge this PR, then try the listener separately.

Copy link
Collaborator Author

@mahadzaryab1 mahadzaryab1 Oct 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yurishkuro I removed the bifurcation for the creation of the server and it looks to be working as expected which makes sense. We can simply rely on OTEL's helpers to create the server. We only need special handling if the ports are the same (and that handling exists already in initListener). I'll do the same for the GRPC server in a follow-up PR.

name: "same port (legacy implementation) [no tracing]",
httpEndpoint: ":8080",
grpcEndpoint: ":8080",
queryString: "/api/traces/123456aBC",
},
{
name: "same port for v3 api",
httpEndpoint: ":8080",
grpcEndpoint: ":8080",
queryString: "/api/v3/traces/123456aBC",
expectedTrace: "/api/v3/traces/{trace_id}",
name: "same port (legacy implementation) for v3 api [no tracing]",
httpEndpoint: ":8080",
grpcEndpoint: ":8080",
queryString: "/api/v3/traces/123456aBC",
},
}

Expand Down
Loading