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

Support configurable error codes in contrib/net/http #2882

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 0 additions & 4 deletions contrib/internal/httptrace/httptrace.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ package httptrace

import (
"context"
"fmt"
"net/http"
"strconv"
"strings"
Expand Down Expand Up @@ -71,9 +70,6 @@ func FinishRequestSpan(s tracer.Span, status int, opts ...tracer.FinishOption) {
statusStr = strconv.Itoa(status)
}
s.SetTag(ext.HTTPCode, statusStr)
if status >= 500 && status < 600 {
s.SetTag(ext.Error, fmt.Errorf("%s: %s", statusStr, http.StatusText(status)))
}
s.Finish(opts...)
}

Expand Down
9 changes: 5 additions & 4 deletions contrib/net/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,11 @@ func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
copy(so, mux.cfg.spanOpts)
so = append(so, httptrace.HeaderTagsFromRequest(r, mux.cfg.headerTags))
TraceAndServe(mux.ServeMux, w, r, &ServeConfig{
Service: mux.cfg.serviceName,
Resource: resource,
SpanOpts: so,
Route: route,
Service: mux.cfg.serviceName,
Resource: resource,
SpanOpts: so,
Route: route,
IsStatusError: mux.cfg.isStatusError,
})
}

Expand Down
10 changes: 10 additions & 0 deletions contrib/net/http/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type config struct {
finishOpts []ddtrace.FinishOption
ignoreRequest func(*http.Request) bool
resourceNamer func(*http.Request) string
isStatusError func(int) bool
headerTags *internal.LockMap
}

Expand All @@ -50,6 +51,7 @@ func defaults(cfg *config) {
}
cfg.ignoreRequest = func(_ *http.Request) bool { return false }
cfg.resourceNamer = func(_ *http.Request) string { return "" }
cfg.isStatusError = func(status int) bool { return status >= 500 && status < 600 }
}

// WithIgnoreRequest holds the function to use for determining if the
Expand Down Expand Up @@ -118,6 +120,14 @@ func WithResourceNamer(namer func(req *http.Request) string) Option {
}
}

// WithStatusCheck sets a span to be an error if the passed function
// returns true for a given status code.
func WithStatusCheck(checker func(statusCode int) bool) Option {
return func(cfg *config) {
cfg.isStatusError = checker
}
}

// NoDebugStack prevents stack traces from being attached to spans finishing
// with an error. This is useful in situations where errors are frequent and
// performance is critical.
Expand Down
7 changes: 7 additions & 0 deletions contrib/net/http/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package http // import "gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http"
//go:generate sh -c "go run make_responsewriter.go | gofmt > trace_gen.go"

import (
"fmt"
"net/http"

"gopkg.in/DataDog/dd-trace-go.v1/contrib/internal/httptrace"
Expand Down Expand Up @@ -42,6 +43,9 @@ type ServeConfig struct {
// in as /user/123 we'll have {"id": "123"}). This field is optional and is used for monitoring
// by AppSec. It is only taken into account when AppSec is enabled.
RouteParams map[string]string
// IsStatusError returns whether or not the passed status code should be marked as
// an error
IsStatusError func(int) bool
// FinishOpts specifies any options to be used when finishing the request span.
FinishOpts []ddtrace.FinishOption
// SpanOpts specifies any options to be applied to the request starting span.
Expand All @@ -67,6 +71,9 @@ func TraceAndServe(h http.Handler, w http.ResponseWriter, r *http.Request, cfg *
span, ctx := httptrace.StartRequestSpan(r, opts...)
rw, ddrw := wrapResponseWriter(w)
defer func() {
if cfg.IsStatusError != nil && cfg.IsStatusError(ddrw.status) {
span.SetTag(ext.Error, fmt.Errorf("%d: %s", ddrw.status, http.StatusText(ddrw.status)))
}
httptrace.FinishRequestSpan(span, ddrw.status, cfg.FinishOpts...)
}()

Expand Down
24 changes: 24 additions & 0 deletions contrib/net/http/trace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,29 @@ func TestTraceAndServe(t *testing.T) {
assert.Equal("200", spans[0].Tag(ext.HTTPCode))
})

t.Run("isStatusError", func(t *testing.T) {
mt := mocktracer.Start()
assert := assert.New(t)
defer mt.Stop()

handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
}
r, err := http.NewRequest("GET", "/", nil)
assert.NoError(err)
w := httptest.NewRecorder()
TraceAndServe(http.HandlerFunc(handler), w, r, &ServeConfig{
Service: "service",
Resource: "resource",
IsStatusError: func(i int) bool { return i >= 400 },
})

spans := mt.FinishedSpans()
assert.Len(spans, 1)
assert.Equal("400", spans[0].Tag(ext.HTTPCode))
assert.Equal("400: Bad Request", spans[0].Tag(ext.Error).(error).Error())
})

t.Run("empty", func(t *testing.T) {
mt := mocktracer.Start()
assert := assert.New(t)
Expand Down Expand Up @@ -319,6 +342,7 @@ func TestTraceAndServe(t *testing.T) {
assert.Equal("/path?<redacted>", span.Tag(ext.HTTPURL))
assert.Equal("200", span.Tag(ext.HTTPCode))
})

}

func TestTraceAndServeHost(t *testing.T) {
Expand Down