-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathsegment.go
123 lines (106 loc) Β· 2.4 KB
/
segment.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package xray
import (
"context"
"net"
"github.com/golang/protobuf/proto"
"goa.design/goa/grpc/middleware"
"goa.design/goa/middleware/xray"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
// GRPCSegment represents an AWS X-Ray segment document for gRPC services.
type GRPCSegment struct {
*xray.Segment
}
// RecordRequest traces a request.
//
// It sets Http.Request & Namespace (ex: "remote")
func (s *GRPCSegment) RecordRequest(ctx context.Context, method string, req interface{}, namespace string) {
s.Lock()
defer s.Unlock()
if s.HTTP == nil {
s.HTTP = &xray.HTTP{}
}
s.Namespace = namespace
s.HTTP.Request = requestData(ctx, method, req)
}
// RecordResponse traces a response.
func (s *GRPCSegment) RecordResponse(resp interface{}) {
s.Lock()
defer s.Unlock()
if s.HTTP == nil {
s.HTTP = &xray.HTTP{}
}
s.HTTP.Response = &xray.Response{
Status: int(codes.OK),
ContentLength: messageLength(resp),
}
}
// RecordError sets Throttle, Fault, Error, and HTTP.Response.
func (s *GRPCSegment) RecordError(err error) {
s.Segment.RecordError(err)
s.Lock()
defer s.Unlock()
if s.HTTP == nil {
s.HTTP = &xray.HTTP{}
}
var (
code codes.Code
length int64
)
{
st, ok := status.FromError(err)
if ok {
code = st.Code()
length = messageLength(st.Proto())
} else {
code = codes.Unknown
}
}
s.HTTP.Response = &xray.Response{
Status: int(code),
ContentLength: length,
}
switch code {
case codes.InvalidArgument, codes.NotFound,
codes.AlreadyExists, codes.PermissionDenied,
codes.Unimplemented, codes.Unauthenticated:
s.Fault = true
default:
s.Error = true
}
}
// requestData creates a Request from a http.Request.
func requestData(ctx context.Context, method string, req interface{}) *xray.Request {
var agent string
{
md, ok := metadata.FromIncomingContext(ctx)
if ok {
agent = middleware.MetadataValue(md, "user-agent")
}
}
var ip string
{
if p, ok := peer.FromContext(ctx); ok {
ip, _, _ = net.SplitHostPort(p.Addr.String())
}
}
return &xray.Request{
Method: "GRPC",
URL: method,
UserAgent: agent,
ClientIP: ip,
ContentLength: messageLength(req),
}
}
func messageLength(msg interface{}) int64 {
var length int64
{
if m, ok := msg.(proto.Message); ok {
length = int64(proto.Size(m))
}
}
return length
}