Beispiel #1
0
int main(){
  //start(); 
  /* Start heartbeat thread */
  printf("strlen %d\n",strlen("中国人"));
  mongoc_init();
  initQueue(&g_qalarm); 
  mgclient = mongoc_client_new ("mongodb://172.16.0.7:27017/");
  int result;
  printf("222\n");
  result = pthread_create(&tid_ping, NULL, (void *)thread_re, NULL);
  if (result != 0) {
     printf("error");
  }
  //pthread_detach(tid_ping);  
  pthread_join(tid_ping,NULL); 
  /*result = pthread_create(&tid_alarm, NULL, (void *)thread_alarm, NULL);
  if (result != 0) {
     printf("error");
  }
  pthread_detach(tid_alarm);  
  result = pthread_create(&tid_query, NULL, (void *)thread_query, NULL);
  if (result != 0) {
     printf("error");
  }
  printf("d%\n",tid_query);
  pthread_join(tid_query,NULL);  */
	//pthread_detach(tid_ping);
  mongoc_client_destroy (mgclient);
  mongoc_cleanup ();
  return 0;
}
Beispiel #2
0
int
main (int   argc,
      char *argv[])
{
    mongoc_client_t *client;
    mongoc_collection_t *collection;
    mongoc_cursor_t *cursor;
    const bson_t *doc;
    bson_t *query;
    char *str;

    mongoc_init ();

    client = mongoc_client_new ("mongodb://localhost:3001/");
    collection = mongoc_client_get_collection (client, "meteor", "sensors");
    query = bson_new ();
    cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

    while (mongoc_cursor_next (cursor, &doc)) {
        str = bson_as_json (doc, NULL);
        printf ("%s\n", str);
        bson_free (str);
    }

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

    return 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;
}
Beispiel #4
0
int
main (int   argc,
      char *argv[])
{
   mongoc_client_pool_t *pool;
   mongoc_client_t *client;
   mongoc_uri_t *uri;
   unsigned count = 10000;

   mongoc_init();

   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;
}
Beispiel #5
0
int
main (int argc, char *argv[])
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;

   if (argc != 2) {
      fprintf (stderr, "usage: %s MONGO_URI\n", argv[0]);
      return EXIT_FAILURE;
   }

   mongoc_init ();

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

   mongoc_client_set_error_api (client, 2);

   collection = mongoc_client_get_collection (client, "local", "oplog.rs");

   tail_collection (collection);

   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   return 0;
}
Beispiel #6
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;
}
Beispiel #7
0
int main (int argc,char* argv[])
{
    mongoc_client_t *client;
    mongoc_collection_t *collection;
    mongoc_cursor_t *cursor;

    const bson_t *doc;

    bson_t *query;

    char *str;

    mongoc_init ();

    client = mongoc_client_new ("mongodb://*****:*****@192.168.0.112:27017/");
    collection = mongoc_client_get_collection (client, "clown", "testCollection");
    query = bson_new ();

    cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

    while (mongoc_cursor_next (cursor, &doc)) {
        str = bson_as_json (doc, NULL);
        printf ("%s\n", str);
        bson_free (str);
    }

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

    return 0;
}
Beispiel #8
0
void *be_mongo_init()
{
	struct mongo_backend *conf;
	conf = (struct mongo_backend *)malloc(sizeof(struct mongo_backend));

	conf->database = strdup(be_mongo_get_option("mongo_database", NULL, "mqGate"));
	conf->user_coll = strdup(be_mongo_get_option("mongo_user_coll", "mongo_collection_users", "users"));
	conf->topiclist_coll = strdup(be_mongo_get_option("mongo_topiclist_coll", "mongo_collection_topics", "topics"));
	conf->user_username_prop = strdup(be_mongo_get_option("mongo_user_username_prop", NULL, "username"));
	conf->user_password_prop = strdup(be_mongo_get_option("mongo_user_password_prop", "mongo_location_password", "password"));
	conf->user_superuser_prop = strdup(be_mongo_get_option("mongo_user_superuser_prop", "mongo_location_superuser", "superuser"));
	conf->user_topics_prop = strdup(be_mongo_get_option("mongo_user_topics_prop", NULL, "topics"));
	conf->user_topiclist_fk_prop = strdup(be_mongo_get_option("mongo_user_topiclist_fk_prop", "mongo_location_topic", "topics"));
	conf->topiclist_key_prop = strdup(be_mongo_get_option("mongo_topiclist_key_prop", "mongo_location_superuser", "_id"));
	conf->topiclist_topics_prop = strdup(be_mongo_get_option("mongo_topiclist_topics_prop", "mongo_location_topic", "topics"));

	mongoc_init();
	mongoc_uri_t *uri = be_mongo_new_uri_from_options();
	if (!uri) {
		_fatal("MongoDB connection options invalid");
	}
	conf->client = mongoc_client_new_from_uri(uri);
	mongoc_uri_destroy(uri);

	return (conf);
}
Beispiel #9
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;
}
Beispiel #10
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;
}
int
main (int argc,
      char *argv[])
{
   mongoc_init();

   repl_1 = ha_replica_set_new("shardtest1");
   node_1_1 = ha_replica_set_add_replica(repl_1, "shardtest1_1");
   node_1_2 = ha_replica_set_add_replica(repl_1, "shardtest1_2");
   node_1_3 = ha_replica_set_add_replica(repl_1, "shardtest1_3");

   repl_2 = ha_replica_set_new("shardtest2");
   node_2_1 = ha_replica_set_add_replica(repl_2, "shardtest2_1");
   node_2_2 = ha_replica_set_add_replica(repl_2, "shardtest2_2");
   node_2_3 = ha_replica_set_add_replica(repl_2, "shardtest2_3");

   cluster = ha_sharded_cluster_new("cluster1");
   ha_sharded_cluster_add_replica_set(cluster, repl_1);
   ha_sharded_cluster_add_replica_set(cluster, repl_2);
   ha_sharded_cluster_add_config(cluster, "config1");
   ha_sharded_cluster_add_router(cluster, "router1");
   ha_sharded_cluster_add_router(cluster, "router2");

   ha_sharded_cluster_start(cluster);
   ha_sharded_cluster_wait_for_healthy(cluster);

   run_test("/ShardedCluster/basic", test1);

   ha_sharded_cluster_shutdown(cluster);

   mongoc_cleanup();

   return 0;
}
int
main (int   argc,
      char *argv[])
{
   double start_time, end_time, delta_time;
   int64_t count;

   if (argc < 3) {
      fprintf(stderr, "usage: %s [options] schema_file mbdump_dir table_names", argv[0]);
      DIE;
   }
   argc--, argv++;
   strcpy(schema_file, argv[0]);
   argc--, argv++;
   strcpy(mbdump_dir, argv[0]);
   argc--, argv++;

   test_suite ();

   mongoc_init ();
   mongoc_log_set_handler (log_local_handler, NULL);

   start_time = dtimeofday ();
   count = execute (argc, &argv[0]);
   end_time = dtimeofday ();
   delta_time = end_time - start_time + 0.0000001;
   fprintf (stderr, "total:\n");
   fprintf (stderr, "info: real: %.2f, count: %"PRId64", %"PRId64" docs/sec\n", delta_time, count, (int64_t)round (count/delta_time));

   mongoc_cleanup ();

   return 0;
}
Beispiel #13
0
/**
 * Initialize libmongoc.
 */
void monary_init(void) {
    mongoc_init();
#ifdef NDEBUG
    mongoc_log_set_handler(monary_log_func, NULL);
#endif
    DEBUG("%s", "monary module initialized");
}
Beispiel #14
0
/*! \brief
 * Create a new connection structure,
 * open the mongodb connection and set reference count to 1
 */
km_mongodb_con_t* db_mongodb_new_connection(const struct db_id* id)
{
	km_mongodb_con_t *ptr;

	if (!id) {
		LM_ERR("invalid parameter value\n");
		return 0;
	}

	ptr = (km_mongodb_con_t*)pkg_malloc(sizeof(km_mongodb_con_t));
	if (!ptr) {
		LM_ERR("no private memory left\n");
		return 0;
	}

	memset(ptr, 0, sizeof(km_mongodb_con_t));
	ptr->ref = 1;

	mongoc_init();
	ptr->con = mongoc_client_new (id->url.s);
	if (!ptr->con) {
		LM_ERR("cannot open connection: %.*s\n", id->url.len, id->url.s);
		goto err;
	}

	LM_DBG("connection open to: %.*s\n", id->url.len, id->url.s);

	ptr->id = (struct db_id*)id;
	return ptr;

 err:
	if (ptr) pkg_free(ptr);
	return 0;
}
Beispiel #15
0
void *be_mongo_init()
{
    struct mongo_backend *conf;
    char *host, *p;

    if ((host = p_stab("mongo_host")) == NULL)
        host = "localhost";
    if ((p = p_stab("mongo_port")) == NULL)
        p = "27017";

     char uristr[128] = {0};
     strcpy(uristr, "mongodb://");
     strcat(uristr, host);
     strcat(uristr, ":");
     strcat(uristr, p);
     printf("mongo: [%s]\n", uristr);

    conf = (struct mongo_backend *)malloc(sizeof(struct mongo_backend));
   mongoc_init ();

   conf->client = mongoc_client_new (uristr);

   if (!conf->client) {
      fprintf (stderr, "Failed to parse URI.\n");
      return NULL;
   }
    return (conf);
}
int
main (int   argc,   /* IN */
      char *argv[]) /* IN */
{
   char *cwd;
   char buf[1024];

   if (argc <= 1 || !!strcmp (argv[1], "-v")) {
      mongoc_log_set_handler (log_handler, NULL);
   }

   mongoc_init ();

   cwd = getcwd(buf, sizeof(buf));
   assert(cwd);

   gTestCAFile = bson_strdup_printf("%s/" CAFILE, cwd);
   gTestPEMFileLocalhost = bson_strdup_printf("%s/" PEMFILE_LOCALHOST, cwd);

   run_test("/ReplicaSet/ssl/client", &test_replica_set_ssl_client);

   bson_free(gTestCAFile);
   bson_free(gTestPEMFileLocalhost);

   mongoc_cleanup();

   return 0;
}
Beispiel #17
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());
}
Beispiel #18
0
int main(int argc, char *argv[]) {
	mongoc_client_t *client;
	mongoc_collection_t *collection;
	mongoc_cursor_t *cursor;
	const bson_t *doc;
	bson_t *query;
	char *str;

	mongoc_init();

	client = mongoc_client_new("mongodb://localhost:27017/");
	collection = mongoc_client_get_collection(client, "stockopedia",
			"instruments");

	query = bson_new();
	bson_t *fields = bson_new();
	BSON_APPEND_INT32(fields, "RIC", 1);

	cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0,
			query, fields, NULL);

	bson_iter_t iter;
	const bson_value_t *value;

	while (mongoc_cursor_next(cursor, &doc)) {
		str = bson_as_json(doc, NULL);
		printf("%s\n", str);

		if (bson_iter_init(&iter, doc)) {
			while (bson_iter_next(&iter)) {
				printf("Found a field named: %s\n", bson_iter_key(&iter));

				value = bson_iter_value(&iter);
				if (value->value_type == BSON_TYPE_UTF8) {
					printf("It's a UTF8 : '%s'\n", value->value.v_utf8.str);
				}
			}
		}

		//printf("Found element key : '%s'\n", bson_iter_key(&iter));

//		if (bson_iter_init(&iter, doc)) {
//
//		}

		bson_free(str);
	}

	//Now fetch quotes for each RIC

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

	return 0;
}
Beispiel #19
0
int
main (int argc,
      char *argv[])
{
   mongoc_init ();
   example ();
   mongoc_cleanup ();

   return 0;
}
Beispiel #20
0
int
main (int   argc,
      char *argv[])
{
    mongoc_init ();
    run_command ();
    mongoc_cleanup ();

    return 0;
}
int
main (int   argc,
      char *argv[])
{
   mongoc_client_t *client;
   mongoc_apm_callbacks_t *callbacks;
   stats_t stats = { 0 }; 
   mongoc_collection_t *collection;
   const char *uristr = "mongodb://127.0.0.1/?appname=cmd-monitoring-example";
   const char *collection_name = "test";
   bson_t doc;

   mongoc_init ();

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

   client = mongoc_client_new (uristr);

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

   mongoc_client_set_error_api (client, 2);
   callbacks = mongoc_apm_callbacks_new ();
   mongoc_apm_set_command_started_cb (callbacks, command_started);
   mongoc_apm_set_command_succeeded_cb (callbacks, command_succeeded );
   mongoc_apm_set_command_failed_cb (callbacks, command_failed);
   mongoc_client_set_apm_callbacks (client,
                                    callbacks,
                                    (void *) &stats /* context pointer */);

   bson_init (&doc);
   BSON_APPEND_INT32 (&doc, "_id", 1);

   collection = mongoc_client_get_collection (client, "test", collection_name);
   mongoc_collection_drop (collection, NULL);
   mongoc_collection_insert (collection, MONGOC_INSERT_NONE, &doc, NULL, NULL);
   /* duplicate key error on the second insert */
   mongoc_collection_insert (collection, MONGOC_INSERT_NONE, &doc, NULL, NULL);

   printf ("started: %d\nsucceeded: %d\nfailed: %d\n",
           stats.started, stats.succeeded, stats.failed);

   bson_destroy (&doc);
   mongoc_collection_destroy (collection);
   mongoc_apm_callbacks_destroy (callbacks);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return EXIT_SUCCESS;
}
Beispiel #22
0
int
main (int   argc,
      char *argv[])
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_error_t error;
   bson_t *query;
   bson_t *update;
   bson_t reply;
   char *str;

   mongoc_init ();

   client = mongoc_client_new ("mongodb://127.0.0.1:27017/");
   collection = mongoc_client_get_collection (client, "test", "test");

   /*
    * Build our query, {"cmpxchg": 1}
    */
   query = BCON_NEW ("cmpxchg", BCON_INT32 (1));

   /*
    * Build our update. {"$set": {"cmpxchg": 2}}
    */
   update = BCON_NEW ("$set", "{", "cmpxchg", BCON_INT32 (2), "}");

   /*
    * Submit the findAndModify.
    */
   if (!mongoc_collection_find_and_modify (collection, query, NULL, update, NULL, false, false, true, &reply, &error)) {
      fprintf (stderr, "find_and_modify() failure: %s\n", error.message);
      return 1;
   }

   /*
    * Print the result as JSON.
    */
   str = bson_as_json (&reply, NULL);
   printf ("%s\n", str);
   bson_free (str);

   /*
    * Cleanup.
    */
   bson_destroy (query);
   bson_destroy (update);
   bson_destroy (&reply);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);

   mongoc_cleanup ();

   return 0;
}
/**
 * Instantiate module.
 * @param[in] conf Module config.
 * @param[in] instance Module instance.
 * @return Zero on success.
 */
static int mod_instantiate(CONF_SECTION *conf, void *instance) {
  rlm_mongodb_t *inst = instance;

  inst->name = cf_section_name2(conf);
  if (!inst->name) {
    inst->name = cf_section_name1(conf);
  }

  if (!strcasecmp(inst->cfg.action, "get")) {
    inst->action = RLM_MONGODB_GET;
    cf_log_err_cs(conf, "action 'get' is not implemented");
    goto err;
  } else if (!strcasecmp(inst->cfg.action, "set")) {
    inst->action = RLM_MONGODB_SET;
  } else {
    cf_log_err_cs(conf, "invalid 'action', use'get' or 'set'");
    goto err;
  }

  if (inst->cfg.remove && inst->cfg.update_query) {
    cf_log_err_cs(conf, "'update_query' and 'remove' can't be used at the same time");
    goto err;
  } else if (!inst->cfg.remove && !inst->cfg.update_query) {
    cf_log_err_cs(conf, "'update_query' or 'remove' must be set for 'set' action");
    goto err;
  }

  if (!cf_pair_find(conf, "pool")) {
    if (!inst->cfg.server) {
      cf_log_err_cs(conf, "Invalid or missing 'server' option");
      goto err;
    }
  } else {
    if (inst->cfg.server) {
      cf_log_err_cs(conf, "Can't use server option when foreign connection pool specified");
      goto err;
    }
  }

  mongoc_init();
  mongoc_log_set_handler(mongoc_log_handler, inst);

  inst->pool = fr_connection_pool_module_init(conf, inst, mod_conn_create, NULL, inst->name);
  if (!inst->pool) {
    goto err;
  }

  return 0;

  err:
  return -1;
}
Beispiel #24
0
int
main (void)
{
   mongoc_collection_t *collection;
   mongoc_database_t *database;
   mongoc_client_t *client;
   bson_error_t error;
   bson_t *options;

   mongoc_init ();
   client = mongoc_client_new (
      "mongodb://localhost:27017/admin?appname=find-and-modify-opts-example");
   mongoc_client_set_error_api (client, 2);
   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_opts (collection);
   fam_sort (collection);

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

   mongoc_cleanup ();
   return 0;
}
int
main (int   argc,
      char *argv[])
{
   TestSuite suite;
   int ret;

   mongoc_init ();

   bson_snprintf (MONGOC_TEST_UNIQUE, sizeof MONGOC_TEST_UNIQUE,
                  "test_%u_%u", (unsigned)time (NULL),
                  (unsigned)gettestpid ());

   set_mongoc_test_host ();

   mongoc_log_set_handler (log_handler, NULL);

   TestSuite_Init (&suite, "", argc, argv);

   test_array_install (&suite);
   test_buffer_install (&suite);
   test_client_install (&suite);
   test_client_pool_install (&suite);
   test_write_command_install (&suite);
   test_bulk_install (&suite);
   test_collection_install (&suite);
   test_cursor_install (&suite);
   test_database_install (&suite);
   test_gridfs_install (&suite);
   test_gridfs_file_page_install (&suite);
   test_list_install (&suite);
   test_matcher_install (&suite);
   test_queue_install (&suite);
   test_read_prefs_install (&suite);
   test_rpc_install (&suite);
   test_stream_install (&suite);
   test_uri_install (&suite);
   test_write_concern_install (&suite);
#ifdef MONGOC_ENABLE_SSL
   test_x509_install (&suite);
   test_stream_tls_install (&suite);
#endif

   ret = TestSuite_Run (&suite);

   TestSuite_Destroy (&suite);

   mongoc_cleanup();

   return ret;
}
int main (int argc, char *argv[])
{
    mongoc_client_t *client;
    mongoc_collection_t *collection;
    bson_error_t error;
    bson_oid_t oid;
    bson_t *doc;

    /* Init mongo C driver */
    mongoc_init ();

    /* Create a new connection to the database a get the specified collection  */
    client = mongoc_client_new ("mongodb://localhost:27017/");
    if (!client) {
        fprintf(stderr, "Connection to database failed!");
        mongoc_cleanup();
        return 0;
    } else {
        printf("Connected to the database successfully\n");
    }
    collection = mongoc_client_get_collection (client, "testdb", "users");

    /* Create a new document (All the documents must have the _id field to be used as primary key) */
    doc = bson_new ();
    bson_oid_init (&oid, NULL);
    BSON_APPEND_OID (doc, "_id", &oid);
    BSON_APPEND_UTF8 (doc, "username", "John");
    BSON_APPEND_UTF8 (doc, "password", "123456");

    /* Insert the document into the collection */
    if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
        printf ("Error inserting the document. - %s\n", error.message);
    } else {
        printf ("Document successfully inserted!\n");
    }

    /* Clean the doc, colletion and client allocations */
    bson_destroy (doc);
    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);

    /* Cleanup after mongo C driver */
    mongoc_cleanup();

    return 0;
}
Beispiel #27
0
void PruebaMongoDB()
{
	mongoc_collection_t *collection;
	   mongoc_client_t *client;
	   mongoc_cursor_t *cursor;
	   const bson_t *item;
	   bson_error_t error;
	   bson_oid_t oid;
	   bson_t *query;
	   bson_t *doc;
	   char *str;
	   bool r;

	   mongoc_init();

	   /* get a handle to our collection */
	   client = mongoc_client_new ("mongodb://localhost:27017");
	   collection = mongoc_client_get_collection (client, "local", "tito");

	   /* insert a document */
	    bson_oid_init (&oid, NULL);
	    doc = BCON_NEW ("_id", BCON_OID (&oid),
	                    "hello", BCON_UTF8 ("world!"));
	    r = mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error);
	    if (!r) {
	       fprintf (stderr, "%s\n", error.message);
	    }

	    /* build a query to execute */
	    query = BCON_NEW ("_id", BCON_OID (&oid));

	    /* execute the query and iterate the results */
	    cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
	    while (mongoc_cursor_next (cursor, &item)) {
	       str = bson_as_json (item, NULL);
	       printf ("%s\n", str);
	       bson_free (str);
	    }

	    /* release everything */
	    mongoc_cursor_destroy (cursor);
	    mongoc_collection_destroy (collection);
	    mongoc_client_destroy (client);
	    bson_destroy (query);
	    bson_destroy (doc);
}
Beispiel #28
0
/**
 * _mongoc_ssl_ctx_new:
 *
 * Create a new ssl context declaratively
 *
 * The opt.pem_pwd parameter, if passed, must exist for the life of this
 * context object (for storing and loading the associated pem file)
 */
SSL_CTX *
_mongoc_ssl_ctx_new (mongoc_ssl_opt_t *opt)
{
   SSL_CTX *ctx = NULL;

   /*
    * Ensure we are initialized. This is safe to call multiple times.
    */
   mongoc_init ();

   ctx = SSL_CTX_new (SSLv23_method ());

   BSON_ASSERT (ctx);

   /* SSL_OP_ALL - Activate all bug workaround options, to support buggy client SSL's.
    * SSL_OP_NO_SSLv2 - Disable SSL v2 support */
   SSL_CTX_set_options (ctx, (SSL_OP_ALL | SSL_OP_NO_SSLv2));

   /* HIGH - Enable strong ciphers
    * !EXPORT - Disable export ciphers (40/56 bit)
    * !aNULL - Disable anonymous auth ciphers
    * @STRENGTH - Sort ciphers based on strength */
   SSL_CTX_set_cipher_list (ctx, "HIGH:!EXPORT:!aNULL@STRENGTH");

   /* If renegotiation is needed, don't return from recv() or send() until it's successful.
    * Note: this is for blocking sockets only. */
   SSL_CTX_set_mode (ctx, SSL_MODE_AUTO_RETRY);

   /* TODO: does this cargo cult actually matter?
    * Disable session caching (see SERVER-10261) */
   SSL_CTX_set_session_cache_mode (ctx, SSL_SESS_CACHE_OFF);

   /* Load in verification certs, private keys and revocation lists */
   if ((!opt->pem_file ||
        _mongoc_ssl_setup_pem_file (ctx, opt->pem_file, opt->pem_pwd))
       && (!(opt->ca_file ||
             opt->ca_dir) ||
           _mongoc_ssl_setup_ca (ctx, opt->ca_file, opt->ca_dir))
       && (!opt->crl_file || _mongoc_ssl_setup_crl (ctx, opt->crl_file))
       ) {
      return ctx;
   } else {
      SSL_CTX_free (ctx);
      return NULL;
   }
}
Beispiel #29
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;
}
// Define main function as an entry to these tests.
// These test functions cannot use the main() defined for unittests because they
// call runGlobalInitializers(). The embedded C API calls mongoDbMain() which
// calls runGlobalInitializers().
int main(int argc, char** argv, char** envp) {

    moe::OptionsParser parser;
    moe::Environment environment;
    moe::OptionSection options;
    std::map<std::string, std::string> env;

    options.addOptionChaining(
        "tempPath", "tempPath", moe::String, "directory to place mongo::TempDir subdirectories");
    std::vector<std::string> argVector(argv, argv + argc);
    mongo::Status ret = parser.run(options, argVector, env, &environment);
    if (!ret.isOK()) {
        std::cerr << options.helpString();
        return EXIT_FAILURE;
    }
    if (environment.count("tempPath")) {
        ::mongo::unittest::TempDir::setTempPath(environment["tempPath"].as<std::string>());
    }

    ::mongo::clearSignalMask();
    ::mongo::setupSynchronousSignalHandlers();
    ::mongo::serverGlobalParams.noUnixSocket = true;
    ::mongo::unittest::setupTestLogger();

    StatusPtr status(mongo_embedded_v1_status_create());
    mongoc_init();

    global_lib_handle = mongo_embedded_v1_lib_init(nullptr, status.get());
    if (global_lib_handle == nullptr) {
        std::cerr << "Error: " << mongo_embedded_v1_status_get_explanation(status.get());
        return EXIT_FAILURE;
    }

    auto result = ::mongo::unittest::Suite::run(std::vector<std::string>(), "", 1);

    if (mongo_embedded_v1_lib_fini(global_lib_handle, status.get()) != MONGO_EMBEDDED_V1_SUCCESS) {
        std::cerr << "Error: " << mongo_embedded_v1_status_get_explanation(status.get());
        return EXIT_FAILURE;
    }

    mongoc_cleanup();
    globalTempDir.reset();
    mongo::quickExit(result);
}