forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
276 lines (236 loc) · 6.01 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
package redis
import (
"encoding/json"
"errors"
"regexp"
"strconv"
"time"
"github.com/garyburd/redigo/redis"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/outputs"
"github.com/elastic/beats/libbeat/outputs/outil"
"github.com/elastic/beats/libbeat/outputs/transport"
)
var (
versionRegex = regexp.MustCompile(`redis_version:(\d+).(\d+)`)
)
type publishFn func(
keys outil.Selector,
data []outputs.Data,
) ([]outputs.Data, error)
type client struct {
*transport.Client
dataType redisDataType
db int
key outil.Selector
password string
publish publishFn
}
type redisDataType uint16
const (
redisListType redisDataType = iota
redisChannelType
)
func newClient(tc *transport.Client, pass string, db int, key outil.Selector, dt redisDataType) *client {
return &client{
Client: tc,
password: pass,
db: db,
dataType: dt,
key: key,
}
}
func (c *client) Connect(to time.Duration) error {
debugf("connect")
err := c.Client.Connect()
if err != nil {
return err
}
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 = makePublish(conn, c.key, c.dataType)
}
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) PublishEvent(data outputs.Data) error {
_, err := c.PublishEvents([]outputs.Data{data})
return err
}
func (c *client) PublishEvents(data []outputs.Data) ([]outputs.Data, error) {
return c.publish(c.key, data)
}
func makePublish(
conn redis.Conn,
key outil.Selector,
dt redisDataType,
) (publishFn, error) {
if dt == redisChannelType {
return makePublishPUBLISH(conn)
}
return makePublishRPUSH(conn, key)
}
func makePublishRPUSH(conn redis.Conn, key outil.Selector) (publishFn, error) {
if !key.IsConst() {
// TODO: more clever bulk handling batching events with same key
return 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 publishEventsBulk(conn, key, "RPUSH"), nil
}
return publishEventsPipeline(conn, "RPUSH"), nil
}
func makePublishPUBLISH(conn redis.Conn) (publishFn, error) {
return publishEventsPipeline(conn, "PUBLISH"), nil
}
func publishEventsBulk(conn redis.Conn, key outil.Selector, command string) publishFn {
// XXX: requires key.IsConst() == true
dest, _ := key.Select(common.MapStr{})
return func(_ outil.Selector, data []outputs.Data) ([]outputs.Data, error) {
args := make([]interface{}, 1, len(data)+1)
args[0] = dest
data, args = serializeEvents(args, 1, data)
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 data, err
}
return nil, nil
}
}
func publishEventsPipeline(conn redis.Conn, command string) publishFn {
return func(key outil.Selector, data []outputs.Data) ([]outputs.Data, error) {
var okEvents []outputs.Data
serialized := make([]interface{}, 0, len(data))
okEvents, serialized = serializeEvents(serialized, 0, data)
if len(serialized) == 0 {
return nil, nil
}
data = okEvents[:0]
for i, serializedEvent := range serialized {
eventKey, err := key.Select(okEvents[i].Event)
if err != nil {
logp.Err("Failed to set redis key: %v", err)
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
}
}
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
}
}
}
return failed, lastErr
}
}
func serializeEvents(
to []interface{},
i int,
data []outputs.Data,
) ([]outputs.Data, []interface{}) {
succeeded := data
for _, d := range data {
jsonEvent, err := json.Marshal(d.Event)
if err != nil {
logp.Err("Failed to convert the event to JSON (%v): %#v", err, d.Event)
goto failLoop
}
to = append(to, jsonEvent)
i++
}
return succeeded, to
failLoop:
succeeded = data[:i]
rest := data[i+1:]
for _, d := range rest {
jsonEvent, err := json.Marshal(d.Event)
if err != nil {
logp.Err("Failed to convert the event to JSON (%v): %#v", err, d.Event)
i++
continue
}
to = append(to, jsonEvent)
i++
}
return succeeded, to
}