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