-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterceptor.go
More file actions
214 lines (194 loc) · 4.77 KB
/
interceptor.go
File metadata and controls
214 lines (194 loc) · 4.77 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package rpcz
import (
"context"
"fmt"
"math/rand/v2"
"net"
"sync"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
)
var (
// SamplingRate is the chance it samples the message.
SamplingRate = 1.0
RetainRPCsPerMethod = 10
RecordMetadata = true
)
var (
ClientOptions = []grpc.DialOption{
grpc.WithChainUnaryInterceptor(UnaryClientInterceptor),
grpc.WithChainStreamInterceptor(StreamClientInterceptor),
}
ServerOptions = []grpc.ServerOption{
grpc.ChainUnaryInterceptor(UnaryServerInterceptor),
grpc.ChainStreamInterceptor(StreamServerInterceptor),
}
)
var (
mtx sync.Mutex
perMethod = map[string]*callForMethod{}
)
func sampleCall(method string) bool {
if SamplingRate >= 1.0 {
return true
} else if SamplingRate <= 0.0 {
return false
}
return rand.Float64() < SamplingRate
}
type callForMethod struct {
calls []*capturedCall
// ptr points at where the next call the circular buffer will be written.
ptr int
}
// Callers should hold mtx.
func (cfm *callForMethod) add(c *capturedCall) {
cfm.calls[cfm.ptr] = c
cfm.ptr = (cfm.ptr + 1) % RetainRPCsPerMethod
}
type capturedCall struct {
inbound bool
statusCode codes.Code
statusMessage string
start time.Time
deadline time.Duration
duration time.Duration
peer net.Addr
metadata metadata.MD
messageBuffer
}
type capturedMessage struct {
stamp time.Time
data []byte
messageType protoreflect.MessageDescriptor
inbound bool
}
func (c *capturedCall) Start(ctx context.Context, md metadata.MD, req interface{}) {
c.start = time.Now()
if dl, ok := ctx.Deadline(); ok {
c.deadline = dl.Sub(c.start)
}
c.metadata = md
if req != nil {
c.recordMessageLocked(req, c.inbound)
}
}
func (c *capturedCall) Record(method string) {
if c.inbound {
method = "recv: " + method
} else {
method = "sent: " + method
}
mtx.Lock()
defer mtx.Unlock()
cfm, ok := perMethod[method]
if !ok {
cfm = &callForMethod{
calls: make([]*capturedCall, RetainRPCsPerMethod),
}
perMethod[method] = cfm
}
cfm.add(c)
}
func (c *capturedCall) RecordMessage(msg interface{}, inbound bool) {
mtx.Lock()
defer mtx.Unlock()
c.recordMessageLocked(msg, inbound)
}
func (c *capturedCall) recordMessageLocked(msg interface{}, inbound bool) {
if c.huge {
c.messageCount++
return
}
if c.messageCount >= 64 {
c.huge = true
c.messageCount++
return
}
cm := capturedMessage{
stamp: time.Now(),
inbound: inbound,
}
if pm, ok := msg.(proto.Message); ok {
b, err := proto.Marshal(pm)
if err != nil {
cm.data = []byte("[Failed to encode protobuf: " + err.Error() + "]")
} else {
cm.data = b
cm.messageType = pm.ProtoReflect().Descriptor()
}
} else if str, ok := msg.(fmt.Stringer); ok {
cm.data = []byte(str.String())
} else {
cm.data = fmt.Append(nil, msg)
}
c.messageBuffer.addMessage(cm)
}
func (c *capturedCall) SetPeer(peer net.Addr) {
mtx.Lock()
defer mtx.Unlock()
c.peer = peer
}
func (c *capturedCall) Complete(err error, peer net.Addr, addReply bool, reply interface{}) {
mtx.Lock()
defer mtx.Unlock()
if addReply {
c.recordMessageLocked(reply, !c.inbound)
}
c.duration = time.Now().Sub(c.start)
st := status.Convert(err)
c.statusCode = st.Code()
c.statusMessage = st.Message()
if peer != nil {
c.peer = peer
}
}
func UnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
if !sampleCall(method) {
return invoker(ctx, method, req, reply, cc, opts...)
}
c := &capturedCall{}
c.Start(ctx, metadataFromOutgoingContext(ctx), req)
c.Record(method)
var p peer.Peer
opts = append(opts, grpc.Peer(&p))
err := invoker(ctx, method, req, reply, cc, opts...)
c.Complete(err, p.Addr, err == nil, reply)
return err
}
func UnaryServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if !sampleCall(info.FullMethod) {
return handler(ctx, req)
}
c := &capturedCall{}
c.inbound = true
if p, ok := peer.FromContext(ctx); ok {
c.peer = p.Addr
}
c.Start(ctx, metadataFromIncomingContext(ctx), req)
c.Record(info.FullMethod)
resp, err := handler(ctx, req)
c.Complete(err, nil, err == nil, resp)
return resp, err
}
func metadataFromIncomingContext(ctx context.Context) metadata.MD {
if md, ok := metadata.FromIncomingContext(ctx); ok {
return md
}
return nil
}
func metadataFromOutgoingContext(ctx context.Context) metadata.MD {
if !RecordMetadata {
return nil
}
if md, ok := metadata.FromOutgoingContext(ctx); ok {
return md
}
return nil
}