Пример #1
0
int
main (int   argc,
      char *argv[])
{
   mongoc_client_pool_t *pool;
   mongoc_client_t *client;
   mongoc_uri_t *uri;
   unsigned count = 10000;

   if (argc > 1) {
      if (!(uri = mongoc_uri_new(argv[1]))) {
         fprintf(stderr, "Failed to parse uri: %s\n", argv[1]);
         return 1;
      }
   } else {
      uri = mongoc_uri_new("mongodb://127.0.0.1:27017/?sockettimeoutms=500");
   }

   if (argc > 2) {
      count = MAX(atoi(argv[2]), 1);
   }

   pool = mongoc_client_pool_new(uri);
   client = mongoc_client_pool_pop(pool);
   test_load(client, count);
   mongoc_client_pool_push(pool, client);
   mongoc_uri_destroy(uri);
   mongoc_client_pool_destroy(pool);

   return 0;
}
static void
multi_download_setup (perf_test_t *test)
{
   multi_download_test_t *download_test;
   multi_download_thread_context_t *ctx;
   mongoc_uri_t *uri;
   int i;

   _setup_load_gridfs_files ();
   perf_test_setup (test);

   download_test = (multi_download_test_t *) test;
   uri = mongoc_uri_new (NULL);
   download_test->pool = mongoc_client_pool_new (uri);

   download_test->cnt = 50; /* DANGER!: assumes test corpus won't change */
   download_test->contexts = (multi_download_thread_context_t *) bson_malloc0 (
      download_test->cnt * sizeof (multi_download_thread_context_t));

   for (i = 0; i < download_test->cnt; i++) {
      ctx = &download_test->contexts[i];
      ctx->filename = bson_strdup_printf ("file%d.txt", i);
      ctx->path = bson_strdup_printf ("%s/%s", test->data_path, ctx->filename);
   }

   mongoc_uri_destroy (uri);
}
Пример #3
0
int mongodb_module_init(struct state_conf *conf, UNUSED char **fields, UNUSED int fieldlens)
{
	char *uri_str = NULL;
	buffer_fill = 0;
	const char *db;

	if (conf->output_args) {
		uri_str = conf->output_args;
	}

	mongoc_init();
	mongoc_log_set_handler(mongodb_module_log, NULL);
	mongoc_uri_t *uri = mongoc_uri_new(uri_str);

	if (uri == NULL) {
		log_fatal("mongodb-module", "URI %s not valid!", uri_str);
	}

	client = mongoc_client_new_from_uri(uri);

	db = mongoc_uri_get_database(uri);
	collection = mongoc_client_get_collection(client, db ? db : strdup("zmap_output"), 
            conf->output_filename ? conf->output_filename : strdup("zmap_output"));
	bulk = mongoc_collection_create_bulk_operation(collection,false,NULL);

	return EXIT_SUCCESS;
}
Пример #4
0
bool
_mongoc_host_list_from_string (mongoc_host_list_t *host_list,
                               const char         *host_and_port)
{
   bool rval = false;
   char *uri_str = NULL;
   mongoc_uri_t *uri = NULL;
   const mongoc_host_list_t *uri_hl;

   BSON_ASSERT (host_list);
   BSON_ASSERT (host_and_port);

   uri_str = bson_strdup_printf("mongodb://%s/", host_and_port);
   if (! uri_str) goto CLEANUP;

   uri = mongoc_uri_new(uri_str);
   if (! uri) goto CLEANUP;

   uri_hl = mongoc_uri_get_hosts(uri);
   if (uri_hl->next) goto CLEANUP;

   memcpy(host_list, uri_hl, sizeof(*uri_hl));

   rval = true;

CLEANUP:

   bson_free(uri_str);
   if (uri) mongoc_uri_destroy(uri);

   return rval;
}
Пример #5
0
int64_t
execute (int   argc,
         char *argv[])
{
    int64_t count = 0;
    const char *uristr = MONGODB_DEFAULT_URI;
    const char *database_name;
    mongoc_uri_t *uri;
    mongoc_client_t *client;
    mongoc_database_t *db;

    bson_t bson_schema;
    bson_error_t error;
    int argi;

    uristr = getenv ("MONGODB_URI");
    uri = mongoc_uri_new (uristr);
    client = mongoc_client_new (uristr);
    database_name = mongoc_uri_get_database (uri);
    db = mongoc_client_get_database (client, database_name);

    bson_init_from_json_file (&bson_schema, schema_file) || WARN_ERROR;
    for (argi = 0; argi < argc; argi++) {
        fprintf (stderr, "[%d/%d] %s\n", argi + 1, argc, argv[argi]);
        count += load_table (db, argv[argi], &bson_schema);
    }
    bson_destroy (&bson_schema);

    mongoc_database_destroy (db);
    mongoc_client_destroy (client);
    mongoc_uri_destroy (uri);
    return count;
}
Пример #6
0
int
main (int   argc,
      char *argv[])
{
   mongoc_read_prefs_t *read_prefs;
   mongoc_client_t *client;
   mongoc_uri_t *uri;

   if (argc < 2) {
      fprintf(stderr, "usage: %s mongodb://...\n", argv[0]);
      return EXIT_FAILURE;
   }

   uri = mongoc_uri_new(argv[1]);
   if (!uri) {
      fprintf(stderr, "Invalid URI: \"%s\"\n", argv[1]);
      return EXIT_FAILURE;
   }

   signal(SIGUSR1, sighandler);
   signal(SIGUSR2, sighandler);

   client = mongoc_client_new_from_uri(uri);

   read_prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);
   mongoc_client_set_read_prefs(client, read_prefs);
   mongoc_read_prefs_destroy(read_prefs);

   test_secondary(client);

   mongoc_client_destroy(client);
   mongoc_uri_destroy(uri);

   return EXIT_SUCCESS;
}
static void
test_mongoc_metadata_append_after_cmd (void)
{
   mongoc_client_pool_t *pool;
   mongoc_client_t *client;
   mongoc_uri_t *uri;

   _reset_metadata ();

   uri = mongoc_uri_new ("mongodb://127.0.0.1?maxpoolsize=1&minpoolsize=1");
   pool = mongoc_client_pool_new (uri);

   /* Make sure that after we pop a client we can't set global metadata */
   pool = mongoc_client_pool_new (uri);

   client = mongoc_client_pool_pop (pool);

   ASSERT (!mongoc_metadata_append ("a", "a", "a"));

   mongoc_client_pool_push (pool, client);

   mongoc_uri_destroy (uri);
   mongoc_client_pool_destroy (pool);

   _reset_metadata ();
}
Пример #8
0
int
main (int   argc,
      char *argv[])
{
   const char *default_uristr = "mongodb://localhost/test";
   char *uristr;
   const char *database_name;
   mongoc_uri_t *uri;
   mongoc_client_t *client;
   mongoc_database_t *db;
   mongoc_collection_t *collection;

   mongoc_init ();

   uristr = getenv ("MONGODB_URI");
   uristr = uristr ? uristr : (char*)default_uristr;
   uri = mongoc_uri_new (uristr);
   client = mongoc_client_new_from_uri (uri);
   database_name = mongoc_uri_get_database (uri);
   db = mongoc_client_get_database (client, database_name);
   collection = mongoc_database_get_collection (db, "test");

   test_suite (db, collection);

   mongoc_collection_destroy (collection);
   mongoc_database_destroy (db);
   mongoc_client_destroy (client);
   mongoc_uri_destroy (uri);

   mongoc_cleanup ();

   return 0;
}
static void
multi_upload_setup (perf_test_t *test)
{
   multi_upload_test_t *upload_test;
   multi_upload_thread_context_t *ctx;
   mongoc_uri_t *uri;
   char *data_dir;
   DIR *dirp;
   struct dirent *dp;
   int i;

   perf_test_setup (test);

   upload_test = (multi_upload_test_t *) test;

   uri = mongoc_uri_new (NULL);
   upload_test->pool = mongoc_client_pool_new (uri);

   data_dir = bson_strdup_printf ("%s/%s", g_test_dir, test->data_path);
   dirp = opendir(data_dir);
   if (!dirp) {
      perror ("opening data path");
      abort ();
   }

   i = 0;

   while ((dp = readdir(dirp)) != NULL) {
      if (!strcmp (get_ext (dp->d_name), "txt")) {
         ++i;
      }
   }

   upload_test->cnt = i;
   upload_test->contexts = (multi_upload_thread_context_t *) bson_malloc0 (
      i * sizeof (multi_upload_thread_context_t));

   rewinddir (dirp);
   i = 0;

   while ((dp = readdir (dirp)) != NULL) {
      if (!strcmp (get_ext (dp->d_name), "txt")) {
         ctx = &upload_test->contexts[i];
         ctx->filename = bson_strdup (dp->d_name);
         ctx->path = bson_strdup_printf (
            "%s/%s/%s", g_test_dir, test->data_path, dp->d_name);

         ++i;
      }
   }

   assert (i == upload_test->cnt);

   closedir (dirp);
   bson_free (data_dir);
   mongoc_uri_destroy (uri);
}
Пример #10
0
static void
test_mongoc_uri_write_concern (void)
{
   const mongoc_write_concern_t *wr;
   mongoc_uri_t *uri;
   const write_concern_test *t;
   int i;
   static const write_concern_test tests [] = {
      { "mongodb://localhost/?safe=false", true, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED },
      { "mongodb://localhost/?safe=true", true, 1 },
      { "mongodb://localhost/?w=-1", true, MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED },
      { "mongodb://localhost/?w=0", true, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED },
      { "mongodb://localhost/?w=1", true, 1 },
      { "mongodb://localhost/?w=2", true, 2 },
      { "mongodb://localhost/?w=majority", true, MONGOC_WRITE_CONCERN_W_MAJORITY },
      { "mongodb://localhost/?w=10", true, 10 },
      { "mongodb://localhost/?w=", true, MONGOC_WRITE_CONCERN_W_DEFAULT },
      { "mongodb://localhost/?w=mytag", true, MONGOC_WRITE_CONCERN_W_TAG, "mytag" },
      { "mongodb://localhost/?w=mytag&safe=false", true, MONGOC_WRITE_CONCERN_W_TAG, "mytag" },
      { "mongodb://localhost/?w=1&safe=false", true, 1 },
      { "mongodb://localhost/?journal=true", true, MONGOC_WRITE_CONCERN_W_DEFAULT },
      { "mongodb://localhost/?w=0&journal=true", false, MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED },
      { "mongodb://localhost/?w=-1&journal=true", false, MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED },
      { "mongodb://localhost/?w=1&journal=true", true, 1 },
      { NULL }
   };

   /* Suppress warnings from two invalid URIs ("journal" and "w" conflict) */
   suppress_one_message();
   suppress_one_message();

   for (i = 0; tests [i].uri; i++) {
      t = &tests [i];

      uri = mongoc_uri_new (t->uri);
      if (t->parses) {
         assert (uri);
      } else {
         assert (!uri);
         continue;
      }

      wr = mongoc_uri_get_write_concern (uri);
      assert (wr);

      assert (t->w == mongoc_write_concern_get_w (wr));

      if (t->wtag) {
         assert (0 == strcmp (t->wtag, mongoc_write_concern_get_wtag (wr)));
      }

      mongoc_uri_destroy (uri);
   }
}
Пример #11
0
ClientPool :: ClientPool (const char *uri, QObject * parent)
   : QObject (parent)
     
{
   std::shared_ptr<mongoc_uri_t> auto_uri (
      mongoc_uri_new(uri), 
      uriDeleter);
   
   auto *pool = mongoc_client_pool_new ( auto_uri.get() );
   std::shared_ptr <mongoc_client_pool_t> newPool (pool, clientPoolDeleter);
   clientPool.swap (newPool);
}
Пример #12
0
static PyObject *
pymongoc_client_pool_tp_new (PyTypeObject *self,
                             PyObject     *args,
                             PyObject     *kwargs)
{
   pymongoc_client_pool_t *pyclient_pool;
   mongoc_uri_t *uri;
   const char *uri_str;
   PyObject *key = NULL;
   PyObject *pyuri = NULL;
   PyObject *ret = NULL;

   if (kwargs) {
      key = PyString_FromStringAndSize("uri", 3);
      if (PyDict_Contains(kwargs, key)) {
         if (!(pyuri = PyDict_GetItem(kwargs, key))) {
            goto cleanup;
         } else if (!PyString_Check(pyuri)) {
            PyErr_SetString(PyExc_TypeError, "uri must be a string.");
            goto cleanup;
         }
      }
   }

   uri_str = pyuri ? PyString_AsString(pyuri) : NULL;
   uri = mongoc_uri_new (uri_str);

   pyclient_pool = (pymongoc_client_pool_t *)
      PyType_GenericNew (&pymongoc_client_pool_type, NULL, NULL);
   if (!pyclient_pool) {
      goto cleanup;
   }

   pyclient_pool->client_pool = mongoc_client_pool_new (uri);
   if (!pyclient_pool->client_pool) {
      PyErr_SetString (PyExc_TypeError, "Invalid URI string.");
      Py_DECREF (pyclient_pool);
      pyclient_pool = NULL;
      goto cleanup;
   }

   ret = (PyObject *)pyclient_pool;

cleanup:
   if (uri) {
      mongoc_uri_destroy (uri);
   }
   Py_XDECREF (key);
   Py_XDECREF (pyuri);

   return ret;
}
Пример #13
0
ConnectionPool::ConnectionPoolImpl::URI::URI( std::string const& connstr ) :
		m_connstr(connstr)
{
	mongoc_uri_t* uri = mongoc_uri_new(connstr.c_str());
	if(!uri)
	{
		std::stringstream strm;
		strm << "Invalid connection-string: \"" << m_connstr << "\"\n";
		throw MongoError(strm.str());
	}

	m_uri.reset( uri, tlib_mongoc_uri_destroy );
}
mongoc_client_t *
mongoc_client_new (const char *uri_string)
{
   const mongoc_write_concern_t *write_concern;
   mongoc_client_t *client;
   mongoc_uri_t *uri;
   const bson_t *options;
   bson_iter_t iter;
   bool has_ssl = false;

   if (!uri_string) {
      uri_string = "mongodb://127.0.0.1/";
   }

   if (!(uri = mongoc_uri_new(uri_string))) {
      return NULL;
   }

   options = mongoc_uri_get_options (uri);

   if (bson_iter_init_find (&iter, options, "ssl") &&
       BSON_ITER_HOLDS_BOOL (&iter) &&
       bson_iter_bool (&iter)) {
      has_ssl = true;
   }

   client = bson_malloc0(sizeof *client);
   client->uri = uri;
   client->request_id = rand ();
   client->initiator = mongoc_client_default_stream_initiator;
   client->initiator_data = client;

   write_concern = mongoc_uri_get_write_concern (uri);
   client->write_concern = mongoc_write_concern_copy (write_concern);

   client->read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY);

   _mongoc_cluster_init (&client->cluster, client->uri, client);

#ifdef MONGOC_ENABLE_SSL
   if (has_ssl) {
      mongoc_client_set_ssl_opts (client, mongoc_ssl_opt_get_default ());
   }
#endif

   mongoc_counter_clients_active_inc ();

   return client;
}
static void
test_mongoc_client_pool_basic (void)
{
   mongoc_client_pool_t *pool;
   mongoc_client_t *client;
   mongoc_uri_t *uri;

   uri = mongoc_uri_new("mongodb://127.0.0.1?maxpoolsize=1&minpoolsize=1");
   pool = mongoc_client_pool_new(uri);
   client = mongoc_client_pool_pop(pool);
   assert(client);
   mongoc_client_pool_push(pool, client);
   mongoc_uri_destroy(uri);
   mongoc_client_pool_destroy(pool);
}
Пример #16
0
mongoc_uri_t *
mongoc_uri_new_for_host_port (const char *hostname,
                              uint16_t    port)
{
   mongoc_uri_t *uri;
   char *str;

   BSON_ASSERT (hostname);
   BSON_ASSERT (port);

   str = bson_strdup_printf("mongodb://%s:%hu/", hostname, port);
   uri = mongoc_uri_new(str);
   bson_free(str);

   return uri;
}
Пример #17
0
mongoc_uri_t *
mongoc_uri_new_for_host_port (const char *hostname,
                              uint16_t    port)
{
   mongoc_uri_t *uri;
   char *str;

   bson_return_val_if_fail(hostname, NULL);
   bson_return_val_if_fail(port, NULL);

   str = bson_strdup_printf("mongodb://%s:%hu/", hostname, port);
   uri = mongoc_uri_new(str);
   bson_free(str);

   return uri;
}
Пример #18
0
static mongoc_uri_t *hippo_mongo_driver_manager_make_uri(const char *dsn, const Array options)
{
	mongoc_uri_t *uri = mongoc_uri_new(dsn);

	if (!uri) {
		throw MongoDriver::Utils::throwInvalidArgumentException("Failed to parse MongoDB URI: '" + String(dsn) + "'");
	}

	for (ArrayIter iter(options); iter; ++iter) {
		const Variant& key = iter.first();
		const Variant& value = iter.second();
		const char *s_key = key.toString().c_str();

		if (
			!strcasecmp(s_key, "journal") ||
			!strcasecmp(s_key, "readpreference") ||
			!strcasecmp(s_key, "readpreferencetags") ||
			!strcasecmp(s_key, "safe") ||
			!strcasecmp(s_key, "slaveok") ||
			!strcasecmp(s_key, "w") ||
			!strcasecmp(s_key, "wtimeoutms")
		) {
			continue;
		}

		if (mongoc_uri_option_is_bool(s_key)) {
			mongoc_uri_set_option_as_bool(uri, s_key, value.toBoolean());
		} else if (mongoc_uri_option_is_int32(s_key) && value.isInteger()) {
			mongoc_uri_set_option_as_int32(uri, s_key, (int32_t) value.toInt64());
		} else if (mongoc_uri_option_is_utf8(s_key) && value.isString()) {
			mongoc_uri_set_option_as_utf8(uri, s_key, value.toString().c_str());
		} else if (value.isString()) {
			if (!strcasecmp(s_key, "username")) {
				mongoc_uri_set_username(uri, value.toString().c_str());
			} else if (!strcasecmp(s_key, "password")) {
				mongoc_uri_set_password(uri, value.toString().c_str());
			} else if (!strcasecmp(s_key, "database")) {
				mongoc_uri_set_database(uri, value.toString().c_str());
			} else if (!strcasecmp(s_key, "authsource")) {
				mongoc_uri_set_auth_source(uri, value.toString().c_str());
			}
		}
	}

	return uri;
}
Пример #19
0
static MONGO * get_mongodb_connection(void) {

	persistent_users_db_t * pud = get_persistent_users_db();

	MONGO * mydbconnection = (MONGO *) pthread_getspecific(connection_key);

	if (!mydbconnection) {
		mongoc_init();
		mongoc_log_set_handler(&mongo_logger, NULL);

		mydbconnection = (MONGO *) turn_malloc(sizeof(MONGO));
		mydbconnection->uri = mongoc_uri_new(pud->userdb);

		if (!mydbconnection->uri) {
			TURN_LOG_FUNC(
					TURN_LOG_LEVEL_ERROR,
					"Cannot open parse MongoDB URI <%s>, connection string format error\n",
					pud->userdb);
			MongoFree(mydbconnection);
			mydbconnection = NULL;
		} else {
			mydbconnection->client = mongoc_client_new_from_uri(
					mydbconnection->uri);
			if (!mydbconnection->client) {
				TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
						"Cannot initialize MongoDB connection\n");
				MongoFree(mydbconnection);
				mydbconnection = NULL;
			} else {
				mydbconnection->database = mongoc_uri_get_database(
						mydbconnection->uri);
				if (!mydbconnection->database)
					mydbconnection->database = MONGO_DEFAULT_DB;
				if(mydbconnection) {
					(void) pthread_setspecific(connection_key, mydbconnection);
				}
				TURN_LOG_FUNC(
					TURN_LOG_LEVEL_INFO,
					"Opened MongoDB URI <%s>\n",
					pud->userdb);
			}
		}
	}
	return mydbconnection;
}
Пример #20
0
static void
test_clone (void)
{
   mongoc_cursor_t *clone;
   mongoc_cursor_t *cursor;
   mongoc_client_t *client;
   const bson_t *doc;
   bson_error_t error;
   mongoc_uri_t *uri;
   bson_bool_t r;
   bson_t q = BSON_INITIALIZER;
   char *uristr;

   uristr = bson_strdup_printf("mongodb://%s/", HOST);
   uri = mongoc_uri_new(uristr);
   bson_free(uristr);

   client = mongoc_client_new_from_uri(uri);
   BSON_ASSERT(client);

   cursor = _mongoc_cursor_new(client, "test.test", MONGOC_QUERY_NONE, 0, 1, 1,
                               FALSE, &q, NULL, NULL);
   BSON_ASSERT(cursor);

   r = mongoc_cursor_next(cursor, &doc);
   if (!r && mongoc_cursor_error(cursor, &error)) {
      MONGOC_ERROR("%s", error.message);
      abort();
   }

   clone = mongoc_cursor_clone(cursor);
   BSON_ASSERT(cursor);

   r = mongoc_cursor_next(clone, &doc);
   if (!r && mongoc_cursor_error(clone, &error)) {
      MONGOC_ERROR("%s", error.message);
      abort();
   }

   mongoc_cursor_destroy(cursor);
   mongoc_cursor_destroy(clone);
   mongoc_client_destroy(client);
   mongoc_uri_destroy(uri);
}
Пример #21
0
/*
 *--------------------------------------------------------------------------
 *
 * mongoc_client_new --
 *
 *       Create a new mongoc_client_t using the URI provided.
 *
 *       @uri should be a MongoDB URI string such as "mongodb://localhost/"
 *       More information on the format can be found at
 *       http://docs.mongodb.org/manual/reference/connection-string/
 *
 * Returns:
 *       A newly allocated mongoc_client_t or NULL if @uri_string is
 *       invalid.
 *
 * Side effects:
 *       None.
 *
 *--------------------------------------------------------------------------
 */
mongoc_client_t *
mongoc_client_new(const char *uri_string)
{
   mongoc_topology_t *topology;
   mongoc_client_t   *client;
   mongoc_uri_t      *uri;


   if (!uri_string) {
      uri_string = "mongodb://127.0.0.1/";
   }

   if (!(uri = mongoc_uri_new (uri_string))) {
      return NULL;
   }

   topology = mongoc_topology_new(uri, true);

   client = _mongoc_client_new_from_uri (uri, topology);
   mongoc_uri_destroy (uri);

   return client;
}
Пример #22
0
static void
test_get_host (void)
{
   const mongoc_host_list_t *hosts;
   mongoc_host_list_t host;
   mongoc_client_t *client;
   mongoc_cursor_t *cursor;
   mongoc_uri_t *uri;
   const bson_t *doc;
   bson_error_t error;
   bson_bool_t r;
   bson_t q = BSON_INITIALIZER;
   char *uristr;

   uristr = bson_strdup_printf("mongodb://%s/", HOST);
   uri = mongoc_uri_new(uristr);
   bson_free(uristr);

   hosts = mongoc_uri_get_hosts(uri);

   client = mongoc_client_new_from_uri(uri);
   cursor = _mongoc_cursor_new(client, "test.test", MONGOC_QUERY_NONE, 0, 1, 1,
                               FALSE, &q, NULL, NULL);
   r = mongoc_cursor_next(cursor, &doc);
   if (!r && mongoc_cursor_error(cursor, &error)) {
      MONGOC_ERROR("%s", error.message);
      abort();
   }

   mongoc_cursor_get_host(cursor, &host);
   assert_cmpstr(host.host, hosts->host);
   assert_cmpstr(host.host_and_port, hosts->host_and_port);
   assert_cmpint(host.port, ==, hosts->port);
   assert_cmpint(host.family, ==, hosts->family);

   mongoc_uri_destroy(uri);
}
Пример #23
0
// Return a new mongoc_uri_t which should be freed with mongoc_uri_destroy
mongoc_uri_t *be_mongo_new_uri_from_options() {
	const char *uristr = p_stab("mongo_uri");
	const char *host = p_stab("mongo_host");
	const char *port = p_stab("mongo_port");
	const char *user = p_stab("mongo_user");
	const char *password = p_stab("mongo_password");
	const char *authSource = p_stab("mongo_authSource");
	mongoc_uri_t *uri;

	if (uristr) {
		// URI string trumps everything else. Let the driver parse it.
		uri = mongoc_uri_new(uristr);
	} else if (host || port || user || password || authSource) {
		// Using legacy piecemeal connection options. Assemble the URI.
		uri = mongoc_uri_new_for_host_port(
			host ? host : "localhost",
			(port && atoi(port)) ? atoi(port) : 27017
		);

		// NB: Option setters require mongo-c-driver >= 1.4.0 (Aug 2016)
		if (user != NULL) {
			mongoc_uri_set_username(uri, user);
			if (password != NULL) {
				mongoc_uri_set_password(uri, password);
			}
		}
		if (authSource != NULL) {
			mongoc_uri_set_auth_source(uri, authSource);
		}
	} else {
		// No connection options given at all, use defaults.
		uri = mongoc_uri_new_for_host_port("localhost", 27017);
	}

	return uri;
}
/* a uri with one bogus host */
mongoc_uri_t *
uri_from_ismaster_plus_one (bson_t *ismaster_response)
{
   /* start with one bad host and a comma */
   bson_string_t *uri_str = bson_string_new ("mongodb://" BAD_HOST ",");
   char *name;
   bson_iter_t iter;
   bson_iter_t hosts_iter;

   if ((name = set_name (ismaster_response))) {
      bson_iter_init_find (&iter, ismaster_response, "hosts");
      bson_iter_recurse (&iter, &hosts_iter);
      while (bson_iter_next (&hosts_iter)) {
         assert (BSON_ITER_HOLDS_UTF8 (&hosts_iter));
         bson_string_append (uri_str, bson_iter_utf8 (&hosts_iter, NULL));
         while (bson_iter_next (&hosts_iter)) {
            bson_string_append (uri_str, ",");
            bson_string_append (uri_str, bson_iter_utf8 (&hosts_iter, NULL));
         }

         bson_string_append_printf (
            uri_str, "/?replicaSet=%s&connecttimeoutms=1000", name);
      }

      bson_free (name);
   } else {
      char *host = test_framework_get_host ();

      bson_string_append (uri_str, host);
      bson_string_append (uri_str, "/?connecttimeoutms=1000");

      bson_free (host);
   }

   return mongoc_uri_new (bson_string_free (uri_str, false));
}
Пример #25
0
uint16_t
mock_server_run (mock_server_t *server)
{
   mongoc_socket_t *ssock;
   struct sockaddr_in bind_addr;
   int optval;
   uint16_t bound_port;

   MONGOC_INFO ("Starting mock server on port %d.", server->port);

   ssock = mongoc_socket_new (AF_INET, SOCK_STREAM, 0);
   if (!ssock) {
      perror ("Failed to create socket.");
      return 0;
   }

   optval = 1;
   mongoc_socket_setsockopt (ssock, SOL_SOCKET, SO_REUSEADDR, &optval,
                             sizeof optval);

   memset (&bind_addr, 0, sizeof bind_addr);

   bind_addr.sin_family = AF_INET;
   bind_addr.sin_addr.s_addr = htonl (INADDR_ANY);

   /* bind to unused port */
   bind_addr.sin_port = htons (0);

   if (-1 == mongoc_socket_bind (ssock,
                                 (struct sockaddr *) &bind_addr,
                                 sizeof bind_addr)) {
      perror ("Failed to bind socket");
      return 0;
   }

   if (-1 == mongoc_socket_listen (ssock, 10)) {
      perror ("Failed to put socket into listen mode");
      return 0;
   }

   bound_port = get_port (ssock);
   if (!bound_port) {
      perror ("Failed to get bound port number");
      return 0;
   }

   mongoc_mutex_lock (&server->mutex);

   server->sock = ssock;
   server->port = bound_port;
   /* TODO: configurable timeouts, perhaps from env */
   server->uri_str = bson_strdup_printf (
         "mongodb://127.0.0.1:%hu/?serverselectiontimeoutms=10000&"
         "sockettimeoutms=10000",
         bound_port);
   server->uri = mongoc_uri_new (server->uri_str);

   mongoc_thread_create (&server->main_thread, main_thread, (void *) server);

   /* wait for main thread to start */
   mongoc_cond_wait (&server->cond, &server->mutex);
   mongoc_mutex_unlock (&server->mutex);

   if (mock_server_get_verbose (server)) {
      fprintf (stderr, "listening on port %hu\n", bound_port);
      fflush (stdout);
   }

   return (uint16_t) bound_port;
}
Пример #26
0
void MongoDBConnectionPool::initEnv() {
	mongoc_init();

	ConnectionProperties props = getProperties();
	std::string connectionString = "";

	if(isUnixDomainSocket)
	{
		if(props.getNodes().at(0).getUsername()!="" && props.getNodes().at(0).getPassword()!="") {
			connectionString += (props.getNodes().at(0).getUsername() + ":" +
					props.getNodes().at(0).getPassword() + "@");
		}
		connectionString += "/tmp/mongodb.sock";
		if(props.getNodes().at(0).getDatabaseName()!="") {
			connectionString += "/" + props.getNodes().at(0).getDatabaseName();
		}
	}
	else
	{
		std::string databaseName = "";
		std::cout << props.getNodes().size() << std::endl;
		for (int var = 0; var < (int)props.getNodes().size(); ++var) {
			if(databaseName=="") {
				databaseName = props.getNodes().at(var).getDatabaseName();
			}
			int port = props.getNodes().at(var).getPort();
			if(props.getNodes().at(var).getHost()=="") {
				continue;
			}
			if(port==-1) {
				port = 27017;
			}

			std::cout << props.getNodes().at(var).getHost() << std::endl;
			if(props.getNodes().at(var).getUsername()!="" && props.getNodes().at(var).getPassword()!="") {
				connectionString += (props.getNodes().at(var).getUsername() + ":" +
						props.getNodes().at(var).getPassword() + "@");
			}
			connectionString += props.getNodes().at(var).getHost() + ":" + CastUtil::lexical_cast<std::string>(port);
			if(var!=(int)props.getNodes().size()-1) {
				connectionString += ",";
			}
		}

		if(connectionString.at(connectionString.length()-1)==',') {
			connectionString = connectionString.substr(0, connectionString.length()-1);
		}

		connectionString += "/";

		if(databaseName!="") {
			connectionString += databaseName;
		}

		connectionString += "?";

		if(isReplicaSet && replicaSetName!="") {
			connectionString += "replicaSet="+replicaSetName;
			if(isSSL) {
				connectionString += "&ssl=true";
			}
		} else if(isSSL) {
			connectionString += "ssl=true";
		}
	}

	int poolmin = 2, poolmax = 5;
	if((props.getPoolWriteSize()+props.getPoolReadSize())>0) {
		poolmax = props.getPoolWriteSize()+props.getPoolReadSize();
		if(poolmax<poolmin)
			poolmax += poolmin;
	}

	if(connectionString.at(connectionString.length()-1)=='?') {
		connectionString += "minPoolSize=" + CastUtil::lexical_cast<std::string>(poolmin);
	} else {
		connectionString += "&minPoolSize=" + CastUtil::lexical_cast<std::string>(poolmin);
	}
	connectionString += "&maxPoolSize=" + CastUtil::lexical_cast<std::string>(poolmax);

	connectionString = "mongodb://" + connectionString;

	std::cout << connectionString << std::endl;

	uri = mongoc_uri_new(connectionString.c_str());
	mongoc_client_pool_t *pool = mongoc_client_pool_new(uri);
	setEnv(pool);
	props.setNewConnectionStrategy(true);
}
Пример #27
0
uri::uri(const std::string& uri_string)
    : _impl(bsoncxx::stdx::make_unique<impl>(mongoc_uri_new(uri_string.c_str()))) {
}
Пример #28
0
static void
test_mongoc_uri_new (void)
{
   const mongoc_host_list_t *hosts;
   const bson_t *options;
   const bson_t *credentials;
   bson_t properties;
   mongoc_uri_t *uri;
   bson_iter_t iter;
   bson_iter_t child;

   /* bad uris */
   ASSERT(!mongoc_uri_new("mongodb://"));
   ASSERT(!mongoc_uri_new("mongodb://::"));
   ASSERT(!mongoc_uri_new("mongodb://*****:*****@localhost:27017/foo/?authSource=abcd");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_username(uri), "christian");
   ASSERT_CMPSTR(mongoc_uri_get_password(uri), "secret");
   ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "abcd");
   mongoc_uri_destroy(uri);

   /* should use the default auth source and mechanism */
   uri = mongoc_uri_new("mongodb://*****:*****@localhost:27017");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "admin");
   ASSERT(!mongoc_uri_get_auth_mechanism(uri));
   mongoc_uri_destroy(uri);

   /* should use the db when no authSource is specified */
   uri = mongoc_uri_new("mongodb://*****:*****@localhost/foo");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "foo");
   mongoc_uri_destroy(uri);

   /* should recognize an empty password */
   uri = mongoc_uri_new("mongodb://samantha:@localhost");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_username(uri), "samantha");
   ASSERT_CMPSTR(mongoc_uri_get_password(uri), "");
   mongoc_uri_destroy(uri);

   /* should recognize no password */
   uri = mongoc_uri_new("mongodb://christian@localhost:27017");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_username(uri), "christian");
   ASSERT(!mongoc_uri_get_password(uri));
   mongoc_uri_destroy(uri);

   /* should recognize a url escaped character in the username */
   uri = mongoc_uri_new("mongodb://christian%40realm:pwd@localhost:27017");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_username(uri), "christian@realm");
   mongoc_uri_destroy(uri);

   /* while you shouldn't do this, lets test for it */
   uri = mongoc_uri_new("mongodb://christian%40realm@localhost:27017/db%2ename");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_database(uri), "db.name");
   mongoc_uri_destroy(uri);
   uri = mongoc_uri_new("mongodb://christian%40realm@localhost:27017/db%2Ename");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_database(uri), "db.name");
   mongoc_uri_destroy(uri);

   uri = mongoc_uri_new("mongodb://christian%40realm@localhost:27017/?abcd=%20");
   ASSERT(uri);
   options = mongoc_uri_get_options(uri);
   ASSERT(options);
   ASSERT(bson_iter_init_find(&iter, options, "abcd"));
   ASSERT(BSON_ITER_HOLDS_UTF8(&iter));
   ASSERT_CMPSTR(bson_iter_utf8(&iter, NULL), " ");
   mongoc_uri_destroy(uri);

   uri = mongoc_uri_new("mongodb://christian%40realm@[::6]:27017/?abcd=%20");
   ASSERT(uri);
   options = mongoc_uri_get_options(uri);
   ASSERT(options);
   ASSERT(bson_iter_init_find(&iter, options, "abcd"));
   ASSERT(BSON_ITER_HOLDS_UTF8(&iter));
   ASSERT_CMPSTR(bson_iter_utf8(&iter, NULL), " ");
   mongoc_uri_destroy(uri);

   /* GSSAPI-specific options */

   /* should recognize the GSSAPI mechanism, and use $external as source */
   uri = mongoc_uri_new("mongodb://user%40DOMAIN.COM:password@localhost/?authMechanism=GSSAPI");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_mechanism(uri), "GSSAPI");
   /*ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "$external");*/
   mongoc_uri_destroy(uri);

   /* use $external as source when db is specified */
   uri = mongoc_uri_new("mongodb://user%40DOMAIN.COM:password@localhost/foo/?authMechanism=GSSAPI");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "$external");
   mongoc_uri_destroy(uri);

   /* should not accept authSource other than $external */
   ASSERT(!mongoc_uri_new("mongodb://user%40DOMAIN.COM:password@localhost/foo/?authMechanism=GSSAPI&authSource=bar"));

   /* should accept authMechanismProperties */
   uri = mongoc_uri_new("mongodb://user%40DOMAIN.COM:password@localhost/?authMechanism=GSSAPI"
                        "&authMechanismProperties=SERVICE_NAME:other,CANONICALIZE_HOST_NAME:true");
   ASSERT(uri);
   credentials = mongoc_uri_get_credentials(uri);
   ASSERT(credentials);
   ASSERT(mongoc_uri_get_mechanism_properties(uri, &properties));
   assert (bson_iter_init_find_case (&iter, &properties, "SERVICE_NAME") &&
           BSON_ITER_HOLDS_UTF8 (&iter) &&
           (0 == strcmp (bson_iter_utf8 (&iter, NULL), "other")));
   assert (bson_iter_init_find_case (&iter, &properties, "CANONICALIZE_HOST_NAME") &&
           BSON_ITER_HOLDS_UTF8 (&iter) &&
           (0 == strcmp (bson_iter_utf8 (&iter, NULL), "true")));
   mongoc_uri_destroy(uri);

   /* reverse order of arguments to ensure parsing still succeeds */
   uri = mongoc_uri_new("mongodb://user@localhost/"
                        "?authMechanismProperties=SERVICE_NAME:other"
                        "&authMechanism=GSSAPI");
   ASSERT(uri);
   mongoc_uri_destroy(uri);

   /* deprecated gssapiServiceName option */
   uri = mongoc_uri_new("mongodb://christian%40realm.cc@localhost:27017/?authMechanism=GSSAPI&gssapiServiceName=blah");
   ASSERT(uri);
   options = mongoc_uri_get_options(uri);
   ASSERT(options);
   assert (0 == strcmp (mongoc_uri_get_auth_mechanism (uri), "GSSAPI"));
   assert (0 == strcmp (mongoc_uri_get_username (uri), "*****@*****.**"));
   assert (bson_iter_init_find_case (&iter, options, "gssapiServiceName") &&
           BSON_ITER_HOLDS_UTF8 (&iter) &&
           (0 == strcmp (bson_iter_utf8 (&iter, NULL), "blah")));
   mongoc_uri_destroy(uri);

   /* MONGODB-CR */

   /* should recognize this mechanism */
   uri = mongoc_uri_new("mongodb://user@localhost/?authMechanism=MONGODB-CR");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_mechanism(uri), "MONGODB-CR");
   mongoc_uri_destroy(uri);

   /* X509 */

   /* should recognize this mechanism, and use $external as the source */
   uri = mongoc_uri_new("mongodb://user@localhost/?authMechanism=MONGODB-X509");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_mechanism(uri), "MONGODB-X509");
   /*ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "$external");*/
   mongoc_uri_destroy(uri);

   /* use $external as source when db is specified */
   uri = mongoc_uri_new("mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality"
                        "%2CST%3DmyState%2CC%3DmyCountry@localhost/foo/?authMechanism=MONGODB-X509");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "$external");
   mongoc_uri_destroy(uri);

   /* should not accept authSource other than $external */
   ASSERT(!mongoc_uri_new("mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality"
                          "%2CST%3DmyState%2CC%3DmyCountry@localhost/foo/?authMechanism=MONGODB-X509&authSource=bar"));

   /* should recognize the encoded username */
   uri = mongoc_uri_new("mongodb://CN%3DmyName%2COU%3DmyOrgUnit%2CO%3DmyOrg%2CL%3DmyLocality"
                        "%2CST%3DmyState%2CC%3DmyCountry@localhost/?authMechanism=MONGODB-X509");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_username(uri), "CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry");
   mongoc_uri_destroy(uri);

   /* PLAIN */

   /* should recognize this mechanism */
   uri = mongoc_uri_new("mongodb://user@localhost/?authMechanism=PLAIN");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_mechanism(uri), "PLAIN");
   mongoc_uri_destroy(uri);

   /* SCRAM-SHA1 */

   /* should recognize this mechanism */
   uri = mongoc_uri_new("mongodb://user@localhost/?authMechanism=SCRAM-SHA1");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_mechanism(uri), "SCRAM-SHA1");
   mongoc_uri_destroy(uri);
}
Пример #29
0
uri::uri(bsoncxx::stdx::string_view uri_string)
    : _impl(bsoncxx::stdx::make_unique<impl>(mongoc_uri_new(uri_string.data()))) {
}
static void
test_mongoc_uri_new (void)
{
   const mongoc_host_list_t *hosts;
   const bson_t *options;
   mongoc_uri_t *uri;
   bson_iter_t iter;
   bson_iter_t child;

   ASSERT(!mongoc_uri_new("mongodb://"));
   ASSERT(!mongoc_uri_new("mongodb://::"));
   ASSERT(!mongoc_uri_new("mongodb://*****:*****@localhost:27017?authSource=abcd");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_username(uri), "christian");
   ASSERT_CMPSTR(mongoc_uri_get_password(uri), "secret");
   ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "abcd");
   mongoc_uri_destroy(uri);

   uri = mongoc_uri_new("mongodb://*****:*****@localhost:27017");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_auth_source(uri), "admin");
   mongoc_uri_destroy(uri);

   uri = mongoc_uri_new("mongodb://christian@localhost:27017");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_username(uri), "christian");
   mongoc_uri_destroy(uri);

   uri = mongoc_uri_new("mongodb://christian%40realm@localhost:27017");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_username(uri), "christian@realm");
   mongoc_uri_destroy(uri);

   /* while you shouldn't do this, lets test for it */
   uri = mongoc_uri_new("mongodb://christian%40realm@localhost:27017/db%2ename");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_database(uri), "db.name");
   mongoc_uri_destroy(uri);
   uri = mongoc_uri_new("mongodb://christian%40realm@localhost:27017/db%2Ename");
   ASSERT(uri);
   ASSERT_CMPSTR(mongoc_uri_get_database(uri), "db.name");
   mongoc_uri_destroy(uri);

   uri = mongoc_uri_new("mongodb://christian%40realm@localhost:27017/?abcd=%20");
   ASSERT(uri);
   options = mongoc_uri_get_options(uri);
   ASSERT(options);
   ASSERT(bson_iter_init_find(&iter, options, "abcd"));
   ASSERT(BSON_ITER_HOLDS_UTF8(&iter));
   ASSERT_CMPSTR(bson_iter_utf8(&iter, NULL), " ");
   mongoc_uri_destroy(uri);

   uri = mongoc_uri_new("mongodb://christian%40realm.cc@localhost:27017/?authmechanism=GSSAPI&gssapiservicename=blah");
   ASSERT(uri);
   options = mongoc_uri_get_options(uri);
   ASSERT(options);
   assert (0 == strcmp (mongoc_uri_get_auth_mechanism (uri), "GSSAPI"));
   assert (0 == strcmp (mongoc_uri_get_username (uri), "*****@*****.**"));
   assert (bson_iter_init_find_case (&iter, options, "gssapiservicename") &&
           BSON_ITER_HOLDS_UTF8 (&iter) &&
           (0 == strcmp (bson_iter_utf8 (&iter, NULL), "blah")));
   mongoc_uri_destroy(uri);

   uri = mongoc_uri_new("mongodb://christian%40realm@[::6]:27017/?abcd=%20");
   ASSERT(uri);
   options = mongoc_uri_get_options(uri);
   ASSERT(options);
   ASSERT(bson_iter_init_find(&iter, options, "abcd"));
   ASSERT(BSON_ITER_HOLDS_UTF8(&iter));
   ASSERT_CMPSTR(bson_iter_utf8(&iter, NULL), " ");
   mongoc_uri_destroy(uri);
}