Esempio n. 1
0
        void ConnectionRegistry::killOperationsOnAllConnections( bool withPrompt ) const {
            Prompter prompter( "do you want to kill the current op(s) on the server?" );
            boost::lock_guard<boost::mutex> lk( _mutex );
            for( map<string,set<string> >::const_iterator i = _connectionUris.begin();
                i != _connectionUris.end(); ++i ) {
                string errmsg;
                ConnectionString cs = ConnectionString::parse( i->first, errmsg );
                if ( !cs.isValid() ) {
                    continue;   
                }
                boost::scoped_ptr<DBClientWithCommands> conn( cs.connect( errmsg ) );
                if ( !conn ) {
                    continue;
                }
                
                const set<string>& uris = i->second;

                BSONObj currentOpRes;
                conn->runPseudoCommand("admin",
                                       "currentOp",
                                       "$cmd.sys.inprog", {}, currentOpRes);
                auto inprog = currentOpRes["inprog"].embeddedObject();
                BSONForEach( op, inprog ) {
                    if ( uris.count( op[ "client" ].String() ) ) {
                        if ( !withPrompt || prompter.confirm() ) {
                            BSONObjBuilder cmdBob;
                            BSONObj info;
                            cmdBob.append("op", op["opid"]);
                            auto cmdArgs = cmdBob.done();
                            conn->runPseudoCommand("admin", "killOp", "$cmd.sys.killop",
                                                   cmdArgs, info);
                        }
                        else {
                            return;
                        }
                    }
                }
            }
        }
Esempio n. 2
0
    DBClientBase* DBConnectionPool::get(const string& host, double socketTimeout) {
        DBClientBase * c = _get( host , socketTimeout );
        if ( c ) {
            try {
                onHandedOut( c );
            }
            catch ( std::exception& ) {
                delete c;
                throw;
            }
            return c;
        }

        string errmsg;
        ConnectionString cs = ConnectionString::parse( host , errmsg );
        uassert( 13071 , (string)"invalid hostname [" + host + "]" + errmsg , cs.isValid() );

        c = cs.connect( errmsg, socketTimeout );
        if ( ! c )
            throw SocketException( SocketException::CONNECT_ERROR , host , 11002 , str::stream() << _name << " error: " << errmsg );
        return _finishCreate( host , socketTimeout , c );
    }
switch_status_t mongo_connection_create(DBClientBase **connection, const char *conn_str)
{
  DBClientBase *conn = NULL;
  string conn_string(conn_str), err_msg;
  ConnectionString cs = ConnectionString::parse(conn_string, err_msg);
 
  if (!cs.isValid()) {
    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't parse url: %s\n", err_msg.c_str());
    return SWITCH_STATUS_GENERR;
  }

  try {
    conn = cs.connect(err_msg);
  } catch (DBException &e) {
    switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Can't connect to mongo [%s]: %s\n", conn_str, err_msg.c_str());
    return SWITCH_STATUS_GENERR;
  }

  *connection = conn;
  switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_INFO, "Connected to mongo [%s]\n", conn_str);

  return SWITCH_STATUS_SUCCESS;
}
Esempio n. 4
0
        virtual bool run(OperationContext* txn,
                         const string&,
                         BSONObj& cmdObj,
                         int,
                         string& errmsg,
                         BSONObjBuilder& result,
                         bool fromRepl) {

            string fromhost = cmdObj.getStringField("fromhost");
            if ( fromhost.empty() ) {
                /* copy from self */
                stringstream ss;
                ss << "localhost:" << serverGlobalParams.port;
                fromhost = ss.str();
            }

            BSONObj ret;

            ConnectionString cs = ConnectionString::parse(fromhost, errmsg);
            if (!cs.isValid()) {
                return false;
            }

            authConn_.reset(cs.connect(errmsg));
            if (!authConn_.get()) {
                return false;
            }

            if( !authConn_->runCommand( "admin", BSON( "getnonce" << 1 ), ret ) ) {
                errmsg = "couldn't get nonce " + ret.toString();
                return false;
            }

            result.appendElements( ret );
            return true;
        }
Esempio n. 5
0
    int Tool::main( int argc , char ** argv, char ** envp ) {
        setupSignalHandlers(true);

        static StaticObserver staticObserver;

        mongo::runGlobalInitializersOrDie(argc, argv, envp);

        // hide password from ps output
        for (int i=0; i < (argc-1); ++i) {
            if (!strcmp(argv[i], "-p") || !strcmp(argv[i], "--password")) {
                char* arg = argv[i+1];
                while (*arg) {
                    *arg++ = 'x';
                }
            }
        }

        if (!toolGlobalParams.useDirectClient) {
            if (toolGlobalParams.noconnection) {
                // do nothing
            }
            else {
                string errmsg;

                ConnectionString cs = ConnectionString::parse(toolGlobalParams.connectionString,
                                                              errmsg);
                if ( ! cs.isValid() ) {
                    toolError() << "invalid hostname [" << toolGlobalParams.connectionString << "] "
                              << errmsg << std::endl;
                    ::_exit(-1);
                }

                _conn = cs.connect( errmsg );
                if ( ! _conn ) {
                    toolError() << "couldn't connect to [" << toolGlobalParams.connectionString
                              << "] " << errmsg << std::endl;
                    ::_exit(-1);
                }

                toolInfoOutput() << "connected to: " << toolGlobalParams.connectionString
                                 << std::endl;
            }

        }
        else {
            verify( lastError.get( true ) );

            Client::initThread("tools");
            _conn = new DBDirectClient();
            storageGlobalParams.dbpath = toolGlobalParams.dbpath;
            try {
                acquirePathLock();
            }
            catch ( DBException& ) {
                toolError() << std::endl << "If you are running a mongod on the same "
                             "path you should connect to that instead of direct data "
                              "file access" << std::endl << std::endl;
                dbexit( EXIT_FS );
                ::_exit(EXIT_FAILURE);
            }

            FileAllocator::get()->start();

            dur::startup();
        }

        int ret = -1;
        try {
            if (!toolGlobalParams.useDirectClient && !toolGlobalParams.noconnection)
                auth();
            ret = run();
        }
        catch ( DBException& e ) {
            toolError() << "assertion: " << e.toString() << std::endl;
            ret = -1;
        }
        catch(const boost::filesystem::filesystem_error &fse) {
            /*
              https://jira.mongodb.org/browse/SERVER-2904

              Simple tools that don't access the database, such as
              bsondump, aren't throwing DBExceptions, but are throwing
              boost exceptions.

              The currently available set of error codes don't seem to match
              boost documentation.  boost::filesystem::not_found_error
              (from http://www.boost.org/doc/libs/1_31_0/libs/filesystem/doc/exception.htm)
              doesn't seem to exist in our headers.  Also, fse.code() isn't
              boost::system::errc::no_such_file_or_directory when this
              happens, as you would expect.  And, determined from
              experimentation that the command-line argument gets turned into
              "\\?" instead of "/?" !!!
             */
#if defined(_WIN32)
            if (/*(fse.code() == boost::system::errc::no_such_file_or_directory) &&*/
                (fse.path1() == "\\?"))
                printHelp(cerr);
            else
#endif // _WIN32
                toolError() << "error: " << fse.what() << std::endl;

            ret = -1;
        }

        if ( currentClient.get() )
            currentClient.get()->shutdown();

        if (toolGlobalParams.useDirectClient)
            dbexit( EXIT_CLEAN );

        fflush(stdout);
        fflush(stderr);
        ::_exit(ret);
    }
Esempio n. 6
0
        virtual bool run(OperationContext* txn,
                         const string& dbname,
                         BSONObj& cmdObj,
                         int,
                         string& errmsg,
                         BSONObjBuilder& result,
                         bool fromRepl) {

            string fromhost = cmdObj.getStringField("fromhost");
            bool fromSelf = fromhost.empty();
            if ( fromSelf ) {
                /* copy from self */
                stringstream ss;
                ss << "localhost:" << serverGlobalParams.port;
                fromhost = ss.str();
            }

            CloneOptions cloneOptions;
            cloneOptions.fromDB = cmdObj.getStringField("fromdb");
            cloneOptions.logForRepl = !fromRepl;
            cloneOptions.slaveOk = cmdObj["slaveOk"].trueValue();
            cloneOptions.useReplAuth = false;
            cloneOptions.snapshot = true;
            cloneOptions.mayYield = true;
            cloneOptions.mayBeInterrupted = false;

            string todb = cmdObj.getStringField("todb");
            if ( fromhost.empty() || todb.empty() || cloneOptions.fromDB.empty() ) {
                errmsg = "params missing - {copydb: 1, fromhost: <connection string>, "
                         "fromdb: <db>, todb: <db>}";
                return false;
            }

            if ( !NamespaceString::validDBName( todb ) ) {
                errmsg = "invalid todb name: " + todb;
                return false;
            }

            Cloner cloner;

            // Get MONGODB-CR parameters
            string username = cmdObj.getStringField( "username" );
            string nonce = cmdObj.getStringField( "nonce" );
            string key = cmdObj.getStringField( "key" );

            if ( !username.empty() && !nonce.empty() && !key.empty() ) {
                uassert( 13008, "must call copydbgetnonce first", authConn_.get() );
                BSONObj ret;
                {
                    if ( !authConn_->runCommand( cloneOptions.fromDB,
                                                 BSON( "authenticate" << 1 << "user" << username
                                                       << "nonce" << nonce << "key" << key ), ret ) ) {
                        errmsg = "unable to login " + ret.toString();
                        return false;
                    }
                }
                cloner.setConnection( authConn_.release() );
            }
            else if (cmdObj.hasField(saslCommandConversationIdFieldName) &&
                     cmdObj.hasField(saslCommandPayloadFieldName)) {
                uassert( 25487, "must call copydbsaslstart first", authConn_.get() );
                BSONObj ret;
                if ( !authConn_->runCommand( cloneOptions.fromDB,
                                             BSON( "saslContinue" << 1 <<
                                                   cmdObj[saslCommandConversationIdFieldName] <<
                                                   cmdObj[saslCommandPayloadFieldName] ),
                                             ret ) ) {
                    errmsg = "unable to login " + ret.toString();
                    return false;
                }

                if (!ret["done"].Bool()) {
                    result.appendElements( ret );
                    return true;
                }

                result.append("done", true);
                cloner.setConnection( authConn_.release() );
            }
            else if (!fromSelf) {
                // If fromSelf leave the cloner's conn empty, it will use a DBDirectClient instead.

                ConnectionString cs = ConnectionString::parse(fromhost, errmsg);
                if (!cs.isValid()) {
                    return false;
                }

                DBClientBase* conn = cs.connect(errmsg);
                if (!conn) {
                    return false;
                }
                cloner.setConnection(conn);
            }

            if (fromSelf) {
                // SERVER-4328 todo lock just the two db's not everything for the fromself case
                Lock::GlobalWrite lk(txn->lockState());
                return cloner.go(txn, todb, fromhost, cloneOptions, NULL, errmsg);
            }

            Lock::DBLock lk (txn->lockState(), todb, MODE_X);
            return cloner.go(txn, todb, fromhost, cloneOptions, NULL, errmsg);
        }
Esempio n. 7
0
        virtual bool run(OperationContext* txn,
                         const string& dbname,
                         BSONObj& cmdObj,
                         int,
                         string& errmsg,
                         BSONObjBuilder& result,
                         bool fromRepl) {

            string fromhost = cmdObj.getStringField("fromhost");
            bool fromSelf = fromhost.empty();
            if ( fromSelf ) {
                /* copy from self */
                stringstream ss;
                ss << "localhost:" << serverGlobalParams.port;
                fromhost = ss.str();
            }

            CloneOptions cloneOptions;
            cloneOptions.fromDB = cmdObj.getStringField("fromdb");
            cloneOptions.logForRepl = !fromRepl;
            cloneOptions.slaveOk = cmdObj["slaveOk"].trueValue();
            cloneOptions.useReplAuth = false;
            cloneOptions.snapshot = true;
            cloneOptions.mayYield = true;
            cloneOptions.mayBeInterrupted = false;

            string todb = cmdObj.getStringField("todb");
            if ( fromhost.empty() || todb.empty() || cloneOptions.fromDB.empty() ) {
                errmsg = "parms missing - {copydb: 1, fromhost: <connection string>, "
                         "fromdb: <db>, todb: <db>}";
                return false;
            }

            Cloner cloner;
            string username = cmdObj.getStringField( "username" );
            string nonce = cmdObj.getStringField( "nonce" );
            string key = cmdObj.getStringField( "key" );
            if ( !username.empty() && !nonce.empty() && !key.empty() ) {
                uassert( 13008, "must call copydbgetnonce first", authConn_.get() );
                BSONObj ret;
                {
                    if ( !authConn_->runCommand( cloneOptions.fromDB,
                                                 BSON( "authenticate" << 1 << "user" << username
                                                       << "nonce" << nonce << "key" << key ), ret ) ) {
                        errmsg = "unable to login " + ret.toString();
                        return false;
                    }
                }
                cloner.setConnection( authConn_.release() );
            }
            else if (!fromSelf) {
                // If fromSelf leave the cloner's conn empty, it will use a DBDirectClient instead.

                ConnectionString cs = ConnectionString::parse(fromhost, errmsg);
                if (!cs.isValid()) {
                    return false;
                }

                DBClientBase* conn = cs.connect(errmsg);
                if (!conn) {
                    return false;
                }
                cloner.setConnection(conn);
            }


            // SERVER-4328 todo lock just the two db's not everything for the fromself case
            scoped_ptr<Lock::ScopedLock> lk( fromSelf ?
                                             static_cast<Lock::ScopedLock*>(new Lock::GlobalWrite(txn->lockState())) :
                                             static_cast<Lock::ScopedLock*>(new Lock::DBWrite(txn->lockState(), todb)));
            WriteUnitOfWork wunit(txn);
            if (!cloner.go(txn, todb, fromhost, cloneOptions, NULL, errmsg )) {
                return false;
            }
            wunit.commit();
            return true;
        }
Esempio n. 8
0
void ConnectionRegistry::killOperationsOnAllConnections(bool withPrompt) const {
    Prompter prompter("do you want to kill the current op(s) on the server?");
    stdx::lock_guard<stdx::mutex> lk(_mutex);
    for (map<string, set<string>>::const_iterator i = _connectionUris.begin();
         i != _connectionUris.end();
         ++i) {
        auto status = ConnectionString::parse(i->first);
        if (!status.isOK()) {
            continue;
        }

        const ConnectionString cs(status.getValue());

        string errmsg;
        std::unique_ptr<DBClientWithCommands> conn(cs.connect("MongoDB Shell", errmsg));
        if (!conn) {
            continue;
        }

        const set<string>& uris = i->second;

        BSONObj currentOpRes;
        conn->runPseudoCommand("admin", "currentOp", "$cmd.sys.inprog", {}, currentOpRes);
        if (!currentOpRes["inprog"].isABSONObj()) {
            // We don't have permissions (or the call didn't succeed) - go to the next connection.
            continue;
        }
        auto inprog = currentOpRes["inprog"].embeddedObject();
        for (const auto op : inprog) {
            // For sharded clusters, `client_s` is used instead and `client` is not present.
            string client;
            if (auto elem = op["client"]) {
                // mongod currentOp client
                if (elem.type() != String) {
                    warning() << "Ignoring operation " << op["opid"].toString(false)
                              << "; expected 'client' field in currentOp response to have type "
                                 "string, but found "
                              << typeName(elem.type());
                    continue;
                }
                client = elem.str();
            } else if (auto elem = op["client_s"]) {
                // mongos currentOp client
                if (elem.type() != String) {
                    warning() << "Ignoring operation " << op["opid"].toString(false)
                              << "; expected 'client_s' field in currentOp response to have type "
                                 "string, but found "
                              << typeName(elem.type());
                    continue;
                }
                client = elem.str();
            } else {
                // Internal operation, like TTL index.
                continue;
            }
            if (uris.count(client)) {
                if (!withPrompt || prompter.confirm()) {
                    BSONObjBuilder cmdBob;
                    BSONObj info;
                    cmdBob.appendAs(op["opid"], "op");
                    auto cmdArgs = cmdBob.done();
                    conn->runPseudoCommand("admin", "killOp", "$cmd.sys.killop", cmdArgs, info);
                } else {
                    return;
                }
            }
        }
    }
}
Esempio n. 9
0
    int Tool::main( int argc , char ** argv ) {
        static StaticObserver staticObserver;

        cmdLine.prealloc = false;

        // The default value may vary depending on compile options, but for tools
        // we want durability to be disabled.
        cmdLine.dur = false;

#if( BOOST_VERSION >= 104500 )
    boost::filesystem::path::default_name_check( boost::filesystem2::no_check );
#else
    boost::filesystem::path::default_name_check( boost::filesystem::no_check );
#endif

        _name = argv[0];

        /* using the same style as db.cpp */
        int command_line_style = (((po::command_line_style::unix_style ^
                                    po::command_line_style::allow_guessing) |
                                   po::command_line_style::allow_long_disguise) ^
                                  po::command_line_style::allow_sticky);
        try {
            po::options_description all_options("all options");
            all_options.add(*_options).add(*_hidden_options);

            po::store( po::command_line_parser( argc , argv ).
                       options(all_options).
                       positional( _positonalOptions ).
                       style(command_line_style).run() , _params );

            po::notify( _params );
        }
        catch (po::error &e) {
            cerr << "ERROR: " << e.what() << endl << endl;
            printHelp(cerr);
            ::_exit(EXIT_BADOPTIONS);
        }

        // hide password from ps output
        for (int i=0; i < (argc-1); ++i) {
            if (!strcmp(argv[i], "-p") || !strcmp(argv[i], "--password")) {
                char* arg = argv[i+1];
                while (*arg) {
                    *arg++ = 'x';
                }
            }
        }

        if ( _params.count( "help" ) ) {
            printHelp(cout);
            ::_exit(0);
        }

        if ( _params.count( "version" ) ) {
            printVersion(cout);
            ::_exit(0);
        }

        if ( _params.count( "verbose" ) ) {
            logLevel = 1;
        }

        for (string s = "vv"; s.length() <= 10; s.append("v")) {
            if (_params.count(s)) {
                logLevel = s.length();
            }
        }


#ifdef MONGO_SSL
        if (_params.count("ssl")) {
            mongo::cmdLine.sslOnNormalPorts = true;
        }
#endif

        preSetup();

        bool useDirectClient = hasParam( "dbpath" );

        if ( ! useDirectClient ) {
            _host = "127.0.0.1";
            if ( _params.count( "host" ) )
                _host = _params["host"].as<string>();

            if ( _params.count( "port" ) )
                _host += ':' + _params["port"].as<string>();

            if ( _noconnection ) {
                // do nothing
            }
            else {
                string errmsg;

                ConnectionString cs = ConnectionString::parse( _host , errmsg );
                if ( ! cs.isValid() ) {
                    cerr << "invalid hostname [" << _host << "] " << errmsg << endl;
                    ::_exit(-1);
                }

                _conn = cs.connect( errmsg );
                if ( ! _conn ) {
                    cerr << "couldn't connect to [" << _host << "] " << errmsg << endl;
                    ::_exit(-1);
                }

                (_usesstdout ? cout : cerr ) << "connected to: " << _host << endl;
            }

        }
        else {
            if ( _params.count( "directoryperdb" ) ) {
                directoryperdb = true;
            }
            verify( lastError.get( true ) );

            if (_params.count("journal")){
                cmdLine.dur = true;
            }

            Client::initThread("tools");
            _conn = new DBDirectClient();
            _host = "DIRECT";
            static string myDbpath = getParam( "dbpath" );
            dbpath = myDbpath.c_str();
            try {
                acquirePathLock();
            }
            catch ( DBException& ) {
                cerr << endl << "If you are running a mongod on the same "
                     "path you should connect to that instead of direct data "
                     "file access" << endl << endl;
                dbexit( EXIT_CLEAN );
                ::_exit(-1);
            }

            FileAllocator::get()->start();

            dur::startup();
        }

        if ( _params.count( "db" ) )
            _db = _params["db"].as<string>();

        if ( _params.count( "collection" ) )
            _coll = _params["collection"].as<string>();

        if ( _params.count( "username" ) )
            _username = _params["username"].as<string>();

        if ( _params.count( "password" )
                && ( _password.empty() ) ) {
            _password = askPassword();
        }

        if (_params.count("ipv6"))
            enableIPv6();

        int ret = -1;
        try {
            ret = run();
        }
        catch ( DBException& e ) {
            cerr << "assertion: " << e.toString() << endl;
            ret = -1;
        }
	catch(const boost::filesystem::filesystem_error &fse) {
	    /*
	      https://jira.mongodb.org/browse/SERVER-2904

	      Simple tools that don't access the database, such as
	      bsondump, aren't throwing DBExceptions, but are throwing
	      boost exceptions.

	      The currently available set of error codes don't seem to match
	      boost documentation.  boost::filesystem::not_found_error
	      (from http://www.boost.org/doc/libs/1_31_0/libs/filesystem/doc/exception.htm)
	      doesn't seem to exist in our headers.  Also, fse.code() isn't
	      boost::system::errc::no_such_file_or_directory when this
	      happens, as you would expect.  And, determined from
	      experimentation that the command-line argument gets turned into
	      "\\?" instead of "/?" !!!
	     */
#if defined(_WIN32)
	    if (/*(fse.code() == boost::system::errc::no_such_file_or_directory) &&*/
		(fse.path1() == "\\?"))
		printHelp(cerr);
	    else
#endif // _WIN32
		cerr << "error: " << fse.what() << endl;

	    ret = -1;
	}

        if ( currentClient.get() )
            currentClient.get()->shutdown();

        if ( useDirectClient )
            dbexit( EXIT_CLEAN );
        ::_exit(ret);
    }
Esempio n. 10
0
int main(int argc, const char** argv) {
    if (argc > 2) {
        std::cout << "usage: " << argv[0] << " [MONGODB_URI]" << std::endl;
        return EXIT_FAILURE;
    }

    client::GlobalInstance instance;
    if (!instance.initialized()) {
        std::cout << "failed to initialize the client driver: " << instance.status() << std::endl;
        return EXIT_FAILURE;
    }

    std::string uri = argc == 2 ? argv[1] : "mongodb://localhost:27017";
    std::string errmsg;

    ConnectionString cs = ConnectionString::parse(uri, errmsg);

    if (!cs.isValid()) {
        std::cout << "Error parsing connection string " << uri << ": " << errmsg << std::endl;
        return EXIT_FAILURE;
    }

    boost::scoped_ptr<DBClientBase> conn(cs.connect(errmsg));
    if (!conn) {
        cout << "couldn't connect : " << errmsg << endl;
        return EXIT_FAILURE;
    }

    {
        // clean up old data from any previous tests
        BSONObjBuilder query;
        conn->remove("test.people", query.obj());
    }

    insert(conn.get(), "eliot", 15);
    insert(conn.get(), "sara", 23);

    {
        mongo::BSONObjBuilder query;
        std::auto_ptr<mongo::DBClientCursor> cursor = conn->query("test.people", query.obj());
        if (!cursor.get()) {
            cout << "query failure" << endl;
            return EXIT_FAILURE;
        }

        cout << "using cursor" << endl;
        while (cursor->more()) {
            mongo::BSONObj obj = cursor->next();
            cout << "\t" << obj.jsonString() << endl;
        }
    }

    {
        mongo::BSONObjBuilder query;
        query.append("name", "eliot");
        mongo::BSONObj res = conn->findOne("test.people", query.obj());
        cout << res.isEmpty() << "\t" << res.jsonString() << endl;
    }

    {
        mongo::BSONObjBuilder query;
        query.append("name", "asd");
        mongo::BSONObj res = conn->findOne("test.people", query.obj());
        cout << res.isEmpty() << "\t" << res.jsonString() << endl;
    }

    return EXIT_SUCCESS;
}
Esempio n. 11
0
int main( int argc, const char **argv ) {

    if ( argc > 2 ) {
        std::cout << "usage: " << argv[0] << " [MONGODB_URI]"  << std::endl;
        return EXIT_FAILURE;
    }

    mongo::client::GlobalInstance instance;
    if (!instance.initialized()) {
        std::cout << "failed to initialize the client driver: " << instance.status() << std::endl;
        return EXIT_FAILURE;
    }

    std::string uri = argc == 2 ? argv[1] : "mongodb://localhost:27017";
    std::string errmsg;

    ConnectionString cs = ConnectionString::parse(uri, errmsg);

    if (!cs.isValid()) {
        std::cout << "Error parsing connection string " << uri << ": " << errmsg << std::endl;
        return EXIT_FAILURE;
    }

    boost::scoped_ptr<DBClientBase> conn(cs.connect(errmsg));
    if ( !conn ) {
        cout << "couldn't connect : " << errmsg << endl;
        return EXIT_FAILURE;
    }

    const char * ns = "test.where";

    conn->remove( ns , BSONObj() );

    conn->insert( ns , BSON( "name" << "eliot" << "num" << 17 ) );
    conn->insert( ns , BSON( "name" << "sara" << "num" << 24 ) );

    std::auto_ptr<DBClientCursor> cursor = conn->query( ns , BSONObj() );
    if (!cursor.get()) {
        cout << "query failure" << endl;
        return EXIT_FAILURE;
    }

    while ( cursor->more() ) {
        BSONObj obj = cursor->next();
        cout << "\t" << obj.jsonString() << endl;
    }

    cout << "now using $where" << endl;

    Query q = Query("{}").where("this.name == name" , BSON( "name" << "sara" ));

    cursor = conn->query( ns , q );
    if (!cursor.get()) {
        cout << "query failure" << endl;
        return EXIT_FAILURE;
    }

    int num = 0;
    while ( cursor->more() ) {
        BSONObj obj = cursor->next();
        cout << "\t" << obj.jsonString() << endl;
        num++;
    }
    verify( num == 1 );

    return EXIT_SUCCESS;
}
Esempio n. 12
0
File: tool.cpp Progetto: sivy/mongo
    int Tool::main( int argc , char ** argv ){
        static StaticObserver staticObserver;
        
        cmdLine.prealloc = false;

        boost::filesystem::path::default_name_check( boost::filesystem::no_check );

        _name = argv[0];

        /* using the same style as db.cpp */
        int command_line_style = (((po::command_line_style::unix_style ^
                                    po::command_line_style::allow_guessing) |
                                   po::command_line_style::allow_long_disguise) ^
                                  po::command_line_style::allow_sticky);
        try {
            po::options_description all_options("all options");
            all_options.add(*_options).add(*_hidden_options);

            po::store( po::command_line_parser( argc , argv ).
                       options(all_options).
                       positional( _positonalOptions ).
                       style(command_line_style).run() , _params );

            po::notify( _params );
        } catch (po::error &e) {
            cerr << "ERROR: " << e.what() << endl << endl;
            printHelp(cerr);
            return EXIT_BADOPTIONS;
        }

        // hide password from ps output
        for (int i=0; i < (argc-1); ++i){
            if (!strcmp(argv[i], "-p") || !strcmp(argv[i], "--password")){
                char* arg = argv[i+1];
                while (*arg){
                    *arg++ = 'x';
                }
            }
        }

        if ( _params.count( "help" ) ){
            printHelp(cout);
            return 0;
        }

        if ( _params.count( "verbose" ) ) {
            logLevel = 1;
        }

        for (string s = "vv"; s.length() <= 10; s.append("v")) {
            if (_params.count(s)) {
                logLevel = s.length();
            }
        }
        
        preSetup();

        bool useDirectClient = hasParam( "dbpath" );
        
        if ( ! useDirectClient ) {
            _host = "127.0.0.1";
            if ( _params.count( "host" ) )
                _host = _params["host"].as<string>();

            if ( _params.count( "port" ) )
                _host += ':' + _params["port"].as<string>();
            
            if ( _noconnection ){
                // do nothing
            }
            else {
                string errmsg;

                ConnectionString cs = ConnectionString::parse( _host , errmsg );
                if ( ! cs.isValid() ){
                    cerr << "invalid hostname [" << _host << "] " << errmsg << endl;
                    return -1;
                }
                
                _conn = cs.connect( errmsg );
                if ( ! _conn ){
                    cerr << "couldn't connect to [" << _host << "] " << errmsg << endl;
                    return -1;
                }
            }
            
            (_usesstdout ? cout : cerr ) << "connected to: " << _host << endl;
        }
        else {
            if ( _params.count( "directoryperdb" ) ) {
                directoryperdb = true;
            }
            assert( lastError.get( true ) );
            Client::initThread("tools");
            _conn = new DBDirectClient();
            _host = "DIRECT";
            static string myDbpath = getParam( "dbpath" );
            dbpath = myDbpath.c_str();
            try {
                acquirePathLock();
            }
            catch ( DBException& ){
                cerr << endl << "If you are running a mongod on the same "
                    "path you should connect to that instead of direct data "
                    "file access" << endl << endl;
                dbexit( EXIT_CLEAN );
                return -1;
            }

            theFileAllocator().start();
        }

        if ( _params.count( "db" ) )
            _db = _params["db"].as<string>();

        if ( _params.count( "collection" ) )
            _coll = _params["collection"].as<string>();

        if ( _params.count( "username" ) )
            _username = _params["username"].as<string>();

        if ( _params.count( "password" )
             && ( _password.empty() ) ) {
            _password = askPassword();
        }

        if (_params.count("ipv6"))
            enableIPv6();

        int ret = -1;
        try {
            ret = run();
        }
        catch ( DBException& e ){
            cerr << "assertion: " << e.toString() << endl;
            ret = -1;
        }
    
        if ( currentClient.get() )
            currentClient->shutdown();

        if ( useDirectClient )
            dbexit( EXIT_CLEAN );
        return ret;
    }
Esempio n. 13
0
File: rs.cpp Progetto: 504com/mongo
int main( int argc , const char ** argv ) {
    
    unsigned nThreads = 1;
    bool print = false;
    bool testTimeout = false;

    for ( int i=1; i<argc; i++ ) {
        if ( mongoutils::str::equals( "--threads" , argv[i] ) ) {
            nThreads = atoi( argv[++i] );
        }
        else if ( mongoutils::str::equals( "--print" , argv[i] ) ) {
            print = true;
        }
        // Run a special mode to demonstrate the DBClientReplicaSet so_timeout option.
        else if ( mongoutils::str::equals( "--testTimeout" , argv[i] ) ) {
            testTimeout = true;
        }
        else {
            cerr << "unknown option: " << argv[i] << endl;
            return EXIT_FAILURE;
        }
            
    }

    Status status = client::initialize();
    if ( !status.isOK() ) {
        std::cout << "failed to initialize the client driver: " << status.toString() << endl;
        return EXIT_FAILURE;
    }

    string errmsg;
    ConnectionString cs = ConnectionString::parse( "foo/127.0.0.1" , errmsg );
    if ( ! cs.isValid() ) {
        cout << "error parsing url: " << errmsg << endl;
        return EXIT_FAILURE;
    }

    DBClientReplicaSet * conn = static_cast<DBClientReplicaSet*>( cs.connect( errmsg, testTimeout ? 10 : 0 ) );
    if ( ! conn ) {
        cout << "error connecting: " << errmsg << endl;
        return EXIT_FAILURE;
    }

    string collName = "test.rs1";

    conn->dropCollection( collName );

    if ( testTimeout ) {
        conn->insert( collName, BSONObj() );
        try {
            conn->count( collName, BSON( "$where" << "sleep(40000)" ) );
        } catch( DBException& ) {
            return EXIT_SUCCESS;
        }
        cout << "expected socket exception" << endl;
        return EXIT_FAILURE;
    }
    
    vector<boost::shared_ptr<boost::thread> > threads;
    for ( unsigned i=0; i<nThreads; i++ ) {
        string errmsg;
        threads.push_back( boost::shared_ptr<boost::thread>( 
                               new boost::thread( 
                                   boost::bind( workerThread , 
                                                collName , 
                                                print , 
                                                static_cast<DBClientReplicaSet*>( cs.connect(errmsg) ) ) ) ) );
    }
    
    for ( unsigned i=0; i<threads.size(); i++ ) {
        threads[i]->join();
    }

    return EXIT_SUCCESS;
}