-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
322 lines (276 loc) · 6.97 KB
/
client.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
package redis
import (
"errors"
"regexp"
"strconv"
"time"
"github.com/garyburd/redigo/redis"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/outputs"
"github.com/elastic/beats/libbeat/outputs/codec"
"github.com/elastic/beats/libbeat/outputs/outil"
"github.com/elastic/beats/libbeat/outputs/transport"
"github.com/elastic/beats/libbeat/publisher"
)
var (
versionRegex = regexp.MustCompile(`redis_version:(\d+).(\d+)`)
)
type publishFn func(
keys outil.Selector,
data []publisher.Event,
) ([]publisher.Event, error)
type client struct {
*transport.Client
observer outputs.Observer
index string
dataType redisDataType
db int
key outil.Selector
password string
publish publishFn
codec codec.Codec
timeout time.Duration
}
type redisDataType uint16
const (
redisListType redisDataType = iota
redisChannelType
)
func newClient(
tc *transport.Client,
observer outputs.Observer,
timeout time.Duration,
pass string,
db int, key outil.Selector, dt redisDataType,
index string, codec codec.Codec,
) *client {
return &client{
Client: tc,
observer: observer,
timeout: timeout,
password: pass,
index: index,
db: db,
dataType: dt,
key: key,
codec: codec,
}
}
func (c *client) Connect() error {
debugf("connect")
err := c.Client.Connect()
if err != nil {
return err
}
to := c.timeout
conn := redis.NewConn(c.Client, to, to)
defer func() {
if err != nil {
conn.Close()
}
}()
if err = initRedisConn(conn, c.password, c.db); err == nil {
c.publish, err = c.makePublish(conn)
}
return err
}
func initRedisConn(c redis.Conn, pwd string, db int) error {
if pwd != "" {
if _, err := c.Do("AUTH", pwd); err != nil {
return err
}
}
if _, err := c.Do("PING"); err != nil {
return err
}
if db != 0 {
if _, err := c.Do("SELECT", db); err != nil {
return err
}
}
return nil
}
func (c *client) Close() error {
debugf("close connection")
return c.Client.Close()
}
func (c *client) Publish(batch publisher.Batch) error {
if c == nil {
panic("no client")
}
if batch == nil {
panic("no batch")
}
events := batch.Events()
c.observer.NewBatch(len(events))
rest, err := c.publish(c.key, events)
if rest != nil {
c.observer.Failed(len(rest))
batch.RetryEvents(rest)
return err
}
batch.ACK()
return err
}
func (c *client) makePublish(
conn redis.Conn,
) (publishFn, error) {
if c.dataType == redisChannelType {
return c.makePublishPUBLISH(conn)
}
return c.makePublishRPUSH(conn)
}
func (c *client) makePublishRPUSH(conn redis.Conn) (publishFn, error) {
if !c.key.IsConst() {
// TODO: more clever bulk handling batching events with same key
return c.publishEventsPipeline(conn, "RPUSH"), nil
}
var major, minor int
var versionRaw [][]byte
respRaw, err := conn.Do("INFO")
resp, err := redis.Bytes(respRaw, err)
if err != nil {
return nil, err
}
versionRaw = versionRegex.FindSubmatch(resp)
if versionRaw == nil {
err = errors.New("unable to read redis_version")
return nil, err
}
major, err = strconv.Atoi(string(versionRaw[1]))
if err != nil {
return nil, err
}
minor, err = strconv.Atoi(string(versionRaw[2]))
if err != nil {
return nil, err
}
// Check Redis version number choosing the method
// how RPUSH shall be used. With version 2.4 RPUSH
// can accept multiple values at once turning RPUSH
// into batch like call instead of relying on pipelining.
//
// Versions 1.0 to 2.3 only accept one value being send with
// RPUSH requiring pipelining.
//
// See: http://redis.io/commands/rpush
multiValue := major > 2 || (major == 2 && minor >= 4)
if multiValue {
return c.publishEventsBulk(conn, "RPUSH"), nil
}
return c.publishEventsPipeline(conn, "RPUSH"), nil
}
func (c *client) makePublishPUBLISH(conn redis.Conn) (publishFn, error) {
return c.publishEventsPipeline(conn, "PUBLISH"), nil
}
func (c *client) publishEventsBulk(conn redis.Conn, command string) publishFn {
// XXX: requires key.IsConst() == true
dest, _ := c.key.Select(&beat.Event{Fields: common.MapStr{}})
return func(_ outil.Selector, data []publisher.Event) ([]publisher.Event, error) {
args := make([]interface{}, 1, len(data)+1)
args[0] = dest
okEvents, args := serializeEvents(args, 1, data, c.index, c.codec)
c.observer.Dropped(len(data) - len(okEvents))
if (len(args) - 1) == 0 {
return nil, nil
}
// RPUSH returns total length of list -> fail and retry all on error
_, err := conn.Do(command, args...)
if err != nil {
logp.Err("Failed to %v to redis list with %v", command, err)
return okEvents, err
}
c.observer.Acked(len(okEvents))
return nil, nil
}
}
func (c *client) publishEventsPipeline(conn redis.Conn, command string) publishFn {
return func(key outil.Selector, data []publisher.Event) ([]publisher.Event, error) {
var okEvents []publisher.Event
serialized := make([]interface{}, 0, len(data))
okEvents, serialized = serializeEvents(serialized, 0, data, c.index, c.codec)
c.observer.Dropped(len(data) - len(okEvents))
if len(serialized) == 0 {
return nil, nil
}
data = okEvents[:0]
dropped := 0
for i, serializedEvent := range serialized {
eventKey, err := key.Select(&okEvents[i].Content)
if err != nil {
logp.Err("Failed to set redis key: %v", err)
dropped++
continue
}
data = append(data, okEvents[i])
if err := conn.Send(command, eventKey, serializedEvent); err != nil {
logp.Err("Failed to execute %v: %v", command, err)
return okEvents, err
}
}
c.observer.Dropped(dropped)
if err := conn.Flush(); err != nil {
return data, err
}
failed := data[:0]
var lastErr error
for i := range serialized {
_, err := conn.Receive()
if err != nil {
if _, ok := err.(redis.Error); ok {
logp.Err("Failed to %v event to list with %v",
command, err)
failed = append(failed, data[i])
lastErr = err
} else {
logp.Err("Failed to %v multiple events to list with %v",
command, err)
failed = append(failed, data[i:]...)
lastErr = err
break
}
}
}
c.observer.Acked(len(okEvents) - len(failed))
return failed, lastErr
}
}
func serializeEvents(
to []interface{},
i int,
data []publisher.Event,
index string,
codec codec.Codec,
) ([]publisher.Event, []interface{}) {
succeeded := data
for _, d := range data {
serializedEvent, err := codec.Encode(index, &d.Content)
if err != nil {
logp.Err("Encoding event failed with error: %v", err)
goto failLoop
}
buf := make([]byte, len(serializedEvent))
copy(buf, serializedEvent)
to = append(to, buf)
i++
}
return succeeded, to
failLoop:
succeeded = data[:i]
rest := data[i+1:]
for _, d := range rest {
serializedEvent, err := codec.Encode(index, &d.Content)
if err != nil {
logp.Err("Encoding event failed with error: %v", err)
i++
continue
}
buf := make([]byte, len(serializedEvent))
copy(buf, serializedEvent)
to = append(to, buf)
i++
}
return succeeded, to
}