-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
redis.go
356 lines (305 loc) · 8.68 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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package redis
import (
"bytes"
"strings"
"time"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/beats/v7/libbeat/logp"
"github.com/elastic/beats/v7/libbeat/monitoring"
"github.com/elastic/beats/v7/packetbeat/pb"
"github.com/elastic/beats/v7/packetbeat/procs"
"github.com/elastic/beats/v7/packetbeat/protos"
"github.com/elastic/beats/v7/packetbeat/protos/applayer"
"github.com/elastic/beats/v7/packetbeat/protos/tcp"
)
type stream struct {
applayer.Stream
parser parser
tcptuple *common.TCPTuple
}
type redisConnectionData struct {
streams [2]*stream
requests MessageQueue
responses MessageQueue
}
// Redis protocol plugin
type redisPlugin struct {
// config
ports []int
sendRequest bool
sendResponse bool
transactionTimeout time.Duration
queueConfig MessageQueueConfig
watcher procs.ProcessesWatcher
results protos.Reporter
}
var (
debugf = logp.MakeDebug("redis")
isDebug = false
)
var (
unmatchedResponses = monitoring.NewInt(nil, "redis.unmatched_responses")
unmatchedRequests = monitoring.NewInt(nil, "redis.unmatched_requests")
)
func init() {
protos.Register("redis", New)
}
func New(
testMode bool,
results protos.Reporter,
watcher procs.ProcessesWatcher,
cfg *common.Config,
) (protos.Plugin, error) {
p := &redisPlugin{}
config := defaultConfig
if !testMode {
if err := cfg.Unpack(&config); err != nil {
return nil, err
}
}
if err := p.init(results, watcher, &config); err != nil {
return nil, err
}
return p, nil
}
func (redis *redisPlugin) init(results protos.Reporter, watcher procs.ProcessesWatcher, config *redisConfig) error {
redis.setFromConfig(config)
redis.results = results
redis.watcher = watcher
isDebug = logp.IsDebug("redis")
return nil
}
func (redis *redisPlugin) setFromConfig(config *redisConfig) {
redis.ports = config.Ports
redis.sendRequest = config.SendRequest
redis.sendResponse = config.SendResponse
redis.transactionTimeout = config.TransactionTimeout
redis.queueConfig = config.QueueLimits
}
func (redis *redisPlugin) GetPorts() []int {
return redis.ports
}
func (s *stream) PrepareForNewMessage() {
parser := &s.parser
s.Stream.Reset()
parser.reset()
}
func (redis *redisPlugin) ConnectionTimeout() time.Duration {
return redis.transactionTimeout
}
func (redis *redisPlugin) Parse(
pkt *protos.Packet,
tcptuple *common.TCPTuple,
dir uint8,
private protos.ProtocolData,
) protos.ProtocolData {
defer logp.Recover("ParseRedis exception")
conn := redis.ensureRedisConnection(private)
conn = redis.doParse(conn, pkt, tcptuple, dir)
if conn == nil {
return nil
}
return conn
}
func (redis *redisPlugin) newConnectionData() *redisConnectionData {
return &redisConnectionData{
requests: NewMessageQueue(redis.queueConfig),
responses: NewMessageQueue(redis.queueConfig),
}
}
func (redis *redisPlugin) ensureRedisConnection(private protos.ProtocolData) *redisConnectionData {
if private == nil {
return redis.newConnectionData()
}
priv, ok := private.(*redisConnectionData)
if !ok {
logp.Warn("redis connection data type error, create new one")
return redis.newConnectionData()
}
if priv == nil {
logp.Warn("Unexpected: redis connection data not set, create new one")
return redis.newConnectionData()
}
return priv
}
func (redis *redisPlugin) doParse(
conn *redisConnectionData,
pkt *protos.Packet,
tcptuple *common.TCPTuple,
dir uint8,
) *redisConnectionData {
st := conn.streams[dir]
if st == nil {
st = newStream(pkt.Ts, tcptuple)
conn.streams[dir] = st
if isDebug {
debugf("new stream: %p (dir=%v, len=%v)", st, dir, len(pkt.Payload))
}
}
if err := st.Append(pkt.Payload); err != nil {
if isDebug {
debugf("%v, dropping TCP stream: ", err)
}
return nil
}
if isDebug {
debugf("stream add data: %p (dir=%v, len=%v)", st, dir, len(pkt.Payload))
}
for st.Buf.Len() > 0 {
if st.parser.message == nil {
st.parser.message = newMessage(pkt.Ts)
}
ok, complete := st.parser.parse(&st.Buf)
if !ok {
// drop this tcp stream. Will retry parsing with the next
// segment in it
conn.streams[dir] = nil
if isDebug {
debugf("Ignore Redis message. Drop tcp stream. Try parsing with the next segment")
}
return conn
}
if !complete {
// wait for more data
break
}
msg := st.parser.message
if isDebug {
if msg.isRequest {
debugf("REDIS (%p) request message: %s", conn, msg.message)
} else {
debugf("REDIS (%p) response message: %s", conn, msg.message)
}
}
// all ok, go to next level and reset stream for new message
redis.handleRedis(conn, msg, tcptuple, dir)
st.PrepareForNewMessage()
}
return conn
}
func newStream(ts time.Time, tcptuple *common.TCPTuple) *stream {
s := &stream{
tcptuple: tcptuple,
}
s.parser.message = newMessage(ts)
s.Stream.Init(tcp.TCPMaxDataInStream)
return s
}
func newMessage(ts time.Time) *redisMessage {
return &redisMessage{ts: ts}
}
func (redis *redisPlugin) handleRedis(
conn *redisConnectionData,
m *redisMessage,
tcptuple *common.TCPTuple,
dir uint8,
) {
m.tcpTuple = *tcptuple
m.direction = dir
m.cmdlineTuple = redis.watcher.FindProcessesTupleTCP(tcptuple.IPPort())
if m.isRequest {
// wait for response
if evicted := conn.requests.Append(m); evicted > 0 {
unmatchedRequests.Add(int64(evicted))
}
} else {
if evicted := conn.responses.Append(m); evicted > 0 {
unmatchedResponses.Add(int64(evicted))
}
redis.correlate(conn)
}
}
func (redis *redisPlugin) correlate(conn *redisConnectionData) {
// drop responses with missing requests
if conn.requests.IsEmpty() {
for !conn.responses.IsEmpty() {
debugf("Response from unknown transaction. Ignoring")
unmatchedResponses.Add(1)
conn.responses.Pop()
}
return
}
// merge requests with responses into transactions
for !conn.responses.IsEmpty() && !conn.requests.IsEmpty() {
requ, okReq := conn.requests.Pop().(*redisMessage)
resp, okResp := conn.responses.Pop().(*redisMessage)
if !okReq || !okResp {
logp.Err("invalid type found in message queue")
continue
}
if redis.results != nil {
event := redis.newTransaction(requ, resp)
redis.results(event)
}
}
}
func (redis *redisPlugin) newTransaction(requ, resp *redisMessage) beat.Event {
source, destination := common.MakeEndpointPair(requ.tcpTuple.BaseTuple, requ.cmdlineTuple)
src, dst := &source, &destination
if requ.direction == tcp.TCPDirectionReverse {
src, dst = dst, src
}
evt, pbf := pb.NewBeatEvent(requ.ts)
pbf.SetSource(src)
pbf.SetDestination(dst)
pbf.Source.Bytes = int64(requ.size)
pbf.Destination.Bytes = int64(resp.size)
pbf.Event.Dataset = "redis"
pbf.Event.Start = requ.ts
pbf.Event.End = resp.ts
pbf.Network.Transport = "tcp"
pbf.Network.Protocol = pbf.Event.Dataset
fields := evt.Fields
fields["type"] = pbf.Event.Dataset
fields["method"] = common.NetString(bytes.ToUpper(requ.method))
fields["resource"] = requ.path
fields["query"] = requ.message
if resp.isError {
evt.PutValue("status", common.ERROR_STATUS)
evt.PutValue("redis.error", resp.message)
} else {
evt.PutValue("status", common.OK_STATUS)
evt.PutValue("redis.return_value", resp.message)
}
if redis.sendRequest {
fields["request"] = requ.message
}
if redis.sendResponse {
fields["response"] = resp.message
}
pbf.Event.Action = "redis." + strings.ToLower(string(requ.method))
if resp.isError {
pbf.Event.Outcome = "failure"
}
return evt
}
func (redis *redisPlugin) GapInStream(tcptuple *common.TCPTuple, dir uint8,
nbytes int, private protos.ProtocolData) (priv protos.ProtocolData, drop bool,
) {
// tsg: being packet loss tolerant is probably not very useful for Redis,
// because most requests/response tend to fit in a single packet.
return private, true
}
func (redis *redisPlugin) ReceivedFin(tcptuple *common.TCPTuple, dir uint8,
private protos.ProtocolData,
) protos.ProtocolData {
// TODO: check if we have pending data that we can send up the stack
return private
}