+ char *uri;
+ size_t uri_length;
+ char const *format_string;
+
+ if (node->connected) {
+ return 0;
+ }
+
+ INFO("write_mongodb plugin: Connecting to [%s]:%i",
+ (node->host != NULL) ? node->host : "localhost",
+ (node->port != 0) ? node->port : MONGOC_DEFAULT_PORT);
+
+ if ((node->db != NULL) && (node->user != NULL) && (node->passwd != NULL)) {
+ format_string = "mongodb://%s:%s@%s:%d/?authSource=%s";
+ uri_length = strlen(format_string) + strlen(node->user) +
+ strlen(node->passwd) + strlen(node->host) + 5 +
+ strlen(node->db) + 1;
+ if ((uri = calloc(1, uri_length)) == NULL) {
+ ERROR("write_mongodb plugin: Not enough memory to assemble "
+ "authentication string.");
+ mongoc_client_destroy(node->client);
+ node->client = NULL;
+ node->connected = 0;
+ return -1;
+ }
+ ssnprintf(uri, uri_length, format_string, node->user, node->passwd,
+ node->host, node->port, node->db);
+
+ node->client = mongoc_client_new(uri);
+ if (!node->client) {
+ ERROR("write_mongodb plugin: Authenticating to [%s]%i for database "
+ "\"%s\" as user \"%s\" failed.",
+ (node->host != NULL) ? node->host : "localhost",
+ (node->port != 0) ? node->port : MONGOC_DEFAULT_PORT, node->db,
+ node->user);
+ node->connected = 0;
+ sfree(uri);
+ return -1;
+ }
+ } else {
+ format_string = "mongodb://%s:%d";
+ uri_length = strlen(format_string) + strlen(node->host) + 5 + 1;
+ if ((uri = calloc(1, uri_length)) == NULL) {
+ ERROR("write_mongodb plugin: Not enough memory to assemble "
+ "authentication string.");
+ mongoc_client_destroy(node->client);
+ node->client = NULL;
+ node->connected = 0;
+ return -1;
+ }
+ snprintf(uri, uri_length, format_string, node->host, node->port);
+
+ node->client = mongoc_client_new(uri);
+ if (!node->client) {
+ ERROR("write_mongodb plugin: Connecting to [%s]:%i failed.",
+ (node->host != NULL) ? node->host : "localhost",
+ (node->port != 0) ? node->port : MONGOC_DEFAULT_PORT);
+ node->connected = 0;
+ sfree(uri);
+ return -1;
+ }
+ }
+ sfree(uri);
+
+ node->database = mongoc_client_get_database(node->client, "collectd");
+ if (!node->database) {
+ ERROR("write_mongodb plugin: error creating/getting database");
+ mongoc_client_destroy(node->client);
+ node->client = NULL;
+ node->connected = 0;
+ return -1;
+ }
+
+ node->connected = 1;
+ return 0;
+} /* }}} int wm_initialize */
+
+static int wm_write(const data_set_t *ds, /* {{{ */
+ const value_list_t *vl, user_data_t *ud) {