/* **************************************************************************** * * prepareDatabase - */ static void prepareDatabase(std::string id, std::string type) { /* Set database */ setupDatabase(); DBClientConnection* connection = getMongoConnection(); /* We create one entity: * * - 'id', 'type' with four attributes * A1: X * A1: Y * A2: Z * A3: W */ BSONObj en1 = BSON("_id" << BSON("id" << id << "type" << type) << "attrs" << BSON_ARRAY( BSON("name" << "A1" << "type" << "TA1" << "value" << "X") << BSON("name" << "A1" << "type" << "TA1bis" << "value" << "Y") << BSON("name" << "A2" << "type" << "TA2" << "value" << "Z") << BSON("name" << "A3" << "type" << "TA3" << "value" << "W") ) ); connection->insert(ENTITIES_COLL, en1); }
void run() { DBClientConnection c; c.connect("localhost"); //"192.168.58.1"); cout << "connected ok" << endl; BSONObj p = BSON( "name" << "Joe" << "age" << 33 ); c.insert("tutorial.persons", p); p = BSON( "name" << "Jane" << "age" << 40 ); c.insert("tutorial.persons", p); p = BSON( "name" << "Abe" << "age" << 33 ); c.insert("tutorial.persons", p); p = BSON( "name" << "Methuselah" << "age" << BSONNULL); c.insert("tutorial.persons", p); p = BSON( "name" << "Samantha" << "age" << 21 << "city" << "Los Angeles" << "state" << "CA" ); c.insert("tutorial.persons", p); c.ensureIndex("tutorial.persons", fromjson("{age:1}")); cout << "count:" << c.count("tutorial.persons") << endl; auto_ptr<DBClientCursor> cursor = c.query("tutorial.persons", BSONObj()); while( cursor->more() ) { cout << cursor->next().toString() << endl; } cout << "\nprintifage:\n"; printIfAge(c, 33); }
void SyncClusterConnection::_connect(const std::string& hostStr) { log() << "SyncClusterConnection connecting to [" << hostStr << "]" << endl; const HostAndPort host(hostStr); DBClientConnection* c; if (connectionHook) { c = new DBClientConnection( true, // auto reconnect 0, // socket timeout [this, host](const executor::RemoteCommandResponse& isMasterReply) { return connectionHook(host, isMasterReply); }); } else { c = new DBClientConnection(true); } c->setRequestMetadataWriter(getRequestMetadataWriter()); c->setReplyMetadataReader(getReplyMetadataReader()); c->setSoTimeout(_socketTimeout); Status status = c->connect(host); if (!status.isOK()) { log() << "SyncClusterConnection connect fail to: " << hostStr << causedBy(status); if (status == ErrorCodes::IncompatibleCatalogManager) { // Make sure to propagate IncompatibleCatalogManager errors to trigger catalog manager // swapping. uassertStatusOK(status); } } _connAddresses.push_back(hostStr); _conns.push_back(c); }
bool isSelf(const HostAndPort& hostAndPort, ServiceContext* const ctx) { // Fastpath: check if the host&port in question is bound to one // of the interfaces on this machine. // No need for ip match if the ports do not match if (hostAndPort.port() == serverGlobalParams.port) { std::vector<std::string> myAddrs = serverGlobalParams.bind_ips; // If any of the bound addresses is the default route (0.0.0.0 on IPv4) it means we are // listening on all network interfaces and need to check against any of them. if (myAddrs.empty() || std::any_of(myAddrs.cbegin(), myAddrs.cend(), [](std::string const& addrStr) { return HostAndPort(addrStr, serverGlobalParams.port).isDefaultRoute(); })) { myAddrs = getBoundAddrs(IPv6Enabled()); } const std::vector<std::string> hostAddrs = getAddrsForHost(hostAndPort.host(), hostAndPort.port(), IPv6Enabled()); for (std::vector<std::string>::const_iterator i = myAddrs.begin(); i != myAddrs.end(); ++i) { for (std::vector<std::string>::const_iterator j = hostAddrs.begin(); j != hostAddrs.end(); ++j) { if (*i == *j) { return true; } } } } ctx->waitForStartupComplete(); try { DBClientConnection conn; conn.setSoTimeout(30); // 30 second timeout // We need to avoid the isMaster call triggered by a normal connect, which would // cause a deadlock. 'isSelf' is called by the Replication Coordinator when validating // a replica set configuration document, but the 'isMaster' command requires a lock on the // replication coordinator to execute. As such we call we call 'connectSocketOnly', which // does not call 'isMaster'. if (!conn.connectSocketOnly(hostAndPort).isOK()) { return false; } if (auth::isInternalAuthSet() && !conn.authenticateInternalUser().isOK()) { return false; } BSONObj out; bool ok = conn.simpleCommand("admin", &out, "_isSelf"); bool me = ok && out["id"].type() == jstOID && instanceId == out["id"].OID(); return me; } catch (const std::exception& e) { warning() << "couldn't check isSelf (" << hostAndPort << ") " << e.what() << std::endl; } return false; }
void writeJobAd(ClassAd* ad) { clock_t start, end; double elapsed; ExprTree *expr; const char *name; ad->ResetExpr(); BSONObjBuilder b; start = clock(); while (ad->NextExpr(name,expr)) { b.append(name,ExprTreeToString(expr)); } try { c.insert(db_name, b.obj()); } catch(DBException& e) { cout << "caught DBException " << e.toString() << endl; } end = clock(); elapsed = ((float) (end - start)) / CLOCKS_PER_SEC; std:string last_err = c.getLastError(); if (!last_err.empty()) { printf("getLastError: %s\n",last_err.c_str()); } printf("Time elapsed: %1.9f sec\n",elapsed); }
int main() { try { cout << "connecting to localhost..." << endl; DBClientConnection c; c.connect("localhost"); cout << "connected ok" << endl; bo o = BSON( "hello" << "world" ); cout << "inserting..." << endl; time_t start = time(0); for( unsigned i = 0; i < 1000000; i++ ) { c.insert("test.foo", o); } // wait until all operations applied cout << "getlasterror returns: \"" << c.getLastError() << '"' << endl; time_t done = time(0); time_t dt = done-start; cout << dt << " seconds " << 1000000/dt << " per second" << endl; } catch(DBException& e) { cout << "caught DBException " << e.toString() << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
void run(long time,short spo2,short pr,const char *deviceid) { DBClientConnection c; c.connect(host); BSONObj p = BSONObjBuilder().append(TIMESTAMP,(int)time).append(SPo2,spo2).append(PULSERATE,pr).append(DEVICEID,deviceid).obj(); c.insert(tablename, p); }
Handle<Value> mongoInit(const Arguments& args){ char host[255]; if ( args.Length() > 0 && args[0]->IsString() ){ assert( args[0]->ToString()->Utf8Length() < 250 ); args[0]->ToString()->WriteAscii( host ); } else { strcpy( host , "127.0.0.1" ); } DBClientConnection * conn = new DBClientConnection( true ); string errmsg; if ( ! conn->connect( host , errmsg ) ){ return v8::ThrowException( v8::String::New( "couldn't connect" ) ); } // NOTE I don't believe the conn object will ever be freed. args.This()->Set( CONN_STRING , External::New( conn ) ); args.This()->Set( String::New( "slaveOk" ) , Boolean::New( false ) ); return v8::Undefined(); }
DBClientBase* DBConnectionPool::get(const string& host) { boostlock L(poolMutex); PoolForHost *&p = pools[host]; if ( p == 0 ) p = new PoolForHost(); if ( p->pool.empty() ) { string errmsg; DBClientBase *c; if( host.find(',') == string::npos ) { DBClientConnection *cc = new DBClientConnection(true); if ( !cc->connect(host.c_str(), errmsg) ) { delete cc; uassert( (string)"dbconnectionpool: connect failed" + host , false); return 0; } c = cc; } else { DBClientPaired *p = new DBClientPaired(); if( !p->connect(host) ) { delete p; uassert( (string)"dbconnectionpool: connect failed [2] " + host , false); return 0; } c = p; } return c; } DBClientBase *c = p->pool.front(); p->pool.pop(); return c; }
inline void kill_wrapper(pid_t pid, int sig, int port){ #ifdef _WIN32 if (sig == SIGKILL || port == 0){ assert( handles.count(pid) ); TerminateProcess(handles[pid], 1); // returns failure for "zombie" processes. }else{ DBClientConnection conn; conn.connect("127.0.0.1:" + BSONObjBuilder::numStr(port)); try { conn.simpleCommand("admin", NULL, "shutdown"); } catch (...) { //Do nothing. This command never returns data to the client and the driver doesn't like that. } } #else int x = kill( pid, sig ); if ( x ){ if ( errno == ESRCH ){ } else { cout << "killFailed: " << errnoWithDescription() << endl; assert( x == 0 ); } } #endif }
void em_mongodb::queryincrement(std::string dbcoll,BSONElement last) { // int ret = MDB_FAIL_QUERY; DBClientConnection* pconn = getConn(); if(!pconn) return ; mongo::Query cond = mongo::Query().sort("$natural"); // BSONElement last;// = minKey.firstElement(); while(1) { std::auto_ptr<mongo::DBClientCursor> cursor = pconn->query(dbcoll,cond,0,0,0,QueryOption_CursorTailable|QueryOption_AwaitData); while(1) { if(!cursor->more()) { if(cursor->isDead()) { break; } continue; } BSONObj obj = cursor->next(); last = obj["_id"]; //do something here... incrementfunc(obj); } // cond = mongo::Query("_id"<<BSON("$gt"<<last)).sort("$natural"); } boost::mutex::scoped_lock(m_iomux); m_connpool[pconn] = false; sem_post(&m_jobsem); }
int main(void) { cout << "Welcome." << endl; DBClientConnection conn; string option; string code; string cmd; conn.connect("localhost"); while(1){ cout << "> "; getline(cin, cmd); if(cmd.substr(0,4) == "quit"){ return 0; }else if(cmd.substr(0,5) == "check"){ dealCheck(cmd,conn); }else if(cmd.substr(0,3) == "set"){ dealSet(cmd, code, option); //cout << code << option; if(option == "-n" || option == "-N") conn.update("HXTBBH.coupon", BSON("code" << code), BSON("$set" << BSON("status" << "unused"))); else if(option == "-y" || option == "-Y") conn.update("HXTBBH.coupon", BSON("code" << code), BSON("$set" << BSON("status" << "used"))); }else{ cout << "synax error!" << endl; } } return 0; }
void FXtoBSON::aggregateToDB(const char & t, DBClientConnection &c){ switch(t){ case 'h': c.update(dbH, find(time0, 'h'), BSON("$set" << BSON("quote" << aggregate('h'))),true); Hour.setZero(60, 5); break; case 'd': c.update(dbD, find(time0, 'd'), BSON("$set" << BSON("quote" << aggregate('d'))), true); Day.setZero(24, 5); break; case 'm': c.update(dbM, find(time0, 'm'), BSON("$set" << BSON("quote" << aggregate('m'))), true); Month.setZero(); break; case 'y': c.update(dbY, find(time0, 'y'), BSON("$set" << BSON("quote" << aggregate('y'))), true); Year.setZero(); break; } }
v8::Handle<v8::Value> mongoInsert(const v8::Arguments& args){ jsassert( args.Length() == 2 , "insert needs 2 args" ); jsassert( args[1]->IsObject() , "have to insert an object" ); DBClientConnection * conn = getConnection( args ); GETNS; v8::Handle<v8::Object> in = args[1]->ToObject(); if ( ! in->Has( String::New( "_id" ) ) ){ v8::Handle<v8::Value> argv[1]; in->Set( String::New( "_id" ) , getObjectIdCons()->NewInstance( 0 , argv ) ); } BSONObj o = v8ToMongo( in ); DDD( "want to save : " << o.jsonString() ); try { conn->insert( ns , o ); } catch ( ... ){ return v8::ThrowException( v8::String::New( "socket error on insert" ) ); } return args[1]; }
int main(int argc,char* argv[]){ //check for file name if (argc<2){ cout<<"NO FILENAME PROVIDED"; return 0; } //create object for input text file ifstream input(argv[1]); //connect to the mongo db localhost DBClientConnection c; c.connect("localhost"); XLog logParse("Parsing..."); logParse.start(); parseFile(input,c); logParse.end(); XLog logScrub("Scrubbing..."); logScrub.start(); scrub(c); logScrub.end(); XLog logOutput("Output to file..."); logOutput.start(); outputToFile(c); logOutput.end(); return 0; }
// finds the names of the document with the most fields in a collection std::set<string> getCollFields(DBClientConnection& c, string db, string collection){ int longest; // mongo fieldnames = sql column names set<string> fieldnames; // get the list of ODBC supported fields (columns) from collection.meta collection // collection.meta should only contain one document std::auto_ptr<mongo::DBClientCursor> cursor = c.query(db+"."+collection+".meta"); BSONObj d = cursor->next(); if (d.nFields() != 0){ longest = d.nFields(); d.getFieldNames(fieldnames); } // if no meta collection find collection with most fields if (longest == 0) { cursor = c.query(db+"."+collection); while( cursor->more() ) { // get next doc/row/tuple BSONObj doc = cursor->next(); if(longest < doc.nFields()){ longest = doc.nFields(); doc.getFieldNames(fieldnames); } } } return fieldnames; }
bool isSelf(const HostAndPort& hostAndPort) { // Fastpath: check if the host&port in question is bound to one // of the interfaces on this machine. // No need for ip match if the ports do not match if (hostAndPort.port() == serverGlobalParams.port) { std::vector<std::string> myAddrs = serverGlobalParams.bind_ip.empty() ? getBoundAddrs(IPv6Enabled()) : std::vector<std::string>(); if (!serverGlobalParams.bind_ip.empty()) { boost::split(myAddrs, serverGlobalParams.bind_ip, boost::is_any_of(", ")); } const std::vector<std::string> hostAddrs = getAddrsForHost(hostAndPort.host(), hostAndPort.port(), IPv6Enabled()); for (std::vector<std::string>::const_iterator i = myAddrs.begin(); i != myAddrs.end(); ++i) { for (std::vector<std::string>::const_iterator j = hostAddrs.begin(); j != hostAddrs.end(); ++j) { if (*i == *j) { return true; } } } } if (!Listener::getTimeTracker()) { // this ensures we are actually running a server // this may return true later, so may want to retry return false; } try { DBClientConnection conn; std::string errmsg; if (!conn.connect(hostAndPort, errmsg)) { return false; } if (getGlobalAuthorizationManager()->isAuthEnabled() && isInternalAuthSet()) { if (!authenticateInternalUser(&conn)) { return false; } } BSONObj out; bool ok = conn.simpleCommand("admin" , &out, "_isSelf"); bool me = ok && out["id"].type() == jstOID && instanceId == out["id"].OID(); return me; } catch (const std::exception& e) { warning() << "could't check isSelf (" << hostAndPort << ") " << e.what() << std::endl; } return false; }
void SyncClusterConnection::_connect( string host ){ log() << "SyncClusterConnection connecting to [" << host << "]" << endl; DBClientConnection * c = new DBClientConnection( true ); string errmsg; if ( ! c->connect( host , errmsg ) ) log() << "SyncClusterConnection connect fail to: " << host << " errmsg: " << errmsg << endl; _conns.push_back( c ); }
int toolMain( int argc, char* argv[], char* envp[] ) { mongo::runGlobalInitializersOrDie(argc, argv, envp); if( parseCmdLineOptions( argc, argv) ) return 1; BSONObj nestedDoc = BSON("Firstname" << "David" << "Lastname" << "Smith" << "Address" << BSON( "Street" << "5th Av" << "City" << "New York" ) ); std::vector<std::string> list; list.push_back("mongo new york city"); list.push_back("mongo rome"); list.push_back("mongo dublin"); list.push_back("mongo seoul"); list.push_back("mongo barcelona"); list.push_back("mongo madrid"); list.push_back("mongo chicago"); list.push_back("mongo amsterdam"); list.push_back("mongo delhi"); list.push_back("mongo beijing"); BSONObj args = BSONObjBuilder() .append( "_id", 0 ) .append( "blob", "MongoDB is an open source document-oriented database " "system designed with scalability and developer." ) .append( "nestedDoc", nestedDoc ) .append( "list", list ) .append( "counter", 0 ).obj(); const int numDocsPerDB = static_cast<int>( globalDocGenOption.dbSize * 1024 * 1024 / args.objsize() ); cout << "numDocsPerDB:" << numDocsPerDB << endl; try { DBClientConnection conn; conn.connect( globalDocGenOption.hostname ); cout << "successfully connected to the host" << endl; for( int i=0; i < globalDocGenOption.numdbs; ++i ) { scoped_ptr<DocumentGenerator> docGen( DocumentGenerator::makeDocumentGenerator(args) ); cout << "populating database " << globalDocGenOption.prefix << i << endl; long long j = 0; string ns = mongoutils::str::stream() << globalDocGenOption.prefix << i << ".sampledata"; while( j != numDocsPerDB ) { BSONObj doc = docGen->createDocument(); conn.insert( ns, doc ); ++j; } BSONObj blobIndex = BSON("blob" << 1); conn.ensureIndex(ns, blobIndex); BSONObj listIndex = BSON("list" << 1); conn.ensureIndex(ns, listIndex); } } catch( DBException &e ) { cout << "caught " << e.what() << endl; } return 0; }
/* **************************************************************************** * * MongoDbRemoveFail - * */ TEST(mongoUnsubscribeContextAvailability, MongoDbRemoveFail) { HttpStatusCode ms; UnsubscribeContextAvailabilityRequest req; UnsubscribeContextAvailabilityResponse res; /* Prepare mocks */ const DBException e = DBException("boom!!", 33); BSONObj fakeSub = BSON("_id" << OID("51307b66f481db11bf860001") << "expiration" << 10000000 << "reference" << "http://notify1.me" << "entities" << BSON_ARRAY(BSON("id" << "E1" << "type" << "T1" << "isPattern" << "false")) << "attrs" << BSONArray()); DBClientConnectionMock* connectionMock = new DBClientConnectionMock(); ON_CALL(*connectionMock, findOne("unittest.casubs",_,_,_)) .WillByDefault(Return(fakeSub)); ON_CALL(*connectionMock, remove("unittest.casubs",_,_)) .WillByDefault(Throw(e)); NotifierMock* notifierMock = new NotifierMock(); EXPECT_CALL(*notifierMock, sendNotifyContextAvailabilityRequest(_,_,_,_)) .Times(0); setNotifier(notifierMock); /* Forge the request (from "inside" to "outside") */ req.subscriptionId.set("51307b66f481db11bf860001"); /* Prepare database */ prepareDatabase(); mongoConnect(connectionMock); /* Invoke the function in mongoBackend library */ ms = mongoUnsubscribeContextAvailability(&req, &res); /* Check response is as expected */ EXPECT_EQ(SccOk, ms); EXPECT_EQ("51307b66f481db11bf860001", res.subscriptionId.get()); EXPECT_EQ(SccReceiverInternalError, res.statusCode.code); EXPECT_EQ("Internal Server Error", res.statusCode.reasonPhrase); EXPECT_EQ("collection: unittest.casubs " "- remove() _id: 51307b66f481db11bf860001 " "- exception: boom!!", res.statusCode.details); /* Check database (untouched) */ mongoDisconnect(); // Sleeping a little to "give mongod time to process its input". // Without this sleep, this tests fails around 50% of the times (in Ubuntu 13.04) usleep(1000); mongoConnect("localhost"); DBClientConnection* connection = getMongoConnection(); ASSERT_EQ(2, connection->count(SUBSCRIBECONTEXTAVAIL_COLL, BSONObj())); /* Release mocks */ delete notifierMock; }
/* **************************************************************************** * * MongoDbFindOneFail - * */ TEST(mongoUnsubscribeContext, MongoDbFindOneFail) { HttpStatusCode ms; UnsubscribeContextRequest req; UnsubscribeContextResponse res; /* Prepare mocks */ const DBException e = DBException("boom!!", 33); DBClientConnectionMock* connectionMock = new DBClientConnectionMock(); ON_CALL(*connectionMock, findOne("unittest.csubs",_,_,_)) .WillByDefault(Throw(e)); NotifierMock* notifierMock = new NotifierMock(); EXPECT_CALL(*notifierMock, destroyOntimeIntervalThreads(_)) .Times(0); EXPECT_CALL(*notifierMock, sendNotifyContextRequest(_,_,_)) .Times(0); EXPECT_CALL(*notifierMock, createIntervalThread(_,_)) .Times(0); setNotifier(notifierMock); /* Forge the request (from "inside" to "outside") */ req.subscriptionId.set("51307b66f481db11bf860001"); /* Prepare database */ prepareDatabase(); mongoConnect(connectionMock); /* Invoke the function in mongoBackend library */ ms = mongoUnsubscribeContext(&req, &res); /* Check response is as expected */ EXPECT_EQ(SccOk, ms); EXPECT_EQ("51307b66f481db11bf860001", res.subscriptionId.get()); EXPECT_EQ(SccReceiverInternalError, res.statusCode.code); EXPECT_EQ("Internal Server Error", res.statusCode.reasonPhrase); EXPECT_EQ("collection: unittest.csubs " "- findOne() _id: 51307b66f481db11bf860001 " "- exception: boom!!", res.statusCode.details); /* Check database (untouched) */ mongoDisconnect(); // Sleeping a little to "give mongod time to process its input". // Without this sleep, this tests fails around 10% of the times (in Ubuntu 13.04) usleep(1000); mongoConnect("localhost"); DBClientConnection* connection = getMongoConnection(); int count = connection->count(SUBSCRIBECONTEXT_COLL, BSONObj()); ASSERT_EQ(2, count); /* Release mocks */ delete notifierMock; }
void SyncClusterConnection::_connect( const std::string& host ) { log() << "SyncClusterConnection connecting to [" << host << "]" << endl; DBClientConnection * c = new DBClientConnection( true ); c->setSoTimeout( _socketTimeout ); string errmsg; if ( ! c->connect( host , errmsg ) ) log() << "SyncClusterConnection connect fail to: " << host << " errmsg: " << errmsg << endl; _connAddresses.push_back( host ); _conns.push_back( c ); }
/** Shard collection on key */ void mongoDeploy::shardCollection (string mongoSHostPort, string fullCollection, mongo::BSONObj shardKey) { using namespace mongo; BSONObj info; DBClientConnection c; c.connect (mongoSHostPort); BSONObj cmd = BSON ("shardcollection" << fullCollection << "key" << shardKey); cout << cmd << " -> " << endl; c.runCommand ("admin", cmd, info); cout << info << endl; }
/** Enable sharding on given database */ void mongoDeploy::shardDatabase (string mongoSHostPort, string database) { using namespace mongo; BSONObj info; DBClientConnection c; c.connect (mongoSHostPort); BSONObj cmd = BSON ("enablesharding" << database); cout << cmd << " -> " << endl; c.runCommand ("admin", cmd, info); cout << info << endl; }
BSONObj DBClientReplicaSet::findOne(const string &ns, const Query& query, const BSONObj *fieldsToReturn, int queryOptions) { shared_ptr<ReadPreferenceSetting> readPref( _extractReadPref( query.obj, queryOptions ) ); if ( _isSecondaryQuery( ns, query.obj, *readPref ) ) { LOG( 3 ) << "dbclient_rs findOne using secondary or tagged node selection in " << _getMonitor()->getName() << ", read pref is " << readPref->toBSON() << " (primary : " << ( _master.get() != NULL ? _master->getServerAddress() : "[not cached]" ) << ", lastTagged : " << ( _lastSlaveOkConn.get() != NULL ? _lastSlaveOkConn->getServerAddress() : "[not cached]" ) << ")" << endl; string lastNodeErrMsg; for (size_t retry = 0; retry < MAX_RETRY; retry++) { try { DBClientConnection* conn = selectNodeUsingTags(readPref); if (conn == NULL) { break; } return conn->findOne(ns,query,fieldsToReturn,queryOptions); } catch ( const DBException &dbExcep ) { StringBuilder errMsgBuilder; errMsgBuilder << "can't findone replica set node " << _lastSlaveOkHost.toString() << ": " << causedBy( dbExcep ); lastNodeErrMsg = errMsgBuilder.str(); LOG(1) << lastNodeErrMsg << endl; invalidateLastSlaveOkCache(); } } StringBuilder assertMsg; assertMsg << "Failed to call findOne, no good nodes in " << _getMonitor()->getName(); if ( !lastNodeErrMsg.empty() ) { assertMsg << ", last error: " << lastNodeErrMsg; } uasserted(16379, assertMsg.str()); } LOG( 3 ) << "dbclient_rs findOne to primary node in " << _getMonitor()->getName() << endl; return checkMaster()->findOne(ns,query,fieldsToReturn,queryOptions); }
void dumpCollection(Parameters& params) { DBClientConnection c; string hostPort(params.getHost()); if (hostPort.find(':') == string::npos) { hostPort += ":"; hostPort += to_string(params.getPort()); } c.connect(hostPort); time_t t; time(&t); int documentCount = c.count(params.getDbCollection()); if (params.isDebug()) { cout << "{ " << params.getDbCollection() << ".count: " << documentCount << " }\n"; } string docPrefixString(params.getDbCollection()); // docIndex += "{"; // docIndex += to_string(i++); // docIndex += "}"; unique_ptr<DBClientCursor> cursor = c.query(params.getDbCollection(), BSONObj()); unique_ptr<IBSONRenderer> renderer; switch (params.getStyle()) { case STYLE_DOTTED: renderer = unique_ptr<IBSONRenderer>(new BSONDotNotationDump(params, docPrefixString)); break; case STYLE_TREE: renderer = unique_ptr<IBSONRenderer>(new BSONObjectTypeDump(params, docPrefixString)); break; case STYLE_JSON: case STYLE_JSONPACKED: renderer = unique_ptr<IBSONRenderer>(new JSONDump(params, " ")); break; default: throw std::logic_error("ISE: Undefined STYLE!"); break; } if (renderer) { renderer->setOutputStream(cout); renderer->begin(NULL); int documentIndex = 0; while (cursor->more()) { const BSONObj& o = cursor->next(); // Get the BSON Object renderer->render(o, documentIndex++, documentCount); } renderer->end(NULL); } else { throw std::logic_error("ISE: Undefined renderer!"); } }
bool DBClientReplicaSet::auth(const string &dbname, const string &username, const string &pwd, string& errmsg, bool digestPassword ) { DBClientConnection * m = checkMaster(); // first make sure it actually works if( ! m->auth(dbname, username, pwd, errmsg, digestPassword ) ) return false; // now that it does, we should save so that for a new node we can auth _auths.push_back( AuthInfo( dbname , username , pwd , digestPassword ) ); return true; }
void FXtoBSON::addMinToDB(const BSONObj & document, DBClientConnection & c){ BSONObj FINDhour = find(time1, 'h'); auto_ptr<DBClientCursor> cursor = c.query(dbH, FINDhour); if(cursor->more()){ c.update(dbH , FINDhour, BSON("$set" << document)); } else { c.update(dbH, FINDhour, BSON("$set" << emptyDoc('h')), true); c.update(dbH, FINDhour, BSON("$set" << document)); } }
void SyncClusterConnection::_connect(const std::string& host) { log() << "SyncClusterConnection connecting to [" << host << "]" << endl; DBClientConnection* c = new DBClientConnection(true); c->setRequestMetadataWriter(getRequestMetadataWriter()); c->setReplyMetadataReader(getReplyMetadataReader()); c->setSoTimeout(_socketTimeout); string errmsg; if (!c->connect(HostAndPort(host), errmsg)) log() << "SyncClusterConnection connect fail to: " << host << " errmsg: " << errmsg << endl; _connAddresses.push_back(host); _conns.push_back(c); }
void operator()() const { DBClientConnection dest; string errmsg; while (!dest.connect(mongoBridgeGlobalParams.destUri, errmsg)) sleepmillis( 500 ); Message m; while( 1 ) { try { m.reset(); if ( !mp_.recv( m ) ) { cout << "end connection " << mp_.psock->remoteString() << endl; mp_.shutdown(); break; } sleepmillis(mongoBridgeGlobalParams.delay); int oldId = m.header()->id; if ( m.operation() == dbQuery || m.operation() == dbMsg || m.operation() == dbGetMore ) { bool exhaust = false; if ( m.operation() == dbQuery ) { DbMessage d( m ); QueryMessage q( d ); exhaust = q.queryOptions & QueryOption_Exhaust; } Message response; dest.port().call( m, response ); // nothing to reply with? if ( response.empty() ) cleanup(0); mp_.reply( m, response, oldId ); while ( exhaust ) { MsgData *header = response.header(); QueryResult *qr = (QueryResult *) header; if ( qr->cursorId ) { response.reset(); dest.port().recv( response ); mp_.reply( m, response ); // m argument is ignored anyway } else { exhaust = false; } } } else { dest.port().say( m, oldId ); } } catch ( ... ) { log() << "caught exception in Forwarder, continuing" << endl; } } }