2018-01-10 16:48:04 +00:00
|
|
|
package tracing
|
|
|
|
|
|
|
|
import (
|
2018-11-14 09:18:03 +00:00
|
|
|
"context"
|
2018-01-10 16:48:04 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/opentracing/opentracing-go/ext"
|
2023-02-03 14:24:05 +00:00
|
|
|
"github.com/traefik/traefik/v3/pkg/logs"
|
|
|
|
"github.com/traefik/traefik/v3/pkg/middlewares"
|
|
|
|
"github.com/traefik/traefik/v3/pkg/tracing"
|
2018-11-14 09:18:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
forwarderTypeName = "TracingForwarder"
|
2018-01-10 16:48:04 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type forwarderMiddleware struct {
|
2018-11-14 09:18:03 +00:00
|
|
|
router string
|
|
|
|
service string
|
|
|
|
next http.Handler
|
2018-01-10 16:48:04 +00:00
|
|
|
}
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
// NewForwarder creates a new forwarder middleware that traces the outgoing request.
|
|
|
|
func NewForwarder(ctx context.Context, router, service string, next http.Handler) http.Handler {
|
2022-11-21 17:36:05 +00:00
|
|
|
middlewares.GetLogger(ctx, "tracing", forwarderTypeName).
|
|
|
|
Debug().Str(logs.ServiceName, service).Msg("Added outgoing tracing middleware")
|
2018-11-14 09:18:03 +00:00
|
|
|
|
2018-01-10 16:48:04 +00:00
|
|
|
return &forwarderMiddleware{
|
2018-11-14 09:18:03 +00:00
|
|
|
router: router,
|
|
|
|
service: service,
|
|
|
|
next: next,
|
2018-01-10 16:48:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
func (f *forwarderMiddleware) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|
|
|
tr, err := tracing.FromContext(req.Context())
|
|
|
|
if err != nil {
|
|
|
|
f.next.ServeHTTP(rw, req)
|
|
|
|
return
|
|
|
|
}
|
2018-01-10 16:48:04 +00:00
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
opParts := []string{f.service, f.router}
|
|
|
|
span, req, finish := tr.StartSpanf(req, ext.SpanKindRPCClientEnum, "forward", opParts, "/")
|
|
|
|
defer finish()
|
2018-01-10 16:48:04 +00:00
|
|
|
|
2022-02-10 15:00:09 +00:00
|
|
|
span.SetTag("traefik.service.name", f.service)
|
|
|
|
span.SetTag("traefik.router.name", f.router)
|
2018-11-14 09:18:03 +00:00
|
|
|
ext.HTTPMethod.Set(span, req.Method)
|
|
|
|
ext.HTTPUrl.Set(span, req.URL.String())
|
|
|
|
span.SetTag("http.host", req.Host)
|
2018-01-10 16:48:04 +00:00
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
tracing.InjectRequestHeaders(req)
|
2018-01-10 16:48:04 +00:00
|
|
|
|
2022-11-16 10:38:07 +00:00
|
|
|
recorder := newStatusCodeRecorder(rw, 200)
|
2018-07-31 22:16:03 +00:00
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
f.next.ServeHTTP(recorder, req)
|
2018-07-31 22:16:03 +00:00
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
tracing.LogResponseCode(span, recorder.Status())
|
2018-07-31 22:16:03 +00:00
|
|
|
}
|