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

add httptrace option #788

Merged
merged 20 commits into from
Aug 5, 2020
Merged
Show file tree
Hide file tree
Changes from 8 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
16 changes: 15 additions & 1 deletion module/apmhttp/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ type roundTripper struct {
r http.RoundTripper
requestName RequestNameFunc
requestIgnorer RequestIgnorerFunc
traceRequests bool
}

// RoundTrip delegates to r.r, emitting a span if req's context
Expand Down Expand Up @@ -102,6 +103,10 @@ func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {

name := r.requestName(req)
span := tx.StartSpan(name, "external.http", apm.SpanFromContext(ctx))
var rt requestTracer
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
if r.traceRequests {
ctx = rt.start(ctx, span)
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
}
if !span.Dropped() {
traceContext = span.TraceContext()
ctx = apm.ContextWithSpan(ctx, span)
Expand All @@ -116,10 +121,17 @@ func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := r.r.RoundTrip(req)
if span != nil {
if err != nil {
if r.traceRequests {
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
rt.end()
}
span.End()
} else {
span.Context.SetHTTPStatusCode(resp.StatusCode)
resp.Body = &responseBody{span: span, body: resp.Body}
body := &responseBody{span: span, body: resp.Body}
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
if r.traceRequests {
body.requestTracer = &rt
}
resp.Body = body
}
}
return resp, err
Expand Down Expand Up @@ -158,6 +170,7 @@ func (r *roundTripper) CancelRequest(req *http.Request) {

type responseBody struct {
span *apm.Span
*requestTracer
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
body io.ReadCloser
}

Expand All @@ -178,6 +191,7 @@ func (b *responseBody) Read(p []byte) (n int, err error) {
}

func (b *responseBody) endSpan() {
b.requestTracer.end()
Copy link
Member

Choose a reason for hiding this comment

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

Can you please move this to just before the End() call below (inside the if block)?

addr := (*unsafe.Pointer)(unsafe.Pointer(&b.span))
if old := atomic.SwapPointer(addr, nil); old != nil {
(*apm.Span)(old).End()
Expand Down
18 changes: 18 additions & 0 deletions module/apmhttp/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
Expand Down Expand Up @@ -311,6 +312,23 @@ func TestWithClientRequestName(t *testing.T) {
assert.Equal(t, "http://test", span.Name)
}

func TestWithClientTrace(t *testing.T) {
server := httptest.NewServer(http.NotFoundHandler())
defer server.Close()

_, spans, _ := apmtest.WithTransaction(func(ctx context.Context) {
mustGET(ctx, server.URL, apmhttp.WithClientTrace())
})

require.Len(t, spans, 4)
assert.True(t, strings.HasPrefix(spans[0].Name, "Connect "),
fmt.Sprintf("want: Connect ... got: %s", spans[0].Name))
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
assert.Equal(t, "Request", spans[1].Name)
assert.Equal(t, "Response", spans[2].Name)
assert.Equal(t, model.IfaceMap{
model.IfaceMapItem{Key: "dns", Value: false}}, spans[0].Context.Tags)
}

func mustGET(ctx context.Context, url string, o ...apmhttp.ClientOption) (statusCode int, responseBody string) {
client := apmhttp.WrapClient(http.DefaultClient, o...)
resp, err := ctxhttp.Get(ctx, client, url)
Expand Down
106 changes: 106 additions & 0 deletions module/apmhttp/clienttrace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

package apmhttp

import (
"context"
"crypto/tls"
"fmt"
"net/http/httptrace"

"go.elastic.co/apm"
)

// WithClientTrace returns a ClientOption for
// tracing events within HTTP client requests.
func WithClientTrace() ClientOption {
return func(rt *roundTripper) {
rt.traceRequests = true
}
}

type requestTracer struct {
tx *apm.Transaction

DNS,
TLS,
Request,
Response *apm.Span

Connects map[[2]string]*apm.Span
}

func connectKey(network, addr string) [2]string {
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
func connectKey(network, addr string) [2]string {
type connectKey struct {
network string
addr string
}

(Then use that instead of [2]string everywhere)

return [2]string{network, addr}
}

func (r *requestTracer) start(ctx context.Context, parent *apm.Span) context.Context {
r.tx = apm.TransactionFromContext(ctx)
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
r.Connects = make(map[[2]string]*apm.Span)
return httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
DNSStart: func(i httptrace.DNSStartInfo) {
r.DNS = r.tx.StartSpan(fmt.Sprintf("DNS %s", i.Host), "http.dns", parent)
},

DNSDone: func(i httptrace.DNSDoneInfo) {
r.DNS.End()
},

ConnectStart: func(network, addr string) {
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
span := r.tx.StartSpan(fmt.Sprintf("Connect %s", addr), "http.connect", parent)
if r.DNS == nil {
span.Context.SetLabel("dns", false)
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
}
r.Connects[connectKey(network, addr)] = span
},

ConnectDone: func(network, addr string, err error) {
span := r.Connects[connectKey(network, addr)]
if err != nil {
span.Context.SetLabel("error", err.Error())
}
span.End()
},

TLSHandshakeStart: func() {
r.TLS = r.tx.StartSpan("TLS", "http.tls", parent)
},

TLSHandshakeDone: func(_ tls.ConnectionState, _ error) {
r.TLS.End()
axw marked this conversation as resolved.
Show resolved Hide resolved
},

WroteRequest: func(info httptrace.WroteRequestInfo) {
r.Request = r.tx.StartSpan("Request", "http.request", parent)
},

GotFirstResponseByte: func() {
r.Request.End()
r.Response = r.tx.StartSpan("Response", "http.response", parent)
},
})
}

func (r *requestTracer) end() {
if r == nil {
return
}
graphaelli marked this conversation as resolved.
Show resolved Hide resolved
if r.Response != nil {
r.Response.End()
}
}