SEXP rmongo_connect(SEXP mongo_conn) { mongo* conn = _checkMongo(mongo_conn); mongo_host_port hp; SEXP host = getAttrib(mongo_conn, sym_host); int len = LENGTH(host); int i; if (len == 0) error("No hosts defined\n"); const char* name = CHAR(STRING_ELT(getAttrib(mongo_conn, sym_name), 0)); if (name[0] == '\0') { for (i = 0; i < len; i++) { mongo_parse_host(CHAR(STRING_ELT(host, i)), &hp); if (mongo_connect(conn, hp.host, hp.port) == MONGO_OK) break; } if (i == len) { if (len == 1) Rprintf("Unable to connect to %s:%d, error code = %d\n", hp.host, hp.port, conn->err); else Rprintf("Unable to connect to any of the given hosts, error code = %d\n", conn->err); return mongo_conn; } } else { mongo_replset_init(conn, name); for (i = 0; i < len; i++) { mongo_parse_host(CHAR(STRING_ELT(host, i)), &hp); mongo_replset_add_seed(conn, hp.host, hp.port); } if (mongo_replset_connect(conn) != MONGO_OK) Rprintf("Unable to connect to replset\n"); } int timeout = asInteger(getAttrib(mongo_conn, sym_timeout)); if (timeout > 0) mongo_set_op_timeout(conn, timeout); SEXP username = getAttrib(mongo_conn, sym_username); if (CHAR(STRING_ELT(username, 0))[0] != '\0') { SEXP password = getAttrib(mongo_conn, install("password")); SEXP db = getAttrib(mongo_conn, install("db")); SEXP ret = mongo_authenticate(mongo_conn, username, password, db); if (!LOGICAL(ret)[0]) { mongo_disconnect(conn); Rprintf("Authentication failed.\n"); } } return mongo_conn; }
static void mongo_replset_check_seed( mongo_connection* conn ) { bson out; bson hosts; const char* data; bson_iterator it; bson_iterator it_sub; const char* host_string; mongo_host_port *host_port = NULL; out.data = NULL; out.owned = 1; hosts.data = NULL; hosts.owned = 1; if( mongo_simple_int_command(conn, "admin", "ismaster", 1, &out) == MONGO_OK ) { if( bson_find( &it, &out, "hosts" ) ) { data = bson_iterator_value( &it ); bson_iterator_init( &it_sub, data ); /* Iterate over host list, adding each host to the * connection's host list. */ while( bson_iterator_next( &it_sub ) ) { host_string = bson_iterator_string( &it_sub ); host_port = bson_malloc( sizeof( mongo_host_port ) ); mongo_parse_host( host_string, host_port ); if( host_port ) { mongo_replset_add_node( &conn->replset->hosts, host_port->host, host_port->port ); free( host_port ); host_port = NULL; } } } } bson_destroy( &out ); bson_destroy( &hosts ); mongo_close_socket( conn->sock ); conn->sock = 0; conn->connected = 0; }