Merge branch 'master' into virt_list_domains
[collectd.git] / src / write_mongodb.c
1 /**
2  * collectd - src/write_mongodb.c
3  * Copyright (C) 2010-2013  Florian Forster
4  * Copyright (C) 2010       Akkarit Sangpetch
5  * Copyright (C) 2012       Chris Lundquist
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a
8  * copy of this software and associated documentation files (the "Software"),
9  * to deal in the Software without restriction, including without limitation
10  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11  * and/or sell copies of the Software, and to permit persons to whom the
12  * Software is furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23  * DEALINGS IN THE SOFTWARE.
24  *
25  * Authors:
26  *   Florian Forster <octo at collectd.org>
27  *   Akkarit Sangpetch <asangpet at andrew.cmu.edu>
28  *   Chris Lundquist <clundquist at bluebox.net>
29  **/
30
31 #include "collectd.h"
32
33 #include "common.h"
34 #include "plugin.h"
35 #include "utils_cache.h"
36
37 #define MONGO_HAVE_STDINT 1
38 #include <mongo.h>
39
40 #if (MONGO_MAJOR == 0) && (MONGO_MINOR < 8)
41 #define bson_alloc() bson_create()
42 #define bson_dealloc(b) bson_dispose(b)
43 #endif
44
45 struct wm_node_s {
46   char name[DATA_MAX_NAME_LEN];
47
48   char *host;
49   int port;
50   int timeout;
51
52   /* Authentication information */
53   char *db;
54   char *user;
55   char *passwd;
56
57   _Bool store_rates;
58
59   mongo conn[1];
60   pthread_mutex_t lock;
61 };
62 typedef struct wm_node_s wm_node_t;
63
64 /*
65  * Functions
66  */
67 static bson *wm_create_bson(const data_set_t *ds, /* {{{ */
68                             const value_list_t *vl, _Bool store_rates) {
69   bson *ret;
70   gauge_t *rates;
71
72   ret = bson_alloc(); /* matched by bson_dealloc() */
73   if (ret == NULL) {
74     ERROR("write_mongodb plugin: bson_create failed.");
75     return (NULL);
76   }
77
78   if (store_rates) {
79     rates = uc_get_rate(ds, vl);
80     if (rates == NULL) {
81       ERROR("write_mongodb plugin: uc_get_rate() failed.");
82       return (NULL);
83     }
84   } else {
85     rates = NULL;
86   }
87
88   bson_init(ret); /* matched by bson_destroy() */
89   bson_append_date(ret, "time", (bson_date_t)CDTIME_T_TO_MS(vl->time));
90   bson_append_string(ret, "host", vl->host);
91   bson_append_string(ret, "plugin", vl->plugin);
92   bson_append_string(ret, "plugin_instance", vl->plugin_instance);
93   bson_append_string(ret, "type", vl->type);
94   bson_append_string(ret, "type_instance", vl->type_instance);
95
96   bson_append_start_array(ret, "values"); /* {{{ */
97   for (int i = 0; i < ds->ds_num; i++) {
98     char key[16];
99
100     ssnprintf(key, sizeof(key), "%i", i);
101
102     if (ds->ds[i].type == DS_TYPE_GAUGE)
103       bson_append_double(ret, key, vl->values[i].gauge);
104     else if (store_rates)
105       bson_append_double(ret, key, (double)rates[i]);
106     else if (ds->ds[i].type == DS_TYPE_COUNTER)
107       bson_append_long(ret, key, vl->values[i].counter);
108     else if (ds->ds[i].type == DS_TYPE_DERIVE)
109       bson_append_long(ret, key, vl->values[i].derive);
110     else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
111       bson_append_long(ret, key, vl->values[i].absolute);
112     else
113       assert(23 == 42);
114   }
115   bson_append_finish_array(ret); /* }}} values */
116
117   bson_append_start_array(ret, "dstypes"); /* {{{ */
118   for (int i = 0; i < ds->ds_num; i++) {
119     char key[16];
120
121     ssnprintf(key, sizeof(key), "%i", i);
122
123     if (store_rates)
124       bson_append_string(ret, key, "gauge");
125     else
126       bson_append_string(ret, key, DS_TYPE_TO_STRING(ds->ds[i].type));
127   }
128   bson_append_finish_array(ret); /* }}} dstypes */
129
130   bson_append_start_array(ret, "dsnames"); /* {{{ */
131   for (int i = 0; i < ds->ds_num; i++) {
132     char key[16];
133
134     ssnprintf(key, sizeof(key), "%i", i);
135     bson_append_string(ret, key, ds->ds[i].name);
136   }
137   bson_append_finish_array(ret); /* }}} dsnames */
138
139   bson_finish(ret);
140
141   sfree(rates);
142   return (ret);
143 } /* }}} bson *wm_create_bson */
144
145 static int wm_write(const data_set_t *ds, /* {{{ */
146                     const value_list_t *vl, user_data_t *ud) {
147   wm_node_t *node = ud->data;
148   char collection_name[512];
149   bson *bson_record;
150   int status;
151
152   ssnprintf(collection_name, sizeof(collection_name), "collectd.%s",
153             vl->plugin);
154
155   bson_record = wm_create_bson(ds, vl, node->store_rates);
156   if (bson_record == NULL)
157     return (ENOMEM);
158
159   pthread_mutex_lock(&node->lock);
160
161   if (!mongo_is_connected(node->conn)) {
162     INFO("write_mongodb plugin: Connecting to [%s]:%i",
163          (node->host != NULL) ? node->host : "localhost",
164          (node->port != 0) ? node->port : MONGO_DEFAULT_PORT);
165     status = mongo_connect(node->conn, node->host, node->port);
166     if (status != MONGO_OK) {
167       ERROR("write_mongodb plugin: Connecting to [%s]:%i failed.",
168             (node->host != NULL) ? node->host : "localhost",
169             (node->port != 0) ? node->port : MONGO_DEFAULT_PORT);
170       mongo_destroy(node->conn);
171       pthread_mutex_unlock(&node->lock);
172       return (-1);
173     }
174
175     if ((node->db != NULL) && (node->user != NULL) && (node->passwd != NULL)) {
176       status = mongo_cmd_authenticate(node->conn, node->db, node->user,
177                                       node->passwd);
178       if (status != MONGO_OK) {
179         ERROR("write_mongodb plugin: Authenticating to [%s]%i for database "
180               "\"%s\" as user \"%s\" failed.",
181               (node->host != NULL) ? node->host : "localhost",
182               (node->port != 0) ? node->port : MONGO_DEFAULT_PORT, node->db,
183               node->user);
184         mongo_destroy(node->conn);
185         pthread_mutex_unlock(&node->lock);
186         return (-1);
187       }
188     }
189
190     if (node->timeout > 0) {
191       status = mongo_set_op_timeout(node->conn, node->timeout);
192       if (status != MONGO_OK) {
193         WARNING("write_mongodb plugin: mongo_set_op_timeout(%i) failed: %s",
194                 node->timeout, node->conn->errstr);
195       }
196     }
197   }
198
199   /* Assert if the connection has been established */
200   assert(mongo_is_connected(node->conn));
201
202 #if MONGO_MINOR >= 6
203   /* There was an API change in 0.6.0 as linked below */
204   /* https://github.com/mongodb/mongo-c-driver/blob/master/HISTORY.md */
205   status = mongo_insert(node->conn, collection_name, bson_record, NULL);
206 #else
207   status = mongo_insert(node->conn, collection_name, bson_record);
208 #endif
209
210   if (status != MONGO_OK) {
211     ERROR("write_mongodb plugin: error inserting record: %d", node->conn->err);
212     if (node->conn->err != MONGO_BSON_INVALID)
213       ERROR("write_mongodb plugin: %s", node->conn->errstr);
214     else
215       ERROR("write_mongodb plugin: Invalid BSON structure, error = %#x",
216             (unsigned int)bson_record->err);
217
218     /* Disconnect except on data errors. */
219     if ((node->conn->err != MONGO_BSON_INVALID) &&
220         (node->conn->err != MONGO_BSON_NOT_FINISHED))
221       mongo_destroy(node->conn);
222   }
223
224   pthread_mutex_unlock(&node->lock);
225
226   /* free our resource as not to leak memory */
227   bson_destroy(bson_record); /* matches bson_init() */
228   bson_dealloc(bson_record); /* matches bson_alloc() */
229
230   return (0);
231 } /* }}} int wm_write */
232
233 static void wm_config_free(void *ptr) /* {{{ */
234 {
235   wm_node_t *node = ptr;
236
237   if (node == NULL)
238     return;
239
240   if (mongo_is_connected(node->conn))
241     mongo_destroy(node->conn);
242
243   sfree(node->host);
244   sfree(node);
245 } /* }}} void wm_config_free */
246
247 static int wm_config_node(oconfig_item_t *ci) /* {{{ */
248 {
249   wm_node_t *node;
250   int status;
251
252   node = calloc(1, sizeof(*node));
253   if (node == NULL)
254     return (ENOMEM);
255   mongo_init(node->conn);
256   node->host = NULL;
257   node->store_rates = 1;
258   pthread_mutex_init(&node->lock, /* attr = */ NULL);
259
260   status = cf_util_get_string_buffer(ci, node->name, sizeof(node->name));
261
262   if (status != 0) {
263     sfree(node);
264     return (status);
265   }
266
267   for (int i = 0; i < ci->children_num; i++) {
268     oconfig_item_t *child = ci->children + i;
269
270     if (strcasecmp("Host", child->key) == 0)
271       status = cf_util_get_string(child, &node->host);
272     else if (strcasecmp("Port", child->key) == 0) {
273       status = cf_util_get_port_number(child);
274       if (status > 0) {
275         node->port = status;
276         status = 0;
277       }
278     } else if (strcasecmp("Timeout", child->key) == 0)
279       status = cf_util_get_int(child, &node->timeout);
280     else if (strcasecmp("StoreRates", child->key) == 0)
281       status = cf_util_get_boolean(child, &node->store_rates);
282     else if (strcasecmp("Database", child->key) == 0)
283       status = cf_util_get_string(child, &node->db);
284     else if (strcasecmp("User", child->key) == 0)
285       status = cf_util_get_string(child, &node->user);
286     else if (strcasecmp("Password", child->key) == 0)
287       status = cf_util_get_string(child, &node->passwd);
288     else
289       WARNING("write_mongodb plugin: Ignoring unknown config option \"%s\".",
290               child->key);
291
292     if (status != 0)
293       break;
294   } /* for (i = 0; i < ci->children_num; i++) */
295
296   if ((node->db != NULL) || (node->user != NULL) || (node->passwd != NULL)) {
297     if ((node->db == NULL) || (node->user == NULL) || (node->passwd == NULL)) {
298       WARNING(
299           "write_mongodb plugin: Authentication requires the "
300           "\"Database\", \"User\" and \"Password\" options to be specified, "
301           "but at last one of them is missing. Authentication will NOT be "
302           "used.");
303       sfree(node->db);
304       sfree(node->user);
305       sfree(node->passwd);
306     }
307   }
308
309   if (status == 0) {
310     char cb_name[DATA_MAX_NAME_LEN];
311
312     ssnprintf(cb_name, sizeof(cb_name), "write_mongodb/%s", node->name);
313
314     status = plugin_register_write(
315         cb_name, wm_write, &(user_data_t){
316                                .data = node, .free_func = wm_config_free,
317                            });
318     INFO("write_mongodb plugin: registered write plugin %s %d", cb_name,
319          status);
320   }
321
322   if (status != 0)
323     wm_config_free(node);
324
325   return (status);
326 } /* }}} int wm_config_node */
327
328 static int wm_config(oconfig_item_t *ci) /* {{{ */
329 {
330   for (int i = 0; i < ci->children_num; i++) {
331     oconfig_item_t *child = ci->children + i;
332
333     if (strcasecmp("Node", child->key) == 0)
334       wm_config_node(child);
335     else
336       WARNING("write_mongodb plugin: Ignoring unknown "
337               "configuration option \"%s\" at top level.",
338               child->key);
339   }
340
341   return (0);
342 } /* }}} int wm_config */
343
344 void module_register(void) {
345   plugin_register_complex_config("write_mongodb", wm_config);
346 }