-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
336 lines (277 loc) · 7.24 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
//@deprecated: Starting with version 1.0.0-beta4 the Redis Output is deprecated as
// it's replaced by the Logstash Output that has support for Redis Output plugin.
package redis
import (
"encoding/json"
"errors"
"fmt"
"strings"
"sync/atomic"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/outputs"
"github.com/garyburd/redigo/redis"
)
func init() {
outputs.RegisterOutputPlugin("redis", RedisOutputPlugin{})
}
type RedisOutputPlugin struct{}
func (f RedisOutputPlugin) NewOutput(
config *outputs.MothershipConfig,
topology_expire int,
) (outputs.Outputer, error) {
output := &redisOutput{}
err := output.Init(*config, topology_expire)
if err != nil {
return nil, err
}
return output, nil
}
type redisDataType uint16
const (
RedisListType redisDataType = iota
RedisChannelType
)
type redisOutput struct {
Index string
Conn redis.Conn
TopologyExpire time.Duration
ReconnectInterval time.Duration
Hostname string
Password string
Db int
DbTopology int
Timeout time.Duration
DataType redisDataType
TopologyMap atomic.Value // Value holds a map[string][string]
connected bool
}
type message struct {
trans outputs.Signaler
index string
msg string
}
func (out *redisOutput) Init(config outputs.MothershipConfig, topology_expire int) error {
logp.Warn("Redis Output is deprecated. Please use the Redis Output Plugin from Logstash instead.")
out.Hostname = fmt.Sprintf("%s:%d", config.Host, config.Port)
if config.Password != "" {
out.Password = config.Password
}
if config.Db != 0 {
out.Db = config.Db
}
out.DbTopology = 1
if config.Db_topology != 0 {
out.DbTopology = config.Db_topology
}
out.Timeout = 5 * time.Second
if config.Timeout != 0 {
out.Timeout = time.Duration(config.Timeout) * time.Second
}
out.Index = config.Index
out.ReconnectInterval = time.Duration(1) * time.Second
if config.ReconnectInterval != 0 {
out.ReconnectInterval = time.Duration(config.ReconnectInterval) * time.Second
}
logp.Info("Reconnect Interval set to: %v", out.ReconnectInterval)
expSec := 15
if topology_expire != 0 {
expSec = topology_expire
}
out.TopologyExpire = time.Duration(expSec) * time.Second
switch config.DataType {
case "", "list":
out.DataType = RedisListType
case "channel":
out.DataType = RedisChannelType
default:
return errors.New("Bad Redis data type")
}
logp.Info("[RedisOutput] Using Redis server %s", out.Hostname)
if out.Password != "" {
logp.Info("[RedisOutput] Using password to connect to Redis")
}
logp.Info("[RedisOutput] Redis connection timeout %s", out.Timeout)
logp.Info("[RedisOutput] Redis reconnect interval %s", out.ReconnectInterval)
logp.Info("[RedisOutput] Using index pattern %s", out.Index)
logp.Info("[RedisOutput] Topology expires after %s", out.TopologyExpire)
logp.Info("[RedisOutput] Using db %d for storing events", out.Db)
logp.Info("[RedisOutput] Using db %d for storing topology", out.DbTopology)
logp.Info("[RedisOutput] Using %d data type", out.DataType)
out.Reconnect()
return nil
}
func (out *redisOutput) RedisConnect(db int) (redis.Conn, error) {
conn, err := redis.DialTimeout(
"tcp",
out.Hostname,
out.Timeout, out.Timeout, out.Timeout)
if err != nil {
return nil, err
}
if len(out.Password) > 0 {
_, err = conn.Do("AUTH", out.Password)
if err != nil {
return nil, err
}
}
_, err = conn.Do("PING")
if err != nil {
return nil, err
}
_, err = conn.Do("SELECT", db)
if err != nil {
return nil, err
}
return conn, nil
}
func (out *redisOutput) Connect() error {
var err error
out.Conn, err = out.RedisConnect(out.Db)
if err != nil {
return err
}
out.connected = true
return nil
}
func (out *redisOutput) Close() {
_ = out.Conn.Close()
}
func (out *redisOutput) Reconnect() {
for {
err := out.Connect()
if err != nil {
logp.Warn("Error connecting to Redis (%s). Retrying in %s", err, out.ReconnectInterval)
time.Sleep(out.ReconnectInterval)
} else {
break
}
}
}
func (out *redisOutput) GetNameByIP(ip string) string {
topologyMap, ok := out.TopologyMap.Load().(map[string]string)
if ok {
name, exists := topologyMap[ip]
if exists {
return name
}
}
return ""
}
func (out *redisOutput) PublishIPs(name string, localAddrs []string) error {
logp.Debug("output_redis", "[%s] Publish the IPs %s", name, localAddrs)
// connect to db
conn, err := out.RedisConnect(out.DbTopology)
if err != nil {
return err
}
defer func() { _ = conn.Close() }()
_, err = conn.Do("HSET", name, "ipaddrs", strings.Join(localAddrs, ","))
if err != nil {
logp.Err("[%s] Fail to set the IP addresses: %s", name, err)
return err
}
_, err = conn.Do("EXPIRE", name, int(out.TopologyExpire.Seconds()))
if err != nil {
logp.Err("[%s] Fail to set the expiration time: %s", name, err)
return err
}
out.UpdateLocalTopologyMap(conn)
return nil
}
func (out *redisOutput) UpdateLocalTopologyMap(conn redis.Conn) {
topologyMapTmp := make(map[string]string)
hostnames, err := redis.Strings(conn.Do("KEYS", "*"))
if err != nil {
logp.Err("Fail to get the all shippers from the topology map %s", err)
return
}
for _, hostname := range hostnames {
res, err := redis.String(conn.Do("HGET", hostname, "ipaddrs"))
if err != nil {
logp.Err("[%s] Fail to get the IPs: %s", hostname, err)
} else {
ipaddrs := strings.Split(res, ",")
for _, addr := range ipaddrs {
topologyMapTmp[addr] = hostname
}
}
}
out.TopologyMap.Store(topologyMapTmp)
logp.Debug("output_redis", "Topology %s", topologyMapTmp)
}
func (out *redisOutput) PublishEvent(
signal outputs.Signaler,
opts outputs.Options,
event common.MapStr,
) error {
return out.BulkPublish(signal, opts, []common.MapStr{event})
}
func (out *redisOutput) BulkPublish(
signal outputs.Signaler,
opts outputs.Options,
events []common.MapStr,
) error {
if !opts.Guaranteed {
err := out.doBulkPublish(events)
outputs.Signal(signal, err)
return err
}
for {
err := out.doBulkPublish(events)
if err == nil {
outputs.SignalCompleted(signal)
return nil
}
// TODO: add backoff
time.Sleep(1)
}
}
func (out *redisOutput) doBulkPublish(events []common.MapStr) error {
if !out.connected {
logp.Debug("output_redis", "Droping pkt ...")
return errors.New("Not connected")
}
command := "RPUSH"
if out.DataType == RedisChannelType {
command = "PUBLISH"
}
if len(events) == 1 { // single event
event := events[0]
jsonEvent, err := json.Marshal(event)
if err != nil {
logp.Err("Fail to convert the event to JSON: %s", err)
return err
}
_, err = out.Conn.Do(command, out.Index, string(jsonEvent))
out.onFail(err)
return err
}
for _, event := range events {
jsonEvent, err := json.Marshal(event)
if err != nil {
logp.Err("Fail to convert the event to JSON: %s", err)
continue
}
err = out.Conn.Send(command, out.Index, string(jsonEvent))
if err != nil {
out.onFail(err)
return err
}
}
if err := out.Conn.Flush(); err != nil {
out.onFail(err)
return err
}
_, err := out.Conn.Receive()
out.onFail(err)
return err
}
func (out *redisOutput) onFail(err error) {
if err != nil {
logp.Err("Fail to publish event to REDIS: %s", err)
out.connected = false
go out.Reconnect()
}
}