Skip to content

Commit

Permalink
module/apmgrpc: set span destination context
Browse files Browse the repository at this point in the history
Update the apmgrpc client interceptor to record
span destination address/port and context for
service maps.
  • Loading branch information
axw committed Dec 16, 2020
1 parent 0a73d5b commit e36f271
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
15 changes: 15 additions & 0 deletions module/apmgrpc/client.go
Expand Up @@ -20,10 +20,13 @@
package apmgrpc // import "go.elastic.co/apm/module/apmgrpc"

import (
"net"

"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"

"go.elastic.co/apm"
"go.elastic.co/apm/module/apmhttp"
Expand All @@ -48,13 +51,25 @@ func NewUnaryClientInterceptor(o ...ClientOption) grpc.UnaryClientInterceptor {
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
var peer peer.Peer // maybe set after call if span != nil
span, ctx := startSpan(ctx, method)
if span != nil {
defer span.End()
opts = append(opts, grpc.Peer(&peer))
}
err := invoker(ctx, method, req, resp, cc, opts...)
if span != nil {
setSpanOutcome(span, err)
if peer.Addr != nil {
if tcpAddr, ok := peer.Addr.(*net.TCPAddr); ok {
span.Context.SetDestinationAddress(tcpAddr.IP.String(), tcpAddr.Port)
}
addrString := peer.Addr.String()
span.Context.SetDestinationService(apm.DestinationServiceSpanContext{
Name: addrString,
Resource: addrString,
})
}
}
return err
}
Expand Down
11 changes: 11 additions & 0 deletions module/apmgrpc/client_test.go
Expand Up @@ -20,6 +20,7 @@
package apmgrpc_test

import (
"net"
"os"
"testing"

Expand Down Expand Up @@ -56,6 +57,7 @@ func testClientSpan(t *testing.T, traceparentHeaders ...string) {
defer serverTracer.Close()
s, _, addr := newServer(t, serverTracer)
defer s.GracefulStop()
tcpAddr := addr.(*net.TCPAddr)

conn, client := newClient(t, addr)
defer conn.Close()
Expand Down Expand Up @@ -84,6 +86,15 @@ func testClientSpan(t *testing.T, traceparentHeaders ...string) {
assert.Equal(t, "/helloworld.Greeter/SayHello", clientSpans[0].Name)
assert.Equal(t, "external", clientSpans[0].Type)
assert.Equal(t, "grpc", clientSpans[0].Subtype)
assert.Equal(t, &model.DestinationSpanContext{
Address: tcpAddr.IP.String(),
Port: tcpAddr.Port,
Service: &model.DestinationServiceSpanContext{
Type: "external",
Name: tcpAddr.String(),
Resource: tcpAddr.String(),
},
}, clientSpans[0].Context.Destination)

serverTracer.Flush(nil)
serverTransactions := serverTransport.Payloads().Transactions
Expand Down

0 comments on commit e36f271

Please sign in to comment.