Skip to content

otelhttp: Record metrics on timed out requests #4634

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

Closed
Closed
Show file tree
Hide file tree
Changes from 7 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
39 changes: 36 additions & 3 deletions instrumentation/net/http/otelhttp/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"

import (
"context"
"io"
"net/http"
"time"
Expand Down Expand Up @@ -232,13 +233,14 @@ func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http
attributes = append(attributes, semconv.HTTPStatusCode(rww.statusCode))
}
o := metric.WithAttributes(attributes...)
h.requestBytesCounter.Add(ctx, bw.read, o)
h.responseBytesCounter.Add(ctx, rww.written, o)
ctxWithoutCancel := withoutCancel(ctx)
h.requestBytesCounter.Add(ctxWithoutCancel, bw.read, o)
h.responseBytesCounter.Add(ctxWithoutCancel, rww.written, o)

// Use floating point division here for higher precision (instead of Millisecond method).
elapsedTime := float64(time.Since(requestStartTime)) / float64(time.Millisecond)

h.serverLatencyMeasure.Record(ctx, elapsedTime, o)
h.serverLatencyMeasure.Record(ctxWithoutCancel, elapsedTime, o)
}

func setAfterServeAttributes(span trace.Span, read, wrote int64, statusCode int, rerr, werr error) {
Expand Down Expand Up @@ -281,3 +283,34 @@ func WithRouteTag(route string, h http.Handler) http.Handler {
h.ServeHTTP(w, r)
})
}

func withoutCancel(parent context.Context) context.Context {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a note, including a link, about where this is copied from.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy to do this, but it sounding like the better option might be the SDK native one (so long as we would not need the flexibility of calling those .Add and .Record methods in such a way where we want different behavior based on the context's cancelled state)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added, in case we opt to merge this PR. Thanks @MrAlias!

if parent == nil {
panic("cannot create context from nil parent")
}
return withoutCancelCtx{parent}
}

type withoutCancelCtx struct {
c context.Context
}

func (withoutCancelCtx) Deadline() (deadline time.Time, ok bool) {
return
}

func (withoutCancelCtx) Done() <-chan struct{} {
return nil
}

func (withoutCancelCtx) Err() error {
return nil
}

func (w withoutCancelCtx) Value(key any) any {
return w.c.Value(key)
}

func (w withoutCancelCtx) String() string {
return "withoutCancel"
}
63 changes: 63 additions & 0 deletions instrumentation/net/http/otelhttp/test/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ import (
"context"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -539,3 +541,64 @@ func TestWithRouteTag(t *testing.T) {
}
}
}

func TestCtxWithoutCancel(t *testing.T) {
reader := metric.NewManualReader()
meterProvider := metric.NewMeterProvider(metric.WithReader(reader))

otelHandler := otelhttp.NewHandler(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("hello world"))
require.NoError(t, err)
l, _ := otelhttp.LabelerFromContext(r.Context())
l.Add(attribute.String("foo", "bar"))
}), "test_handler", otelhttp.WithMeterProvider(meterProvider))

ctx, cancel := context.WithCancel(context.Background())
cancel()

l, err := net.Listen("tcp", "localhost:12345")
require.NoError(t, err)

srv := &http.Server{
BaseContext: func(_ net.Listener) context.Context { return ctx },
ReadTimeout: time.Second,
WriteTimeout: 10 * time.Second,
Handler: otelHandler,
}

go func() {
// When Shutdown is called, Serve immediately returns ErrServerClosed.
assert.Equal(t, http.ErrServerClosed, srv.Serve(l))
}()

t.Cleanup(func() {
assert.NoError(t, srv.Shutdown(context.Background()))
})

req, err := http.NewRequest("GET", "http://"+l.Addr().String(), nil)
require.NoError(t, err)

rr := httptest.NewRecorder()
otelHandler.ServeHTTP(rr, req)

// Check that some metrics were recorded.
rm := metricdata.ResourceMetrics{}
err = reader.Collect(ctx, &rm)
require.NoError(t, err)
require.Len(t, rm.ScopeMetrics, 1)

port, err := strconv.Atoi(req.URL.Port())
require.NoError(t, err)

attrs := attribute.NewSet(
semconv.NetHostName(req.URL.Hostname()),
semconv.NetHostPort(port),
semconv.HTTPSchemeHTTP,
semconv.HTTPFlavorKey.String(fmt.Sprintf("1.%d", req.ProtoMinor)),
semconv.HTTPMethod("GET"),
attribute.String("foo", "bar"),
semconv.HTTPStatusCode(200),
)
assertScopeMetrics(t, rm.ScopeMetrics[0], attrs)
}