forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 1
/
redis.go
544 lines (470 loc) · 15.6 KB
/
redis.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
package main
import (
"bytes"
"strconv"
"strings"
"time"
"labix.org/v2/mgo/bson"
)
type RedisMessage struct {
Ts time.Time
NumberOfBulks int64
Bulks []string
Stream_id uint32
Tuple *IpPortTuple
CmdlineTuple *CmdlineTuple
Direction uint8
IsRequest bool
Message string
}
type RedisStream struct {
tcpStream *TcpStream
data []byte
parseOffset int
bytesReceived int
message *RedisMessage
}
type RedisTransaction struct {
Type string
tuple TcpTuple
Src Endpoint
Dst Endpoint
ResponseTime int32
Ts int64
JsTs time.Time
ts time.Time
cmdline *CmdlineTuple
Redis bson.M
Request_raw string
Response_raw string
timer *time.Timer
}
// Keep sorted for future command addition
var RedisCommands = map[string]struct{}{
"APPEND": struct{}{},
"AUTH": struct{}{},
"BGREWRITEAOF": struct{}{},
"BGSAVE": struct{}{},
"BITCOUNT": struct{}{},
"BITOP": struct{}{},
"BITPOS": struct{}{},
"BLPOP": struct{}{},
"BRPOP": struct{}{},
"BRPOPLPUSH": struct{}{},
"CLIENT GETNAME": struct{}{},
"CLIENT KILL": struct{}{},
"CLIENT LIST": struct{}{},
"CLIENT PAUSE": struct{}{},
"CLIENT SETNAME": struct{}{},
"CONFIG GET": struct{}{},
"CONFIG RESETSTAT": struct{}{},
"CONFIG REWRITE": struct{}{},
"CONFIG SET": struct{}{},
"DBSIZE": struct{}{},
"DEBUG OBJECT": struct{}{},
"DEBUG SEGFAULT": struct{}{},
"DECR": struct{}{},
"DECRBY": struct{}{},
"DEL": struct{}{},
"DISCARD": struct{}{},
"DUMP": struct{}{},
"ECHO": struct{}{},
"EVAL": struct{}{},
"EVALSHA": struct{}{},
"EXEC": struct{}{},
"EXISTS": struct{}{},
"EXPIRE": struct{}{},
"EXPIREAT": struct{}{},
"FLUSHALL": struct{}{},
"FLUSHDB": struct{}{},
"GET": struct{}{},
"GETBIT": struct{}{},
"GETRANGE": struct{}{},
"GETSET": struct{}{},
"HDEL": struct{}{},
"HEXISTS": struct{}{},
"HGET": struct{}{},
"HGETALL": struct{}{},
"HINCRBY": struct{}{},
"HINCRBYFLOAT": struct{}{},
"HKEYS": struct{}{},
"HLEN": struct{}{},
"HMGET": struct{}{},
"HMSET": struct{}{},
"HSCAN": struct{}{},
"HSET": struct{}{},
"HSETINX": struct{}{},
"HVALS": struct{}{},
"INCR": struct{}{},
"INCRBY": struct{}{},
"INCRBYFLOAT": struct{}{},
"INFO": struct{}{},
"KEYS": struct{}{},
"LASTSAVE": struct{}{},
"LINDEX": struct{}{},
"LINSERT": struct{}{},
"LLEN": struct{}{},
"LPOP": struct{}{},
"LPUSH": struct{}{},
"LPUSHX": struct{}{},
"LRANGE": struct{}{},
"LREM": struct{}{},
"LSET": struct{}{},
"LTRIM": struct{}{},
"MGET": struct{}{},
"MIGRATE": struct{}{},
"MONITOR": struct{}{},
"MOVE": struct{}{},
"MSET": struct{}{},
"MSETNX": struct{}{},
"MULTI": struct{}{},
"OBJECT": struct{}{},
"PERSIST": struct{}{},
"PEXPIRE": struct{}{},
"PEXPIREAT": struct{}{},
"PFADD": struct{}{},
"PFCOUNT": struct{}{},
"PFMERGE": struct{}{},
"PING": struct{}{},
"PSETEX": struct{}{},
"PSUBSCRIBE": struct{}{},
"PTTL": struct{}{},
"PUBLISH": struct{}{},
"PUBSUB": struct{}{},
"PUNSUBSCRIBE": struct{}{},
"QUIT": struct{}{},
"RANDOMKEY": struct{}{},
"RENAME": struct{}{},
"RENAMENX": struct{}{},
"RESTORE": struct{}{},
"RPOP": struct{}{},
"RPOPLPUSH": struct{}{},
"RPUSH": struct{}{},
"RPUSHX": struct{}{},
"SADD": struct{}{},
"SAVE": struct{}{},
"SCAN": struct{}{},
"SCARD": struct{}{},
"SCRIPT EXISTS": struct{}{},
"SCRIPT FLUSH": struct{}{},
"SCRIPT KILL": struct{}{},
"SCRIPT LOAD": struct{}{},
"SDIFF": struct{}{},
"SDIFFSTORE": struct{}{},
"SELECT": struct{}{},
"SET": struct{}{},
"SETBIT": struct{}{},
"SETEX": struct{}{},
"SETNX": struct{}{},
"SETRANGE": struct{}{},
"SHUTDOWN": struct{}{},
"SINTER": struct{}{},
"SINTERSTORE": struct{}{},
"SISMEMBER": struct{}{},
"SLAVEOF": struct{}{},
"SLOWLOG": struct{}{},
"SMEMBERS": struct{}{},
"SMOVE": struct{}{},
"SORT": struct{}{},
"SPOP": struct{}{},
"SRANDMEMBER": struct{}{},
"SREM": struct{}{},
"SSCAN": struct{}{},
"STRLEN": struct{}{},
"SUBSCRIBE": struct{}{},
"SUNION": struct{}{},
"SUNIONSTORE": struct{}{},
"SYNC": struct{}{},
"TIME": struct{}{},
"TTL": struct{}{},
"TYPE": struct{}{},
"UNSUBSCRIBE": struct{}{},
"UNWATCH": struct{}{},
"WATCH": struct{}{},
"ZADD": struct{}{},
"ZCARD": struct{}{},
"ZCOUNT": struct{}{},
"ZINCRBY": struct{}{},
"ZINTERSTORE": struct{}{},
"ZRANGE": struct{}{},
"ZRANGEBYSCORE": struct{}{},
"ZRANK": struct{}{},
"ZREM": struct{}{},
"ZREMRANGEBYLEX": struct{}{},
"ZREMRANGEBYRANK": struct{}{},
"ZREMRANGEBYSCORE": struct{}{},
"ZREVRANGE": struct{}{},
"ZREVRANGEBYSCORE": struct{}{},
"ZREVRANK": struct{}{},
"ZSCAN": struct{}{},
"ZSCORE": struct{}{},
"ZUNIONSTORE": struct{}{},
}
var redisTransactionsMap = make(map[TcpTuple]*RedisTransaction, TransactionsHashSize)
func (stream *RedisStream) PrepareForNewMessage() {
stream.data = stream.data[stream.parseOffset:]
stream.parseOffset = 0
stream.message.NumberOfBulks = 0
stream.message.Bulks = []string{}
stream.message.IsRequest = false
}
func redisMessageParser(s *RedisStream) (bool, bool) {
var err error
var value string
m := s.message
for s.parseOffset < len(s.data) {
if s.data[s.parseOffset] == '*' {
//Multi Bulk Message
found, line, off := readLine(s.data, s.parseOffset)
if !found {
DEBUG("redis", "End of line not found, waiting for more data")
return true, false
}
if len(line) == 3 && line[1] == '-' && line[2] == '1' {
//NULL Multi Bulk
s.parseOffset = off
value = "nil"
} else {
m.NumberOfBulks, err = strconv.ParseInt(line[1:], 10, 64)
if err != nil {
ERR("Failed to read number of bulk messages: %s", err)
return false, false
}
s.parseOffset = off
m.Bulks = []string{}
continue
}
} else if s.data[s.parseOffset] == '$' {
old_offset := s.parseOffset
// Bulk Reply
found, line, off := readLine(s.data, s.parseOffset)
if !found {
DEBUG("redis", "End of line not found, waiting for more data")
s.parseOffset = old_offset
return true, false
}
if len(line) == 3 && line[1] == '-' && line[2] == '1' {
// NULL Bulk Reply
value = "nil"
s.parseOffset = off
} else {
length, err := strconv.ParseInt(line[1:], 10, 64)
if err != nil {
ERR("Failed to read bulk message: %s", err)
return false, false
}
s.parseOffset = off
found, line, off = readLine(s.data, s.parseOffset)
if !found {
DEBUG("redis", "End of line not found, waiting for more data")
s.parseOffset = old_offset
return true, false
}
if int64(len(line)) != length {
ERR("Wrong length of data: %d instead of %d", len(line), length)
return false, false
}
value = line
s.parseOffset = off
}
} else if s.data[s.parseOffset] == ':' {
// Integer reply
found, line, off := readLine(s.data, s.parseOffset)
if !found {
return true, false
}
n, err := strconv.ParseInt(line[1:], 10, 64)
if err != nil {
ERR("Failed to read integer reply: %s", err)
return false, false
}
value = strconv.Itoa(int(n))
s.parseOffset = off
} else if s.data[s.parseOffset] == '+' {
// Status Reply
found, line, off := readLine(s.data, s.parseOffset)
if !found {
return true, false
}
value = line[1:]
s.parseOffset = off
} else if s.data[s.parseOffset] == '-' {
// Error Reply
found, line, off := readLine(s.data, s.parseOffset)
if !found {
return true, false
}
value = line[1:]
s.parseOffset = off
} else {
DEBUG("redis", "Unexpected message starting with %s", s.data[s.parseOffset:])
return false, false
}
// add value
if m.NumberOfBulks > 0 {
m.NumberOfBulks = m.NumberOfBulks - 1
m.Bulks = append(m.Bulks, value)
if len(m.Bulks) == 1 {
// check if it's a command
if isRedisCommand(value) {
m.IsRequest = true
}
}
if m.NumberOfBulks == 0 {
// the last bulk received
m.Message = strings.Join(m.Bulks, " ")
return true, true
}
} else {
m.Message = value
return true, true
}
} //end for
return true, false
}
func readLine(data []byte, offset int) (bool, string, int) {
q := bytes.Index(data[offset:], []byte("\r\n"))
if q == -1 {
return false, "", 0
}
return true, string(data[offset : offset+q]), offset + q + 2
}
func ParseRedis(pkt *Packet, tcp *TcpStream, dir uint8) {
defer RECOVER("ParseRedis exception")
if tcp.redisData[dir] == nil {
tcp.redisData[dir] = &RedisStream{
tcpStream: tcp,
data: pkt.payload,
message: &RedisMessage{Ts: pkt.ts},
}
} else {
// concatenate bytes
tcp.redisData[dir].data = append(tcp.redisData[dir].data, pkt.payload...)
if len(tcp.redisData[dir].data) > TCP_MAX_DATA_IN_STREAM {
DEBUG("redis", "Stream data too large, dropping TCP stream")
tcp.redisData[dir] = nil
return
}
}
stream := tcp.redisData[dir]
for len(stream.data) > 0 {
if stream.message == nil {
stream.message = &RedisMessage{Ts: pkt.ts}
}
ok, complete := redisMessageParser(tcp.redisData[dir])
if !ok {
// drop this tcp stream. Will retry parsing with the next
// segment in it
tcp.redisData[dir] = nil
DEBUG("redis", "Ignore Redis message. Drop tcp stream. Try parsing with the next segment")
return
}
if complete {
if stream.message.IsRequest {
DEBUG("redis", "REDIS request message: %s", stream.message.Message)
} else {
DEBUG("redis", "REDIS response message: %s", stream.message.Message)
}
// all ok, go to next level
handleRedis(stream.message, tcp, dir)
// and reset message
stream.PrepareForNewMessage()
} else {
// wait for more data
break
}
}
}
func isRedisCommand(key string) bool {
_, exists := RedisCommands[key]
return exists
}
func handleRedis(m *RedisMessage, tcp *TcpStream,
dir uint8) {
m.Stream_id = tcp.id
m.Tuple = tcp.tuple
m.Direction = dir
m.CmdlineTuple = procWatcher.FindProcessesTuple(tcp.tuple)
if m.IsRequest {
receivedRedisRequest(m)
} else {
receivedRedisResponse(m)
}
}
func receivedRedisRequest(msg *RedisMessage) {
// Add it to the HT
tuple := TcpTuple{
Src_ip: msg.Tuple.Src_ip,
Dst_ip: msg.Tuple.Dst_ip,
Src_port: msg.Tuple.Src_port,
Dst_port: msg.Tuple.Dst_port,
stream_id: msg.Stream_id,
}
trans := redisTransactionsMap[tuple]
if trans != nil {
if len(trans.Redis) != 0 {
WARN("Two requests without a Response. Dropping old request")
}
} else {
trans = &RedisTransaction{Type: "redis", tuple: tuple}
redisTransactionsMap[tuple] = trans
}
trans.Redis = bson.M{
"request": msg.Message,
}
trans.Request_raw = msg.Message
trans.cmdline = msg.CmdlineTuple
trans.ts = msg.Ts
trans.Ts = int64(trans.ts.UnixNano() / 1000) // transactions have microseconds resolution
trans.JsTs = msg.Ts
trans.Src = Endpoint{
Ip: Ipv4_Ntoa(tuple.Src_ip),
Port: tuple.Src_port,
Proc: string(msg.CmdlineTuple.Src),
}
trans.Dst = Endpoint{
Ip: Ipv4_Ntoa(tuple.Dst_ip),
Port: tuple.Dst_port,
Proc: string(msg.CmdlineTuple.Dst),
}
if trans.timer != nil {
trans.timer.Stop()
}
trans.timer = time.AfterFunc(TransactionTimeout, func() { trans.Expire() })
}
func (trans *RedisTransaction) Expire() {
// remove from map
delete(redisTransactionsMap, trans.tuple)
}
func receivedRedisResponse(msg *RedisMessage) {
tuple := TcpTuple{
Src_ip: msg.Tuple.Src_ip,
Dst_ip: msg.Tuple.Dst_ip,
Src_port: msg.Tuple.Src_port,
Dst_port: msg.Tuple.Dst_port,
stream_id: msg.Stream_id,
}
trans := redisTransactionsMap[tuple]
if trans == nil {
WARN("Response from unknown transaction. Ignoring.")
return
}
// check if the request was received
if len(trans.Redis) == 0 {
WARN("Response from unknown transaction. Ignoring.")
return
}
trans.Redis["response"] = msg.Message
trans.Response_raw = msg.Message
trans.ResponseTime = int32(msg.Ts.Sub(trans.ts).Nanoseconds() / 1e6) // resp_time in milliseconds
err := Publisher.PublishRedisTransaction(trans)
if err != nil {
WARN("Publish failure: %s", err)
}
DEBUG("redis", "Redis transaction completed: %s", trans.Redis)
// remove from map
delete(redisTransactionsMap, trans.tuple)
if trans.timer != nil {
trans.timer.Stop()
}
}