Merge branch 'collectd-5.6' into collectd-5.7
[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 #if HAVE_STDINT_H
38 #define MONGO_HAVE_STDINT 1
39 #else
40 #define MONGO_USE_LONG_LONG_INT 1
41 #endif
42 #include <mongo.h>
43
44 #if (MONGO_MAJOR == 0) && (MONGO_MINOR < 8)
45 #define bson_alloc() bson_create()
46 #define bson_dealloc(b) bson_dispose(b)
47 #endif
48
49 struct wm_node_s {
50   char name[DATA_MAX_NAME_LEN];
51
52   char *host;
53   int port;
54   int timeout;
55
56   /* Authentication information */
57   char *db;
58   char *user;
59   char *passwd;
60
61   _Bool store_rates;
62
63   mongo conn[1];
64   pthread_mutex_t lock;
65 };
66 typedef struct wm_node_s wm_node_t;
67
68 /*
69  * Functions
70  */
71 static bson *wm_create_bson(const data_set_t *ds, /* {{{ */
72                             const value_list_t *vl, _Bool store_rates) {
73   bson *ret;
74   gauge_t *rates;
75
76   ret = bson_alloc(); /* matched by bson_dealloc() */
77   if (ret == NULL) {
78     ERROR("write_mongodb plugin: bson_create failed.");
79     return (NULL);
80   }
81
82   if (store_rates) {
83     rates = uc_get_rate(ds, vl);
84     if (rates == NULL) {
85       ERROR("write_mongodb plugin: uc_get_rate() failed.");
86       return (NULL);
87     }
88   } else {
89     rates = NULL;
90   }
91
92   bson_init(ret); /* matched by bson_destroy() */
93   bson_append_date(ret, "time", (bson_date_t)CDTIME_T_TO_MS(vl->time));
94   bson_append_string(ret, "host", vl->host);
95   bson_append_string(ret, "plugin", vl->plugin);
96   bson_append_string(ret, "plugin_instance", vl->plugin_instance);
97   bson_append_string(ret, "type", vl->type);
98   bson_append_string(ret, "type_instance", vl->type_instance);
99
100   bson_append_start_array(ret, "values"); /* {{{ */
101   for (int i = 0; i < ds->ds_num; i++) {
102     char key[16];
103
104     ssnprintf(key, sizeof(key), "%i", i);
105
106     if (ds->ds[i].type == DS_TYPE_GAUGE)
107       bson_append_double(ret, key, vl->values[i].gauge);
108     else if (store_rates)
109       bson_append_double(ret, key, (double)rates[i]);
110     else if (ds->ds[i].type == DS_TYPE_COUNTER)
111       bson_append_long(ret, key, vl->values[i].counter);
112     else if (ds->ds[i].type == DS_TYPE_DERIVE)
113       bson_append_long(ret, key, vl->values[i].derive);
114     else if (ds->ds[i].type == DS_TYPE_ABSOLUTE)
115       bson_append_long(ret, key, vl->values[i].absolute);
116     else
117       assert(23 == 42);
118   }
119   bson_append_finish_array(ret); /* }}} values */
120
121   bson_append_start_array(ret, "dstypes"); /* {{{ */
122   for (int i = 0; i < ds->ds_num; i++) {
123     char key[16];
124
125     ssnprintf(key, sizeof(key), "%i", i);
126
127     if (store_rates)
128       bson_append_string(ret, key, "gauge");
129     else
130       bson_append_string(ret, key, DS_TYPE_TO_STRING(ds->ds[i].type));
131   }
132   bson_append_finish_array(ret); /* }}} dstypes */
133
134   bson_append_start_array(ret, "dsnames"); /* {{{ */
135   for (int i = 0; i < ds->ds_num; i++) {
136     char key[16];
137
138     ssnprintf(key, sizeof(key), "%i", i);
139     bson_append_string(ret, key, ds->ds[i].name);
140   }
141   bson_append_finish_array(ret); /* }}} dsnames */
142
143   bson_finish(ret);
144
145   sfree(rates);
146   return (ret);
147 } /* }}} bson *wm_create_bson */
148
149 static int wm_write(const data_set_t *ds, /* {{{ */
150                     const value_list_t *vl, user_data_t *ud) {
151   wm_node_t *node = ud->data;
152   char collection_name[512];
153   bson *bson_record;
154   int status;
155
156   ssnprintf(collection_name, sizeof(collection_name), "collectd.%s",
157             vl->plugin);
158
159   bson_record = wm_create_bson(ds, vl, node->store_rates);
160   if (bson_record == NULL)
161     return (ENOMEM);
162
163   pthread_mutex_lock(&node->lock);
164
165   if (!mongo_is_connected(node->conn)) {
166     INFO("write_mongodb plugin: Connecting to [%s]:%i",
167          (node->host != NULL) ? node->host : "localhost",
168          (node->port != 0) ? node->port : MONGO_DEFAULT_PORT);
169     status = mongo_connect(node->conn, node->host, node->port);
170     if (status != MONGO_OK) {
171       ERROR("write_mongodb plugin: Connecting to [%s]:%i failed.",
172             (node->host != NULL) ? node->host : "localhost",
173             (node->port != 0) ? node->port : MONGO_DEFAULT_PORT);
174       mongo_destroy(node->conn);
175       pthread_mutex_unlock(&node->lock);
176       return (-1);
177     }
178
179     if ((node->db != NULL) && (node->user != NULL) && (node->passwd != NULL)) {
180       status = mongo_cmd_authenticate(node->conn, node->db, node->user,
181                                       node->passwd);
182       if (status != MONGO_OK) {
183         ERROR("write_mongodb plugin: Authenticating to [%s]%i for database "
184               "\"%s\" as user \"%s\" failed.",
185               (node->host != NULL) ? node->host : "localhost",
186               (node->port != 0) ? node->port : MONGO_DEFAULT_PORT, node->db,
187               node->user);
188         mongo_destroy(node->conn);
189         pthread_mutex_unlock(&node->lock);
190         return (-1);
191       }
192     }
193
194     if (node->timeout > 0) {
195       status = mongo_set_op_timeout(node->conn, node->timeout);
196       if (status != MONGO_OK) {
197         WARNING("write_mongodb plugin: mongo_set_op_timeout(%i) failed: %s",
198                 node->timeout, node->conn->errstr);
199       }
200     }
201   }
202
203   /* Assert if the connection has been established */
204   assert(mongo_is_connected(node->conn));
205
206 #if MONGO_MINOR >= 6
207   /* There was an API change in 0.6.0 as linked below */
208   /* https://github.com/mongodb/mongo-c-driver/blob/master/HISTORY.md */
209   status = mongo_insert(node->conn, collection_name, bson_record, NULL);
210 #else
211   status = mongo_insert(node->conn, collection_name, bson_record);
212 #endif
213
214   if (status != MONGO_OK) {
215     ERROR("write_mongodb plugin: error inserting record: %d", node->conn->err);
216     if (node->conn->err != MONGO_BSON_INVALID)
217       ERROR("write_mongodb plugin: %s", node->conn->errstr);
218     else
219       ERROR("write_mongodb plugin: Invalid BSON structure, error = %#x",
220             (unsigned int)bson_record->err);
221
222     /* Disconnect except on data errors. */
223     if ((node->conn->err != MONGO_BSON_INVALID) &&
224         (node->conn->err != MONGO_BSON_NOT_FINISHED))
225       mongo_destroy(node->conn);
226   }
227
228   pthread_mutex_unlock(&node->lock);
229
230   /* free our resource as not to leak memory */
231   bson_destroy(bson_record); /* matches bson_init() */
232   bson_dealloc(bson_record); /* matches bson_alloc() */
233
234   return (0);
235 } /* }}} int wm_write */
236
237 static void wm_config_free(void *ptr) /* {{{ */
238 {
239   wm_node_t *node = ptr;
240
241   if (node == NULL)
242     return;
243
244   if (mongo_is_connected(node->conn))
245     mongo_destroy(node->conn);
246
247   sfree(node->host);
248   sfree(node);
249 } /* }}} void wm_config_free */
250
251 static int wm_config_node(oconfig_item_t *ci) /* {{{ */
252 {
253   wm_node_t *node;
254   int status;
255
256   node = calloc(1, sizeof(*node));
257   if (node == NULL)
258     return (ENOMEM);
259   mongo_init(node->conn);
260   node->host = NULL;
261   node->store_rates = 1;
262   pthread_mutex_init(&node->lock, /* attr = */ NULL);
263
264   status = cf_util_get_string_buffer(ci, node->name, sizeof(node->name));
265
266   if (status != 0) {
267     sfree(node);
268     return (status);
269   }
270
271   for (int i = 0; i < ci->children_num; i++) {
272     oconfig_item_t *child = ci->children + i;
273
274     if (strcasecmp("Host", child->key) == 0)
275       status = cf_util_get_string(child, &node->host);
276     else if (strcasecmp("Port", child->key) == 0) {
277       status = cf_util_get_port_number(child);
278       if (status > 0) {
279         node->port = status;
280         status = 0;
281       }
282     } else if (strcasecmp("Timeout", child->key) == 0)
283       status = cf_util_get_int(child, &node->timeout);
284     else if (strcasecmp("StoreRates", child->key) == 0)
285       status = cf_util_get_boolean(child, &node->store_rates);
286     else if (strcasecmp("Database", child->key) == 0)
287       status = cf_util_get_string(child, &node->db);
288     else if (strcasecmp("User", child->key) == 0)
289       status = cf_util_get_string(child, &node->user);
290     else if (strcasecmp("Password", child->key) == 0)
291       status = cf_util_get_string(child, &node->passwd);
292     else
293       WARNING("write_mongodb plugin: Ignoring unknown config option \"%s\".",
294               child->key);
295
296     if (status != 0)
297       break;
298   } /* for (i = 0; i < ci->children_num; i++) */
299
300   if ((node->db != NULL) || (node->user != NULL) || (node->passwd != NULL)) {
301     if ((node->db == NULL) || (node->user == NULL) || (node->passwd == NULL)) {
302       WARNING(
303           "write_mongodb plugin: Authentication requires the "
304           "\"Database\", \"User\" and \"Password\" options to be specified, "
305           "but at last one of them is missing. Authentication will NOT be "
306           "used.");
307       sfree(node->db);
308       sfree(node->user);
309       sfree(node->passwd);
310     }
311   }
312
313   if (status == 0) {
314     char cb_name[DATA_MAX_NAME_LEN];
315
316     ssnprintf(cb_name, sizeof(cb_name), "write_mongodb/%s", node->name);
317
318     status = plugin_register_write(
319         cb_name, wm_write, &(user_data_t){
320                                .data = node, .free_func = wm_config_free,
321                            });
322     INFO("write_mongodb plugin: registered write plugin %s %d", cb_name,
323          status);
324   }
325
326   if (status != 0)
327     wm_config_free(node);
328
329   return (status);
330 } /* }}} int wm_config_node */
331
332 static int wm_config(oconfig_item_t *ci) /* {{{ */
333 {
334   for (int i = 0; i < ci->children_num; i++) {
335     oconfig_item_t *child = ci->children + i;
336
337     if (strcasecmp("Node", child->key) == 0)
338       wm_config_node(child);
339     else
340       WARNING("write_mongodb plugin: Ignoring unknown "
341               "configuration option \"%s\" at top level.",
342               child->key);
343   }
344
345   return (0);
346 } /* }}} int wm_config */
347
348 void module_register(void) {
349   plugin_register_complex_config("write_mongodb", wm_config);
350 }
351
352 /* vim: set sw=2 sts=2 tw=78 et fdm=marker : */