-
Notifications
You must be signed in to change notification settings - Fork 0
/
faultinjector.go
331 lines (288 loc) · 10.2 KB
/
faultinjector.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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package service
import (
"context"
"fmt"
"reflect"
"strings"
"sync"
faultinjectorpb "github.com/Netflix-skunkworks/grpc_fault/faultinjector"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/vm"
proto "github.com/golang/protobuf/proto" // nolint: staticcheck
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var (
defaultFaultInjectionServer = grpc.NewServer()
defaultInterceptor = NewInterceptor(context.TODO(), defaultFaultInjectionServer)
)
type FaultInjectorInterceptor interface {
UnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error
// Only the method is passed to the fault injection inspection
StreamClientInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error)
RegisterService(service grpc.ServiceDesc)
}
// GenerateInterceptor can be used to register an interceptor for a given grpc service. If a service is not registered
// the interceptor methods will error out
func RegisterInterceptor(service grpc.ServiceDesc) {
if !isDefaultEnabled() {
return
}
defaultInterceptor.RegisterService(service)
}
func UnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return defaultInterceptor.UnaryClientInterceptor(ctx, method, req, reply, cc, invoker, opts...)
}
func StreamClientInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
return defaultInterceptor.StreamClientInterceptor(ctx, desc, cc, method, streamer, opts...)
}
// NewInterceptor can be used to generate a single instance of the interceptor
func NewInterceptor(ctx context.Context, server *grpc.Server) FaultInjectorInterceptor {
fii := &faultInjectorInterceptor{}
fis := &faultInjectorServer{
fii: fii,
}
faultinjectorpb.RegisterFaultInjectorServer(server, fis)
return fii
}
type faultInjectorInterceptor struct {
// Map of services -> *serviceFaultInjectorInterceptor
services sync.Map
}
func (f *faultInjectorInterceptor) RegisterService(service grpc.ServiceDesc) {
sfii := &serviceFaultInjectorInterceptor{
service: service,
}
for idx := range service.Methods {
method := service.Methods[idx]
sfii.methods.Store(method.MethodName, &methodFaultInjectorInterceptor{})
}
f.services.LoadOrStore(service.ServiceName, sfii)
}
func (f *faultInjectorInterceptor) UnaryClientInterceptor(ctx context.Context, methodAndService string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
// Can either be:
// * /helloworld.Greeter/SayHello
// Or:
// * helloworld.Greeter/SayHello
splitMethod := strings.Split(strings.TrimLeft(methodAndService, "/"), "/")
serviceName := splitMethod[0]
methodName := splitMethod[1]
msg := rr{}
if val, ok := req.(proto.Message); ok {
msg.req = val
}
var messageChan chan rr
val, ok := f.services.Load(serviceName)
if ok {
sfii := val.(*serviceFaultInjectorInterceptor)
val, ok = sfii.methods.Load(methodName)
if ok {
mfii := val.(*methodFaultInjectorInterceptor)
mfii.lock.RLock()
program := mfii.program
messageChan = mfii.messageChan
mfii.lock.RUnlock()
if program != nil {
val, err := vm.Run(program, makeEnv(req))
if err != nil {
log.Ctx(ctx).WithLevel(zerolog.WarnLevel).Err(err).Msg("Could not run program")
} else if val != nil {
err, ok := val.(error)
if !ok {
log.Ctx(ctx).WithLevel(zerolog.WarnLevel).Str("type", fmt.Sprintf("%T", err)).Msg("Received unexpected type from program")
}
if status.Code(err) != codes.OK {
msg.err = err
select {
case messageChan <- msg:
default:
}
return err
}
}
}
}
}
err := invoker(ctx, methodAndService, req, reply, cc, opts...)
msg.err = err
if val, ok := reply.(proto.Message); ok {
msg.resp = val
}
select {
case messageChan <- msg:
default:
}
return err
}
func (f *faultInjectorInterceptor) StreamClientInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
log.Ctx(ctx).WithLevel(zerolog.InfoLevel).Str("method", method).Msg("Invoked stream client interceptor")
return streamer(ctx, desc, cc, method, opts...)
}
type serviceFaultInjectorInterceptor struct {
service grpc.ServiceDesc
// Map of method name -> methodFaultInjectorInterceptor
methods sync.Map
}
type methodFaultInjectorInterceptor struct {
lock sync.RWMutex
expression string
program *vm.Program
messageChan chan rr
}
type faultInjectorServer struct {
fii *faultInjectorInterceptor
}
func (f *faultInjectorServer) EnumerateServices(ctx context.Context, request *faultinjectorpb.EnumerateServicesRequest) (*faultinjectorpb.EnumerateServicesResponse, error) {
resp := faultinjectorpb.EnumerateServicesResponse{}
f.fii.services.Range(func(key, value interface{}) bool {
servicename := key.(string)
methods := []*faultinjectorpb.Method{}
sfii := value.(*serviceFaultInjectorInterceptor)
sfii.methods.Range(func(key, value interface{}) bool {
methodName := key.(string)
mfii := value.(*methodFaultInjectorInterceptor)
mfii.lock.RLock()
methods = append(methods, &faultinjectorpb.Method{
Name: methodName,
Expression: mfii.expression,
})
mfii.lock.RUnlock()
return true
})
resp.Services = append(resp.Services, &faultinjectorpb.Service{
Name: servicename,
Methods: methods,
})
return true
})
return &resp, nil
}
func (f *faultInjectorServer) RegisterFault(ctx context.Context, req *faultinjectorpb.RegisterFaultRequest) (*faultinjectorpb.RegisterFaultResponse, error) {
val, ok := f.fii.services.Load(req.Service)
if !ok {
return nil, status.Errorf(codes.NotFound, "service %s not found", req.Service)
}
service := val.(*serviceFaultInjectorInterceptor)
val, ok = service.methods.Load(req.Method)
if !ok {
return nil, status.Errorf(codes.NotFound, "method %s not found", req.Method)
}
mfii := val.(*methodFaultInjectorInterceptor)
// ht is the interface of the service.
ht := reflect.TypeOf(service.service.HandlerType).Elem()
reflectedMethod, ok := ht.MethodByName(req.Method)
if !ok {
return nil, status.Errorf(codes.NotFound, "method %s not found on reflection", req.Method)
}
fakeReq := reflect.New(reflectedMethod.Type.In(1)).Interface()
env := makeEnv(fakeReq)
pgrm, err := expr.Compile(req.Expression, expr.Env(env), expr.Optimize(true))
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "Could not compile the program: %s", err.Error())
}
mfii.lock.Lock()
mfii.program = pgrm
mfii.expression = req.Expression
mfii.lock.Unlock()
return &faultinjectorpb.RegisterFaultResponse{}, nil
}
type rr struct {
req proto.Message
resp proto.Message
err error
}
func (f *faultInjectorServer) Listen(req *faultinjectorpb.ListenRequest, resp faultinjectorpb.FaultInjector_ListenServer) error {
listenerChannel := make(chan rr, 100)
val, ok := f.fii.services.Load(req.Service)
if !ok {
return status.Errorf(codes.NotFound, "Service %s not found", req.Service)
}
sfii := val.(*serviceFaultInjectorInterceptor)
val, ok = sfii.methods.Load(req.Method)
if !ok {
return status.Errorf(codes.NotFound, "Method %s not found", req.Method)
}
mfii := val.(*methodFaultInjectorInterceptor)
mfii.lock.Lock()
if mfii.messageChan != nil {
mfii.lock.Unlock()
return status.Errorf(codes.AlreadyExists, "Listener already exists for %s / %s", req.Service, req.Method)
}
mfii.messageChan = listenerChannel
mfii.lock.Unlock()
defer func() {
mfii.lock.Lock()
defer mfii.lock.Unlock()
mfii.messageChan = nil
}()
for {
select {
case <-resp.Context().Done():
return nil
case rr := <-listenerChannel:
val := &faultinjectorpb.ListenResponse{
Request: rr.req.String(),
}
if rr.resp != nil {
val.Reply = rr.resp.String()
}
if rr.err != nil {
val.Error = rr.err.Error()
}
err := resp.Send(val)
if err != nil {
return err
}
}
}
}
func makeCodeFunction(c codes.Code) func(msg string) error {
return func(msg string) error {
return status.Error(c, msg)
}
}
func makeEnv(req interface{}) map[string]interface{} {
env := map[string]interface{}{
"req": req,
"OK": func() error {
return nil
},
"Canceled": makeCodeFunction(codes.Canceled),
"Unknown": makeCodeFunction(codes.Unknown),
"InvalidArgument": makeCodeFunction(codes.InvalidArgument),
"DeadlineExceeded": makeCodeFunction(codes.DeadlineExceeded),
"NotFound": makeCodeFunction(codes.NotFound),
"AlreadyExists": makeCodeFunction(codes.AlreadyExists),
"PermissionDenied": makeCodeFunction(codes.PermissionDenied),
"ResourceExhausted": makeCodeFunction(codes.ResourceExhausted),
"FailedPrecondition": makeCodeFunction(codes.FailedPrecondition),
"Aborted": makeCodeFunction(codes.Aborted),
"OutOfRange": makeCodeFunction(codes.OutOfRange),
"Unimplemented": makeCodeFunction(codes.Unimplemented),
"Internal": makeCodeFunction(codes.Internal),
"Unavailable": makeCodeFunction(codes.Unavailable),
"DataLoss": makeCodeFunction(codes.DataLoss),
"Unauthenticated": makeCodeFunction(codes.Unauthenticated),
}
return env
}
func (f *faultInjectorServer) RemoveFault(ctx context.Context, req *faultinjectorpb.RemoveFaultRequest) (*faultinjectorpb.RemoveFaultResponse, error) {
val, ok := f.fii.services.Load(req.Service)
if !ok {
return nil, status.Errorf(codes.NotFound, "service %s not found", req.Service)
}
service := val.(*serviceFaultInjectorInterceptor)
val, ok = service.methods.Load(req.Method)
if !ok {
return nil, status.Errorf(codes.NotFound, "method %s not found", req.Service)
}
method := val.(*methodFaultInjectorInterceptor)
method.lock.Lock()
defer method.lock.Unlock()
method.expression = ""
method.program = nil
return &faultinjectorpb.RemoveFaultResponse{}, nil
}