static void
test_mongoc_client_authenticate (void)
{
    mongoc_collection_t *collection;
    mongoc_database_t *database;
    mongoc_client_t *client;
    mongoc_cursor_t *cursor;
    const bson_t *doc;
    bson_error_t error;
    char *username;
    char *uri;
    bool r;
    bson_t q;

    username = gen_test_user ();
    uri = gen_good_uri (username);

    /*
     * Add a user to the test database.
     */
    client = mongoc_client_new(gTestUri);
    database = mongoc_client_get_database(client, "test");
    mongoc_database_remove_user (database, username, &error);
    r = mongoc_database_add_user(database, username, "testpass", NULL, NULL, &error);
    ASSERT_CMPINT(r, ==, 1);
    mongoc_database_destroy(database);
    mongoc_client_destroy(client);

    /*
     * Try authenticating with that user.
     */
    bson_init(&q);
    client = mongoc_client_new(uri);
    collection = mongoc_client_get_collection(client, "test", "test");
    cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0,
                                    &q, NULL, NULL);
    r = mongoc_cursor_next(cursor, &doc);
    if (!r) {
        r = mongoc_cursor_error(cursor, &error);
        if (r) {
            MONGOC_ERROR("Authentication failure: \"%s\"", error.message);
        }
        assert(!r);
    }
    mongoc_cursor_destroy(cursor);

    /*
     * Remove all test users.
     */
    database = mongoc_client_get_database (client, "test");
    r = mongoc_database_remove_all_users (database, &error);
    assert (r);
    mongoc_database_destroy (database);

    mongoc_collection_destroy(collection);
    mongoc_client_destroy(client);

    bson_free (username);
    bson_free (uri);
}
Ejemplo n.º 2
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;
}
Ejemplo n.º 3
0
int mainnn(int argc, char** argv) {

    mongoc_init();

    mongoc_client_t *client;
    mongoc_database_t *database;
    mongoc_collection_t *collection;

    client = mongoc_client_new("mongodb://localhost/?appname=insert-example");
    database = mongoc_client_get_database(client, "test");
    collection = mongoc_client_get_collection(client, "test", "devices");
    
    iot::messaging::Message m(m1);
    std::cerr << m.toString() << std::endl;
    
    m.fromString(m2);
    std::cerr << m.toString() << std::endl;
    
    iot::messaging::Message mm;
    const std::string s = mm.toString();
    
    std::cerr << mm.toString() << std::endl;    
    
    mongoc_collection_destroy(collection);
    mongoc_database_destroy(database);
    mongoc_client_destroy(client);

    mongoc_cleanup();

    return EXIT_SUCCESS;
}
Ejemplo n.º 4
0
int
main (int argc,
      char *argv[])
{
   bson_t *options;
   bson_error_t error;
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   mongoc_database_t *database;

   mongoc_init ();

   client = mongoc_client_new ("mongodb://localhost/");
   database = mongoc_client_get_database (client, "testasdf");

   /* Create schema validator */
   options = BCON_NEW ("validator", "{", "number", "{", "$gte", BCON_INT32 (5), "}", "}");
   collection = mongoc_database_create_collection (database, "collname", options, &error);

   if (collection) {
      bulk5_fail (collection);
      bulk5_success (collection);
      mongoc_collection_destroy (collection);
   } else {
      fprintf(stderr, "Couldn't create collection: '%s'\n", error.message);
   }

   bson_free (options);
   mongoc_database_destroy (database);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return 0;
}
Ejemplo n.º 5
0
int main(void)
{
   mongoc_collection_t *collection;
   mongoc_database_t *database;
   mongoc_client_t *client;
   bson_error_t error;
   bson_t *options;

   client = mongoc_client_new ("mongodb://localhost:27017/admin");
   database = mongoc_client_get_database (client, "databaseName");

   options = BCON_NEW ( "validator", "{", "age", "{", "$lte", BCON_INT32 (34), "}", "}", "validationAction", BCON_UTF8 ("error"), "validationLevel", BCON_UTF8 ("moderate"));

   collection = mongoc_database_create_collection (database, "collectionName", options, &error);
   if (!collection) {
      fprintf(stderr, "Got error: \"%s\" on line %d\n", error.message, __LINE__);
      return 1;
   }

   fam_flags (collection);
   fam_bypass (collection);
   fam_update (collection);
   fam_fields (collection);
   fam_sort (collection);

   mongoc_collection_drop (collection, NULL);
   bson_destroy (options);
   mongoc_database_destroy (database);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   return 0;
}
Ejemplo n.º 6
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;
}
Ejemplo n.º 7
0
dbproxy::dbproxy(boost::shared_ptr<config::config> _config) {
    mongoc_init();

    mongoc_uri_t * _uri = mongoc_uri_new_for_host_port(_config->get_value_string("ip").c_str(), _config->get_value_int("port"));
    _client = mongoc_client_new(mongoc_uri_get_string(_uri));
    mongoc_uri_destroy(_uri);

    _db = mongoc_client_get_database(_client, _config->get_value_string("db").c_str());
}
static void
test_create_collection (void)
{
   mongoc_database_t *database;
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error = { 0 };
   bson_t options;
   bson_t storage_opts;
   bson_t wt_opts;

   char *dbname;
   char *name;
   bool r;

   client = mongoc_client_new (gTestUri);
   assert (client);

   dbname = gen_collection_name ("dbtest");
   database = mongoc_client_get_database (client, dbname);
   assert (database);
   bson_free (dbname);

   bson_init (&options);
   BSON_APPEND_INT32 (&options, "size", 1234);
   BSON_APPEND_INT32 (&options, "max", 4567);
   BSON_APPEND_BOOL (&options, "capped", true);
   BSON_APPEND_BOOL (&options, "autoIndexId", true);

   BSON_APPEND_DOCUMENT_BEGIN(&options, "storage", &storage_opts);
   BSON_APPEND_DOCUMENT_BEGIN(&storage_opts, "wiredtiger", &wt_opts);
   BSON_APPEND_UTF8(&wt_opts, "configString", "block_compressor=zlib");
   bson_append_document_end(&storage_opts, &wt_opts);
   bson_append_document_end(&options, &storage_opts);


   name = gen_collection_name ("create_collection");
   collection = mongoc_database_create_collection (database, name, &options, &error);
   assert (collection);
   bson_destroy (&options);
   bson_free (name);

   r = mongoc_collection_drop (collection, &error);
   assert (r);

   r = mongoc_database_drop (database, &error);
   assert (r);

   mongoc_collection_destroy (collection);
   mongoc_database_destroy (database);
   mongoc_client_destroy (client);
}
Ejemplo n.º 9
0
static void
test_command (void)
{
   mongoc_database_t *database;
   mongoc_client_t *client;
   mongoc_cursor_t *cursor;
   bson_error_t error;
   const bson_t *doc;
   bool r;
   bson_t cmd = BSON_INITIALIZER;
   bson_t reply;

   client = mongoc_client_new (gTestUri);
   assert (client);

   database = mongoc_client_get_database (client, "admin");

   /*
    * Test a known working command, "ping".
    */
   bson_append_int32 (&cmd, "ping", 4, 1);

   cursor = mongoc_database_command (database, MONGOC_QUERY_NONE, 0, 1, 0, &cmd, NULL, NULL);
   assert (cursor);

   r = mongoc_cursor_next (cursor, &doc);
   assert (r);
   assert (doc);

   r = mongoc_cursor_next (cursor, &doc);
   assert (!r);
   assert (!doc);

   mongoc_cursor_destroy (cursor);


   /*
    * Test a non-existing command to ensure we get the failure.
    */
   bson_reinit (&cmd);
   bson_append_int32 (&cmd, "a_non_existing_command", -1, 1);

   r = mongoc_database_command_simple (database, &cmd, NULL, &reply, &error);
   assert (!r);
   assert (error.domain == MONGOC_ERROR_QUERY);
   assert (error.code == MONGOC_ERROR_QUERY_COMMAND_NOT_FOUND);
   assert (!strcmp ("no such cmd: a_non_existing_command", error.message));

   mongoc_database_destroy (database);
   mongoc_client_destroy (client);
   bson_destroy (&cmd);
}
Ejemplo n.º 10
0
static void
test_load (mongoc_client_t *client,
           unsigned         iterations)
{
   mongoc_collection_t *col;
   mongoc_database_t *db;
   bson_error_t error;
   unsigned i;
   bson_t b;
   bson_t q;

   bson_init(&b);
   bson_append_int32(&b, "ping", 4, 1);

   bson_init(&q);

   db = mongoc_client_get_database(client, "admin");
   col = mongoc_client_get_collection(client, "test", "test");

   for (i = 0; i < iterations; i++) {
      ping(db, &b);
      fetch(col, &q);
   }

   if (!mongoc_collection_drop(col, &error)) {
      MONGOC_WARNING("Failed to drop collection: %s", error.message);
   }

   mongoc_database_destroy(db);
   db = mongoc_client_get_database(client, "test");

   if (!mongoc_database_drop(db, &error)) {
      MONGOC_WARNING("Failed to drop database: %s", error.message);
   }

   mongoc_database_destroy(db);
   mongoc_collection_destroy(col);
   bson_destroy(&b);
}
static void
_drop_database (gridfs_test_t *gridfs_test)
{
   mongoc_database_t *db;
   bson_error_t error;

   db = mongoc_client_get_database (gridfs_test->client, "perftest");
   if (!mongoc_database_drop (db, &error)) {
      MONGOC_ERROR ("database_drop: %s\n", error.message);
      abort ();
   }

   mongoc_database_destroy (db);
}
Ejemplo n.º 12
0
mongoc_database_t *
mongoc_client_get_default_database (mongoc_client_t *client)
{
   const char *db;

   BSON_ASSERT (client);
   db = mongoc_uri_get_database (client->uri);

   if (db) {
      return mongoc_client_get_database (client, db);
   }

   return NULL;
}
static void
multi_upload_before (perf_test_t *test)
{
   multi_upload_test_t *upload_test;
   mongoc_client_t *client;
   mongoc_gridfs_t *gridfs;
   bson_error_t error;
   mongoc_database_t *db;
   multi_upload_thread_context_t *ctx;
   int i;

   perf_test_before (test);

   upload_test = (multi_upload_test_t *) test;
   client = mongoc_client_pool_pop (upload_test->pool);
   db = mongoc_client_get_database (client, "perftest");
   if (!mongoc_database_drop (db, &error)) {
      MONGOC_ERROR ("database_drop: %s\n", error.message);
      abort ();
   }

   gridfs = mongoc_client_get_gridfs (client, "perftest", NULL, &error);
   if (!gridfs) {
      MONGOC_ERROR ("get_gridfs: %s\n", error.message);
      abort ();
   }

   write_one_byte_file (gridfs);
   mongoc_gridfs_destroy (gridfs);
   mongoc_client_pool_push (upload_test->pool, client);

   for (i = 0; i < upload_test->cnt; i++) {
      ctx = &upload_test->contexts[i];
      ctx->client = mongoc_client_pool_pop (upload_test->pool);
      ctx->gridfs = mongoc_client_get_gridfs (ctx->client, "perftest",
                                              NULL, &error);
      if (!ctx->gridfs) {
         MONGOC_ERROR ("get_gridfs: %s\n", error.message);
         abort ();
      }

      ctx->stream = mongoc_stream_file_new_for_path (ctx->path, O_RDONLY, 0);
      if (!ctx->stream) {
         perror ("stream_new_for_path");
         abort ();
      }
   }

   mongoc_database_destroy (db);
}
Ejemplo n.º 14
0
static bson_bool_t
ha_replica_set_get_status (ha_replica_set_t *replica_set,
                           bson_t           *status)
{
   mongoc_database_t *db;
   mongoc_client_t *client;
   mongoc_cursor_t *cursor;
   const bson_t *doc;
   bson_bool_t ret = FALSE;
   ha_node_t *node;
   bson_t cmd;
   char *uristr;

   bson_init(&cmd);
   bson_append_int32(&cmd, "replSetGetStatus", -1, 1);

   for (node = replica_set->nodes; !ret && node; node = node->next) {
      uristr = bson_strdup_printf("mongodb://127.0.0.1:%hu/?slaveOk=true",
                                  node->port);
      client = mongoc_client_new(uristr);
#ifdef MONGOC_ENABLE_SSL
      if (replica_set->ssl_opt) {
         mongoc_client_set_ssl_opts(client, replica_set->ssl_opt);
      }
#endif
      bson_free(uristr);

      db = mongoc_client_get_database(client, "admin");

      if ((cursor = mongoc_database_command(db,
                                            MONGOC_QUERY_SLAVE_OK,
                                            0,
                                            1,
                                            &cmd,
                                            NULL,
                                            NULL))) {
         if (mongoc_cursor_next(cursor, &doc)) {
            bson_copy_to(doc, status);
            ret = TRUE;
         }
         mongoc_cursor_destroy(cursor);
      }

      mongoc_database_destroy(db);
      mongoc_client_destroy(client);
   }

   return ret;
}
Ejemplo n.º 15
0
int
main (int   argc,
      char *argv[])
{
   mongoc_database_t *database;
   mongoc_cursor_t *cursor;
   mongoc_client_t *client;
   const bson_t *reply;
   bson_uint16_t port;
   bson_error_t error;
   bson_t ping;
   char *host_and_port;
   char *str;

   if (argc < 2 || argc > 3) {
      fprintf(stderr, "usage: %s HOSTNAME [PORT]\n", argv[0]);
      return 1;
   }

   port = (argc == 3) ? atoi(argv[2]) : 27017;
   host_and_port = bson_strdup_printf("mongodb://%s:%hu", argv[1], port);
   client = mongoc_client_new(host_and_port);
   if (!client) {
      fprintf(stderr, "Invalid hostname or port: %s\n", host_and_port);
      return 2;
   }

   bson_init(&ping);
   bson_append_int32(&ping, "ping", 4, 1);
   database = mongoc_client_get_database(client, "test");
   cursor = mongoc_database_command(database, 0, 0, 1, 0, &ping, NULL, NULL);
   if (mongoc_cursor_next(cursor, &reply)) {
      str = bson_as_json(reply, NULL);
      fprintf(stdout, "%s\n", str);
      bson_free(str);
   } else if (mongoc_cursor_error(cursor, &error)) {
      fprintf(stderr, "Ping failure: %s\n", error.message);
      return 3;
   }

   mongoc_cursor_destroy(cursor);
   bson_destroy(&ping);
   mongoc_client_destroy(client);
   bson_free(host_and_port);

   return 0;
}
Ejemplo n.º 16
0
static void
test_has_collection (void)
{
   mongoc_collection_t *collection;
   mongoc_database_t *database;
   mongoc_client_t *client;
   bson_error_t error;
   char *name;
   bool r;
   bson_oid_t oid;
   bson_t b;

   client = mongoc_client_new (gTestUri);
   assert (client);

   name = gen_collection_name ("has_collection");
   collection = mongoc_client_get_collection (client, "test", name);
   assert (collection);

   database = mongoc_client_get_database (client, "test");
   assert (database);

   bson_init (&b);
   bson_oid_init (&oid, NULL);
   bson_append_oid (&b, "_id", 3, &oid);
   bson_append_utf8 (&b, "hello", 5, "world", 5);
   r = mongoc_collection_insert (collection, MONGOC_INSERT_NONE, &b, NULL,
                                 &error);
   if (!r) {
      MONGOC_WARNING ("%s\n", error.message);
   }
   assert (r);
   bson_destroy (&b);

   r = mongoc_database_has_collection (database, name, &error);
   assert (!error.domain);
   assert (r);

   bson_free (name);
   mongoc_database_destroy (database);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
}
Ejemplo n.º 17
0
static void
test_create_collection (void)
{
   mongoc_database_t *database;
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error = { 0 };
   bson_t options;
   char *dbname;
   char *name;
   bool r;

   client = mongoc_client_new (gTestUri);
   assert (client);

   dbname = gen_collection_name ("dbtest");
   database = mongoc_client_get_database (client, dbname);
   assert (database);
   bson_free (dbname);

   bson_init (&options);
   BSON_APPEND_INT32 (&options, "size", 1234);
   BSON_APPEND_INT32 (&options, "max", 4567);
   BSON_APPEND_BOOL (&options, "capped", true);
   BSON_APPEND_BOOL (&options, "autoIndexId", true);

   name = gen_collection_name ("create_collection");
   collection = mongoc_database_create_collection (database, name, &options, &error);
   assert (collection);
   bson_free (name);

   r = mongoc_collection_drop (collection, &error);
   assert (r);

   r = mongoc_database_drop (database, &error);
   assert (r);

   mongoc_collection_destroy (collection);
   mongoc_database_destroy (database);
   mongoc_client_destroy (client);
}
Ejemplo n.º 18
0
static void
test_mongoc_client_authenticate (void)
{
   mongoc_collection_t *collection;
   mongoc_database_t *database;
   mongoc_client_t *client;
   mongoc_cursor_t *cursor;
   const bson_t *doc;
   bson_error_t error;
   bool r;
   bson_t q;

   /*
    * Add a user to the test database.
    */
   client = mongoc_client_new(gTestUri);
   database = mongoc_client_get_database(client, "test");
   mongoc_database_remove_user (database, "testuser", &error);
   r = mongoc_database_add_user(database, "testuser", "testpass", NULL, NULL, &error);
   ASSERT_CMPINT(r, ==, 1);
   mongoc_database_destroy(database);
   mongoc_client_destroy(client);

   /*
    * Try authenticating with that user.
    */
   bson_init(&q);
   client = mongoc_client_new(gTestUriWithPassword);
   collection = mongoc_client_get_collection(client, "test", "test");
   cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 1, 0,
                                   &q, NULL, NULL);
   r = mongoc_cursor_next(cursor, &doc);
   if (!r) {
      r = mongoc_cursor_error(cursor, &error);
      if (r) MONGOC_ERROR("%s", error.message);
      assert(!r);
   }
   mongoc_cursor_destroy(cursor);
   mongoc_collection_destroy(collection);
   mongoc_client_destroy(client);
}
Ejemplo n.º 19
0
bool
copydb (mongoc_client_t *client, const char *other_host_and_port)
{
    mongoc_database_t *admindb;
    bson_t *command;
    bson_t reply;
    bson_error_t error;
    bool res;

    BSON_ASSERT (other_host_and_port);
    /* Must do this from the admin db */
    admindb = mongoc_client_get_database (client, "admin");

    command = BCON_NEW ("copydb",
                        BCON_INT32 (1),
                        "fromdb",
                        BCON_UTF8 ("test"),
                        "todb",
                        BCON_UTF8 ("test2"),

                        /* If you want from a different host */
                        "fromhost",
                        BCON_UTF8 (other_host_and_port));
    res =
        mongoc_database_command_simple (admindb, command, NULL, &reply, &error);
    if (!res) {
        fprintf (stderr, "Error with copydb: %s\n", error.message);
        goto cleanup;
    }

    /* Do something with the reply */
    print_res (&reply);

cleanup:
    bson_destroy (&reply);
    bson_destroy (command);
    mongoc_database_destroy (admindb);

    return res;
}
Ejemplo n.º 20
0
void connect_mongo_db(const char *host, const char *name)
{
    bson_t              *command,
    reply;
    
    bson_error_t        error;
    char                *str;
    bool                retval;
    
    mongoc_init();
    client = mongoc_client_new(host);
    //连接失败
    if(client == NULL){
        printf("connect mongodb fail db_host: %s" , host);
        return;
    }
    
    command = BCON_NEW ("ping", BCON_INT32 (1));
    
    retval = mongoc_client_command_simple (client, "admin", command, NULL, &reply, &error);
    
    if (!retval) {
        fprintf (stderr, "%s\n", error.message);
        bson_destroy (&reply);
        return;
    }
    
    str = bson_as_json (&reply, NULL);
    printf ("%s\n", str);
    bson_destroy (&reply);
    bson_destroy (command);
    bson_free (str);
    database = mongoc_client_get_database(client, name);
    
    mongoc_cleanup();
    return;
};
Ejemplo n.º 21
0
	RESULTCODE TileWorkspaceMongo::Open()
	{
		if(m_mongo!=NULL)
		{
			return AG_FAILURE;
		}

		const char* szServer   = m_props.GetValue(AUGE_DB_SERVER);
		const char* szInstance = m_props.GetValue(AUGE_DB_INSTANCE);
		const char* szDatabase = m_props.GetValue(AUGE_DB_DATABASE);
		const char* szUser     = m_props.GetValue(AUGE_DB_USER);
		const char* szPassword = m_props.GetValue(AUGE_DB_PASSWORD);
		const char* szEncoding = m_props.GetValue(AUGE_DB_ENCODING);

		if(szServer==NULL||szDatabase==NULL||szUser==NULL||szPassword==NULL)
		{
			return AG_FAILURE;
		}

		char constr[AUGE_NAME_MAX] = {0};
		g_sprintf(constr, "mongodb://%s:%s/", szServer, szInstance);
		m_mongo = mongoc_client_new(constr);
		if(m_mongo == NULL)
		{
			char msg[AUGE_MSG_MAX];
			g_snprintf(msg, AUGE_MSG_MAX, "Cannot to connect to mongdo %s:%s", szServer, szInstance);
			GLogger* pLogger = augeGetLoggerInstance();
			pLogger->Error(msg, __FILE__, __LINE__);

			GError* pError = augeGetErrorInstance();
			pError->SetError(msg);
			return AG_FAILURE;
		}
		m_mongo_db = mongoc_client_get_database(m_mongo, szDatabase);
		m_database = szDatabase;
		return AG_SUCCESS;
	}
Ejemplo n.º 22
0
static void
test_drop (void)
{
   mongoc_database_t *database;
   mongoc_client_t *client;
   bson_error_t error = { 0 };
   char *dbname;
   bool r;

   client = mongoc_client_new (gTestUri);
   assert (client);

   dbname = gen_collection_name ("db_drop_test");
   database = mongoc_client_get_database (client, dbname);
   bson_free (dbname);

   r = mongoc_database_drop (database, &error);
   assert (r);
   assert (!error.domain);
   assert (!error.code);

   mongoc_database_destroy (database);
   mongoc_client_destroy (client);
}
Ejemplo n.º 23
0
static int init()
{
    str_t tmp = empty_str;
    str_t host = conf_lookup(&robot.conf, str_from("DB_HOST")).string;
    str_t name = conf_lookup(&robot.conf, str_from("DB_NAME")).string;
    size_t i;

    int rc = 1;

    str_cat(&tmp, "mongodb://");
    str_ncat(&tmp, host.ptr, host.len);
    robot.mongoc_client = mongoc_client_new(tmp.ptr);
    if (robot.mongoc_client == NULL)
    {
        rc = 0;
        fprintf(stderr, "mongoc_client_new(\"%s\") error!!!!\n", tmp.ptr);
        goto end;
    }

    robot.mongoc_database = mongoc_client_get_database(robot.mongoc_client, name.ptr);
    if (robot.mongoc_database == NULL)
    {
        rc = 0;
        fprintf(stderr, "mongoc_client_get_database(\"%s\") error!!!!\n", name.ptr);
        goto end;
    }

    {
        mongoc_collection_t* message_collection;
        mongoc_index_opt_t opt;
        bson_error_t error;
        bson_t keys;

        message_collection = mongoc_database_get_collection(robot.mongoc_database, "message");
        if (message_collection == NULL)
        {
            rc = 0;
            fprintf(stderr, "mongoc_database_get_collection(\"message\") error!!!!\n");
            goto end;
        }

        mongoc_index_opt_init(&opt);

        // from+type 做联合索引
        bson_init(&keys);
        BSON_APPEND_INT32(&keys, "from", 1);
        BSON_APPEND_INT32(&keys, "type", 1);

        if (!mongoc_collection_create_index(message_collection, &keys, &opt, &error)) MONGOC_WARNING("%s\n", error.message);

        bson_destroy(&keys);

        // time 做逆序索引
        bson_init(&keys);
        BSON_APPEND_INT32(&keys, "time", -1);

        if (!mongoc_collection_create_index(message_collection, &keys, &opt, &error)) MONGOC_WARNING("%s\n", error.message);

        bson_destroy(&keys);

        // content 做全文索引
        bson_init(&keys);
        BSON_APPEND_UTF8(&keys, "content", "text");

        if (!mongoc_collection_create_index(message_collection, &keys, &opt, &error)) MONGOC_WARNING("%s\n", error.message);

        bson_destroy(&keys);
    }

    {
        mongoc_collection_t* unprocessed_collection;
        mongoc_index_opt_t opt;
        bson_error_t error;
        bson_t keys;

        unprocessed_collection = mongoc_database_get_collection(robot.mongoc_database, "unprocessed");
        if (unprocessed_collection == NULL)
        {
            rc = 0;
            fprintf(stderr, "mongoc_database_get_collection(\"unprocessed\") error!!!!\n");
            goto end;
        }

        mongoc_index_opt_init(&opt);

        // time 做逆序索引
        bson_init(&keys);
        BSON_APPEND_INT32(&keys, "time", -1);

        if (!mongoc_collection_create_index(unprocessed_collection, &keys, &opt, &error)) MONGOC_WARNING("%s\n", error.message);

        bson_destroy(&keys);
    }

    for (i = 0; modules[i]; ++i)
    {
        if (modules[i]->module_init)
        {
            rc = modules[i]->module_init();
            if (!rc) goto end;
        }
    }
end:
    str_free(tmp);
    return rc;
}
Ejemplo n.º 24
0
static void
test_get_collection_names (void)
{
   mongoc_database_t *database;
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error = { 0 };
   bson_t options;
   int r;
   int namecount = 0;

   char **names;
   char **name;
   char *curname;

   char *dbname;
   char *name1;
   char *name2;
   char *name3;
   char *name4;
   char *name5;
   const char *system_prefix = "system.";

   client = mongoc_client_new (gTestUri);
   assert (client);

   dbname = gen_collection_name ("dbtest");
   database = mongoc_client_get_database (client, dbname);

   assert (database);
   bson_free (dbname);

   bson_init (&options);

   name1 = gen_collection_name ("name1");
   name2 = gen_collection_name ("name2");
   name3 = gen_collection_name ("name3");
   name4 = gen_collection_name ("name4");
   name5 = gen_collection_name ("name5");

   collection = mongoc_database_create_collection (database, name1, &options,
                                                   &error);
   assert (collection);
   mongoc_collection_destroy (collection);

   collection = mongoc_database_create_collection (database, name2, &options,
                                                   &error);
   assert (collection);
   mongoc_collection_destroy (collection);

   collection = mongoc_database_create_collection (database, name3, &options,
                                                   &error);
   assert (collection);
   mongoc_collection_destroy (collection);

   collection = mongoc_database_create_collection (database, name4, &options,
                                                   &error);
   assert (collection);
   mongoc_collection_destroy (collection);

   collection = mongoc_database_create_collection (database, name5, &options,
                                                   &error);
   assert (collection);
   mongoc_collection_destroy (collection);

   names = mongoc_database_get_collection_names (database, &error);
   assert (!error.domain);
   assert (!error.code);

   for (name = names; *name; ++name) {
      /* inefficient, but OK for a unit test. */
      curname = *name;

      if (0 == strcmp (curname, name1) ||
          0 == strcmp (curname, name2) ||
          0 == strcmp (curname, name3) ||
          0 == strcmp (curname, name4) ||
          0 == strcmp (curname, name5)) {
         ++namecount;
      } else if (0 ==
                 strncmp (curname, system_prefix, strlen (system_prefix))) {
         /* Collections prefixed with 'system.' are system collections */
      } else {
         assert (false);
      }

      bson_free (curname);
   }

   assert (namecount == 5);

   bson_free (name1);
   bson_free (name2);
   bson_free (name3);
   bson_free (name4);
   bson_free (name5);

   bson_free (names);

   r = mongoc_database_drop (database, &error);
   assert (r);
   assert (!error.domain);
   assert (!error.code);

   mongoc_database_destroy (database);
   mongoc_client_destroy (client);
}
Ejemplo n.º 25
0
static void
test_get_collection_info (void)
{
   mongoc_database_t *database;
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error = { 0 };
   bson_iter_t iter;
   bson_iter_t col_array;
   bson_iter_t col_iter;
   bson_t capped_options = BSON_INITIALIZER;
   bson_t autoindexid_options = BSON_INITIALIZER;
   bson_t noopts_options = BSON_INITIALIZER;
   bson_t name_filter = BSON_INITIALIZER;
   int r;
   int num_infos = 0;

   bson_t *infos = NULL;
   const char *name;
   char *dbname;
   char *capped_name;
   char *autoindexid_name;
   char *noopts_name;

   client = mongoc_client_new (gTestUri);
   assert (client);

   dbname = gen_collection_name ("dbtest");
   database = mongoc_client_get_database (client, dbname);

   assert (database);
   bson_free (dbname);

   capped_name = gen_collection_name ("capped");
   BSON_APPEND_BOOL (&capped_options, "capped", true);
   BSON_APPEND_INT32 (&capped_options, "size", 10000000);
   BSON_APPEND_INT32 (&capped_options, "max", 1024);

   autoindexid_name = gen_collection_name ("autoindexid");
   BSON_APPEND_BOOL (&autoindexid_options, "autoIndexId", false);

   noopts_name = gen_collection_name ("noopts");

   collection = mongoc_database_create_collection (database, capped_name,
                                                   &capped_options, &error);
   assert (collection);
   mongoc_collection_destroy (collection);

   collection = mongoc_database_create_collection (database, autoindexid_name,
                                                   &autoindexid_options,
                                                   &error);
   assert (collection);
   mongoc_collection_destroy (collection);

   collection = mongoc_database_create_collection (database, noopts_name,
                                                   &noopts_options, &error);
   assert (collection);
   mongoc_collection_destroy (collection);

   /* first we filter on collection name. */
   BSON_APPEND_UTF8 (&name_filter, "name", noopts_name);

   /* We only test with filters since get_collection_names will
    * test w/o filters for us. */

   /* Filter on an exact match of name */
   infos = mongoc_database_get_collection_info (database, &name_filter, &error);
   assert (infos);
   assert (!error.domain);
   assert (!error.code);

   if (bson_iter_init_find (&iter, infos, "collections") &&
       BSON_ITER_HOLDS_ARRAY (&iter) &&
       bson_iter_recurse (&iter, &col_array)) {
      while (bson_iter_next (&col_array)) {
         if (BSON_ITER_HOLDS_DOCUMENT (&col_array) &&
             bson_iter_recurse (&col_array, &col_iter) &&
             bson_iter_find (&col_iter, "name") &&
             BSON_ITER_HOLDS_UTF8 (&col_iter) &&
             (name = bson_iter_utf8 (&col_iter, NULL))) {
            ++num_infos;
            assert (0 == strcmp (name, noopts_name));
         } else {
            assert (false);
         }
       }
   }

   assert (1 == num_infos);

   num_infos = 0;
   bson_destroy (infos);
   infos = NULL;

   r = mongoc_database_drop (database, &error);
   assert (r);
   assert (!error.domain);
   assert (!error.code);

   bson_free (capped_name);
   bson_free (noopts_name);
   bson_free (autoindexid_name);

   mongoc_database_destroy (database);
   mongoc_client_destroy (client);
}
int
main (int   argc,
      char *argv[])
{
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   mongoc_cursor_t *cursor;
   bson_error_t error;
   const bson_t *doc;
   const char *uristr = "mongodb://*****:*****@localhost/?authMechanism=PLAIN&authSource=$external";
   const char *database_name = "test";
   const char *collection_name = "query1";
   const char *user_role = "ro";

   if (argc == 2 && !strcmp("--help",argv[1])) {
     printf ("Usage: [uri [database [collection [ro|rw]]]]\n");
     return EXIT_FAILURE;
   }

   if (argc > 1) {
      uristr = argv [1];
   }

   if (argc > 2) {
      database_name = argv [2];
   }

   if (argc > 3) {
      collection_name = argv [3];
   }

   if (argc > 4) {
      user_role = argv [4];
   }

   mongoc_init ();

   client = mongoc_client_new (uristr);
   collection = mongoc_client_get_collection (client, database_name, collection_name);

   if (!client) {
      fprintf (stderr, "Failed to parse URI.\n");
      return EXIT_FAILURE;
   }

   // write

   if (!strcasecmp(user_role,"rw")) {

      bson_t *rwbson;
      bson_error_t rwerror;

      rwbson = bson_new();
      time_t now = time(NULL);
      bson_append_utf8(rwbson,"db",-1,database_name,-1);
      bson_append_time_t(rwbson,"date",-1,now);
      mongoc_client_get_database(client, database_name);
      bool ret = mongoc_collection_insert(collection, MONGOC_INSERT_NONE, rwbson, NULL,
                                                                     &rwerror);

      bson_destroy(rwbson);

      if (!ret)
          return EXIT_FAILURE;

   }

   // read
   bson_t roquery;
   bson_init (&roquery);
   char *str;

#if 0
   eson_append_utf8 (&roquery, "hello", -1, "world", -1);
#endif

   cursor = mongoc_collection_find (collection,
                                    MONGOC_QUERY_NONE,
                                    0,
                                    0,
                                    0,
                                    &roquery,
                                    NULL,  /* Fields, NULL for all. */
                                    NULL); /* Read Prefs, NULL for default */
   while (mongoc_cursor_next (cursor, &doc)) {
      str = bson_as_json (doc, NULL);
      fprintf (stdout, "%s\n", str);
      bson_free (str);
   }

   if (mongoc_cursor_error (cursor, &error)) {
      fprintf (stderr, "Cursor Failure: %s\n", error.message);
      return EXIT_FAILURE;
   }

   bson_destroy (&roquery);

  // close server connection

   mongoc_cursor_destroy (cursor);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return EXIT_SUCCESS;
}
Ejemplo n.º 27
0
int
main (int   argc,
      char *argv[])
{
   mongoc_database_t *database = NULL;
   mongoc_client_t *client = NULL;
   mongoc_collection_t *collection = NULL;
   char *host_and_port;
   int res = 0;
   char* other_host_and_port = NULL;

   if (argc < 2 || argc > 3) {
      fprintf (stderr, "usage: %s MONGOD-1-CONNECTION-STRING "
               "[MONGOD-2-HOST-NAME:MONGOD-2-PORT]\n",
               argv[0]);
      fprintf (stderr,
               "MONGOD-1-CONNECTION-STRING can be "
               "of the following forms:\n");
      fprintf (stderr, "localhost\t\t\t\tlocal machine\n");
      fprintf (stderr, "localhost:27018\t\t\t\tlocal machine on port 27018\n");
      fprintf (stderr,
               "mongodb://*****:*****@localhost:27017\t"
               "local machine on port 27017, and authenticate with username "
               "user and password pass\n");
      return 1;
   }

   mongoc_init ();

   if (strncmp (argv[1], "mongodb://", 10) == 0) {
      host_and_port = bson_strdup (argv [1]);
   } else {
      host_and_port = bson_strdup_printf ("mongodb://%s", argv[1]);
   }
   other_host_and_port = argc > 2 ? argv[2] : NULL;

   client = mongoc_client_new (host_and_port);

   if (!client) {
      fprintf(stderr, "Invalid hostname or port: %s\n", host_and_port);
      res = 2;
      goto cleanup;
   }

   database = mongoc_client_get_database (client, "test");
   collection = mongoc_database_get_collection (database, COLLECTION_NAME);

   printf ("Inserting data\n");
   if (!insert_data (collection)) {
      res = 3;
      goto cleanup;
   }

   printf ("explain\n");
   if (!explain (collection)) {
      res = 4;
      goto cleanup;
   }

   if (other_host_and_port) {
      printf ("copydb\n");
      if (!copydb (client, other_host_and_port)) {
         res = 5;
         goto cleanup;
      }

      printf ("clone collection\n");
      if (!clone_collection (database, other_host_and_port)) {
         res = 6;
         goto cleanup;
      }
   }

cleanup:
   if (collection) {
      mongoc_collection_destroy (collection);
   }

   if (database) {
      mongoc_database_destroy (database);
   }

   if (client) {
      mongoc_client_destroy (client);
   }

   bson_free (host_and_port);
   mongoc_cleanup ();
   return res;
}
Ejemplo n.º 28
0
int
main (int argc, char *argv[])
{
   const char *uri_str = "mongodb://localhost:27017";
   mongoc_client_t *client;
   mongoc_database_t *database;
   mongoc_collection_t *collection;
   bson_t *command, reply, *insert;
   bson_error_t error;
   char *str;
   bool retval;

   /*
    * Required to initialize libmongoc's internals
    */
   mongoc_init ();

   /*
    * Optionally get MongoDB URI from command line
    */
   if (argc > 1) {
      uri_str = argv[1];
   }

   /*
    * Create a new client instance
    */
   client = mongoc_client_new (uri_str);

   /*
    * Register the application name so we can track it in the profile logs
    * on the server. This can also be done from the URI (see other examples).
    */
   mongoc_client_set_appname (client, "connect-example");

   /*
    * Get a handle on the database "db_name" and collection "coll_name"
    */
   database = mongoc_client_get_database (client, "db_name");
   collection = mongoc_client_get_collection (client, "db_name", "coll_name");

   /*
    * Do work. This example pings the database, prints the result as JSON and
    * performs an insert
    */
   command = BCON_NEW ("ping", BCON_INT32 (1));

   retval = mongoc_client_command_simple (
      client, "admin", command, NULL, &reply, &error);

   if (!retval) {
      fprintf (stderr, "%s\n", error.message);
      return EXIT_FAILURE;
   }

   str = bson_as_json (&reply, NULL);
   printf ("%s\n", str);

   insert = BCON_NEW ("hello", BCON_UTF8 ("world"));

   if (!mongoc_collection_insert (
          collection, MONGOC_INSERT_NONE, insert, NULL, &error)) {
      fprintf (stderr, "%s\n", error.message);
   }

   bson_destroy (insert);
   bson_destroy (&reply);
   bson_destroy (command);
   bson_free (str);

   /*
    * Release our handles and clean up libmongoc
    */
   mongoc_collection_destroy (collection);
   mongoc_database_destroy (database);
   mongoc_client_destroy (client);
   mongoc_cleanup ();

   return 0;
}
Ejemplo n.º 29
0
static void
ha_replica_set_configure (ha_replica_set_t *replica_set,
                          ha_node_t        *primary)
{
   mongoc_database_t *database;
   mongoc_client_t *client;
   mongoc_cursor_t *cursor;
   const bson_t *doc;
   bson_error_t error;
   bson_iter_t iter;
   ha_node_t *node;
   bson_t ar;
   bson_t cmd;
   bson_t config;
   bson_t member;
   char *str;
   char *uristr;
   char hoststr[32];
   char key[8];
   int i = 0;

   uristr = bson_strdup_printf("mongodb://127.0.0.1:%hu/", primary->port);
   client = mongoc_client_new(uristr);
#ifdef MONGOC_ENABLE_SSL
   if (replica_set->ssl_opt) {
      mongoc_client_set_ssl_opts(client, replica_set->ssl_opt);
   }
#endif
   bson_free(uristr);

   bson_init(&cmd);
   bson_append_document_begin(&cmd, "replSetInitiate", -1, &config);
   bson_append_utf8(&config, "_id", 3, replica_set->name, -1);
   bson_append_array_begin(&config, "members", -1, &ar);
   for (node = replica_set->nodes; node; node = node->next) {
      snprintf(key, sizeof key, "%u", i);
      key[sizeof key - 1] = '\0';

      snprintf(hoststr, sizeof hoststr, "127.0.0.1:%hu", node->port);
      hoststr[sizeof hoststr - 1] = '\0';

      bson_append_document_begin(&ar, key, -1, &member);
      bson_append_int32(&member, "_id", -1, i);
      bson_append_utf8(&member, "host", -1, hoststr, -1);
      bson_append_bool(&member, "arbiterOnly", -1, node->is_arbiter);
      bson_append_document_end(&ar, &member);

      i++;
   }
   bson_append_array_end(&config, &ar);
   bson_append_document_end(&cmd, &config);

   str = bson_as_json(&cmd, NULL);
   MONGOC_DEBUG("Config: %s", str);
   bson_free(str);

   database = mongoc_client_get_database(client, "admin");

again:
   cursor = mongoc_database_command(database,
                                    MONGOC_QUERY_NONE,
                                    0,
                                    1,
                                    &cmd,
                                    NULL,
                                    NULL);

   while (mongoc_cursor_next(cursor, &doc)) {
      str = bson_as_json(doc, NULL);
      MONGOC_DEBUG("Reply: %s", str);
      bson_free(str);
      if (bson_iter_init_find(&iter, doc, "ok") &&
          bson_iter_as_bool(&iter)) {
         goto cleanup;
      }
   }

   if (mongoc_cursor_error(cursor, &error)) {
      mongoc_cursor_destroy(cursor);
      MONGOC_WARNING("%s: Retrying in 1 second.", error.message);
      sleep(1);
      goto again;
   }

cleanup:
   mongoc_cursor_destroy(cursor);
   mongoc_database_destroy(database);
   mongoc_client_destroy(client);
   bson_destroy(&cmd);
}
Ejemplo n.º 30
0
static void
test_bypass_validation (void *context)
{
   mongoc_collection_t *collection;
   bson_t reply = BSON_INITIALIZER;
   mongoc_bulk_operation_t *bulk;
   mongoc_database_t *database;
   mongoc_write_concern_t *wr;
   mongoc_client_t *client;
   bson_error_t error;
   bson_t *options;
   char *collname;
   char *dbname;
   int r;
   int i;

   client = test_framework_client_new ();
   assert (client);

   dbname = gen_collection_name ("dbtest");
   collname = gen_collection_name ("bypass");
   database = mongoc_client_get_database (client, dbname);
   collection = mongoc_database_get_collection (database, collname);
   assert (collection);

   options = tmp_bson ("{'validator': {'number': {'$gte': 5}}, 'validationAction': 'error'}");
   ASSERT_OR_PRINT (mongoc_database_create_collection (database, collname, options, &error), error);

   /* {{{ Default fails validation */
   bulk = mongoc_collection_create_bulk_operation(collection, true, NULL);
   for (i = 0; i < 3; i++) {
      bson_t *doc = tmp_bson (bson_strdup_printf ("{'number': 3, 'high': %d }", i));

      mongoc_bulk_operation_insert (bulk, doc);
   }
   r = mongoc_bulk_operation_execute (bulk, &reply, &error);
   ASSERT(!r);

   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, 121, "Document failed validation");
   mongoc_bulk_operation_destroy (bulk);
   /* }}} */

   /* {{{ bypass_document_validation=false Fails validation */
   bulk = mongoc_collection_create_bulk_operation(collection, true, NULL);
   mongoc_bulk_operation_set_bypass_document_validation (bulk, false);
   for (i = 0; i < 3; i++) {
      bson_t *doc = tmp_bson (bson_strdup_printf ("{'number': 3, 'high': %d }", i));

      mongoc_bulk_operation_insert (bulk, doc);
   }
   r = mongoc_bulk_operation_execute (bulk, &reply, &error);
   ASSERT(!r);

   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, 121, "Document failed validation");
   mongoc_bulk_operation_destroy (bulk);
   /* }}} */

   /* {{{ bypass_document_validation=true ignores validation */
   bulk = mongoc_collection_create_bulk_operation(collection, true, NULL);
   mongoc_bulk_operation_set_bypass_document_validation (bulk, true);
   for (i = 0; i < 3; i++) {
      bson_t *doc = tmp_bson (bson_strdup_printf ("{'number': 3, 'high': %d }", i));

      mongoc_bulk_operation_insert (bulk, doc);
   }
   r = mongoc_bulk_operation_execute (bulk, &reply, &error);
   ASSERT_OR_PRINT(r, error);
   mongoc_bulk_operation_destroy (bulk);
   /* }}} */

   /* {{{ w=0 and bypass_document_validation=set fails */
   bulk = mongoc_collection_create_bulk_operation(collection, true, NULL);
   wr = mongoc_write_concern_new ();
   mongoc_write_concern_set_w (wr, 0);
   mongoc_bulk_operation_set_write_concern (bulk, wr);
   mongoc_bulk_operation_set_bypass_document_validation (bulk, true);
   for (i = 0; i < 3; i++) {
      bson_t *doc = tmp_bson (bson_strdup_printf ("{'number': 3, 'high': %d }", i));

      mongoc_bulk_operation_insert (bulk, doc);
   }
   r = mongoc_bulk_operation_execute (bulk, &reply, &error);
   ASSERT_OR_PRINT(!r, error);
   ASSERT_ERROR_CONTAINS (error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG,
         "Cannot set bypassDocumentValidation for unacknowledged writes");
   mongoc_bulk_operation_destroy (bulk);
   mongoc_write_concern_destroy (wr);
   /* }}} */

   ASSERT_OR_PRINT (mongoc_collection_drop (collection, &error), error);

   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
}