traefik/pkg/middlewares/tracing/forwarder.go

59 lines
1.4 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"
2018-01-10 16:48:04 +00:00
"net/http"
2019-03-15 08:42:03 +00:00
"github.com/containous/traefik/pkg/middlewares"
"github.com/containous/traefik/pkg/tracing"
2018-01-10 16:48:04 +00:00
"github.com/opentracing/opentracing-go/ext"
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 {
middlewares.GetLogger(ctx, "tracing", forwarderTypeName).
Debugf("Added outgoing tracing middleware %s", service)
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
2018-11-14 09:18:03 +00:00
span.SetTag("service.name", f.service)
span.SetTag("router.name", f.router)
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
2018-11-14 09:18:03 +00:00
recorder := newStatusCodeRecoder(rw, 200)
2018-11-14 09:18:03 +00:00
f.next.ServeHTTP(recorder, req)
2018-11-14 09:18:03 +00:00
tracing.LogResponseCode(span, recorder.Status())
}