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