当前位置: 首页>>代码示例>>C++>>正文


C++ DBClientConnection::auth方法代码示例

本文整理汇总了C++中DBClientConnection::auth方法的典型用法代码示例。如果您正苦于以下问题:C++ DBClientConnection::auth方法的具体用法?C++ DBClientConnection::auth怎么用?C++ DBClientConnection::auth使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DBClientConnection的用法示例。


在下文中一共展示了DBClientConnection::auth方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: auth

    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;
    }
开发者ID:BendustiK,项目名称:mongo,代码行数:11,代码来源:dbclient_rs.cpp

示例2: kill_wrapper

      inline void kill_wrapper( pid_t pid, int sig, int port, const BSONObj& opt ) {
#ifdef _WIN32
            if (sig == SIGKILL || port == 0) {
                verify( registry._handles.count(pid) );
                TerminateProcess(registry._handles[pid], 1); // returns failure for "zombie" processes.
            }
            else {
                DBClientConnection conn;
                try {
                    conn.connect("127.0.0.1:" + BSONObjBuilder::numStr(port));

                    BSONElement authObj = opt["auth"];

                    if ( !authObj.eoo() ){
                        string errMsg;
                        conn.auth( "admin", authObj["user"].String(),
                                   authObj["pwd"].String(), errMsg );

                        if ( !errMsg.empty() ) {
                            cout << "Failed to authenticate before shutdown: "
                                 << errMsg << endl;
                        }
                    }

                    BSONObj info;
                    BSONObjBuilder b;
                    b.append( "shutdown", 1 );
                    b.append( "force", 1 );
                    conn.runCommand( "admin", b.done(), info );
                }
                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 {
                    log() << "killFailed: " << errnoWithDescription() << endl;
                    verify( x == 0 );
                }
            }

#endif
        }
开发者ID:89snake89,项目名称:mongo,代码行数:47,代码来源:shell_utils_launcher.cpp

示例3: testDbEval

    /* TODO: unit tests should run this? */
    void testDbEval() {
        DBClientConnection c;
        string err;
        if ( !c.connect("localhost", err) ) {
            out() << "can't connect to server " << err << endl;
            return;
        }

        if( !c.auth("dwight", "u", "p", err) ) { 
            out() << "can't authenticate " << err << endl;
            return;
        }

        BSONObj info;
        BSONElement retValue;
        BSONObjBuilder b;
        b.append("0", 99);
        BSONObj args = b.done();
        bool ok = c.eval("dwight", "function() { return args[0]; }", info, retValue, &args);
        out() << "eval ok=" << ok << endl;
        out() << "retvalue=" << retValue.toString() << endl;
        out() << "info=" << info.toString() << endl;

        out() << endl;

        int x = 3;
        assert( c.eval("dwight", "function() { return 3; }", x) );

        out() << "***\n";

        BSONObj foo = fromjson("{\"x\":7}");
        out() << foo.toString() << endl;
        int res=0;
        ok = c.eval("dwight", "function(parm1) { return parm1.x; }", foo, res);
        out() << ok << " retval:" << res << endl;
    }
开发者ID:tanfulai,项目名称:mongo,代码行数:37,代码来源:dbclient.cpp

示例4: isSelf

bool HostAndPort::isSelf() const {

    if( dyn() ) {
        MONGO_LOG(2) << "isSelf " << _dynName << ' ' << dynHostMyName() << endl;
        return dynHostMyName() == _dynName;
    }

    int _p = port();
    int p = _p == -1 ? CmdLine::DefaultDBPort : _p;

    if( p != cmdLine.port ) {
        // shortcut - ports have to match at the very least
        return false;
    }

    string host = str::stream() << this->host() << ":" << p;

    {
        // check cache for this host
        // debatably something _could_ change, but I'm not sure right now (erh 10/14/2010)
        scoped_lock lk( isSelfCommand._cacheLock );
        map<string,bool>::const_iterator i = isSelfCommand._cache.find( host );
        if ( i != isSelfCommand._cache.end() )
            return i->second;
    }

#if !defined(_WIN32) && !defined(__sunos__)
    // on linux and os x we can do a quick check for an ip match

    const vector<string> myaddrs = getMyAddrs();
    const vector<string> addrs = getAllIPs(_host);

    for (vector<string>::const_iterator i=myaddrs.begin(), iend=myaddrs.end(); i!=iend; ++i) {
        for (vector<string>::const_iterator j=addrs.begin(), jend=addrs.end(); j!=jend; ++j) {
            string a = *i;
            string b = *j;

            if ( a == b ||
                    ( str::startsWith( a , "127." ) && str::startsWith( b , "127." ) )  // 127. is all loopback
               ) {

                // add to cache
                scoped_lock lk( isSelfCommand._cacheLock );
                isSelfCommand._cache[host] = true;
                return true;
            }
        }
    }

#endif

    if ( ! Listener::getTimeTracker() ) {
        // this ensures we are actually running a server
        // this may return true later, so may want to retry
        return false;
    }

    try {
        isSelfCommand.init();
        DBClientConnection conn;
        string errmsg;
        if ( ! conn.connect( host , errmsg ) ) {
            // should this go in the cache?
            return false;
        }

        if (!noauth && cmdLine.keyFile &&
                !conn.auth("local", internalSecurity.user, internalSecurity.pwd, errmsg, false)) {
            return false;
        }

        BSONObj out;
        bool ok = conn.simpleCommand( "admin" , &out , "_isSelf" );
        bool me = ok && out["id"].type() == jstOID && isSelfCommand._id == out["id"].OID();

        // add to cache
        scoped_lock lk( isSelfCommand._cacheLock );
        isSelfCommand._cache[host] = me;

        return me;
    }
    catch ( std::exception& e ) {
        warning() << "could't check isSelf (" << host << ") " << e.what() << endl;
    }

    return false;
}
开发者ID:tanakh,项目名称:mongo,代码行数:87,代码来源:isself.cpp

示例5: main

int main(int argc, char* argv[])
{
	// Check the required number of command line arguments.
	if (argc != 5)
	{
		cout << "usr host user pwd jobs_path" << endl;
		return 0;
	}

	// Fetch command line arguments.
	const auto host = argv[1];
	const auto user = argv[2];
	const auto pwd = argv[3];
	const path jobs_path = argv[4];

	// Connect to host and authenticate user.
	DBClientConnection conn;
	{
		cout << local_time() << "Connecting to " << host << " and authenticating " << user << endl;
		string errmsg;
		if ((!conn.connect(host, errmsg)) || (!conn.auth("istar", user, pwd, errmsg)))
		{
			cerr << local_time() << errmsg << endl;
			return 1;
		}
	}

	// Initialize constants.
	cout << local_time() << "Initializing" << endl;
	const auto collection = "istar.usr";
	const auto epoch = date(1970, 1, 1);
	const size_t num_usrs = 2;
	constexpr array<size_t, num_usrs> qn{{ 12, 60 }};
	constexpr array<double, num_usrs> qv{{ 1.0 / qn[0], 1.0 / qn[1] }};
	const size_t num_references = 4;
	const size_t num_subsets = 5;
	const array<string, num_subsets> SubsetSMARTS
	{{
		"[!#1]", // heavy
		"[#6+0!$(*~[#7,#8,F]),SH0+0v2,s+0,S^3,Cl+0,Br+0,I+0]", // hydrophobic
		"[a]", // aromatic
		"[$([O,S;H1;v2]-[!$(*=[O,N,P,S])]),$([O,S;H0;v2]),$([O,S;-]),$([N&v3;H1,H2]-[!$(*=[O,N,P,S])]),$([N;v3;H0]),$([n,o,s;+0]),F]", // acceptor
		"[N!H0v3,N!H0+v4,OH+0,SH+0,nH+0]", // donor
	}};

	// Initialize variables.
	array<array<double, qn.back()>, 1> qw;
	array<array<double, qn.back()>, 1> lw;
	auto q = qw[0];
	auto l = lw[0];

	// Read ZINC ID file.
	const string_array<size_t> zincids("16_zincid.txt");
	const auto num_ligands = zincids.size();

	// Read SMILES file.
	const string_array<size_t> smileses("16_smiles.txt");
	assert(smileses.size() == num_ligands);

	// Read supplier file.
	const string_array<size_t> suppliers("16_supplier.txt");
	assert(suppliers.size() == num_ligands);

	// Read property files of floating point types and integer types.
	const auto zfproperties = read<array<float, 4>>("16_zfprop.f32");
	assert(zfproperties.size() == num_ligands);
	const auto ziproperties = read<array<int16_t, 5>>("16_ziprop.i16");
	assert(ziproperties.size() == num_ligands);

	// Open files for subsequent reading.
	std::ifstream usrcat_bin("16_usrcat.f64");
	stream_array<size_t> ligands("16_ligand.pdbqt");
	assert(ligands.size() == num_ligands);
	array<vector<double>, 2> scores
	{{
		vector<double>(num_ligands, 0),
		vector<double>(num_ligands, 0)
	}};
	const auto& u0scores = scores[0];
	const auto& u1scores = scores[1];
	vector<size_t> scase(num_ligands);

	// Enter event loop.
	cout << local_time() << "Entering event loop" << endl;
	bool sleeping = false;
	while (true)
	{
		// Fetch an incompleted job in a first-come-first-served manner.
		if (!sleeping) cout << local_time() << "Fetching an incompleted job" << endl;
		BSONObj info;
		conn.runCommand("istar", BSON("findandmodify" << "usr" << "query" << BSON("done" << BSON("$exists" << false) << "started" << BSON("$exists" << false)) << "sort" << BSON("submitted" << 1) << "update" << BSON("$set" << BSON("started" << Date_t(duration_cast<std::chrono::milliseconds>(system_clock::now().time_since_epoch()).count())))), info); // conn.findAndModify() is available since MongoDB C++ Driver legacy-1.0.0
		const auto value = info["value"];
		if (value.isNull())
		{
			// No incompleted jobs. Sleep for a while.
			if (!sleeping) cout << local_time() << "Sleeping" << endl;
			sleeping = true;
			this_thread::sleep_for(chrono::seconds(10));
			continue;
		}
//.........这里部分代码省略.........
开发者ID:ZhangJingrong,项目名称:istar,代码行数:101,代码来源:main.cpp

示例6: kill_wrapper

      inline void kill_wrapper( ProcessId pid, int sig, int port, const BSONObj& opt ) {
#ifdef _WIN32
            if (sig == SIGKILL || port == 0) {
                verify( registry._handles.count(pid) );
                TerminateProcess(registry._handles[pid], 1); // returns failure for "zombie" processes.
                return;
            }

            std::string eventName = getShutdownSignalName(pid.asUInt32());

            HANDLE event = OpenEventA(EVENT_MODIFY_STATE, FALSE, eventName.c_str());
            if (event == NULL) {
                int gle = GetLastError();
                if (gle != ERROR_FILE_NOT_FOUND) {
                    warning() << "kill_wrapper OpenEvent failed: " << errnoWithDescription();
                }
                else {
                    log() << "kill_wrapper OpenEvent failed to open event to the process "
                        << pid.asUInt32()
                        << ". It has likely died already or server is running an older version."
                        << " Attempting to shutdown through admin command.";

                    // Back-off to the old way of shutting down the server on Windows, in case we
                    // are managing a pre-2.6.0rc0 service, which did not have the event.
                    //
                    try {
                        DBClientConnection conn;
                        conn.connect("127.0.0.1:" + BSONObjBuilder::numStr(port));

                        BSONElement authObj = opt["auth"];

                        if (!authObj.eoo()){
                            string errMsg;
                            conn.auth("admin", authObj["user"].String(),
                                authObj["pwd"].String(), errMsg);

                            if (!errMsg.empty()) {
                                cout << "Failed to authenticate before shutdown: "
                                    << errMsg << endl;
                            }
                        }

                        BSONObj info;
                        BSONObjBuilder b;
                        b.append("shutdown", 1);
                        b.append("force", 1);
                        conn.runCommand("admin", b.done(), info);
                    }
                    catch (...) {
                        // Do nothing. This command never returns data to the client and the driver
                        // doesn't like that.
                        //
                    }
                }
                return;
            }

            ON_BLOCK_EXIT(CloseHandle, event);

            bool result = SetEvent(event);
            if (!result) {
                error() << "kill_wrapper SetEvent failed: " << errnoWithDescription();
                return;
            }
#else
            int x = kill( pid.toNative(), sig );
            if ( x ) {
                if ( errno == ESRCH ) {
                }
                else {
                    log() << "killFailed: " << errnoWithDescription() << endl;
                    verify( x == 0 );
                }
            }

#endif
        }
开发者ID:ambroff,项目名称:mongo,代码行数:77,代码来源:shell_utils_launcher.cpp

示例7: main

int main(int argc, char* argv[])
{
	// Check the required number of command line arguments.
	if (argc != 5)
	{
		cout << "usr host user pwd jobs_path" << endl;
		return 0;
	}

	// Fetch command line arguments.
	const auto host = argv[1];
	const auto user = argv[2];
	const auto pwd = argv[3];
	const path jobs_path = argv[4];

	DBClientConnection conn;
	{
		// Connect to host and authenticate user.
		cout << local_time() << "Connecting to " << host << " and authenticating " << user << endl;
		string errmsg;
		if ((!conn.connect(host, errmsg)) || (!conn.auth("istar", user, pwd, errmsg)))
		{
			cerr << local_time() << errmsg << endl;
			return 1;
		}
	}

	// Initialize constants.
	cout << local_time() << "Initializing" << endl;
	const auto collection = "istar.usr2";
	const size_t num_usrs = 2;
	const array<string, 2> usr_names{{ "USR", "USRCAT" }};
	constexpr array<size_t, num_usrs> qn{{ 12, 60 }};
	constexpr array<double, num_usrs> qv{{ 1.0 / qn[0], 1.0 / qn[1] }};
	const size_t num_refPoints = 4;
	const size_t num_subsets = 5;
	const array<string, num_subsets> SubsetSMARTS
	{{
		"[!#1]", // heavy
		"[#6+0!$(*~[#7,#8,F]),SH0+0v2,s+0,S^3,Cl+0,Br+0,I+0]", // hydrophobic
		"[a]", // aromatic
		"[$([O,S;H1;v2]-[!$(*=[O,N,P,S])]),$([O,S;H0;v2]),$([O,S;-]),$([N&v3;H1,H2]-[!$(*=[O,N,P,S])]),$([N;v3;H0]),$([n,o,s;+0]),F]", // acceptor
		"[N!H0v3,N!H0+v4,OH+0,SH+0,nH+0]", // donor
	}};
	const size_t num_hits = 100;

	// Wrap SMARTS strings to RWMol objects.
	array<unique_ptr<ROMol>, num_subsets> SubsetMols;
	for (size_t k = 0; k < num_subsets; ++k)
	{
		SubsetMols[k].reset(reinterpret_cast<ROMol*>(SmartsToMol(SubsetSMARTS[k])));
	}

	// Read ZINC ID file.
	const string_array<size_t> zincids("16/zincid.txt");
	const auto num_ligands = zincids.size();
	cout << local_time() << "Found " << num_ligands << " database molecules" << endl;

	// Read SMILES file.
	const string_array<size_t> smileses("16/smiles.txt");
	assert(smileses.size() == num_ligands);

	// Read supplier file.
	const string_array<size_t> suppliers("16/supplier.txt");
	assert(suppliers.size() == num_ligands);

	// Read property files of floating point types and integer types.
	const auto zfproperties = read<array<float, 4>>("16/zfprop.f32");
	assert(zfproperties.size() == num_ligands);
	const auto ziproperties = read<array<int16_t, 5>>("16/ziprop.i16");
	assert(ziproperties.size() == num_ligands);

	// Read cumulative number of conformers file.
	const auto mconfss = read<size_t>("16/mconfs.u64");
	const auto num_conformers = mconfss.back();
	assert(mconfss.size() == num_ligands);
	assert(num_conformers >= num_ligands);
	cout << local_time() << "Found " << num_conformers << " database conformers" << endl;

	// Read feature file.
	const auto features = read<array<double, qn.back()>>("16/usrcat.f64");
	assert(features.size() == num_conformers);

	// Read ligand footer file and open ligand SDF file for seeking and reading.
	stream_array<size_t> ligands("16/ligand.sdf");
	assert(ligands.size() == num_conformers);

	// Initialize variables.
	array<vector<int>, num_subsets> subsets;
	array<vector<double>, num_refPoints> dista;
	alignas(32) array<double, qn.back()> q;

	// Initialize vectors to store compounds' primary score and their corresponding conformer.
	vector<double> scores(num_ligands); // Primary score of molecules.
	vector<size_t> cnfids(num_ligands); // ID of conformer with the best primary score.
	const auto compare = [&](const size_t val0, const size_t val1) // Sort by the primary score.
	{
		return scores[val0] < scores[val1];
	};

//.........这里部分代码省略.........
开发者ID:HongjianLi,项目名称:USR-VS,代码行数:101,代码来源:main.cpp

示例8: _auth

    void DBClientReplicaSet::_auth( const BSONObj& params ) {

        // We prefer to authenticate against a primary, but otherwise a secondary is ok too
        // Empty tag matches every secondary
        shared_ptr<ReadPreferenceSetting> readPref(
            new ReadPreferenceSetting( ReadPreference_PrimaryPreferred, TagSet() ) );

        LOG(3) << "dbclient_rs authentication of " << _getMonitor()->getName() << endl;

        // NOTE that we retry MAX_RETRY + 1 times, since we're always primary preferred we don't
        // fallback to the primary.
        Status lastNodeStatus = Status::OK();
        for ( size_t retry = 0; retry < MAX_RETRY + 1; retry++ ) {
            try {
                DBClientConnection* conn = selectNodeUsingTags( readPref );

                if ( conn == NULL ) {
                    break;
                }

                conn->auth( params );

                // Cache the new auth information since we now validated it's good
                _auths[params[saslCommandUserDBFieldName].str()] = params.getOwned();

                // Ensure the only child connection open is the one we authenticated against - other
                // child connections may not have full authentication information.
                // NOTE: _lastSlaveOkConn may or may not be the same as _master
                dassert(_lastSlaveOkConn.get() == conn || _master.get() == conn);
                if ( conn != _lastSlaveOkConn.get() ) {
                    _lastSlaveOkHost = HostAndPort();
                    _lastSlaveOkConn.reset();
                }
                if ( conn != _master.get() ) {
                    _masterHost = HostAndPort();
                    _master.reset();
                }

                return;
            }
            catch ( const DBException &ex ) {

                // We care if we can't authenticate (i.e. bad password) in credential params.
                if ( isAuthenticationException( ex ) ) {
                    throw;
                }

                StringBuilder errMsgB;
                errMsgB << "can't authenticate against replica set node "
                        << _lastSlaveOkHost.toString();
                lastNodeStatus = ex.toStatus( errMsgB.str() );

                LOG(1) << lastNodeStatus.reason() << endl;
                invalidateLastSlaveOkCache();
            }
        }

        if ( lastNodeStatus.isOK() ) {
            StringBuilder assertMsgB;
            assertMsgB << "Failed to authenticate, no good nodes in " << _getMonitor()->getName();
            uasserted( ErrorCodes::NodeNotFound, assertMsgB.str() );
        }
        else {
            uasserted( lastNodeStatus.code(), lastNodeStatus.reason() );
        }
    }
开发者ID:joegen,项目名称:sipx-externals,代码行数:66,代码来源:dbclient_rs.cpp


注:本文中的DBClientConnection::auth方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。