redis plugin: report CPU usage
[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 redis_node_s;
63 typedef struct redis_node_s redis_node_t;
64 struct redis_node_s {
65   char *name;
66   char *host;
67   char *passwd;
68   int port;
69   struct timeval timeout;
70   redisContext *redisContext;
71   redis_query_t *queries;
72
73   redis_node_t *next;
74 };
75
76 static bool redis_have_instances;
77 static int redis_read(user_data_t *user_data);
78
79 static void redis_node_free(void *arg) {
80   redis_node_t *rn = arg;
81   if (rn == NULL)
82     return;
83
84   redis_query_t *rq = rn->queries;
85   while (rq != NULL) {
86     redis_query_t *next = rq->next;
87     sfree(rq);
88     rq = next;
89   }
90
91   redisFree(rn->redisContext);
92   sfree(rn->name);
93   sfree(rn->host);
94   sfree(rn->passwd);
95   sfree(rn);
96 } /* void redis_node_free */
97
98 static int redis_node_add(redis_node_t *rn) /* {{{ */
99 {
100   DEBUG("redis plugin: Adding node \"%s\".", rn->name);
101
102   /* Disable automatic generation of default instance in the init callback. */
103   redis_have_instances = true;
104
105   char cb_name[sizeof("redis/") + DATA_MAX_NAME_LEN];
106   snprintf(cb_name, sizeof(cb_name), "redis/%s", rn->name);
107
108   return plugin_register_complex_read(
109       /* group = */ "redis",
110       /* name      = */ cb_name,
111       /* callback  = */ redis_read,
112       /* interval  = */ 0,
113       &(user_data_t){
114           .data = rn, .free_func = redis_node_free,
115       });
116 } /* }}} */
117
118 static redis_query_t *redis_config_query(oconfig_item_t *ci) /* {{{ */
119 {
120   redis_query_t *rq;
121   int status;
122
123   rq = calloc(1, sizeof(*rq));
124   if (rq == NULL) {
125     ERROR("redis plugin: calloc failed adding redis_query.");
126     return NULL;
127   }
128   status = cf_util_get_string_buffer(ci, rq->query, sizeof(rq->query));
129   if (status != 0)
130     goto err;
131
132   /*
133    * Default to a gauge type.
134    */
135   (void)strncpy(rq->type, "gauge", sizeof(rq->type));
136   (void)sstrncpy(rq->instance, rq->query, sizeof(rq->instance));
137   replace_special(rq->instance, sizeof(rq->instance));
138
139   rq->database = 0;
140
141   for (int i = 0; i < ci->children_num; i++) {
142     oconfig_item_t *option = ci->children + i;
143
144     if (strcasecmp("Type", option->key) == 0) {
145       status = cf_util_get_string_buffer(option, rq->type, sizeof(rq->type));
146     } else if (strcasecmp("Instance", option->key) == 0) {
147       status =
148           cf_util_get_string_buffer(option, rq->instance, sizeof(rq->instance));
149     } else if (strcasecmp("Database", option->key) == 0) {
150       status = cf_util_get_int(option, &rq->database);
151       if (rq->database < 0) {
152         WARNING("redis plugin: The \"Database\" option must be positive "
153                 "integer or zero");
154         status = -1;
155       }
156     } else {
157       WARNING("redis plugin: unknown configuration option: %s", option->key);
158       status = -1;
159     }
160     if (status != 0)
161       goto err;
162   }
163   return rq;
164 err:
165   free(rq);
166   return NULL;
167 } /* }}} */
168
169 static int redis_config_node(oconfig_item_t *ci) /* {{{ */
170 {
171   redis_node_t *rn = calloc(1, sizeof(*rn));
172   if (rn == NULL) {
173     ERROR("redis plugin: calloc failed adding node.");
174     return ENOMEM;
175   }
176
177   rn->port = REDIS_DEF_PORT;
178   rn->timeout.tv_sec = REDIS_DEF_TIMEOUT_SEC;
179
180   rn->host = strdup(REDIS_DEF_HOST);
181   if (rn->host == NULL) {
182     ERROR("redis plugin: strdup failed adding node.");
183     sfree(rn);
184     return ENOMEM;
185   }
186
187   int status = cf_util_get_string(ci, &rn->name);
188   if (status != 0) {
189     sfree(rn->host);
190     sfree(rn);
191     return status;
192   }
193
194   for (int i = 0; i < ci->children_num; i++) {
195     oconfig_item_t *option = ci->children + i;
196
197     if (strcasecmp("Host", option->key) == 0)
198       status = cf_util_get_string(option, &rn->host);
199     else if (strcasecmp("Port", option->key) == 0) {
200       status = cf_util_get_port_number(option);
201       if (status > 0) {
202         rn->port = status;
203         status = 0;
204       }
205     } else if (strcasecmp("Query", option->key) == 0) {
206       redis_query_t *rq = redis_config_query(option);
207       if (rq == NULL) {
208         status = 1;
209       } else {
210         rq->next = rn->queries;
211         rn->queries = rq;
212       }
213     } else if (strcasecmp("Timeout", option->key) == 0) {
214       int timeout;
215       status = cf_util_get_int(option, &timeout);
216       if (status == 0) {
217         rn->timeout.tv_usec = timeout * 1000;
218         rn->timeout.tv_sec = rn->timeout.tv_usec / 1000000L;
219         rn->timeout.tv_usec %= 1000000L;
220       }
221     } else if (strcasecmp("Password", option->key) == 0)
222       status = cf_util_get_string(option, &rn->passwd);
223     else
224       WARNING("redis plugin: Option `%s' not allowed inside a `Node' "
225               "block. I'll ignore this option.",
226               option->key);
227
228     if (status != 0)
229       break;
230   }
231
232   if (status != 0) {
233     redis_node_free(rn);
234     return status;
235   }
236
237   return redis_node_add(rn);
238 } /* }}} int redis_config_node */
239
240 static int redis_config(oconfig_item_t *ci) /* {{{ */
241 {
242   for (int i = 0; i < ci->children_num; i++) {
243     oconfig_item_t *option = ci->children + i;
244
245     if (strcasecmp("Node", option->key) == 0)
246       redis_config_node(option);
247     else
248       WARNING("redis plugin: Option `%s' not allowed in redis"
249               " configuration. It will be ignored.",
250               option->key);
251   }
252
253   return 0;
254 } /* }}} */
255
256 __attribute__((nonnull(2))) static void
257 redis_submit(char *plugin_instance, const char *type, const char *type_instance,
258              value_t value) /* {{{ */
259 {
260   value_list_t vl = VALUE_LIST_INIT;
261
262   vl.values = &value;
263   vl.values_len = 1;
264   sstrncpy(vl.plugin, "redis", sizeof(vl.plugin));
265   if (plugin_instance != NULL)
266     sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
267   sstrncpy(vl.type, type, sizeof(vl.type));
268   if (type_instance != NULL)
269     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
270
271   plugin_dispatch_values(&vl);
272 } /* }}} */
273
274 __attribute__((nonnull(2))) static void
275 redis_submit2(char *plugin_instance, const char *type,
276               const char *type_instance, value_t value0,
277               value_t value1) /* {{{ */
278 {
279   value_list_t vl = VALUE_LIST_INIT;
280   value_t values[] = {value0, value1};
281
282   vl.values = values;
283   vl.values_len = STATIC_ARRAY_SIZE(values);
284
285   sstrncpy(vl.plugin, "redis", sizeof(vl.plugin));
286   sstrncpy(vl.type, type, sizeof(vl.type));
287
288   if (plugin_instance != NULL)
289     sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
290
291   if (type_instance != NULL)
292     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
293
294   plugin_dispatch_values(&vl);
295 } /* }}} */
296
297 static int redis_init(void) /* {{{ */
298 {
299   if (redis_have_instances)
300     return 0;
301
302   redis_node_t *rn = calloc(1, sizeof(*rn));
303   if (rn == NULL)
304     return ENOMEM;
305
306   rn->port = REDIS_DEF_PORT;
307   rn->timeout.tv_sec = REDIS_DEF_TIMEOUT_SEC;
308
309   rn->name = strdup("default");
310   rn->host = strdup(REDIS_DEF_HOST);
311
312   if (rn->name == NULL || rn->host == NULL)
313     return ENOMEM;
314
315   return redis_node_add(rn);
316 } /* }}} int redis_init */
317
318 static void *c_redisCommand(redis_node_t *rn, const char *format, ...) {
319   redisContext *c = rn->redisContext;
320
321   if (c == NULL)
322     return NULL;
323
324   va_list ap;
325   va_start(ap, format);
326   void *reply = redisvCommand(c, format, ap);
327   va_end(ap);
328
329   if (reply == NULL) {
330     ERROR("redis plugin: Connection error: %s", c->errstr);
331     redisFree(rn->redisContext);
332     rn->redisContext = NULL;
333   }
334
335   return reply;
336 } /* void c_redisCommand */
337
338 static int redis_get_info_value(char const *info_line, char const *field_name,
339                                 int ds_type, value_t *val) {
340   char *str = strstr(info_line, field_name);
341   static char buf[MAX_REDIS_VAL_SIZE];
342   if (str) {
343     int i;
344
345     str += strlen(field_name) + 1; /* also skip the ':' */
346     for (i = 0; (*str && (isdigit((unsigned char)*str) || *str == '.'));
347          i++, str++)
348       buf[i] = *str;
349     buf[i] = '\0';
350
351     if (parse_value(buf, val, ds_type) == -1) {
352       WARNING("redis plugin: Unable to parse field `%s'.", field_name);
353       return -1;
354     }
355
356     return 0;
357   }
358   return -1;
359 } /* int redis_get_info_value */
360
361 static int redis_handle_info(char *node, char const *info_line,
362                              char const *type, char const *type_instance,
363                              char const *field_name, int ds_type) /* {{{ */
364 {
365   value_t val;
366   if (redis_get_info_value(info_line, field_name, ds_type, &val) != 0)
367     return -1;
368
369   redis_submit(node, type, type_instance, val);
370   return 0;
371 } /* }}} int redis_handle_info */
372
373 static int redis_handle_query(redis_node_t *rn, redis_query_t *rq) /* {{{ */
374 {
375   redisReply *rr;
376   const data_set_t *ds;
377   value_t val;
378
379   ds = plugin_get_ds(rq->type);
380   if (!ds) {
381     ERROR("redis plugin: DS type `%s' not defined.", rq->type);
382     return -1;
383   }
384
385   if (ds->ds_num != 1) {
386     ERROR("redis plugin: DS type `%s' has too many datasources. This is not "
387           "supported currently.",
388           rq->type);
389     return -1;
390   }
391
392   if ((rr = c_redisCommand(rn, "SELECT %d", rq->database)) == NULL) {
393     WARNING("redis plugin: unable to switch to database `%d' on node `%s'.",
394             rq->database, rn->name);
395     return -1;
396   }
397
398   if ((rr = c_redisCommand(rn, rq->query)) == NULL) {
399     WARNING("redis plugin: unable to carry out query `%s'.", rq->query);
400     return -1;
401   }
402
403   switch (rr->type) {
404   case REDIS_REPLY_INTEGER:
405     switch (ds->ds[0].type) {
406     case DS_TYPE_COUNTER:
407       val.counter = (counter_t)rr->integer;
408       break;
409     case DS_TYPE_GAUGE:
410       val.gauge = (gauge_t)rr->integer;
411       break;
412     case DS_TYPE_DERIVE:
413       val.gauge = (derive_t)rr->integer;
414       break;
415     case DS_TYPE_ABSOLUTE:
416       val.gauge = (absolute_t)rr->integer;
417       break;
418     }
419     break;
420   case REDIS_REPLY_STRING:
421     if (parse_value(rr->str, &val, ds->ds[0].type) == -1) {
422       WARNING("redis plugin: Query `%s': Unable to parse value.", rq->query);
423       freeReplyObject(rr);
424       return -1;
425     }
426     break;
427   case REDIS_REPLY_ERROR:
428     WARNING("redis plugin: Query `%s' failed: %s.", rq->query, rr->str);
429     freeReplyObject(rr);
430     return -1;
431   case REDIS_REPLY_ARRAY:
432     WARNING("redis plugin: Query `%s' should return string or integer. Arrays "
433             "are not supported.",
434             rq->query);
435     freeReplyObject(rr);
436     return -1;
437   default:
438     WARNING("redis plugin: Query `%s': Cannot coerce redis type (%i).",
439             rq->query, rr->type);
440     freeReplyObject(rr);
441     return -1;
442   }
443
444   redis_submit(rn->name, rq->type,
445                (strlen(rq->instance) > 0) ? rq->instance : NULL, val);
446   freeReplyObject(rr);
447   return 0;
448 } /* }}} int redis_handle_query */
449
450 static int redis_db_stats(char *node, char const *info_line) /* {{{ */
451 {
452   /* redis_db_stats parses and dispatches Redis database statistics,
453    * currently the number of keys for each database.
454    * info_line needs to have the following format:
455    *   db0:keys=4,expires=0,avg_ttl=0
456    */
457
458   for (int db = 0; db < REDIS_DEF_DB_COUNT; db++) {
459     static char buf[MAX_REDIS_VAL_SIZE];
460     static char field_name[12];
461     static char db_id[4];
462     value_t val;
463     char *str;
464     int i;
465
466     snprintf(field_name, sizeof(field_name), "db%d:keys=", db);
467
468     str = strstr(info_line, field_name);
469     if (!str)
470       continue;
471
472     str += strlen(field_name);
473     for (i = 0; (*str && isdigit((int)*str)); i++, str++)
474       buf[i] = *str;
475     buf[i] = '\0';
476
477     if (parse_value(buf, &val, DS_TYPE_GAUGE) != 0) {
478       WARNING("redis plugin: Unable to parse field `%s'.", field_name);
479       return -1;
480     }
481
482     snprintf(db_id, sizeof(db_id), "%d", db);
483     redis_submit(node, "records", db_id, val);
484   }
485   return 0;
486
487 } /* }}} int redis_db_stats */
488
489 static void redis_check_connection(redis_node_t *rn) {
490   if (rn->redisContext)
491     return;
492
493   redisContext *rh = redisConnectWithTimeout(rn->host, rn->port, rn->timeout);
494
495   if (rh == NULL) {
496     ERROR("redis plugin: can't allocate redis context");
497     return;
498   }
499   if (rh->err) {
500     ERROR("redis plugin: unable to connect to node `%s' (%s:%d): %s.", rn->name,
501           rn->host, rn->port, rh->errstr);
502     redisFree(rh);
503     return;
504   }
505
506   rn->redisContext = rh;
507
508   if (rn->passwd) {
509     redisReply *rr;
510
511     DEBUG("redis plugin: authenticating node `%s' passwd(%s).", rn->name,
512           rn->passwd);
513
514     if ((rr = c_redisCommand(rn, "AUTH %s", rn->passwd)) == NULL) {
515       WARNING("redis plugin: unable to authenticate on node `%s'.", rn->name);
516       return;
517     }
518
519     if (rr->type != REDIS_REPLY_STATUS) {
520       WARNING("redis plugin: invalid authentication on node `%s'.", rn->name);
521       freeReplyObject(rr);
522       redisFree(rn->redisContext);
523       rn->redisContext = NULL;
524       return;
525     }
526
527     freeReplyObject(rr);
528   }
529   return;
530 } /* void redis_check_connection */
531
532 static void redis_read_server_info(redis_node_t *rn) {
533   redisReply *rr;
534
535   if ((rr = c_redisCommand(rn, "INFO")) == NULL) {
536     WARNING("redis plugin: unable to get INFO from node `%s'.", rn->name);
537     return;
538   }
539
540   redis_handle_info(rn->name, rr->str, "uptime", NULL, "uptime_in_seconds",
541                     DS_TYPE_GAUGE);
542   redis_handle_info(rn->name, rr->str, "current_connections", "clients",
543                     "connected_clients", DS_TYPE_GAUGE);
544   redis_handle_info(rn->name, rr->str, "blocked_clients", NULL,
545                     "blocked_clients", DS_TYPE_GAUGE);
546   redis_handle_info(rn->name, rr->str, "memory", NULL, "used_memory",
547                     DS_TYPE_GAUGE);
548   redis_handle_info(rn->name, rr->str, "memory_lua", NULL, "used_memory_lua",
549                     DS_TYPE_GAUGE);
550   /* changes_since_last_save: Deprecated in redis version 2.6 and above */
551   redis_handle_info(rn->name, rr->str, "volatile_changes", NULL,
552                     "changes_since_last_save", DS_TYPE_GAUGE);
553   redis_handle_info(rn->name, rr->str, "total_connections", NULL,
554                     "total_connections_received", DS_TYPE_DERIVE);
555   redis_handle_info(rn->name, rr->str, "total_operations", NULL,
556                     "total_commands_processed", DS_TYPE_DERIVE);
557   redis_handle_info(rn->name, rr->str, "operations_per_second", NULL,
558                     "instantaneous_ops_per_sec", DS_TYPE_GAUGE);
559   redis_handle_info(rn->name, rr->str, "expired_keys", NULL, "expired_keys",
560                     DS_TYPE_DERIVE);
561   redis_handle_info(rn->name, rr->str, "evicted_keys", NULL, "evicted_keys",
562                     DS_TYPE_DERIVE);
563   redis_handle_info(rn->name, rr->str, "pubsub", "channels", "pubsub_channels",
564                     DS_TYPE_GAUGE);
565   redis_handle_info(rn->name, rr->str, "pubsub", "patterns", "pubsub_patterns",
566                     DS_TYPE_GAUGE);
567   redis_handle_info(rn->name, rr->str, "current_connections", "slaves",
568                     "connected_slaves", DS_TYPE_GAUGE);
569   redis_handle_info(rn->name, rr->str, "cache_result", "hits", "keyspace_hits",
570                     DS_TYPE_DERIVE);
571   redis_handle_info(rn->name, rr->str, "cache_result", "misses",
572                     "keyspace_misses", DS_TYPE_DERIVE);
573   redis_handle_info(rn->name, rr->str, "total_bytes", "input",
574                     "total_net_input_bytes", DS_TYPE_DERIVE);
575   redis_handle_info(rn->name, rr->str, "total_bytes", "output",
576                     "total_net_output_bytes", DS_TYPE_DERIVE);
577
578   while (42) {
579     value_t rusage_user;
580     value_t rusage_syst;
581
582     if (redis_get_info_value(rr->str, "used_cpu_user", DS_TYPE_GAUGE,
583                              &rusage_user) != 0)
584       break;
585
586     if (redis_get_info_value(rr->str, "used_cpu_sys", DS_TYPE_GAUGE,
587                              &rusage_syst) != 0)
588       break;
589
590     redis_submit2(rn->name, "ps_cputime", "daemon",
591                   (value_t){.derive = rusage_user.gauge * 1000000},
592                   (value_t){.derive = rusage_syst.gauge * 1000000});
593     break;
594   }
595
596   while (42) {
597     value_t rusage_user;
598     value_t rusage_syst;
599
600     if (redis_get_info_value(rr->str, "used_cpu_user_children", DS_TYPE_GAUGE,
601                              &rusage_user) != 0)
602       break;
603
604     if (redis_get_info_value(rr->str, "used_cpu_sys_children", DS_TYPE_GAUGE,
605                              &rusage_syst) != 0)
606       break;
607
608     redis_submit2(rn->name, "ps_cputime", "children",
609                   (value_t){.derive = rusage_user.gauge * 1000000},
610                   (value_t){.derive = rusage_syst.gauge * 1000000});
611     break;
612   }
613
614   redis_db_stats(rn->name, rr->str);
615
616   freeReplyObject(rr);
617 } /* void redis_read_server_info */
618
619 static int redis_read(user_data_t *user_data) /* {{{ */
620 {
621   redis_node_t *rn = user_data->data;
622
623   DEBUG("redis plugin: querying info from node `%s' (%s:%d).", rn->name,
624         rn->host, rn->port);
625
626   redis_check_connection(rn);
627
628   if (!rn->redisContext) /* no connection */
629     return -1;
630
631   redis_read_server_info(rn);
632
633   if (!rn->redisContext) /* connection lost */
634     return -1;
635
636   for (redis_query_t *rq = rn->queries; rq != NULL; rq = rq->next) {
637     redis_handle_query(rn, rq);
638     if (!rn->redisContext) /* connection lost */
639       return -1;
640   }
641
642   return 0;
643 }
644 /* }}} */
645
646 void module_register(void) /* {{{ */
647 {
648   plugin_register_complex_config("redis", redis_config);
649   plugin_register_init("redis", redis_init);
650 }
651 /* }}} */