/
redis_sentinel.go
439 lines (347 loc) · 10.5 KB
/
redis_sentinel.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
//go:generate ../../../tools/readme_config_includer/generator
package redis_sentinel
import (
"bufio"
_ "embed"
"fmt"
"io"
"net/url"
"strconv"
"strings"
"sync"
"github.com/go-redis/redis/v7"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
//go:embed sample.conf
var sampleConfig string
type RedisSentinel struct {
Servers []string `toml:"servers"`
tls.ClientConfig
clients []*RedisSentinelClient
}
type RedisSentinelClient struct {
sentinel *redis.SentinelClient
tags map[string]string
}
const measurementMasters = "redis_sentinel_masters"
const measurementSentinel = "redis_sentinel"
const measurementSentinels = "redis_sentinel_sentinels"
const measurementReplicas = "redis_sentinel_replicas"
func init() {
inputs.Add("redis_sentinel", func() telegraf.Input {
return &RedisSentinel{}
})
}
func (*RedisSentinel) SampleConfig() string {
return sampleConfig
}
func (r *RedisSentinel) Init() error {
if len(r.Servers) == 0 {
r.Servers = []string{"tcp://localhost:26379"}
}
r.clients = make([]*RedisSentinelClient, len(r.Servers))
tlsConfig, err := r.ClientConfig.TLSConfig()
if err != nil {
return err
}
for i, serv := range r.Servers {
u, err := url.Parse(serv)
if err != nil {
return fmt.Errorf("unable to parse to address %q: %v", serv, err)
}
password := ""
if u.User != nil {
password, _ = u.User.Password()
}
var address string
tags := map[string]string{}
switch u.Scheme {
case "tcp":
address = u.Host
tags["source"] = u.Hostname()
tags["port"] = u.Port()
case "unix":
address = u.Path
tags["socket"] = u.Path
default:
return fmt.Errorf("invalid scheme %q, expected tcp or unix", u.Scheme)
}
sentinel := redis.NewSentinelClient(
&redis.Options{
Addr: address,
Password: password,
Network: u.Scheme,
PoolSize: 1,
TLSConfig: tlsConfig,
},
)
r.clients[i] = &RedisSentinelClient{
sentinel: sentinel,
tags: tags,
}
}
return nil
}
// Redis list format has string key/values adjacent, so convert to a map for easier use
func toMap(vals []interface{}) map[string]string {
m := make(map[string]string)
for idx := 0; idx < len(vals)-1; idx += 2 {
key, keyOk := vals[idx].(string)
value, valueOk := vals[idx+1].(string)
if keyOk && valueOk {
m[key] = value
}
}
return m
}
func castFieldValue(value string, fieldType configFieldType) (interface{}, error) {
var castedValue interface{}
var err error
switch fieldType {
case configFieldTypeFloat:
castedValue, err = strconv.ParseFloat(value, 64)
case configFieldTypeInteger:
castedValue, err = strconv.ParseInt(value, 10, 64)
case configFieldTypeString:
castedValue = value
default:
return nil, fmt.Errorf("unsupported field type %v", fieldType)
}
if err != nil {
return nil, fmt.Errorf("casting value %v failed: %v", value, err)
}
return castedValue, nil
}
func prepareFieldValues(fields map[string]string, typeMap map[string]configFieldType) (map[string]interface{}, error) {
preparedFields := make(map[string]interface{})
for key, val := range fields {
key = strings.ReplaceAll(key, "-", "_")
valType, ok := typeMap[key]
if !ok {
continue
}
castedVal, err := castFieldValue(val, valType)
if err != nil {
return nil, err
}
preparedFields[key] = castedVal
}
return preparedFields, nil
}
// Reads stats from all configured servers accumulates stats.
// Returns one of the errors encountered while gather stats (if any).
func (r *RedisSentinel) Gather(acc telegraf.Accumulator) error {
var wg sync.WaitGroup
for _, client := range r.clients {
wg.Add(1)
go func(acc telegraf.Accumulator, client *RedisSentinelClient) {
defer wg.Done()
masters, err := client.gatherMasterStats(acc)
acc.AddError(err)
for _, master := range masters {
acc.AddError(client.gatherReplicaStats(acc, master))
acc.AddError(client.gatherSentinelStats(acc, master))
}
acc.AddError(client.gatherInfoStats(acc))
}(acc, client)
}
wg.Wait()
return nil
}
func (client *RedisSentinelClient) gatherInfoStats(acc telegraf.Accumulator) error {
infoCmd := redis.NewStringCmd("info", "all")
if err := client.sentinel.Process(infoCmd); err != nil {
return err
}
info, err := infoCmd.Result()
if err != nil {
return err
}
rdr := strings.NewReader(info)
infoTags, infoFields, err := convertSentinelInfoOutput(client.tags, rdr)
if err != nil {
return err
}
acc.AddFields(measurementSentinel, infoFields, infoTags)
return nil
}
func (client *RedisSentinelClient) gatherMasterStats(acc telegraf.Accumulator) ([]string, error) {
var masterNames []string
mastersCmd := redis.NewSliceCmd("sentinel", "masters")
if err := client.sentinel.Process(mastersCmd); err != nil {
return masterNames, err
}
masters, err := mastersCmd.Result()
if err != nil {
return masterNames, err
}
// Break out of the loop if one of the items comes out malformed
// It's safe to assume that if we fail parsing one item that the rest will fail too
// This is because we are iterating over a single server response
for _, master := range masters {
master, ok := master.([]interface{})
if !ok {
return masterNames, fmt.Errorf("unable to process master response")
}
m := toMap(master)
masterName, ok := m["name"]
if !ok {
return masterNames, fmt.Errorf("unable to resolve master name")
}
masterNames = append(masterNames, masterName)
quorumCmd := redis.NewStringCmd("sentinel", "ckquorum", masterName)
quorumErr := client.sentinel.Process(quorumCmd)
sentinelMastersTags, sentinelMastersFields, err := convertSentinelMastersOutput(client.tags, m, quorumErr)
if err != nil {
return masterNames, err
}
acc.AddFields(measurementMasters, sentinelMastersFields, sentinelMastersTags)
}
return masterNames, nil
}
func (client *RedisSentinelClient) gatherReplicaStats(acc telegraf.Accumulator, masterName string) error {
replicasCmd := redis.NewSliceCmd("sentinel", "replicas", masterName)
if err := client.sentinel.Process(replicasCmd); err != nil {
return err
}
replicas, err := replicasCmd.Result()
if err != nil {
return err
}
// Break out of the loop if one of the items comes out malformed
// It's safe to assume that if we fail parsing one item that the rest will fail too
// This is because we are iterating over a single server response
for _, replica := range replicas {
replica, ok := replica.([]interface{})
if !ok {
return fmt.Errorf("unable to process replica response")
}
rm := toMap(replica)
replicaTags, replicaFields, err := convertSentinelReplicaOutput(client.tags, masterName, rm)
if err != nil {
return err
}
acc.AddFields(measurementReplicas, replicaFields, replicaTags)
}
return nil
}
func (client *RedisSentinelClient) gatherSentinelStats(acc telegraf.Accumulator, masterName string) error {
sentinelsCmd := redis.NewSliceCmd("sentinel", "sentinels", masterName)
if err := client.sentinel.Process(sentinelsCmd); err != nil {
return err
}
sentinels, err := sentinelsCmd.Result()
if err != nil {
return err
}
// Break out of the loop if one of the items comes out malformed
// It's safe to assume that if we fail parsing one item that the rest will fail too
// This is because we are iterating over a single server response
for _, sentinel := range sentinels {
sentinel, ok := sentinel.([]interface{})
if !ok {
return fmt.Errorf("unable to process sentinel response")
}
sm := toMap(sentinel)
sentinelTags, sentinelFields, err := convertSentinelSentinelsOutput(client.tags, masterName, sm)
if err != nil {
return err
}
acc.AddFields(measurementSentinels, sentinelFields, sentinelTags)
}
return nil
}
// converts `sentinel masters <name>` output to tags and fields
func convertSentinelMastersOutput(
globalTags map[string]string,
master map[string]string,
quorumErr error,
) (map[string]string, map[string]interface{}, error) {
tags := globalTags
tags["master"] = master["name"]
fields, err := prepareFieldValues(master, measurementMastersFields)
if err != nil {
return nil, nil, err
}
fields["has_quorum"] = quorumErr == nil
return tags, fields, nil
}
// converts `sentinel sentinels <name>` output to tags and fields
func convertSentinelSentinelsOutput(
globalTags map[string]string,
masterName string,
sentinelMaster map[string]string,
) (map[string]string, map[string]interface{}, error) {
tags := globalTags
tags["sentinel_ip"] = sentinelMaster["ip"]
tags["sentinel_port"] = sentinelMaster["port"]
tags["master"] = masterName
fields, err := prepareFieldValues(sentinelMaster, measurementSentinelsFields)
if err != nil {
return nil, nil, err
}
return tags, fields, nil
}
// converts `sentinel replicas <name>` output to tags and fields
func convertSentinelReplicaOutput(
globalTags map[string]string,
masterName string,
replica map[string]string,
) (map[string]string, map[string]interface{}, error) {
tags := globalTags
tags["replica_ip"] = replica["ip"]
tags["replica_port"] = replica["port"]
tags["master"] = masterName
fields, err := prepareFieldValues(replica, measurementReplicasFields)
if err != nil {
return nil, nil, err
}
return tags, fields, nil
}
// convertSentinelInfoOutput parses `INFO` command output
// Largely copied from the Redis input plugin's gatherInfoOutput()
func convertSentinelInfoOutput(
globalTags map[string]string,
rdr io.Reader,
) (map[string]string, map[string]interface{}, error) {
scanner := bufio.NewScanner(rdr)
rawFields := make(map[string]string)
tags := globalTags
for scanner.Scan() {
line := scanner.Text()
if len(line) == 0 {
continue
}
// Redis denotes configuration sections with a hashtag
// Example of the section header: # Clients
if line[0] == '#' {
// Nothing interesting here
continue
}
parts := strings.SplitN(line, ":", 2)
if len(parts) < 2 {
// Not a valid configuration option
continue
}
key := strings.TrimSpace(parts[0])
val := strings.TrimSpace(parts[1])
rawFields[key] = val
}
fields, err := prepareFieldValues(rawFields, measurementSentinelFields)
if err != nil {
return nil, nil, err
}
// Rename the field and convert it to nanoseconds
secs, ok := fields["uptime_in_seconds"].(int64)
if !ok {
return nil, nil, fmt.Errorf("uptime type %T is not int64", fields["uptime_in_seconds"])
}
fields["uptime_ns"] = secs * 1000_000_000
delete(fields, "uptime_in_seconds")
// Rename in order to match the "redis" input plugin
fields["clients"] = fields["connected_clients"]
delete(fields, "connected_clients")
return tags, fields, nil
}