Fix compile time issues
[collectd.git] / src / write_redis.c
1 /**
2  * collectd - src/write_redis.c
3  * Copyright (C) 2010-2015  Florian Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian Forster <ff at octo.it>
25  **/
26
27 #include "collectd.h"
28
29 #include "plugin.h"
30 #include "utils/common/common.h"
31
32 #include <hiredis/hiredis.h>
33 #include <sys/time.h>
34
35 #ifndef REDIS_DEFAULT_PREFIX
36 #define REDIS_DEFAULT_PREFIX "collectd/"
37 #endif
38
39 struct wr_node_s {
40   char name[DATA_MAX_NAME_LEN];
41
42   char *host;
43   int port;
44   struct timeval timeout;
45   char *prefix;
46   int database;
47   int max_set_size;
48   int max_set_duration;
49   bool store_rates;
50
51   redisContext *conn;
52   pthread_mutex_t lock;
53 };
54 typedef struct wr_node_s wr_node_t;
55
56 /*
57  * Functions
58  */
59 static int wr_write(const data_set_t *ds, /* {{{ */
60                     const value_list_t *vl, user_data_t *ud) {
61   wr_node_t *node = ud->data;
62   char ident[512];
63   char key[512];
64   char value[512] = {0};
65   char time[24];
66   size_t value_size;
67   char *value_ptr;
68   int status;
69   redisReply *rr;
70
71   status = FORMAT_VL(ident, sizeof(ident), vl);
72   if (status != 0)
73     return status;
74   ssnprintf(key, sizeof(key), "%s%s",
75             (node->prefix != NULL) ? node->prefix : REDIS_DEFAULT_PREFIX,
76             ident);
77   ssnprintf(time, sizeof(time), "%.9f", CDTIME_T_TO_DOUBLE(vl->time));
78
79   value_size = sizeof(value);
80   value_ptr = &value[0];
81   status = format_values(value_ptr, value_size, ds, vl, node->store_rates);
82   if (status != 0)
83     return status;
84
85   pthread_mutex_lock(&node->lock);
86
87   if (node->conn == NULL) {
88     node->conn =
89         redisConnectWithTimeout((char *)node->host, node->port, node->timeout);
90     if (node->conn == NULL) {
91       ERROR("write_redis plugin: Connecting to host \"%s\" (port %i) failed: "
92             "Unknown reason",
93             (node->host != NULL) ? node->host : "localhost",
94             (node->port != 0) ? node->port : 6379);
95       pthread_mutex_unlock(&node->lock);
96       return -1;
97     } else if (node->conn->err) {
98       ERROR(
99           "write_redis plugin: Connecting to host \"%s\" (port %i) failed: %s",
100           (node->host != NULL) ? node->host : "localhost",
101           (node->port != 0) ? node->port : 6379, node->conn->errstr);
102       pthread_mutex_unlock(&node->lock);
103       return -1;
104     }
105
106     rr = redisCommand(node->conn, "SELECT %d", node->database);
107     if (rr == NULL)
108       WARNING("SELECT command error. database:%d message:%s", node->database,
109               node->conn->errstr);
110     else
111       freeReplyObject(rr);
112   }
113
114   rr = redisCommand(node->conn, "ZADD %s %s %s", key, time, value);
115   if (rr == NULL)
116     WARNING("ZADD command error. key:%s message:%s", key, node->conn->errstr);
117   else
118     freeReplyObject(rr);
119
120   if (node->max_set_size >= 0) {
121     rr = redisCommand(node->conn, "ZREMRANGEBYRANK %s %d %d", key, 0,
122                       (-1 * node->max_set_size) - 1);
123     if (rr == NULL)
124       WARNING("ZREMRANGEBYRANK command error. key:%s message:%s", key,
125               node->conn->errstr);
126     else
127       freeReplyObject(rr);
128   }
129
130   if (node->max_set_duration > 0) {
131     /*
132      * remove element, scored less than 'current-max_set_duration'
133      * '(...' indicates 'less than' in redis CLI.
134      */
135     rr = redisCommand(node->conn, "ZREMRANGEBYSCORE %s -1 (%.9f", key,
136                       (CDTIME_T_TO_DOUBLE(vl->time) - node->max_set_duration));
137     if (rr == NULL)
138       WARNING("ZREMRANGEBYSCORE command error. key:%s message:%s", key,
139               node->conn->errstr);
140     else
141       freeReplyObject(rr);
142   }
143
144   /* TODO(octo): This is more overhead than necessary. Use the cache and
145    * metadata to determine if it is a new metric and call SADD only once for
146    * each metric. */
147   rr = redisCommand(
148       node->conn, "SADD %svalues %s",
149       (node->prefix != NULL) ? node->prefix : REDIS_DEFAULT_PREFIX, ident);
150   if (rr == NULL)
151     WARNING("SADD command error. ident:%s message:%s", ident,
152             node->conn->errstr);
153   else
154     freeReplyObject(rr);
155
156   pthread_mutex_unlock(&node->lock);
157
158   return 0;
159 } /* }}} int wr_write */
160
161 static void wr_config_free(void *ptr) /* {{{ */
162 {
163   wr_node_t *node = ptr;
164
165   if (node == NULL)
166     return;
167
168   if (node->conn != NULL) {
169     redisFree(node->conn);
170     node->conn = NULL;
171   }
172
173   sfree(node->host);
174   sfree(node);
175 } /* }}} void wr_config_free */
176
177 static int wr_config_node(oconfig_item_t *ci) /* {{{ */
178 {
179   wr_node_t *node;
180   int timeout;
181   int status;
182
183   node = calloc(1, sizeof(*node));
184   if (node == NULL)
185     return ENOMEM;
186   node->host = NULL;
187   node->port = 0;
188   node->timeout.tv_sec = 1;
189   node->timeout.tv_usec = 0;
190   node->conn = NULL;
191   node->prefix = NULL;
192   node->database = 0;
193   node->max_set_size = -1;
194   node->max_set_duration = -1;
195   node->store_rates = true;
196   pthread_mutex_init(&node->lock, /* attr = */ NULL);
197
198   status = cf_util_get_string_buffer(ci, node->name, sizeof(node->name));
199   if (status != 0) {
200     sfree(node);
201     return status;
202   }
203
204   for (int i = 0; i < ci->children_num; i++) {
205     oconfig_item_t *child = ci->children + i;
206
207     if (strcasecmp("Host", child->key) == 0)
208       status = cf_util_get_string(child, &node->host);
209     else if (strcasecmp("Port", child->key) == 0) {
210       status = cf_util_get_port_number(child);
211       if (status > 0) {
212         node->port = status;
213         status = 0;
214       }
215     } else if (strcasecmp("Timeout", child->key) == 0) {
216       status = cf_util_get_int(child, &timeout);
217       if (status == 0) {
218         node->timeout.tv_usec = timeout * 1000;
219         node->timeout.tv_sec = node->timeout.tv_usec / 1000000L;
220         node->timeout.tv_usec %= 1000000L;
221       }
222     } else if (strcasecmp("Prefix", child->key) == 0) {
223       status = cf_util_get_string(child, &node->prefix);
224     } else if (strcasecmp("Database", child->key) == 0) {
225       status = cf_util_get_int(child, &node->database);
226     } else if (strcasecmp("MaxSetSize", child->key) == 0) {
227       status = cf_util_get_int(child, &node->max_set_size);
228     } else if (strcasecmp("MaxSetDuration", child->key) == 0) {
229       status = cf_util_get_int(child, &node->max_set_duration);
230     } else if (strcasecmp("StoreRates", child->key) == 0) {
231       status = cf_util_get_boolean(child, &node->store_rates);
232     } else
233       WARNING("write_redis plugin: Ignoring unknown config option \"%s\".",
234               child->key);
235
236     if (status != 0)
237       break;
238   } /* for (i = 0; i < ci->children_num; i++) */
239
240   if (status == 0) {
241     char cb_name[sizeof("write_redis/") + DATA_MAX_NAME_LEN];
242
243     ssnprintf(cb_name, sizeof(cb_name), "write_redis/%s", node->name);
244
245     status = plugin_register_write(cb_name, wr_write,
246                                    &(user_data_t){
247                                        .data = node,
248                                        .free_func = wr_config_free,
249                                    });
250   }
251
252   if (status != 0)
253     wr_config_free(node);
254
255   return status;
256 } /* }}} int wr_config_node */
257
258 static int wr_config(oconfig_item_t *ci) /* {{{ */
259 {
260   for (int i = 0; i < ci->children_num; i++) {
261     oconfig_item_t *child = ci->children + i;
262
263     if (strcasecmp("Node", child->key) == 0)
264       wr_config_node(child);
265     else
266       WARNING("write_redis plugin: Ignoring unknown "
267               "configuration option \"%s\" at top level.",
268               child->key);
269   }
270
271   return 0;
272 } /* }}} int wr_config */
273
274 void module_register(void) {
275   plugin_register_complex_config("write_redis", wr_config);
276 }