write_tsdb: enable TCP keepalive on network socket
[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 #include "configfile.h"
28
29 #include <sys/time.h>
30 #include <hiredis/hiredis.h>
31
32 #ifndef HOST_NAME_MAX
33 # define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
34 #endif
35
36 #define REDIS_DEF_HOST   "localhost"
37 #define REDIS_DEF_PASSWD ""
38 #define REDIS_DEF_PORT    6379
39 #define REDIS_DEF_TIMEOUT 2000
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 {
61     char query[MAX_REDIS_QUERY];
62     char type[DATA_MAX_NAME_LEN];
63     char instance[DATA_MAX_NAME_LEN];
64     redis_query_t *next;
65 };
66
67 struct redis_node_s;
68 typedef struct redis_node_s redis_node_t;
69 struct redis_node_s
70 {
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 = NULL;
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   {
95     ERROR ("redis plugin: A node with the name `%s' already exists.",
96         rn->name);
97     return (-1);
98   }
99
100   rn_copy = malloc (sizeof (*rn_copy));
101   if (rn_copy == NULL)
102   {
103     ERROR ("redis plugin: malloc failed adding redis_node to the tree.");
104     return (-1);
105   }
106
107   memcpy (rn_copy, rn, sizeof (*rn_copy));
108   rn_copy->next = NULL;
109
110   DEBUG ("redis plugin: Adding node \"%s\".", rn->name);
111
112   if (nodes_head == NULL)
113     nodes_head = rn_copy;
114   else
115   {
116     rn_ptr = nodes_head;
117     while (rn_ptr->next != NULL)
118       rn_ptr = rn_ptr->next;
119     rn_ptr->next = rn_copy;
120   }
121
122   return (0);
123 } /* }}} */
124
125 static redis_query_t *redis_config_query (oconfig_item_t *ci) /* {{{ */
126 {
127     redis_query_t *rq;
128     int status;
129
130     rq = calloc(1, sizeof(*rq));
131     if (rq == NULL) {
132         ERROR("redis plugin: calloc failed adding redis_query.");
133         return NULL;
134     }
135     status = cf_util_get_string_buffer(ci, rq->query, sizeof(rq->query));
136     if (status != 0)
137         goto err;
138
139     /*
140      * Default to a gauge type.
141      */
142     (void)strncpy(rq->type, "gauge", sizeof(rq->type));
143     (void)sstrncpy(rq->instance, rq->query, sizeof(rq->instance));
144     replace_special(rq->instance, sizeof(rq->instance));
145
146     for (int i = 0; i < ci->children_num; i++) {
147         oconfig_item_t *option = ci->children + i;
148
149         if (strcasecmp("Type", option->key) == 0) {
150             status = cf_util_get_string_buffer(option, rq->type, sizeof(rq->type));
151         } else if (strcasecmp("Instance", option->key) == 0) {
152             status = cf_util_get_string_buffer(option, rq->instance, sizeof(rq->instance));
153         } else {
154             WARNING("redis plugin: unknown configuration option: %s", option->key);
155             status = -1;
156         }
157         if (status != 0)
158             goto err;
159     }
160     return rq;
161  err:
162     free(rq);
163     return NULL;
164 } /* }}} */
165
166 static int redis_config_node (oconfig_item_t *ci) /* {{{ */
167 {
168   redis_query_t *rq;
169   int status;
170   int timeout;
171
172   redis_node_t rn = {
173     .port = REDIS_DEF_PORT,
174     .timeout.tv_usec = REDIS_DEF_TIMEOUT
175   };
176
177   sstrncpy (rn.host, REDIS_DEF_HOST, sizeof (rn.host));
178
179   status = cf_util_get_string_buffer (ci, rn.name, sizeof (rn.name));
180   if (status != 0)
181     return (status);
182
183   for (int i = 0; i < ci->children_num; i++)
184   {
185     oconfig_item_t *option = ci->children + i;
186
187     if (strcasecmp ("Host", option->key) == 0)
188       status = cf_util_get_string_buffer (option, rn.host, sizeof (rn.host));
189     else if (strcasecmp ("Port", option->key) == 0)
190     {
191       status = cf_util_get_port_number (option);
192       if (status > 0)
193       {
194         rn.port = status;
195         status = 0;
196       }
197     }
198     else if (strcasecmp ("Query", option->key) == 0)
199     {
200       rq = redis_config_query(option);
201       if (rq == NULL) {
202           status =1;
203       } else {
204           rq->next = rn.queries;
205           rn.queries = rq;
206       }
207     }
208     else if (strcasecmp ("Timeout", option->key) == 0)
209     {
210       status = cf_util_get_int (option, &timeout);
211       if (status == 0) rn.timeout.tv_usec = timeout;
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.", option->key);
218
219     if (status != 0)
220       break;
221   }
222
223   if (status != 0)
224     return (status);
225
226   return (redis_node_add (&rn));
227 } /* }}} int redis_config_node */
228
229 static int redis_config (oconfig_item_t *ci) /* {{{ */
230 {
231   for (int i = 0; i < ci->children_num; i++)
232   {
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.", option->key);
240   }
241
242   if (nodes_head == NULL)
243   {
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)))
252 static void redis_submit (char *plugin_instance,
253     const char *type, const char *type_instance,
254     value_t value) /* {{{ */
255 {
256   value_t values[1];
257   value_list_t vl = VALUE_LIST_INIT;
258
259   values[0] = value;
260
261   vl.values = values;
262   vl.values_len = 1;
263   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
264   sstrncpy (vl.plugin, "redis", sizeof (vl.plugin));
265   if (plugin_instance != NULL)
266     sstrncpy (vl.plugin_instance, plugin_instance,
267         sizeof (vl.plugin_instance));
268   sstrncpy (vl.type, type, sizeof (vl.type));
269   if (type_instance != NULL)
270     sstrncpy (vl.type_instance, type_instance,
271         sizeof (vl.type_instance));
272
273   plugin_dispatch_values (&vl);
274 } /* }}} */
275
276 static int redis_init (void) /* {{{ */
277 {
278   redis_node_t rn = {
279     .name = "default",
280     .host = REDIS_DEF_HOST,
281     .port = REDIS_DEF_PORT,
282     .timeout.tv_sec = 0,
283     .timeout.tv_usec = REDIS_DEF_TIMEOUT,
284     .next = NULL
285 };
286
287   if (nodes_head == NULL)
288     redis_node_add (&rn);
289
290   return (0);
291 } /* }}} int redis_init */
292
293 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) /* {{{ */
294 {
295   char *str = strstr (info_line, field_name);
296   static char buf[MAX_REDIS_VAL_SIZE];
297   value_t val;
298   if (str)
299   {
300     int i;
301
302     str += strlen (field_name) + 1; /* also skip the ':' */
303     for(i=0;(*str && (isdigit((unsigned char)*str) || *str == '.'));i++,str++)
304       buf[i] = *str;
305     buf[i] ='\0';
306
307     if(parse_value (buf, &val, ds_type) == -1)
308     {
309       WARNING ("redis plugin: Unable to parse field `%s'.", field_name);
310       return (-1);
311     }
312
313     redis_submit (node, type, type_instance, val);
314     return (0);
315   }
316   return (-1);
317
318 } /* }}} int redis_handle_info */
319
320 static int redis_handle_query (redisContext *rh, redis_node_t *rn, redis_query_t *rq) /* {{{ */
321 {
322     redisReply *rr;
323     const data_set_t *ds;
324     value_t val;
325
326     ds = plugin_get_ds (rq->type);
327     if (!ds) {
328         ERROR ("redis plugin: DataSet `%s' not defined.", rq->type);
329         return (-1);
330     }
331
332     if (ds->ds_num != 1) {
333         ERROR ("redis plugin: DS `%s' has too many types.", rq->type);
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: Unable to parse field `%s'.", rq->type);
362             freeReplyObject (rr);
363             return (-1);
364         }
365         break;
366     default:
367         WARNING("redis plugin: Cannot coerce redis type.");
368         freeReplyObject(rr);
369         return (-1);
370     }
371
372     redis_submit(rn->name, rq->type, (strlen(rq->instance) >0)?rq->instance:NULL, val);
373     freeReplyObject (rr);
374     return 0;
375 } /* }}} int redis_handle_query */
376
377 static int redis_read (void) /* {{{ */
378 {
379   for (redis_node_t *rn = nodes_head; rn != NULL; rn = rn->next)
380   {
381     redisContext *rh;
382     redisReply   *rr;
383
384     DEBUG ("redis plugin: querying info from node `%s' (%s:%d).", rn->name, rn->host, rn->port);
385
386     rh = redisConnectWithTimeout ((char *)rn->host, rn->port, rn->timeout);
387     if (rh == NULL)
388     {
389       ERROR ("redis plugin: unable to connect to node `%s' (%s:%d).", rn->name, rn->host, rn->port);
390       continue;
391     }
392
393     if (strlen (rn->passwd) > 0)
394     {
395       DEBUG ("redis plugin: authenticating node `%s' passwd(%s).", rn->name, rn->passwd);
396
397       if ((rr = redisCommand (rh, "AUTH %s", rn->passwd)) == NULL)
398       {
399         WARNING ("redis plugin: unable to authenticate on node `%s'.", rn->name);
400         goto redis_fail;
401       }
402
403       if (rr->type != REDIS_REPLY_STATUS)
404       {
405         WARNING ("redis plugin: invalid authentication on node `%s'.", rn->name);
406         goto redis_fail;
407       }
408
409       freeReplyObject (rr);
410     }
411
412     if ((rr = redisCommand(rh, "INFO")) == NULL)
413     {
414       WARNING ("redis plugin: unable to get info from node `%s'.", rn->name);
415       goto redis_fail;
416     }
417
418     redis_handle_info (rn->name, rr->str, "uptime", NULL, "uptime_in_seconds", DS_TYPE_GAUGE);
419     redis_handle_info (rn->name, rr->str, "current_connections", "clients", "connected_clients", DS_TYPE_GAUGE);
420     redis_handle_info (rn->name, rr->str, "blocked_clients", NULL, "blocked_clients", DS_TYPE_GAUGE);
421     redis_handle_info (rn->name, rr->str, "memory", NULL, "used_memory", DS_TYPE_GAUGE);
422     redis_handle_info (rn->name, rr->str, "memory_lua", NULL, "used_memory_lua", DS_TYPE_GAUGE);
423     /* changes_since_last_save: Deprecated in redis version 2.6 and above */
424     redis_handle_info (rn->name, rr->str, "volatile_changes", NULL, "changes_since_last_save", DS_TYPE_GAUGE);
425     redis_handle_info (rn->name, rr->str, "total_connections", NULL, "total_connections_received", DS_TYPE_DERIVE);
426     redis_handle_info (rn->name, rr->str, "total_operations", NULL, "total_commands_processed", DS_TYPE_DERIVE);
427     redis_handle_info (rn->name, rr->str, "operations_per_second", NULL, "instantaneous_ops_per_sec", DS_TYPE_GAUGE);
428     redis_handle_info (rn->name, rr->str, "expired_keys", NULL, "expired_keys", DS_TYPE_DERIVE);
429     redis_handle_info (rn->name, rr->str, "evicted_keys", NULL, "evicted_keys", DS_TYPE_DERIVE);
430     redis_handle_info (rn->name, rr->str, "pubsub", "channels", "pubsub_channels", DS_TYPE_GAUGE);
431     redis_handle_info (rn->name, rr->str, "pubsub", "patterns", "pubsub_patterns", DS_TYPE_GAUGE);
432     redis_handle_info (rn->name, rr->str, "current_connections", "slaves", "connected_slaves", DS_TYPE_GAUGE);
433     redis_handle_info (rn->name, rr->str, "cache_result", "hits", "keyspace_hits", DS_TYPE_DERIVE);
434     redis_handle_info (rn->name, rr->str, "cache_result", "misses", "keyspace_misses", DS_TYPE_DERIVE);
435     redis_handle_info (rn->name, rr->str, "total_bytes", "input", "total_net_input_bytes", DS_TYPE_DERIVE);
436     redis_handle_info (rn->name, rr->str, "total_bytes", "output", "total_net_output_bytes", DS_TYPE_DERIVE);
437
438     for (redis_query_t *rq = rn->queries; rq != NULL; rq = rq->next)
439         redis_handle_query(rh, rn, rq);
440
441 redis_fail:
442     if (rr != NULL)
443       freeReplyObject (rr);
444     redisFree (rh);
445   }
446
447   return 0;
448 }
449 /* }}} */
450
451 void module_register (void) /* {{{ */
452 {
453   plugin_register_complex_config ("redis", redis_config);
454   plugin_register_init ("redis", redis_init);
455   plugin_register_read ("redis", redis_read);
456   /* TODO: plugin_register_write: one redis list per value id with
457    * X elements */
458 }
459 /* }}} */
460
461 /* vim: set sw=2 sts=2 et fdm=marker : */