f4de380050a6770a6af75b27510983b13e8b8361
[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 #ifndef HOST_NAME_MAX
32 #define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
33 #endif
34
35 #define REDIS_DEF_HOST "localhost"
36 #define REDIS_DEF_PASSWD ""
37 #define REDIS_DEF_PORT 6379
38 #define REDIS_DEF_TIMEOUT_SEC 2
39 #define REDIS_DEF_DB_COUNT 256
40 #define MAX_REDIS_NODE_NAME 64
41 #define MAX_REDIS_PASSWD_LENGTH 512
42 #define MAX_REDIS_VAL_SIZE 256
43 #define MAX_REDIS_QUERY 2048
44
45 /* Redis plugin configuration example:
46  *
47  * <Plugin redis>
48  *   <Node "mynode">
49  *     Host "localhost"
50  *     Port "6379"
51  *     Timeout 2
52  *     Password "foobar"
53  *   </Node>
54  * </Plugin>
55  */
56
57 struct redis_query_s;
58 typedef struct redis_query_s redis_query_t;
59 struct redis_query_s {
60   char query[MAX_REDIS_QUERY];
61   char type[DATA_MAX_NAME_LEN];
62   char instance[DATA_MAX_NAME_LEN];
63   int database;
64
65   redis_query_t *next;
66 };
67
68 struct redis_node_s;
69 typedef struct redis_node_s redis_node_t;
70 struct redis_node_s {
71   char name[MAX_REDIS_NODE_NAME];
72   char host[HOST_NAME_MAX];
73   char passwd[MAX_REDIS_PASSWD_LENGTH];
74   int port;
75   struct timeval timeout;
76   redis_query_t *queries;
77
78   redis_node_t *next;
79 };
80
81 static redis_node_t *nodes_head;
82
83 static int redis_node_add(const redis_node_t *rn) /* {{{ */
84 {
85   redis_node_t *rn_copy;
86   redis_node_t *rn_ptr;
87
88   /* Check for duplicates first */
89   for (rn_ptr = nodes_head; rn_ptr != NULL; rn_ptr = rn_ptr->next)
90     if (strcmp(rn->name, rn_ptr->name) == 0)
91       break;
92
93   if (rn_ptr != NULL) {
94     ERROR("redis plugin: A node with the name `%s' already exists.", rn->name);
95     return -1;
96   }
97
98   rn_copy = malloc(sizeof(*rn_copy));
99   if (rn_copy == NULL) {
100     ERROR("redis plugin: malloc failed adding redis_node to the tree.");
101     return -1;
102   }
103
104   memcpy(rn_copy, rn, sizeof(*rn_copy));
105   rn_copy->next = NULL;
106
107   DEBUG("redis plugin: Adding node \"%s\".", rn->name);
108
109   if (nodes_head == NULL)
110     nodes_head = rn_copy;
111   else {
112     rn_ptr = nodes_head;
113     while (rn_ptr->next != NULL)
114       rn_ptr = rn_ptr->next;
115     rn_ptr->next = rn_copy;
116   }
117
118   return 0;
119 } /* }}} */
120
121 static redis_query_t *redis_config_query(oconfig_item_t *ci) /* {{{ */
122 {
123   redis_query_t *rq;
124   int status;
125
126   rq = calloc(1, sizeof(*rq));
127   if (rq == NULL) {
128     ERROR("redis plugin: calloc failed adding redis_query.");
129     return NULL;
130   }
131   status = cf_util_get_string_buffer(ci, rq->query, sizeof(rq->query));
132   if (status != 0)
133     goto err;
134
135   /*
136    * Default to a gauge type.
137    */
138   (void)strncpy(rq->type, "gauge", sizeof(rq->type));
139   (void)sstrncpy(rq->instance, rq->query, sizeof(rq->instance));
140   replace_special(rq->instance, sizeof(rq->instance));
141
142   rq->database = 0;
143
144   for (int i = 0; i < ci->children_num; i++) {
145     oconfig_item_t *option = ci->children + i;
146
147     if (strcasecmp("Type", option->key) == 0) {
148       status = cf_util_get_string_buffer(option, rq->type, sizeof(rq->type));
149     } else if (strcasecmp("Instance", option->key) == 0) {
150       status =
151           cf_util_get_string_buffer(option, rq->instance, sizeof(rq->instance));
152     } else if (strcasecmp("Database", option->key) == 0) {
153       status = cf_util_get_int(option, &rq->database);
154       if (rq->database < 0) {
155         WARNING("redis plugin: The \"Database\" option must be positive "
156                 "integer or zero");
157         status = -1;
158       }
159     } else {
160       WARNING("redis plugin: unknown configuration option: %s", option->key);
161       status = -1;
162     }
163     if (status != 0)
164       goto err;
165   }
166   return rq;
167 err:
168   free(rq);
169   return NULL;
170 } /* }}} */
171
172 static int redis_config_node(oconfig_item_t *ci) /* {{{ */
173 {
174   redis_query_t *rq;
175   int status;
176   int timeout;
177
178   redis_node_t rn = {.port = REDIS_DEF_PORT,
179                      .timeout.tv_sec = REDIS_DEF_TIMEOUT_SEC};
180
181   sstrncpy(rn.host, REDIS_DEF_HOST, sizeof(rn.host));
182
183   status = cf_util_get_string_buffer(ci, rn.name, sizeof(rn.name));
184   if (status != 0)
185     return status;
186
187   for (int i = 0; i < ci->children_num; i++) {
188     oconfig_item_t *option = ci->children + i;
189
190     if (strcasecmp("Host", option->key) == 0)
191       status = cf_util_get_string_buffer(option, rn.host, sizeof(rn.host));
192     else if (strcasecmp("Port", option->key) == 0) {
193       status = cf_util_get_port_number(option);
194       if (status > 0) {
195         rn.port = status;
196         status = 0;
197       }
198     } else if (strcasecmp("Query", option->key) == 0) {
199       rq = redis_config_query(option);
200       if (rq == NULL) {
201         status = 1;
202       } else {
203         rq->next = rn.queries;
204         rn.queries = rq;
205       }
206     } else if (strcasecmp("Timeout", option->key) == 0) {
207       status = cf_util_get_int(option, &timeout);
208       if (status == 0) {
209         rn.timeout.tv_usec = timeout * 1000;
210         rn.timeout.tv_sec = rn.timeout.tv_usec / 1000000L;
211         rn.timeout.tv_usec %= 1000000L;
212       }
213     } else if (strcasecmp("Password", option->key) == 0)
214       status = cf_util_get_string_buffer(option, rn.passwd, sizeof(rn.passwd));
215     else
216       WARNING("redis plugin: Option `%s' not allowed inside a `Node' "
217               "block. I'll ignore this option.",
218               option->key);
219
220     if (status != 0)
221       break;
222   }
223
224   if (status != 0)
225     return status;
226
227   return redis_node_add(&rn);
228 } /* }}} int redis_config_node */
229
230 static int redis_config(oconfig_item_t *ci) /* {{{ */
231 {
232   for (int i = 0; i < ci->children_num; i++) {
233     oconfig_item_t *option = ci->children + i;
234
235     if (strcasecmp("Node", option->key) == 0)
236       redis_config_node(option);
237     else
238       WARNING("redis plugin: Option `%s' not allowed in redis"
239               " configuration. It will be ignored.",
240               option->key);
241   }
242
243   if (nodes_head == NULL) {
244     ERROR("redis plugin: No valid node configuration could be found.");
245     return ENOENT;
246   }
247
248   return 0;
249 } /* }}} */
250
251 __attribute__((nonnull(2))) static void
252 redis_submit(char *plugin_instance, const char *type, const char *type_instance,
253              value_t value) /* {{{ */
254 {
255   value_list_t vl = VALUE_LIST_INIT;
256
257   vl.values = &value;
258   vl.values_len = 1;
259   sstrncpy(vl.plugin, "redis", sizeof(vl.plugin));
260   if (plugin_instance != NULL)
261     sstrncpy(vl.plugin_instance, plugin_instance, sizeof(vl.plugin_instance));
262   sstrncpy(vl.type, type, sizeof(vl.type));
263   if (type_instance != NULL)
264     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
265
266   plugin_dispatch_values(&vl);
267 } /* }}} */
268
269 static int redis_init(void) /* {{{ */
270 {
271   redis_node_t rn = {.name = "default",
272                      .host = REDIS_DEF_HOST,
273                      .port = REDIS_DEF_PORT,
274                      .timeout.tv_sec = REDIS_DEF_TIMEOUT_SEC,
275                      .next = NULL};
276
277   if (nodes_head == NULL)
278     redis_node_add(&rn);
279
280   return 0;
281 } /* }}} int redis_init */
282
283 static int redis_handle_info(char *node, char const *info_line,
284                              char const *type, char const *type_instance,
285                              char const *field_name, int ds_type) /* {{{ */
286 {
287   char *str = strstr(info_line, field_name);
288   static char buf[MAX_REDIS_VAL_SIZE];
289   value_t val;
290   if (str) {
291     int i;
292
293     str += strlen(field_name) + 1; /* also skip the ':' */
294     for (i = 0; (*str && (isdigit((unsigned char)*str) || *str == '.'));
295          i++, str++)
296       buf[i] = *str;
297     buf[i] = '\0';
298
299     if (parse_value(buf, &val, ds_type) == -1) {
300       WARNING("redis plugin: Unable to parse field `%s'.", field_name);
301       return -1;
302     }
303
304     redis_submit(node, type, type_instance, val);
305     return 0;
306   }
307   return -1;
308
309 } /* }}} int redis_handle_info */
310
311 static int redis_handle_query(redisContext *rh, redis_node_t *rn,
312                               redis_query_t *rq) /* {{{ */
313 {
314   redisReply *rr;
315   const data_set_t *ds;
316   value_t val;
317
318   ds = plugin_get_ds(rq->type);
319   if (!ds) {
320     ERROR("redis plugin: DS type `%s' not defined.", rq->type);
321     return -1;
322   }
323
324   if (ds->ds_num != 1) {
325     ERROR("redis plugin: DS type `%s' has too many datasources. This is not "
326           "supported currently.",
327           rq->type);
328     return -1;
329   }
330
331   if ((rr = redisCommand(rh, "SELECT %d", rq->database)) == NULL) {
332     WARNING("redis plugin: unable to switch to database `%d' on node `%s'.",
333             rq->database, rn->name);
334     return -1;
335   }
336
337   if ((rr = redisCommand(rh, rq->query)) == NULL) {
338     WARNING("redis plugin: unable to carry out query `%s'.", rq->query);
339     return -1;
340   }
341
342   switch (rr->type) {
343   case REDIS_REPLY_INTEGER:
344     switch (ds->ds[0].type) {
345     case DS_TYPE_COUNTER:
346       val.counter = (counter_t)rr->integer;
347       break;
348     case DS_TYPE_GAUGE:
349       val.gauge = (gauge_t)rr->integer;
350       break;
351     case DS_TYPE_DERIVE:
352       val.gauge = (derive_t)rr->integer;
353       break;
354     case DS_TYPE_ABSOLUTE:
355       val.gauge = (absolute_t)rr->integer;
356       break;
357     }
358     break;
359   case REDIS_REPLY_STRING:
360     if (parse_value(rr->str, &val, ds->ds[0].type) == -1) {
361       WARNING("redis plugin: Query `%s': Unable to parse value.", rq->query);
362       freeReplyObject(rr);
363       return -1;
364     }
365     break;
366   case REDIS_REPLY_ARRAY:
367     WARNING("redis plugin: Query `%s' should return string or integer. Arrays "
368             "are not supported.",
369             rq->query);
370     freeReplyObject(rr);
371     return -1;
372   default:
373     WARNING("redis plugin: Query `%s': Cannot coerce redis type (%i).",
374             rq->query, rr->type);
375     freeReplyObject(rr);
376     return -1;
377   }
378
379   redis_submit(rn->name, rq->type,
380                (strlen(rq->instance) > 0) ? rq->instance : NULL, val);
381   freeReplyObject(rr);
382   return 0;
383 } /* }}} int redis_handle_query */
384
385 static int redis_db_stats(char *node, char const *info_line) /* {{{ */
386 {
387   /* redis_db_stats parses and dispatches Redis database statistics,
388    * currently the number of keys for each database.
389    * info_line needs to have the following format:
390    *   db0:keys=4,expires=0,avg_ttl=0
391    */
392
393   for (int db = 0; db < REDIS_DEF_DB_COUNT; db++) {
394     static char buf[MAX_REDIS_VAL_SIZE];
395     static char field_name[12];
396     static char db_id[4];
397     value_t val;
398     char *str;
399     int i;
400
401     snprintf(field_name, sizeof(field_name), "db%d:keys=", db);
402
403     str = strstr(info_line, field_name);
404     if (!str)
405       continue;
406
407     str += strlen(field_name);
408     for (i = 0; (*str && isdigit((int)*str)); i++, str++)
409       buf[i] = *str;
410     buf[i] = '\0';
411
412     if (parse_value(buf, &val, DS_TYPE_GAUGE) != 0) {
413       WARNING("redis plugin: Unable to parse field `%s'.", field_name);
414       return -1;
415     }
416
417     snprintf(db_id, sizeof(db_id), "%d", db);
418     redis_submit(node, "records", db_id, val);
419   }
420   return 0;
421
422 } /* }}} int redis_db_stats */
423
424 static int redis_read(void) /* {{{ */
425 {
426   for (redis_node_t *rn = nodes_head; rn != NULL; rn = rn->next) {
427     redisContext *rh;
428     redisReply *rr;
429
430     DEBUG("redis plugin: querying info from node `%s' (%s:%d).", rn->name,
431           rn->host, rn->port);
432
433     rh = redisConnectWithTimeout((char *)rn->host, rn->port, rn->timeout);
434     if (rh == NULL) {
435       ERROR("redis plugin: can't allocate redis context");
436       continue;
437     }
438     if (rh->err) {
439       ERROR("redis plugin: unable to connect to node `%s' (%s:%d): %s.",
440             rn->name, rn->host, rn->port, rh->errstr);
441       redisFree(rh);
442       continue;
443     }
444
445     if (strlen(rn->passwd) > 0) {
446       DEBUG("redis plugin: authenticating node `%s' passwd(%s).", rn->name,
447             rn->passwd);
448
449       if ((rr = redisCommand(rh, "AUTH %s", rn->passwd)) == NULL) {
450         WARNING("redis plugin: unable to authenticate on node `%s'.", rn->name);
451         goto redis_fail;
452       }
453
454       if (rr->type != REDIS_REPLY_STATUS) {
455         WARNING("redis plugin: invalid authentication on node `%s'.", rn->name);
456         goto redis_fail;
457       }
458
459       freeReplyObject(rr);
460     }
461
462     if ((rr = redisCommand(rh, "INFO")) == NULL) {
463       WARNING("redis plugin: unable to get info from node `%s'.", rn->name);
464       goto redis_fail;
465     }
466
467     redis_handle_info(rn->name, rr->str, "uptime", NULL, "uptime_in_seconds",
468                       DS_TYPE_GAUGE);
469     redis_handle_info(rn->name, rr->str, "current_connections", "clients",
470                       "connected_clients", DS_TYPE_GAUGE);
471     redis_handle_info(rn->name, rr->str, "blocked_clients", NULL,
472                       "blocked_clients", DS_TYPE_GAUGE);
473     redis_handle_info(rn->name, rr->str, "memory", NULL, "used_memory",
474                       DS_TYPE_GAUGE);
475     redis_handle_info(rn->name, rr->str, "memory_lua", NULL, "used_memory_lua",
476                       DS_TYPE_GAUGE);
477     /* changes_since_last_save: Deprecated in redis version 2.6 and above */
478     redis_handle_info(rn->name, rr->str, "volatile_changes", NULL,
479                       "changes_since_last_save", DS_TYPE_GAUGE);
480     redis_handle_info(rn->name, rr->str, "total_connections", NULL,
481                       "total_connections_received", DS_TYPE_DERIVE);
482     redis_handle_info(rn->name, rr->str, "total_operations", NULL,
483                       "total_commands_processed", DS_TYPE_DERIVE);
484     redis_handle_info(rn->name, rr->str, "operations_per_second", NULL,
485                       "instantaneous_ops_per_sec", DS_TYPE_GAUGE);
486     redis_handle_info(rn->name, rr->str, "expired_keys", NULL, "expired_keys",
487                       DS_TYPE_DERIVE);
488     redis_handle_info(rn->name, rr->str, "evicted_keys", NULL, "evicted_keys",
489                       DS_TYPE_DERIVE);
490     redis_handle_info(rn->name, rr->str, "pubsub", "channels",
491                       "pubsub_channels", DS_TYPE_GAUGE);
492     redis_handle_info(rn->name, rr->str, "pubsub", "patterns",
493                       "pubsub_patterns", DS_TYPE_GAUGE);
494     redis_handle_info(rn->name, rr->str, "current_connections", "slaves",
495                       "connected_slaves", DS_TYPE_GAUGE);
496     redis_handle_info(rn->name, rr->str, "cache_result", "hits",
497                       "keyspace_hits", DS_TYPE_DERIVE);
498     redis_handle_info(rn->name, rr->str, "cache_result", "misses",
499                       "keyspace_misses", DS_TYPE_DERIVE);
500     redis_handle_info(rn->name, rr->str, "total_bytes", "input",
501                       "total_net_input_bytes", DS_TYPE_DERIVE);
502     redis_handle_info(rn->name, rr->str, "total_bytes", "output",
503                       "total_net_output_bytes", DS_TYPE_DERIVE);
504
505     redis_db_stats(rn->name, rr->str);
506
507     for (redis_query_t *rq = rn->queries; rq != NULL; rq = rq->next)
508       redis_handle_query(rh, rn, rq);
509
510   redis_fail:
511     if (rr != NULL)
512       freeReplyObject(rr);
513     redisFree(rh);
514   }
515
516   return 0;
517 }
518 /* }}} */
519
520 void module_register(void) /* {{{ */
521 {
522   plugin_register_complex_config("redis", redis_config);
523   plugin_register_init("redis", redis_init);
524   plugin_register_read("redis", redis_read);
525   /* TODO: plugin_register_write: one redis list per value id with
526    * X elements */
527 }
528 /* }}} */