traefik/pkg/middlewares/tracing/entrypoint.go

63 lines
1.8 KiB
Go
Raw Normal View History

2018-01-10 16:48:04 +00:00
package tracing
import (
2018-11-14 09:18:03 +00:00
"context"
"errors"
2018-01-10 16:48:04 +00:00
"net/http"
2018-11-14 09:18:03 +00:00
"github.com/containous/alice"
2023-02-03 14:24:05 +00:00
"github.com/traefik/traefik/v3/pkg/middlewares"
"github.com/traefik/traefik/v3/pkg/tracing"
2024-01-08 08:10:06 +00:00
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
2018-01-10 16:48:04 +00:00
)
2018-11-14 09:18:03 +00:00
const (
entryPointTypeName = "TracingEntryPoint"
)
2024-01-08 08:10:06 +00:00
type entryPointTracing struct {
tracer *tracing.Tracer
2024-01-08 08:10:06 +00:00
entryPoint string
next http.Handler
}
// WrapEntryPointHandler Wraps tracing to alice.Constructor.
func WrapEntryPointHandler(ctx context.Context, tracer *tracing.Tracer, entryPointName string) alice.Constructor {
2024-01-08 08:10:06 +00:00
return func(next http.Handler) (http.Handler, error) {
if tracer == nil {
return nil, errors.New("unexpected nil tracer")
}
2024-01-08 08:10:06 +00:00
return newEntryPoint(ctx, tracer, entryPointName, next), nil
}
}
// newEntryPoint creates a new tracing middleware for incoming requests.
func newEntryPoint(ctx context.Context, tracer *tracing.Tracer, entryPointName string, next http.Handler) http.Handler {
2022-11-21 17:36:05 +00:00
middlewares.GetLogger(ctx, "tracing", entryPointTypeName).Debug().Msg("Creating middleware")
2018-11-14 09:18:03 +00:00
2024-01-08 08:10:06 +00:00
return &entryPointTracing{
2018-11-14 09:18:03 +00:00
entryPoint: entryPointName,
2024-01-08 08:10:06 +00:00
tracer: tracer,
2018-11-14 09:18:03 +00:00
next: next,
}
}
2024-01-08 08:10:06 +00:00
func (e *entryPointTracing) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
tracingCtx := tracing.ExtractCarrierIntoContext(req.Context(), req.Header)
tracingCtx, span := e.tracer.Start(tracingCtx, "EntryPoint", trace.WithSpanKind(trace.SpanKindServer))
defer span.End()
2018-01-10 16:48:04 +00:00
2024-01-08 08:10:06 +00:00
req = req.WithContext(tracingCtx)
2018-01-10 16:48:04 +00:00
2024-01-08 08:10:06 +00:00
span.SetAttributes(attribute.String("entry_point", e.entryPoint))
2018-01-10 16:48:04 +00:00
e.tracer.CaptureServerRequest(span, req)
2018-01-10 16:48:04 +00:00
recorder := newStatusCodeRecorder(rw, http.StatusOK)
2018-11-14 09:18:03 +00:00
e.next.ServeHTTP(recorder, req)
2018-01-10 16:48:04 +00:00
e.tracer.CaptureResponse(span, recorder.Header(), recorder.Status(), trace.SpanKindServer)
}