-
Notifications
You must be signed in to change notification settings - Fork 438
/
stats_client.go
71 lines (62 loc) · 1.92 KB
/
stats_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
package grpc
import (
"context"
"net"
"google.golang.org/grpc/stats"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
// NewClientStatsHandler returns a gRPC client stats.Handler to trace RPC calls.
func NewClientStatsHandler(opts ...Option) stats.Handler {
cfg := new(config)
clientDefaults(cfg)
for _, fn := range opts {
fn(cfg)
}
return &clientStatsHandler{
cfg: cfg,
}
}
type clientStatsHandler struct{ cfg *config }
// TagRPC starts a new span for the initiated RPC request.
func (h *clientStatsHandler) TagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context {
spanOpts := append([]tracer.StartSpanOption{tracer.Tag(ext.SpanKind, ext.SpanKindClient)}, h.cfg.spanOpts...)
_, ctx = startSpanFromContext(
ctx,
rti.FullMethodName,
h.cfg.spanName,
h.cfg.serviceName,
spanOpts...,
)
ctx = injectSpanIntoContext(ctx)
return ctx
}
// HandleRPC processes the RPC ending event by finishing the span from the context.
func (h *clientStatsHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) {
span, ok := tracer.SpanFromContext(ctx)
if !ok {
return
}
switch rs := rs.(type) {
case *stats.OutHeader:
host, port, err := net.SplitHostPort(rs.RemoteAddr.String())
if err == nil {
if host != "" {
span.SetTag(ext.TargetHost, host)
}
span.SetTag(ext.TargetPort, port)
}
case *stats.End:
finishWithError(span, rs.Error, h.cfg)
}
}
// TagConn implements stats.Handler.
func (h *clientStatsHandler) TagConn(ctx context.Context, _ *stats.ConnTagInfo) context.Context {
return ctx
}
// HandleConn implements stats.Handler.
func (h *clientStatsHandler) HandleConn(_ context.Context, _ stats.ConnStats) {}