forked from oliver006/redis_exporter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
redis.go
509 lines (440 loc) · 12.9 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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package exporter
import (
"fmt"
"log"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/garyburd/redigo/redis"
"github.com/prometheus/client_golang/prometheus"
)
// RedisHost represents a set of Redis Hosts to health check.
type RedisHost struct {
Addrs []string
Passwords []string
}
type dbKeyPair struct {
db, key string
}
// Exporter implementes the prometheus.Exporter interface, and exports Redis metrics.
type Exporter struct {
redis RedisHost
namespace string
keys []dbKeyPair
keyValues *prometheus.GaugeVec
keySizes *prometheus.GaugeVec
duration prometheus.Gauge
scrapeErrors prometheus.Gauge
totalScrapes prometheus.Counter
metrics map[string]*prometheus.GaugeVec
metricsMtx sync.RWMutex
sync.RWMutex
}
type scrapeResult struct {
Name string
Value float64
Addr string
DB string
}
var (
metricMap = map[string]string{
// # Server
"uptime_in_seconds": "uptime_in_seconds",
// # Clients
"connected_clients": "connected_clients",
"blocked_clients": "blocked_clients",
// # Memory
"used_memory": "memory_used_bytes",
"used_memory_rss": "memory_used_rss_bytes",
"used_memory_peak": "memory_used_peak_bytes",
"used_memory_lua": "memory_used_lua_bytes",
"max_memory": "memory_max_bytes",
"mem_fragmentation_ratio": "memory_fragmentation_ratio",
// # Persistence
"rdb_changes_since_last_save": "rdb_changes_since_last_save",
"rdb_last_bgsave_time_sec": "rdb_last_bgsave_duration_sec",
"rdb_current_bgsave_time_sec": "rdb_current_bgsave_duration_sec",
"aof_enabled": "aof_enabled",
"aof_rewrite_in_progress": "aof_rewrite_in_progress",
"aof_rewrite_scheduled": "aof_rewrite_scheduled",
"aof_last_rewrite_time_sec": "aof_last_rewrite_duration_sec",
"aof_current_rewrite_time_sec": "aof_current_rewrite_duration_sec",
// # Stats
"total_connections_received": "connections_received_total",
"total_commands_processed": "commands_processed_total",
"total_net_input_bytes": "net_input_bytes_total",
"total_net_output_bytes": "net_output_bytes_total",
"rejected_connections": "rejected_connections_total",
"expired_keys": "expired_keys_total",
"evicted_keys": "evicted_keys_total",
"keyspace_hits": "keyspace_hits_total",
"keyspace_misses": "keyspace_misses_total",
"pubsub_channels": "pubsub_channels",
"pubsub_patterns": "pubsub_patterns",
// # Replication
"loading": "loading_dump_file",
"connected_slaves": "connected_slaves",
"repl_backlog_size": "replication_backlog_bytes",
// # CPU
"used_cpu_sys": "used_cpu_sys",
"used_cpu_user": "used_cpu_user",
"used_cpu_sys_children": "used_cpu_sys_children",
"used_cpu_user_children": "used_cpu_user_children",
}
)
func (e *Exporter) initGauges() {
e.metrics = map[string]*prometheus.GaugeVec{}
e.metrics["db_keys"] = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: e.namespace,
Name: "db_keys",
Help: "Total number of keys by DB",
}, []string{"addr", "db"})
e.metrics["db_keys_expiring"] = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: e.namespace,
Name: "db_keys_expiring",
Help: "Total number of expiring keys by DB",
}, []string{"addr", "db"})
e.metrics["db_avg_ttl_seconds"] = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: e.namespace,
Name: "db_avg_ttl_seconds",
Help: "Avg TTL in seconds",
}, []string{"addr", "db"})
// Emulate a Summary.
e.metrics["command_call_duration_seconds_count"] = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: e.namespace,
Name: "command_call_duration_seconds_count",
Help: "Total number of calls per command",
}, []string{"addr", "cmd"})
e.metrics["command_call_duration_seconds_sum"] = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: e.namespace,
Name: "command_call_duration_seconds_sum",
Help: "Total amount of time in seconds spent per command",
}, []string{"addr", "cmd"})
}
// NewRedisExporter returns a new exporter of Redis metrics.
// note to self: next time we add an argument, instead add a RedisExporter struct
func NewRedisExporter(redis RedisHost, namespace, checkKeys string) (*Exporter, error) {
for _, addr := range redis.Addrs {
parts := strings.Split(addr, ":")
if len(parts) != 2 {
return nil, fmt.Errorf("Invalid parameter --redis.addr: %s", addr)
}
}
e := Exporter{
redis: redis,
namespace: namespace,
keyValues: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "key_value",
Help: "The value of \"key\"",
}, []string{"db", "key"}),
keySizes: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "key_size",
Help: "The length or size of \"key\"",
}, []string{"db", "key"}),
duration: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "exporter_last_scrape_duration_seconds",
Help: "The last scrape duration.",
}),
totalScrapes: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "exporter_scrapes_total",
Help: "Current total redis scrapes.",
}),
scrapeErrors: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "exporter_last_scrape_error",
Help: "The last scrape error status.",
}),
}
var err error
for _, k := range strings.Split(checkKeys, ",") {
db := "0"
key := ""
frags := strings.Split(k, "=")
switch len(frags) {
case 1:
db = "0"
key, err = url.QueryUnescape(strings.TrimSpace(frags[0]))
case 2:
db = strings.Replace(strings.TrimSpace(frags[0]), "db", "", -1)
key, err = url.QueryUnescape(strings.TrimSpace(frags[1]))
default:
err = fmt.Errorf("")
}
if err != nil {
log.Printf("Couldn't parse db/key string: %s", k)
continue
}
e.keys = append(e.keys, dbKeyPair{db, key})
}
e.initGauges()
return &e, nil
}
// Describe outputs Redis metric descriptions.
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
for _, m := range e.metrics {
m.Describe(ch)
}
e.keySizes.Describe(ch)
e.keyValues.Describe(ch)
ch <- e.duration.Desc()
ch <- e.totalScrapes.Desc()
ch <- e.scrapeErrors.Desc()
}
// Collect fetches new metrics from the RedisHost and updates the appropriate metrics.
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
scrapes := make(chan scrapeResult)
e.Lock()
defer e.Unlock()
e.initGauges()
go e.scrape(scrapes)
e.setMetrics(scrapes)
e.keySizes.Collect(ch)
e.keyValues.Collect(ch)
ch <- e.duration
ch <- e.totalScrapes
ch <- e.scrapeErrors
e.collectMetrics(ch)
}
func includeMetric(s string) bool {
if strings.HasPrefix(s, "db") || strings.HasPrefix(s, "cmdstat_") || strings.HasPrefix(s, "cluster_") {
return true
}
_, ok := metricMap[s]
return ok
}
func extractVal(s string) (val float64, err error) {
split := strings.Split(s, "=")
if len(split) != 2 {
return 0, fmt.Errorf("nope")
}
val, err = strconv.ParseFloat(split[1], 64)
if err != nil {
return 0, fmt.Errorf("nope")
}
return
}
/*
valid example: db0:keys=1,expires=0,avg_ttl=0
*/
func parseDBKeyspaceString(db string, stats string) (keysTotal float64, keysExpiringTotal float64, avgTTL float64, ok bool) {
ok = false
if !strings.HasPrefix(db, "db") {
return
}
split := strings.Split(stats, ",")
if len(split) != 3 && len(split) != 2 {
return
}
var err error
ok = true
if keysTotal, err = extractVal(split[0]); err != nil {
ok = false
return
}
if keysExpiringTotal, err = extractVal(split[1]); err != nil {
ok = false
return
}
avgTTL = -1
if len(split) > 2 {
if avgTTL, err = extractVal(split[2]); err != nil {
ok = false
return
}
avgTTL /= 1000
}
return
}
func (e *Exporter) extractInfoMetrics(info, addr string, scrapes chan<- scrapeResult) error {
cmdstats := false
lines := strings.Split(info, "\r\n")
for _, line := range lines {
if len(line) > 0 && line[0] == '#' {
if strings.Contains(line, "Commandstats") {
cmdstats = true
}
continue
}
if (len(line) < 2) || (!strings.Contains(line, ":")) {
cmdstats = false
continue
}
split := strings.Split(line, ":")
if len(split) != 2 || !includeMetric(split[0]) {
continue
}
if cmdstats {
/*
cmdstat_get:calls=21,usec=175,usec_per_call=8.33
cmdstat_set:calls=61,usec=3139,usec_per_call=51.46
cmdstat_setex:calls=75,usec=1260,usec_per_call=16.80
*/
frags := strings.Split(split[0], "_")
if len(frags) != 2 {
continue
}
cmd := frags[1]
frags = strings.Split(split[1], ",")
if len(frags) != 3 {
continue
}
var calls float64
var usecTotal float64
var err error
if calls, err = extractVal(frags[0]); err != nil {
continue
}
if usecTotal, err = extractVal(frags[1]); err != nil {
continue
}
e.metricsMtx.RLock()
e.metrics["command_call_duration_seconds_count"].WithLabelValues(addr, cmd).Set(calls)
e.metrics["command_call_duration_seconds_sum"].WithLabelValues(addr, cmd).Set(usecTotal / 1e6)
e.metricsMtx.RUnlock()
continue
}
if keysTotal, keysEx, avgTTL, ok := parseDBKeyspaceString(split[0], split[1]); ok {
scrapes <- scrapeResult{Name: "db_keys", Addr: addr, DB: split[0], Value: keysTotal}
scrapes <- scrapeResult{Name: "db_keys_expiring", Addr: addr, DB: split[0], Value: keysEx}
if avgTTL > -1 {
scrapes <- scrapeResult{Name: "db_avg_ttl_seconds", Addr: addr, DB: split[0], Value: avgTTL}
}
continue
}
metricName := split[0]
if newName, ok := metricMap[metricName]; ok {
metricName = newName
}
var err error
var val float64
switch split[1] {
case "ok":
val = 1
case "fail":
val = 0
default:
val, err = strconv.ParseFloat(split[1], 64)
}
if err != nil {
log.Printf("couldn't parse %s, err: %s", split[1], err)
continue
}
scrapes <- scrapeResult{Name: metricName, Addr: addr, Value: val}
}
return nil
}
func extractConfigMetrics(config []string, addr string, scrapes chan<- scrapeResult) error {
if len(config)%2 != 0 {
return fmt.Errorf("invalid config: %#v", config)
}
for pos := 0; pos < len(config)/2; pos++ {
val, err := strconv.ParseFloat(config[pos*2+1], 64)
if err != nil {
log.Printf("couldn't parse %s, err: %s", config[pos*2+1], err)
continue
}
scrapes <- scrapeResult{Name: fmt.Sprintf("config_%s", config[pos*2]), Addr: addr, Value: val}
}
return nil
}
func (e *Exporter) scrape(scrapes chan<- scrapeResult) {
defer close(scrapes)
now := time.Now().UnixNano()
e.totalScrapes.Inc()
errorCount := 0
for idx, addr := range e.redis.Addrs {
split := strings.Split(addr, "://")
proto := "tcp"
realAddr := addr
if len(split) == 2 {
proto = strings.TrimSpace(split[0])
realAddr = strings.TrimSpace(split[1])
}
c, err := redis.Dial(proto, realAddr)
if err != nil {
log.Printf("redis err: %s", err)
errorCount++
continue
}
defer c.Close()
if len(e.redis.Passwords) > idx && e.redis.Passwords[idx] != "" {
if _, err := c.Do("AUTH", e.redis.Passwords[idx]); err != nil {
log.Printf("redis err: %s", err)
errorCount++
continue
}
}
info, err := redis.String(c.Do("INFO", "ALL"))
if err == nil {
err = e.extractInfoMetrics(info, addr, scrapes)
}
if err != nil {
log.Printf("redis err: %s", err)
errorCount++
continue
}
config, err := redis.Strings(c.Do("CONFIG", "GET", "maxmemory"))
if err == nil {
err = extractConfigMetrics(config, addr, scrapes)
}
if err != nil {
log.Printf("redis err: %s", err)
errorCount++
continue
}
for _, k := range e.keys {
if _, err := c.Do("SELECT", k.db); err != nil {
continue
}
if tempVal, err := c.Do("GET", k.key); err == nil && tempVal != nil {
if val, err := strconv.ParseFloat(fmt.Sprintf("%s", tempVal), 64); err == nil {
e.keyValues.WithLabelValues("db"+k.db, k.key).Set(val)
}
}
for _, op := range []string{
"HLEN",
"LLEN",
"SCARD",
"ZCARD",
"PFCOUNT",
"STRLEN",
} {
if tempVal, err := c.Do(op, k.key); err == nil && tempVal != nil {
e.keySizes.WithLabelValues("db"+k.db, k.key).Set(float64(tempVal.(int64)))
break
}
}
}
}
e.scrapeErrors.Set(float64(errorCount))
e.duration.Set(float64(time.Now().UnixNano()-now) / 1000000000)
}
func (e *Exporter) setMetrics(scrapes <-chan scrapeResult) {
for scr := range scrapes {
name := scr.Name
if _, ok := e.metrics[name]; !ok {
e.metricsMtx.Lock()
e.metrics[name] = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: e.namespace,
Name: name,
}, []string{"addr"})
e.metricsMtx.Unlock()
}
var labels prometheus.Labels = map[string]string{"addr": scr.Addr}
if len(scr.DB) > 0 {
labels["db"] = scr.DB
}
e.metrics[name].With(labels).Set(float64(scr.Value))
}
}
func (e *Exporter) collectMetrics(metrics chan<- prometheus.Metric) {
for _, m := range e.metrics {
m.Collect(metrics)
}
}