forked from brahma-adshonor/gorr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_hook.go
394 lines (321 loc) · 11.6 KB
/
redis_hook.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
package gorr
import (
"fmt"
"reflect"
"github.com/brahma-adshonor/gohook"
"github.com/go-redis/redis"
)
// please disable inlining by adding following gcflags to compiler
// go build -gcflags=all='-l=1' -o main main.go
/* there are two ways to hook redis operation. We should support both, but use #2 by default.
1. use gohook to hook NewClient() or NewClusterClient(), and insert a call to hooks.AddHook() to hijack redis command processing.
=>support from v6.15.4, which is not formally released by the date of this writting.
=>rely on the internal implementation of cmdable.Get() etc.
=>will skip other user customized Hook, as our Hook will always return error on replay state.
2. use gohook to hook client.Process() or client.ProcessContext()
=>all user customized Hook added by AddHook will be skiped
=>Process() might be inlined in future release, as it is a really short function, inlining can be fixed by adding build flags to compiler to stop inlining in debug build.
=>due to the subtle implementation of redis.Client.Process() before 6.15.1(Client.Process() not exist, only baseClient.Process, which can not be hooked), hook for client.Process won't work,
instead, we add wrapper to client.Process() by calling client.WrapProcess(), which does not present in later version, yep, it is tricky.
Redis command object(StringCmd, IntCmd, etc) is immutable, we are not able to set result into it, this makes a lot of troubles,
the workaround for this is we are going to hook the getter of the object. and maybe we should make a pull request to upstream, adding setter api to redis Command object.
*/
/*
hook point:
1. Client.Process()/ClusterClient.Process: for recoding/replaying cmd
2. Client.WrapProcess(): for go redis < 6.15.1, Client.Process() is not available.
3. NewClient()/NewRedisClient(): used to call WrapProcess()/AdHook() on client objects.
4. IntCmd/StringCmd/FloatCmd/SliceCmd/StatusCmd/etc: hook Result()/Val() method.
5. Client.WrapPipelineProcess()/ClusterClient.WrapPipelineProcess(): for go redis < 6.15.1, used to intercept queued cmds.
6. hook added by Client.AddHook()/ClusterClient.AdHook(): for go redis > 6.15.1, used to intercept pipeline cmd.
7. Pipeline.Exec()/Pipeline.ExecContext(): used to ignore dummy error from hook added by AdHook()
*/
// client.Process wrapper
func clientProcessWrapper(c *redis.Client, oldProcess func(cmd redis.Cmder) error) func(redis.Cmder) error {
return func(cmd redis.Cmder) error {
var err error
id := buildRedisClientId(c)
key := buildRedisCmdKey(id, cmd)
GlobalMgr.notifier("calling client.ProcessWrapper", key, []byte(""))
if GlobalMgr.ShouldRecord() {
err = oldProcess(cmd)
if err != nil && err != redis.Nil {
GlobalMgr.notifier("redis Client.Process() wrapper recording failed", key, []byte(err.Error()))
return err
}
saveRedisCmdValue(key, cmd)
} else {
addKeyToRedisCmd(cmd, key)
}
return err
}
}
func wrapRedisClientProcess(c *redis.Client, fn func(func(redis.Cmder) error) func(redis.Cmder) error) bool {
m := reflect.ValueOf(c).MethodByName("WrapProcess")
if !m.IsNil() {
m.Call([]reflect.Value{reflect.ValueOf(fn)})
return true
}
return false
}
func newRedisClient(opt *redis.Options) *redis.Client {
c := newRedisClientTrampoline(opt)
if c == nil {
return c
}
if redisHasProcessWrap {
wrap := func(old func(cmd redis.Cmder) error) func(redis.Cmder) error {
return clientProcessWrapper(c, old)
}
succ := wrapRedisClientProcess(c, wrap)
if succ {
GlobalMgr.notifier("call redis.WrapProcess for go redis < 6.15.4 done", "", []byte(""))
} else {
GlobalMgr.notifier("cannot call redis.WrapProcess()", "should not hook redis.NewClient()", []byte(""))
}
wrap2 := func(old func([]redis.Cmder) error) func([]redis.Cmder) error {
return clientPipelineProcessWrapper(c, old)
}
succ2 := wrapRedisPipelineProcessor(c, wrap2)
if succ2 {
GlobalMgr.notifier("call redis.WrapProcessPipeline for go redis < 6.15.4 done", "", []byte(""))
} else {
GlobalMgr.notifier("cannot call redis.WrapProcessPipeline()", "should not hook redis.NewClient()", []byte(""))
}
}
if redisHasHook {
m := reflect.ValueOf(c).MethodByName("AddHook")
if !m.IsNil() {
id := buildRedisClientId(c)
m.Call([]reflect.Value{reflect.ValueOf(&redisHook{id: id})})
}
}
return c
}
//go:noinline
func newRedisClientTrampoline(opt *redis.Options) *redis.Client {
fmt.Printf("dummy function for regrestion testing")
fmt.Printf("dummy function for regrestion testing")
for i := 0; i < 100000; i++ {
fmt.Printf("id:%d\n", i)
go func() { fmt.Printf("hello world\n") }()
}
if opt != nil {
panic("trampoline function is not allowed to be called directlyis not allowed to be called")
}
return nil
}
func newRedisClusterClient(opt *redis.ClusterOptions) *redis.ClusterClient {
c := newRedisClusterClientTrampoline(opt)
if c == nil {
return c
}
if redisHasProcessWrap {
wrap2 := func(old func([]redis.Cmder) error) func([]redis.Cmder) error {
return clusterClientPipelineProcessWrapper(c, old)
}
succ2 := wrapRedisPipelineProcessor(c, wrap2)
if succ2 {
GlobalMgr.notifier("call redis.WrapProcessPipeline for go redis < 6.15.4 done", "", []byte(""))
} else {
GlobalMgr.notifier("cannot call redis.WrapProcessPipeline()", "should not hook redis.NewClient()", []byte(""))
}
}
if redisHasHook {
m := reflect.ValueOf(c).MethodByName("AddHook")
if !m.IsNil() {
id := buildRedisClusterClientId(c)
m.Call([]reflect.Value{reflect.ValueOf(&redisHook{id: id})})
}
}
return c
}
//go:noinline
func newRedisClusterClientTrampoline(opt *redis.ClusterOptions) *redis.ClusterClient {
fmt.Printf("dummy function for regrestion testing")
fmt.Printf("dummy function for regrestion testing:%v", opt)
for i := 0; i < 100000; i++ {
fmt.Printf("id:%d\n", i)
go func() { fmt.Printf("hello world\n") }()
}
if opt != nil {
panic("trampoline function is not allowed to be called directlyis not allowed to be called")
}
return nil
}
// redis.Client.Process() hook
func redisClientProcess(c *redis.Client, cmd redis.Cmder) error {
var err error
id := buildRedisClientId(c)
key := buildRedisCmdKey(id, cmd)
if GlobalMgr.ShouldRecord() {
err = redisClientProcessTrampoline(c, cmd)
if err != nil && err != redis.Nil {
GlobalMgr.notifier("redis Client.Process() recording failed", key, []byte(err.Error()))
return err
}
saveRedisCmdValue(key, cmd)
} else {
addKeyToRedisCmd(cmd, key)
}
return err
}
//go:nosplit
func redisClientProcessTrampoline(c *redis.Client, cmd redis.Cmder) error {
fmt.Printf("dummy function for regrestion testing:%v", c)
for i := 0; i < 100000; i++ {
fmt.Printf("id:%d\n", i)
go func() { fmt.Printf("hello world\n") }()
}
if c != nil {
fmt.Printf("id:%d\n", 233)
panic("trampoline redis redis.Client.Process() function is not allowed to be called")
}
return nil
}
func redisClusterClientProcess(c *redis.ClusterClient, cmd redis.Cmder) error {
var err error
id := buildRedisClusterClientId(c)
key := buildRedisCmdKey(id, cmd)
if GlobalMgr.ShouldRecord() {
err = redisClusterClientProcessTrampoline(c, cmd)
if err != nil && err != redis.Nil {
GlobalMgr.notifier("redis ClusterClient.Process() recording failed", key, []byte(err.Error()))
return err
}
saveRedisCmdValue(key, cmd)
} else {
addKeyToRedisCmd(cmd, key)
}
return err
}
//go:nosplit
func redisClusterClientProcessTrampoline(c *redis.ClusterClient, cmd redis.Cmder) error {
fmt.Printf("dummy function for regrestion testing:%v", c)
for i := 0; i < 100000; i++ {
fmt.Printf("id:%d\n", i)
go func() { fmt.Printf("hello world\n") }()
}
if c != nil {
fmt.Printf("id:%d\n", 111)
panic("trampoline redis redis.ClusterClient.Process() function is not allowed to be called")
}
return nil
}
type CmdValue struct {
cmd interface{}
fn string
replace interface{}
trampoline interface{}
}
var (
cmd = []CmdValue{
CmdValue{&redis.IntCmd{}, "Val", intCmdValue, nil},
CmdValue{&redis.FloatCmd{}, "Val", floatCmdValue, nil},
CmdValue{&redis.StringCmd{}, "Val", stringCmdValue, nil},
CmdValue{&redis.StatusCmd{}, "Val", statusCmdValue, nil},
CmdValue{&redis.StringSliceCmd{}, "Val", stringSliceCmdValue, nil},
CmdValue{&redis.StringCmd{}, "Result", stringCmdResult, nil},
CmdValue{&redis.StatusCmd{}, "Result", statusCmdResult, nil},
CmdValue{&redis.StringSliceCmd{}, "Result", stringSliceCmdResult, nil},
}
)
func UnHookRedisFunc() error {
var c1 redis.Client
var c2 redis.ClusterClient
var pl redis.Pipeline
msg := ""
for _, c := range cmd {
v := reflect.ValueOf(c.cmd)
err := gohook.UnHookMethod(v.Interface(), c.fn)
if err != nil {
msg += fmt.Sprintf("unhook %s() for %s failed, err:%s@@", c.fn, v.Type().Name(), err.Error())
}
}
err1 := gohook.UnHookMethod(&c1, "Process")
if err1 != nil {
msg += fmt.Sprintf("unhook redis.Client.Process failed:%s@@", err1.Error())
}
err12 := gohook.UnHook(redis.NewClient)
if err12 != nil {
msg += fmt.Sprintf("unhook redis.NewClient() failed:%s@@", err12.Error())
}
err13 := gohook.UnHook(redis.NewClusterClient)
if err13 != nil {
msg += fmt.Sprintf("unhook redis.NewClusterClient() failed:%s@@", err13.Error())
}
err2 := gohook.UnHookMethod(&c2, "Process")
if err2 != nil {
msg += fmt.Sprintf("unhook redis.ClusterClient.Process failed:%s@@", err2.Error())
}
if redisHasHook {
err := gohook.UnHookMethod(&pl, "Exec")
if err != nil {
msg += fmt.Sprintf("unhook redis pipeline.Exec() failed:%s@@", err.Error())
}
err = gohook.UnHookMethod(&pl, "ExecContext")
if err != nil {
msg += fmt.Sprintf("unhook redis pipeline.ExecContext() failed:%s@@", err.Error())
}
}
if msg != "" {
return fmt.Errorf(msg)
}
return nil
}
func HookRedisFunc() error {
var err error
var c1 redis.Client
var c2 redis.ClusterClient
var pl redis.Pipeline
defer func() {
if err != nil {
UnHookRedisFunc()
}
}()
err = gohook.HookMethod(&c1, "Process", redisClientProcess, redisClientProcessTrampoline)
if err != nil {
return fmt.Errorf("hook redis.Client.Process() failed, err:%s", err.Error())
}
err = gohook.Hook(redis.NewClient, newRedisClient, newRedisClientTrampoline)
if err != nil {
GlobalMgr.notifier("hook redis.NewClient() failed", err.Error(), []byte(""))
return fmt.Errorf("hook redis.NewClient() failed, err:%s", err.Error())
}
err = gohook.Hook(redis.NewClusterClient, newRedisClusterClient, newRedisClusterClientTrampoline)
if err != nil {
GlobalMgr.notifier("hook redis.NewClusterClient() failed", err.Error(), []byte(""))
return fmt.Errorf("hook redis.NewClusterClient() failed, err:%s", err.Error())
}
err = gohook.HookMethod(&c2, "Process", redisClusterClientProcess, redisClusterClientProcessTrampoline)
if err != nil {
return fmt.Errorf("hook redis cluster client failed, err:%s", err.Error())
}
if redisHasHook {
err = gohook.HookMethod(&pl, "Exec", redisPipelineExec, redisPipelineExecTramp)
if err != nil {
return fmt.Errorf("hook redis pipeline.Exec() failed, err:%s", err.Error())
}
err = gohook.HookMethod(&pl, "ExecContext", redisPipelineExecContext, redisPipelineExecContextTramp)
if err != nil {
return fmt.Errorf("hook redis pipeline.Exec() failed, err:%s", err.Error())
}
}
if !GlobalMgr.ShouldRecord() {
// replay
for _, c := range cmd {
v := reflect.ValueOf(c.cmd)
r := reflect.ValueOf(c.replace)
t := reflect.ValueOf(c.trampoline)
if c.trampoline == nil {
err = gohook.HookMethod(v.Interface(), c.fn, r.Interface(), nil)
} else {
err = gohook.HookMethod(v.Interface(), c.fn, r.Interface(), t.Interface())
}
if err != nil {
return fmt.Errorf("unhook %s() for %s failed, err:%s@@", c.fn, v.Type().Name(), err.Error())
}
}
}
return nil
}