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