Tracing: Improve HTTP request/middleware spans and standalone apiserver (#85715)

Fixes so that auth middleware trace/span doesn't wrap the next handlers.
Allow tracing service name to be overridden in standalone apiserver.
Change k8s api tracing operation name to KubernetesAPI from 
grafana-apiserver (which is the service name)
This commit is contained in:
Marcus Efraimsson
2024-04-11 13:28:23 +02:00
committed by GitHub
parent 877aaf87d2
commit 3e385763c5
3 changed files with 22 additions and 12 deletions

View File

@@ -84,11 +84,11 @@ func CopyWithReqContext(ctx context.Context) context.Context {
// Middleware provides a middleware to initialize the request context.
func (h *ContextHandler) Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, span := h.tracer.Start(r.Context(), "Auth - Middleware")
defer span.End() // this will span to next handlers as well
ctx := r.Context()
_, span := h.tracer.Start(ctx, "Auth - Middleware")
reqContext := &contextmodel.ReqContext{
Context: web.FromContext(ctx), // Extract web context from context (no knowledge of the trace)
Context: web.FromContext(ctx),
SignedInUser: &user.SignedInUser{
Permissions: map[int64]map[string][]string{},
},
@@ -106,12 +106,13 @@ func (h *ContextHandler) Middleware(next http.Handler) http.Handler {
// This modifies both r and reqContext.Req since they point to the same value
*reqContext.Req = *reqContext.Req.WithContext(ctx)
traceID := tracing.TraceIDFromContext(reqContext.Req.Context(), false)
ctx = trace.ContextWithSpan(reqContext.Req.Context(), span)
traceID := tracing.TraceIDFromContext(ctx, false)
if traceID != "" {
reqContext.Logger = reqContext.Logger.New("traceID", traceID)
}
identity, err := h.authnService.Authenticate(reqContext.Req.Context(), &authn.Request{HTTPRequest: reqContext.Req, Resp: reqContext.Resp})
identity, err := h.authnService.Authenticate(ctx, &authn.Request{HTTPRequest: reqContext.Req, Resp: reqContext.Resp})
if err != nil {
// Hack: set all errors on LookupTokenErr, so we can check it in auth middlewares
reqContext.LookupTokenErr = err
@@ -134,6 +135,9 @@ func (h *ContextHandler) Middleware(next http.Handler) http.Handler {
reqContext.Resp.Before(h.addIDHeaderEndOfRequestFunc(reqContext.SignedInUser))
}
// End the span to make next handlers not wrapped within middleware span
span.End()
next.ServeHTTP(w, r)
})
}