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