Merge remote-tracking branch 'github/pr/2276'
[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 "common.h"
30 #include "plugin.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   _Bool store_rates;
49
50   redisContext *conn;
51   pthread_mutex_t lock;
52 };
53 typedef struct wr_node_s wr_node_t;
54
55 /*
56  * Functions
57  */
58 static int wr_write(const data_set_t *ds, /* {{{ */
59                     const value_list_t *vl, user_data_t *ud) {
60   wr_node_t *node = ud->data;
61   char ident[512];
62   char key[512];
63   char value[512] = {0};
64   char time[24];
65   size_t value_size;
66   char *value_ptr;
67   int status;
68   redisReply *rr;
69
70   status = FORMAT_VL(ident, sizeof(ident), vl);
71   if (status != 0)
72     return status;
73   snprintf(key, sizeof(key), "%s%s",
74            (node->prefix != NULL) ? node->prefix : REDIS_DEFAULT_PREFIX, ident);
75   snprintf(time, sizeof(time), "%.9f", CDTIME_T_TO_DOUBLE(vl->time));
76
77   value_size = sizeof(value);
78   value_ptr = &value[0];
79   status = format_values(value_ptr, value_size, ds, vl, node->store_rates);
80   if (status != 0)
81     return status;
82
83   pthread_mutex_lock(&node->lock);
84
85   if (node->conn == NULL) {
86     node->conn =
87         redisConnectWithTimeout((char *)node->host, node->port, node->timeout);
88     if (node->conn == NULL) {
89       ERROR("write_redis plugin: Connecting to host \"%s\" (port %i) failed: "
90             "Unknown reason",
91             (node->host != NULL) ? node->host : "localhost",
92             (node->port != 0) ? node->port : 6379);
93       pthread_mutex_unlock(&node->lock);
94       return -1;
95     } else if (node->conn->err) {
96       ERROR(
97           "write_redis plugin: Connecting to host \"%s\" (port %i) failed: %s",
98           (node->host != NULL) ? node->host : "localhost",
99           (node->port != 0) ? node->port : 6379, node->conn->errstr);
100       pthread_mutex_unlock(&node->lock);
101       return -1;
102     }
103
104     rr = redisCommand(node->conn, "SELECT %d", node->database);
105     if (rr == NULL)
106       WARNING("SELECT command error. database:%d message:%s", node->database,
107               node->conn->errstr);
108     else
109       freeReplyObject(rr);
110   }
111
112   rr = redisCommand(node->conn, "ZADD %s %s %s", key, time, value);
113   if (rr == NULL)
114     WARNING("ZADD command error. key:%s message:%s", key, node->conn->errstr);
115   else
116     freeReplyObject(rr);
117
118   if (node->max_set_size >= 0) {
119     rr = redisCommand(node->conn, "ZREMRANGEBYRANK %s %d %d", key, 0,
120                       (-1 * node->max_set_size) - 1);
121     if (rr == NULL)
122       WARNING("ZREMRANGEBYRANK command error. key:%s message:%s", key,
123               node->conn->errstr);
124     else
125       freeReplyObject(rr);
126   }
127
128   /* TODO(octo): This is more overhead than necessary. Use the cache and
129    * metadata to determine if it is a new metric and call SADD only once for
130    * each metric. */
131   rr = redisCommand(
132       node->conn, "SADD %svalues %s",
133       (node->prefix != NULL) ? node->prefix : REDIS_DEFAULT_PREFIX, ident);
134   if (rr == NULL)
135     WARNING("SADD command error. ident:%s message:%s", ident,
136             node->conn->errstr);
137   else
138     freeReplyObject(rr);
139
140   pthread_mutex_unlock(&node->lock);
141
142   return 0;
143 } /* }}} int wr_write */
144
145 static void wr_config_free(void *ptr) /* {{{ */
146 {
147   wr_node_t *node = ptr;
148
149   if (node == NULL)
150     return;
151
152   if (node->conn != NULL) {
153     redisFree(node->conn);
154     node->conn = NULL;
155   }
156
157   sfree(node->host);
158   sfree(node);
159 } /* }}} void wr_config_free */
160
161 static int wr_config_node(oconfig_item_t *ci) /* {{{ */
162 {
163   wr_node_t *node;
164   int timeout;
165   int status;
166
167   node = calloc(1, sizeof(*node));
168   if (node == NULL)
169     return ENOMEM;
170   node->host = NULL;
171   node->port = 0;
172   node->timeout.tv_sec = 0;
173   node->timeout.tv_usec = 1000;
174   node->conn = NULL;
175   node->prefix = NULL;
176   node->database = 0;
177   node->max_set_size = -1;
178   node->store_rates = 1;
179   pthread_mutex_init(&node->lock, /* attr = */ NULL);
180
181   status = cf_util_get_string_buffer(ci, node->name, sizeof(node->name));
182   if (status != 0) {
183     sfree(node);
184     return status;
185   }
186
187   for (int i = 0; i < ci->children_num; i++) {
188     oconfig_item_t *child = ci->children + i;
189
190     if (strcasecmp("Host", child->key) == 0)
191       status = cf_util_get_string(child, &node->host);
192     else if (strcasecmp("Port", child->key) == 0) {
193       status = cf_util_get_port_number(child);
194       if (status > 0) {
195         node->port = status;
196         status = 0;
197       }
198     } else if (strcasecmp("Timeout", child->key) == 0) {
199       status = cf_util_get_int(child, &timeout);
200       if (status == 0)
201         node->timeout.tv_usec = timeout;
202     } else if (strcasecmp("Prefix", child->key) == 0) {
203       status = cf_util_get_string(child, &node->prefix);
204     } else if (strcasecmp("Database", child->key) == 0) {
205       status = cf_util_get_int(child, &node->database);
206     } else if (strcasecmp("MaxSetSize", child->key) == 0) {
207       status = cf_util_get_int(child, &node->max_set_size);
208     } else if (strcasecmp("StoreRates", child->key) == 0) {
209       status = cf_util_get_boolean(child, &node->store_rates);
210     } else
211       WARNING("write_redis plugin: Ignoring unknown config option \"%s\".",
212               child->key);
213
214     if (status != 0)
215       break;
216   } /* for (i = 0; i < ci->children_num; i++) */
217
218   if (status == 0) {
219     char cb_name[sizeof("write_redis/") + DATA_MAX_NAME_LEN];
220
221     snprintf(cb_name, sizeof(cb_name), "write_redis/%s", node->name);
222
223     status =
224         plugin_register_write(cb_name, wr_write,
225                               &(user_data_t){
226                                   .data = node, .free_func = wr_config_free,
227                               });
228   }
229
230   if (status != 0)
231     wr_config_free(node);
232
233   return status;
234 } /* }}} int wr_config_node */
235
236 static int wr_config(oconfig_item_t *ci) /* {{{ */
237 {
238   for (int i = 0; i < ci->children_num; i++) {
239     oconfig_item_t *child = ci->children + i;
240
241     if (strcasecmp("Node", child->key) == 0)
242       wr_config_node(child);
243     else
244       WARNING("write_redis plugin: Ignoring unknown "
245               "configuration option \"%s\" at top level.",
246               child->key);
247   }
248
249   return 0;
250 } /* }}} int wr_config */
251
252 void module_register(void) {
253   plugin_register_complex_config("write_redis", wr_config);
254 }