redis plugin: Report keyspace hitratio
[collectd.git] / src / redis.c
1 /**
2  * collectd - src/redis.c, based on src/memcached.c
3  * Copyright (C) 2010       Andrés J. Díaz <ajdiaz@connectical.com>
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Andrés J. Díaz <ajdiaz@connectical.com>
21  **/
22
23 #include "collectd.h"
24
25 #include "common.h"
26 #include "plugin.h"
27
28 #include <hiredis/hiredis.h>
29 #include <sys/time.h>
30
31 #define REDIS_DEF_HOST "localhost"
32 #define REDIS_DEF_PASSWD ""
33 #define REDIS_DEF_PORT 6379
34 #define REDIS_DEF_TIMEOUT_SEC 2
35 #define REDIS_DEF_DB_COUNT 256
36 #define MAX_REDIS_VAL_SIZE 256
37 #define MAX_REDIS_QUERY 2048
38
39 /* Redis plugin configuration example:
40  *
41  * <Plugin redis>
42  *   <Node "mynode">
43  *     Host "localhost"
44  *     Port "6379"
45  *     Timeout 2
46  *     Password "foobar"
47  *   </Node>
48  * </Plugin>
49  */
50
51 struct redis_query_s;
52 typedef struct redis_query_s redis_query_t;
53 struct redis_query_s {
54   char query[MAX_REDIS_QUERY];
55   char type[DATA_MAX_NAME_LEN];
56   char instance[DATA_MAX_NAME_LEN];
57   int database;
58
59   redis_query_t *next;
60 };
61
62 struct prev_s {
63   derive_t keyspace_hits;
64   derive_t keyspace_misses;
65 };
66 typedef struct prev_s prev_t;
67
68 struct redis_node_s;
69 typedef struct redis_node_s redis_node_t;
70 struct redis_node_s {
71   char *name;
72   char *host;
73   char *passwd;
74   int port;
75   struct timeval timeout;
76   bool report_command_stats;
77   bool report_cpu_usage;
78   redisContext *redisContext;
79   redis_query_t *queries;
80   prev_t prev;
81
82   redis_node_t *next;
83 };
84
85 static bool redis_have_instances;
86 static int redis_read(user_data_t *user_data);
87
88 static void redis_node_free(void *arg) {
89   redis_node_t *rn = arg;
90   if (rn == NULL)
91     return;
92
93   redis_query_t *rq = rn->queries;
94   while (rq != NULL) {
95     redis_query_t *next = rq->next;
96     sfree(rq);
97     rq = next;
98   }
99
100   redisFree(rn->redisContext);
101   sfree(rn->name);
102   sfree(rn->host);
103   sfree(rn->passwd);
104   sfree(rn);
105 } /* void redis_node_free */
106
107 static int redis_node_add(redis_node_t *rn) /* {{{ */
108 {
109   DEBUG("redis plugin: Adding node \"%s\".", rn->name);
110
111   /* Disable automatic generation of default instance in the init callback. */
112   redis_have_instances = true;
113
114   char cb_name[sizeof("redis/") + DATA_MAX_NAME_LEN];
115   snprintf(cb_name, sizeof(cb_name), "redis/%s", rn->name);
116
117   return plugin_register_complex_read(
118       /* group = */ "redis",
119       /* name      = */ cb_name,
120       /* callback  = */ redis_read,
121       /* interval  = */ 0,
122       &(user_data_t){
123           .data = rn, .free_func = redis_node_free,
124       });
125 } /* }}} */
126
127 static redis_query_t *redis_config_query(oconfig_item_t *ci) /* {{{ */
128 {
129   redis_query_t *rq;
130   int status;
131
132   rq = calloc(1, sizeof(*rq));
133   if (rq == NULL) {
134     ERROR("redis plugin: calloc failed adding redis_query.");
135     return NULL;
136   }
137   status = cf_util_get_string_buffer(ci, rq->query, sizeof(rq->query));
138   if (status != 0)
139     goto err;
140
141   /*
142    * Default to a gauge type.
143    */
144   (void)strncpy(rq->type, "gauge", sizeof(rq->type));
145   (void)sstrncpy(rq->instance, rq->query, sizeof(rq->instance));
146   replace_special(rq->instance, sizeof(rq->instance));
147
148   rq->database = 0;
149
150   for (int i = 0; i < ci->children_num; i++) {
151     oconfig_item_t *option = ci->children + i;
152
153     if (strcasecmp("Type", option->key) == 0) {
154       status = cf_util_get_string_buffer(option, rq->type, sizeof(rq->type));
155     } else if (strcasecmp("Instance", option->key) == 0) {
156       status =
157           cf_util_get_string_buffer(option, rq->instance, sizeof(rq->instance));
158     } else if (strcasecmp("Database", option->key) == 0) {
159       status = cf_util_get_int(option, &rq->database);
160       if (rq->database < 0) {
161         WARNING("redis plugin: The \"Database\" option must be positive "
162                 "integer or zero");
163         status = -1;
164       }
165     } else {
166       WARNING("redis plugin: unknown configuration option: %s", option->key);
167       status = -1;
168     }
169     if (status != 0)
170       goto err;
171   }
172   return rq;
173 err:
174   free(rq);
175   return NULL;
176 } /* }}} */
177
178 static int redis_config_node(oconfig_item_t *ci) /* {{{ */
179 {
180   redis_node_t *rn = calloc(1, sizeof(*rn));
181   if (rn == NULL) {
182     ERROR("redis plugin: calloc failed adding node.");
183     return ENOMEM;
184   }
185
186   rn->port = REDIS_DEF_PORT;
187   rn->timeout.tv_sec = REDIS_DEF_TIMEOUT_SEC;
188   rn->report_cpu_usage = true;
189
190   rn->host = strdup(REDIS_DEF_HOST);
191   if (rn->host == NULL) {
192     ERROR("redis plugin: strdup failed adding node.");
193     sfree(rn);
194     return ENOMEM;
195   }
196
197   int status = cf_util_get_string(ci, &rn->name);
198   if (status != 0) {
199     sfree(rn->host);
200     sfree(rn);
201     return status;
202   }
203
204   for (int i = 0; i < ci->children_num; i++) {
205     oconfig_item_t *option = ci->children + i;
206
207     if (strcasecmp("Host", option->key) == 0)
208       status = cf_util_get_string(option, &rn->host);
209     else if (strcasecmp("Port", option->key) == 0) {
210       status = cf_util_get_port_number(option);
211       if (status > 0) {
212         rn->port = status;
213         status = 0;
214       }
215     } else if (strcasecmp("Query", option->key) == 0) {
216       redis_query_t *rq = redis_config_query(option);
217       if (rq == NULL) {
218         status = 1;
219       } else {
220         rq->next = rn->queries;
221         rn->queries = rq;
222       }
223     } else if (strcasecmp("Timeout", option->key) == 0) {
224       int timeout;
225       status = cf_util_get_int(option, &timeout);
226       if (status == 0) {
227         rn->timeout.tv_usec = timeout * 1000;
228         rn->timeout.tv_sec = rn->timeout.tv_usec / 1000000L;
229         rn->timeout.tv_usec %= 1000000L;
230       }
231     } else if (strcasecmp("Password", option->key) == 0)
232       status = cf_util_get_string(option, &rn->passwd);
233     else if (strcasecmp("ReportCommandStats", option->key) == 0)
234       status = cf_util_get_boolean(option, &rn->report_command_stats);
235     else if (strcasecmp("ReportCpuUsage", option->key) == 0)
236       status = cf_util_get_boolean(option, &rn->report_cpu_usage);
237     else
238       WARNING("redis plugin: Option `%s' not allowed inside a `Node' "
239               "block. I'll ignore this option.",
240               option->key);
241
242     if (status != 0)
243       break;
244   }
245
246   if (status != 0) {
247     redis_node_free(rn);
248     return status;
249   }
250
251   return redis_node_add(rn);
252 } /* }}} int redis_config_node */
253
254 static int redis_config(oconfig_item_t *ci) /* {{{ */
255 {
256   for (int i = 0; i < ci->children_num; i++) {
257     oconfig_item_t *option = ci->children + i;
258
259     if (strcasecmp("Node", option->key) == 0)
260       redis_config_node(option);
261     else
262       WARNING("redis plugin: Option `%s' not allowed in redis"
263               " configuration. It will be ignored.",
264               option->key);
265   }
266
267   return 0;
268 } /* }}} */
269
270 __attribute__((nonnull(2))) static void
271 redis_submit(const char *plugin_instance, const char *type,
272              const char *type_instance, value_t value) /* {{{ */
273 {
274   value_list_t vl = VALUE_LIST_INIT;
275
276   vl.values = &value;
277   vl.values_len = 1;
278   sstrncpy(vl.plugin, "redis", sizeof(vl.plugin));
279   if (plugin_instance != NULL)
280     sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
281   sstrncpy(vl.type, type, sizeof(vl.type));
282   if (type_instance != NULL)
283     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
284
285   plugin_dispatch_values(&vl);
286 } /* }}} */
287
288 __attribute__((nonnull(2))) static void
289 redis_submit2(const char *plugin_instance, const char *type,
290               const char *type_instance, value_t value0,
291               value_t value1) /* {{{ */
292 {
293   value_list_t vl = VALUE_LIST_INIT;
294   value_t values[] = {value0, value1};
295
296   vl.values = values;
297   vl.values_len = STATIC_ARRAY_SIZE(values);
298
299   sstrncpy(vl.plugin, "redis", sizeof(vl.plugin));
300   sstrncpy(vl.type, type, sizeof(vl.type));
301
302   if (plugin_instance != NULL)
303     sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
304
305   if (type_instance != NULL)
306     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
307
308   plugin_dispatch_values(&vl);
309 } /* }}} */
310
311 static int redis_init(void) /* {{{ */
312 {
313   if (redis_have_instances)
314     return 0;
315
316   redis_node_t *rn = calloc(1, sizeof(*rn));
317   if (rn == NULL)
318     return ENOMEM;
319
320   rn->port = REDIS_DEF_PORT;
321   rn->timeout.tv_sec = REDIS_DEF_TIMEOUT_SEC;
322
323   rn->name = strdup("default");
324   rn->host = strdup(REDIS_DEF_HOST);
325
326   if (rn->name == NULL || rn->host == NULL) {
327     sfree(rn->name);
328     sfree(rn->host);
329     sfree(rn);
330     return ENOMEM;
331   }
332
333   return redis_node_add(rn);
334 } /* }}} int redis_init */
335
336 static void *c_redisCommand(redis_node_t *rn, const char *format, ...) {
337   redisContext *c = rn->redisContext;
338
339   if (c == NULL)
340     return NULL;
341
342   va_list ap;
343   va_start(ap, format);
344   void *reply = redisvCommand(c, format, ap);
345   va_end(ap);
346
347   if (reply == NULL) {
348     ERROR("redis plugin: Connection error: %s", c->errstr);
349     redisFree(rn->redisContext);
350     rn->redisContext = NULL;
351   }
352
353   return reply;
354 } /* void c_redisCommand */
355
356 static int redis_get_info_value(char const *info_line, char const *field_name,
357                                 int ds_type, value_t *val) {
358   char *str = strstr(info_line, field_name);
359   static char buf[MAX_REDIS_VAL_SIZE];
360   if (str) {
361     int i;
362
363     str += strlen(field_name) + 1; /* also skip the ':' */
364     for (i = 0; (*str && (isdigit((unsigned char)*str) || *str == '.'));
365          i++, str++)
366       buf[i] = *str;
367     buf[i] = '\0';
368
369     if (parse_value(buf, val, ds_type) == -1) {
370       WARNING("redis plugin: Unable to parse field `%s'.", field_name);
371       return -1;
372     }
373
374     return 0;
375   }
376   return -1;
377 } /* int redis_get_info_value */
378
379 static int redis_handle_info(char *node, char const *info_line,
380                              char const *type, char const *type_instance,
381                              char const *field_name, int ds_type) /* {{{ */
382 {
383   value_t val;
384   if (redis_get_info_value(info_line, field_name, ds_type, &val) != 0)
385     return -1;
386
387   redis_submit(node, type, type_instance, val);
388   return 0;
389 } /* }}} int redis_handle_info */
390
391 static int redis_handle_query(redis_node_t *rn, redis_query_t *rq) /* {{{ */
392 {
393   redisReply *rr;
394   const data_set_t *ds;
395   value_t val;
396
397   ds = plugin_get_ds(rq->type);
398   if (!ds) {
399     ERROR("redis plugin: DS type `%s' not defined.", rq->type);
400     return -1;
401   }
402
403   if (ds->ds_num != 1) {
404     ERROR("redis plugin: DS type `%s' has too many datasources. This is not "
405           "supported currently.",
406           rq->type);
407     return -1;
408   }
409
410   if ((rr = c_redisCommand(rn, "SELECT %d", rq->database)) == NULL) {
411     WARNING("redis plugin: unable to switch to database `%d' on node `%s'.",
412             rq->database, rn->name);
413     return -1;
414   }
415
416   if ((rr = c_redisCommand(rn, rq->query)) == NULL) {
417     WARNING("redis plugin: unable to carry out query `%s'.", rq->query);
418     return -1;
419   }
420
421   switch (rr->type) {
422   case REDIS_REPLY_INTEGER:
423     switch (ds->ds[0].type) {
424     case DS_TYPE_COUNTER:
425       val.counter = (counter_t)rr->integer;
426       break;
427     case DS_TYPE_GAUGE:
428       val.gauge = (gauge_t)rr->integer;
429       break;
430     case DS_TYPE_DERIVE:
431       val.gauge = (derive_t)rr->integer;
432       break;
433     case DS_TYPE_ABSOLUTE:
434       val.gauge = (absolute_t)rr->integer;
435       break;
436     }
437     break;
438   case REDIS_REPLY_STRING:
439     if (parse_value(rr->str, &val, ds->ds[0].type) == -1) {
440       WARNING("redis plugin: Query `%s': Unable to parse value.", rq->query);
441       freeReplyObject(rr);
442       return -1;
443     }
444     break;
445   case REDIS_REPLY_ERROR:
446     WARNING("redis plugin: Query `%s' failed: %s.", rq->query, rr->str);
447     freeReplyObject(rr);
448     return -1;
449   case REDIS_REPLY_ARRAY:
450     WARNING("redis plugin: Query `%s' should return string or integer. Arrays "
451             "are not supported.",
452             rq->query);
453     freeReplyObject(rr);
454     return -1;
455   default:
456     WARNING("redis plugin: Query `%s': Cannot coerce redis type (%i).",
457             rq->query, rr->type);
458     freeReplyObject(rr);
459     return -1;
460   }
461
462   redis_submit(rn->name, rq->type,
463                (strlen(rq->instance) > 0) ? rq->instance : NULL, val);
464   freeReplyObject(rr);
465   return 0;
466 } /* }}} int redis_handle_query */
467
468 static int redis_db_stats(const char *node, char const *info_line) /* {{{ */
469 {
470   /* redis_db_stats parses and dispatches Redis database statistics,
471    * currently the number of keys for each database.
472    * info_line needs to have the following format:
473    *   db0:keys=4,expires=0,avg_ttl=0
474    */
475
476   for (int db = 0; db < REDIS_DEF_DB_COUNT; db++) {
477     static char buf[MAX_REDIS_VAL_SIZE];
478     static char field_name[12];
479     static char db_id[4];
480     value_t val;
481     char *str;
482     int i;
483
484     snprintf(field_name, sizeof(field_name), "db%d:keys=", db);
485
486     str = strstr(info_line, field_name);
487     if (!str)
488       continue;
489
490     str += strlen(field_name);
491     for (i = 0; (*str && isdigit((int)*str)); i++, str++)
492       buf[i] = *str;
493     buf[i] = '\0';
494
495     if (parse_value(buf, &val, DS_TYPE_GAUGE) != 0) {
496       WARNING("redis plugin: Unable to parse field `%s'.", field_name);
497       return -1;
498     }
499
500     snprintf(db_id, sizeof(db_id), "%d", db);
501     redis_submit(node, "records", db_id, val);
502   }
503   return 0;
504
505 } /* }}} int redis_db_stats */
506
507 static void redis_cpu_usage(const char *node, char const *info_line) {
508   while (42) {
509     value_t rusage_user;
510     value_t rusage_syst;
511
512     if (redis_get_info_value(info_line, "used_cpu_user", DS_TYPE_GAUGE,
513                              &rusage_user) != 0)
514       break;
515
516     if (redis_get_info_value(info_line, "used_cpu_sys", DS_TYPE_GAUGE,
517                              &rusage_syst) != 0)
518       break;
519
520     redis_submit2(node, "ps_cputime", "daemon",
521                   (value_t){.derive = rusage_user.gauge * 1000000},
522                   (value_t){.derive = rusage_syst.gauge * 1000000});
523     break;
524   }
525
526   while (42) {
527     value_t rusage_user;
528     value_t rusage_syst;
529
530     if (redis_get_info_value(info_line, "used_cpu_user_children", DS_TYPE_GAUGE,
531                              &rusage_user) != 0)
532       break;
533
534     if (redis_get_info_value(info_line, "used_cpu_sys_children", DS_TYPE_GAUGE,
535                              &rusage_syst) != 0)
536       break;
537
538     redis_submit2(node, "ps_cputime", "children",
539                   (value_t){.derive = rusage_user.gauge * 1000000},
540                   (value_t){.derive = rusage_syst.gauge * 1000000});
541     break;
542   }
543 } /* void redis_cpu_usage */
544
545 static gauge_t calculate_ratio_percent(derive_t part1, derive_t part2,
546                                        derive_t *prev1, derive_t *prev2) {
547   if ((*prev1 == 0) || (*prev2 == 0) || (part1 < *prev1) || (part2 < *prev2)) {
548     *prev1 = part1;
549     *prev2 = part2;
550     return NAN;
551   }
552
553   derive_t num = part1 - *prev1;
554   derive_t denom = part2 - *prev2 + num;
555
556   *prev1 = part1;
557   *prev2 = part2;
558
559   if (denom == 0)
560     return NAN;
561
562   if (num == 0)
563     return 0;
564
565   return 100.0 * (gauge_t)num / (gauge_t)denom;
566 } /* gauge_t calculate_ratio_percent */
567
568 static void redis_keyspace_usage(redis_node_t *rn, char const *info_line) {
569   value_t hits, misses;
570
571   if (redis_get_info_value(info_line, "keyspace_hits", DS_TYPE_DERIVE, &hits) !=
572       0)
573     return;
574
575   if (redis_get_info_value(info_line, "keyspace_misses", DS_TYPE_DERIVE,
576                            &misses) != 0)
577     return;
578
579   redis_submit(rn->name, "cache_result", "hits", hits);
580   redis_submit(rn->name, "cache_result", "misses", misses);
581
582   prev_t *prev = &rn->prev;
583   gauge_t ratio = calculate_ratio_percent(
584       hits.derive, misses.derive, &prev->keyspace_hits, &prev->keyspace_misses);
585   redis_submit(rn->name, "percent", "hitratio", (value_t){.gauge = ratio});
586
587 } /* void redis_keyspace_usage */
588
589 static void redis_check_connection(redis_node_t *rn) {
590   if (rn->redisContext)
591     return;
592
593   redisContext *rh = redisConnectWithTimeout(rn->host, rn->port, rn->timeout);
594
595   if (rh == NULL) {
596     ERROR("redis plugin: can't allocate redis context");
597     return;
598   }
599   if (rh->err) {
600     ERROR("redis plugin: unable to connect to node `%s' (%s:%d): %s.", rn->name,
601           rn->host, rn->port, rh->errstr);
602     redisFree(rh);
603     return;
604   }
605
606   rn->redisContext = rh;
607
608   if (rn->passwd) {
609     redisReply *rr;
610
611     DEBUG("redis plugin: authenticating node `%s' passwd(%s).", rn->name,
612           rn->passwd);
613
614     if ((rr = c_redisCommand(rn, "AUTH %s", rn->passwd)) == NULL) {
615       WARNING("redis plugin: unable to authenticate on node `%s'.", rn->name);
616       return;
617     }
618
619     if (rr->type != REDIS_REPLY_STATUS) {
620       WARNING("redis plugin: invalid authentication on node `%s'.", rn->name);
621       freeReplyObject(rr);
622       redisFree(rn->redisContext);
623       rn->redisContext = NULL;
624       return;
625     }
626
627     freeReplyObject(rr);
628   }
629   return;
630 } /* void redis_check_connection */
631
632 static void redis_read_server_info(redis_node_t *rn) {
633   redisReply *rr;
634
635   if ((rr = c_redisCommand(rn, "INFO")) == NULL) {
636     WARNING("redis plugin: unable to get INFO from node `%s'.", rn->name);
637     return;
638   }
639
640   redis_handle_info(rn->name, rr->str, "uptime", NULL, "uptime_in_seconds",
641                     DS_TYPE_GAUGE);
642   redis_handle_info(rn->name, rr->str, "current_connections", "clients",
643                     "connected_clients", DS_TYPE_GAUGE);
644   redis_handle_info(rn->name, rr->str, "blocked_clients", NULL,
645                     "blocked_clients", DS_TYPE_GAUGE);
646   redis_handle_info(rn->name, rr->str, "memory", NULL, "used_memory",
647                     DS_TYPE_GAUGE);
648   redis_handle_info(rn->name, rr->str, "memory_lua", NULL, "used_memory_lua",
649                     DS_TYPE_GAUGE);
650   /* changes_since_last_save: Deprecated in redis version 2.6 and above */
651   redis_handle_info(rn->name, rr->str, "volatile_changes", NULL,
652                     "changes_since_last_save", DS_TYPE_GAUGE);
653   redis_handle_info(rn->name, rr->str, "total_connections", NULL,
654                     "total_connections_received", DS_TYPE_DERIVE);
655   redis_handle_info(rn->name, rr->str, "total_operations", NULL,
656                     "total_commands_processed", DS_TYPE_DERIVE);
657   redis_handle_info(rn->name, rr->str, "operations_per_second", NULL,
658                     "instantaneous_ops_per_sec", DS_TYPE_GAUGE);
659   redis_handle_info(rn->name, rr->str, "expired_keys", NULL, "expired_keys",
660                     DS_TYPE_DERIVE);
661   redis_handle_info(rn->name, rr->str, "evicted_keys", NULL, "evicted_keys",
662                     DS_TYPE_DERIVE);
663   redis_handle_info(rn->name, rr->str, "pubsub", "channels", "pubsub_channels",
664                     DS_TYPE_GAUGE);
665   redis_handle_info(rn->name, rr->str, "pubsub", "patterns", "pubsub_patterns",
666                     DS_TYPE_GAUGE);
667   redis_handle_info(rn->name, rr->str, "current_connections", "slaves",
668                     "connected_slaves", DS_TYPE_GAUGE);
669   redis_handle_info(rn->name, rr->str, "total_bytes", "input",
670                     "total_net_input_bytes", DS_TYPE_DERIVE);
671   redis_handle_info(rn->name, rr->str, "total_bytes", "output",
672                     "total_net_output_bytes", DS_TYPE_DERIVE);
673
674   redis_keyspace_usage(rn, rr->str);
675
676   redis_db_stats(rn->name, rr->str);
677
678   if (rn->report_cpu_usage)
679     redis_cpu_usage(rn->name, rr->str);
680
681   freeReplyObject(rr);
682 } /* void redis_read_server_info */
683
684 static void redis_read_command_stats(redis_node_t *rn) {
685   redisReply *rr;
686
687   if ((rr = c_redisCommand(rn, "INFO commandstats")) == NULL) {
688     WARNING("redis plugin: node `%s': unable to get `INFO commandstats'.",
689             rn->name);
690     return;
691   }
692
693   if (rr->type != REDIS_REPLY_STRING) {
694     WARNING("redis plugin: node `%s' `INFO commandstats' returned unsupported "
695             "redis type %i.",
696             rn->name, rr->type);
697     freeReplyObject(rr);
698     return;
699   }
700
701   char *command;
702   char *line;
703   char *ptr = rr->str;
704   char *saveptr = NULL;
705   while ((line = strtok_r(ptr, "\n\r", &saveptr)) != NULL) {
706     ptr = NULL;
707
708     if (line[0] == '#')
709       continue;
710
711     /* command name */
712     if (strstr(line, "cmdstat_") != line) {
713       ERROR("redis plugin: not found 'cmdstat_' prefix in line '%s'", line);
714       continue;
715     }
716
717     char *values = strstr(line, ":");
718     if (values == NULL) {
719       ERROR("redis plugin: not found ':' separator in line '%s'", line);
720       continue;
721     }
722
723     /* Null-terminate command token */
724     values[0] = '\0';
725     command = line + strlen("cmdstat_");
726     values++;
727
728     /* parse values */
729     /* cmdstat_publish:calls=20795774,usec=111039258,usec_per_call=5.34 */
730     char *field;
731     char *saveptr_field = NULL;
732     while ((field = strtok_r(values, "=", &saveptr_field)) != NULL) {
733       values = NULL;
734
735       const char *type;
736       /* only these are supported */
737       if (strcmp(field, "calls") == 0)
738         type = "commands";
739       else if (strcmp(field, "usec") == 0)
740         type = "redis_command_cputime";
741       else
742         continue;
743
744       if ((field = strtok_r(NULL, ",", &saveptr_field)) == NULL)
745         continue;
746
747       char *endptr = NULL;
748       errno = 0;
749       derive_t value = strtoll(field, &endptr, 0);
750
751       if ((endptr == field) || (errno != 0))
752         continue;
753
754       redis_submit(rn->name, type, command, (value_t){.derive = value});
755     }
756   }
757   freeReplyObject(rr);
758 } /* void redis_read_command_stats */
759
760 static int redis_read(user_data_t *user_data) /* {{{ */
761 {
762   redis_node_t *rn = user_data->data;
763
764   DEBUG("redis plugin: querying info from node `%s' (%s:%d).", rn->name,
765         rn->host, rn->port);
766
767   redis_check_connection(rn);
768
769   if (!rn->redisContext) /* no connection */
770     return -1;
771
772   redis_read_server_info(rn);
773
774   if (!rn->redisContext) /* connection lost */
775     return -1;
776
777   if (rn->report_command_stats) {
778     redis_read_command_stats(rn);
779
780     if (!rn->redisContext) /* connection lost */
781       return -1;
782   }
783
784   for (redis_query_t *rq = rn->queries; rq != NULL; rq = rq->next) {
785     redis_handle_query(rn, rq);
786     if (!rn->redisContext) /* connection lost */
787       return -1;
788   }
789
790   return 0;
791 }
792 /* }}} */
793
794 void module_register(void) /* {{{ */
795 {
796   plugin_register_complex_config("redis", redis_config);
797   plugin_register_init("redis", redis_init);
798 }
799 /* }}} */