bool DocumentSourceMatch::accept(
        const intrusive_ptr<Document> &pDocument) const {

        /*
          The matcher only takes BSON documents, so we have to make one.

          LATER
          We could optimize this by making a document with only the
          fields referenced by the Matcher.  We could do this by looking inside
          the Matcher's BSON before it is created, and recording those.  The
          easiest implementation might be to hold onto an ExpressionDocument
          in here, and give that pDocument to create the created subset of
          fields, and then convert that instead.
        */
        BSONObjBuilder objBuilder;
        pDocument->toBson(&objBuilder);
        BSONObj obj(objBuilder.done());

        return matcher.matches(obj);
    }
Beispiel #2
0
    bool DBClientWithCommands::auth(const string &dbname, const string &username, const string &password_text, string& errmsg, bool digestPassword) {
        string password = password_text;
        if( digestPassword )
            password = createPasswordDigest( username , password_text );

        BSONObj info;
        string nonce;
        if( !runCommand(dbname, getnoncecmdobj, info) ) {
            errmsg = "getnonce fails - connection problem?";
            return false;
        }
        {
            BSONElement e = info.getField("nonce");
            assert( e.type() == String );
            nonce = e.valuestr();
        }

        BSONObj authCmd;
        BSONObjBuilder b;
        {

            b << "authenticate" << 1 << "nonce" << nonce << "user" << username;
            md5digest d;
            {
                md5_state_t st;
                md5_init(&st);
                md5_append(&st, (const md5_byte_t *) nonce.c_str(), nonce.size() );
                md5_append(&st, (const md5_byte_t *) username.data(), username.length());
                md5_append(&st, (const md5_byte_t *) password.c_str(), password.size() );
                md5_finish(&st, d);
            }
            b << "key" << digestToString( d );
            authCmd = b.done();
        }

        if( runCommand(dbname, authCmd, info) )
            return true;

        errmsg = info.toString();
        return false;
    }
Beispiel #3
0
    Status Collection::validate( OperationContext* txn,
                                 bool full, bool scanData,
                                 ValidateResults* results, BSONObjBuilder* output ){

        MyValidateAdaptor adaptor;
        Status status = _recordStore->validate( txn, full, scanData, &adaptor, results, output );
        if ( !status.isOK() )
            return status;

        { // indexes
            output->append("nIndexes", _indexCatalog.numIndexesReady( txn ) );
            int idxn = 0;
            try  {
                BSONObjBuilder indexes; // not using subObjStart to be exception safe
                IndexCatalog::IndexIterator i = _indexCatalog.getIndexIterator(txn, false);
                while( i.more() ) {
                    const IndexDescriptor* descriptor = i.next();
                    log(LogComponent::kIndexing) << "validating index " << descriptor->indexNamespace() << endl;
                    IndexAccessMethod* iam = _indexCatalog.getIndex( descriptor );
                    invariant( iam );

                    int64_t keys;
                    iam->validate(txn, &keys);
                    indexes.appendNumber(descriptor->indexNamespace(),
                                         static_cast<long long>(keys));
                    idxn++;
                }
                output->append("keysPerIndex", indexes.done());
            }
            catch ( DBException& exc ) {
                string err = str::stream() <<
                    "exception during index validate idxn "<<
                    BSONObjBuilder::numStr(idxn) <<
                    ": " << exc.toString();
                results->errors.push_back( err );
                results->valid = false;
            }
        }

        return Status::OK();
    }
Beispiel #4
0
void pretouchN(vector<BSONObj>& v, unsigned a, unsigned b) {
    Client* c = currentClient.get();
    if (c == 0) {
        Client::initThread("pretouchN");
        c = &cc();
    }

    OperationContextImpl txn;  // XXX
    ScopedTransaction transaction(&txn, MODE_S);
    Lock::GlobalRead lk(txn.lockState());

    for (unsigned i = a; i <= b; i++) {
        const BSONObj& op = v[i];
        const char* which = "o";
        const char* opType = op.getStringField("op");
        if (*opType == 'i')
            ;
        else if (*opType == 'u')
            which = "o2";
        else
            continue;
        /* todo : other operations */

        try {
            BSONObj o = op.getObjectField(which);
            BSONElement _id;
            if (o.getObjectID(_id)) {
                const char* ns = op.getStringField("ns");
                BSONObjBuilder b;
                b.append(_id);
                BSONObj result;
                Client::Context ctx(&txn, ns);
                if (Helpers::findById(&txn, ctx.db(), ns, b.done(), result))
                    _dummy_z += result.objsize();  // touch
            }
        } catch (DBException& e) {
            log() << "ignoring assertion in pretouchN() " << a << ' ' << b << ' ' << i << ' '
                  << e.toString() << endl;
        }
    }
}
Beispiel #5
0
 virtual bool run(const char *ns, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
     string fromhost = cmdObj.getStringField("from");
     if ( fromhost.empty() ) {
         errmsg = "missing from spec";
         return false;
     }
     string collection = cmdObj.getStringField("startCloneCollection");
     if ( collection.empty() ) {
         errmsg = "missing startCloneCollection spec";
         return false;
     }
     BSONObj query = cmdObj.getObjectField("query");
     if ( query.isEmpty() )
         query = BSONObj();
     BSONElement copyIndexesSpec = cmdObj.getField("copyindexes");
     bool copyIndexes = copyIndexesSpec.isBoolean() ? copyIndexesSpec.boolean() : true;
     // Will not be used if doesn't exist.
     int logSizeMb = cmdObj.getIntField( "logSizeMb" );
     
     /* replication note: we must logOp() not the command, but the cloned data -- if the slave
      were to clone it would get a different point-in-time and not match.
      */
     setClient( collection.c_str() );
     
     log() << "startCloneCollection.  db:" << ns << " collection:" << collection << " from: " << fromhost << " query: " << query << endl;
     
     Cloner c;
     long long cursorId;
     bool res = c.startCloneCollection( fromhost.c_str(), collection.c_str(), query, errmsg, !fromRepl, copyIndexes, logSizeMb, cursorId );
     
     if ( res ) {
         BSONObjBuilder b;
         b << "fromhost" << fromhost;
         b << "collection" << collection;
         b << "query" << query;
         b.appendDate( "cursorId", cursorId );
         BSONObj token = b.done();
         result << "finishToken" << token;
     }
     return res;
 }
    Status startConfigUpgrade(const string& configServer,
                              int currentVersion,
                              const OID& upgradeID) {
        BSONObjBuilder setUpgradeIdObj;
        setUpgradeIdObj << VersionType::upgradeId(upgradeID);
        setUpgradeIdObj << VersionType::upgradeState(BSONObj());

        try {
            ScopedDbConnection conn(configServer, 30);
            conn->update(VersionType::ConfigNS,
                         BSON("_id" << 1 << VersionType::currentVersion(currentVersion)),
                         BSON("$set" << setUpgradeIdObj.done()));
            _checkGLE(conn);
            conn.done();
        }
        catch (const DBException& e) {
            return e.toStatus("could not initialize version info for upgrade");
        }

        return Status::OK();
    }
Beispiel #7
0
            void run() {
                create();
                ASSERT_EQUALS( 2, nExtents() );
                BSONObj b = bigObj();

                DiskLoc l[ 8 ];
                for ( int i = 0; i < 8; ++i ) {
                    l[ i ] = theDataFileMgr.insert( ns(), b.objdata(), b.objsize() );
                    ASSERT( !l[ i ].isNull() );
                    ASSERT_EQUALS( i < 2 ? i + 1 : 3 + i % 2, nRecords() );
                    if ( i > 3 )
                        ASSERT( l[ i ] == l[ i - 4 ] );
                }

                // Too big
                BSONObjBuilder bob;
                bob.append( "a", string( 787, 'a' ) );
                BSONObj bigger = bob.done();
                ASSERT( theDataFileMgr.insert( ns(), bigger.objdata(), bigger.objsize() ).isNull() );
                ASSERT_EQUALS( 0, nRecords() );
            }
 Status AuthzManagerExternalStateMongod::dropIndexes(
         const NamespaceString& collectionName,
         const BSONObj& writeConcern) {
     DBDirectClient client;
     try {
         client.dropIndexes(collectionName.ns());
         BSONObjBuilder gleBuilder;
         gleBuilder.append("getLastError", 1);
         gleBuilder.appendElements(writeConcern);
         BSONObj res;
         client.runCommand("admin", gleBuilder.done(), res);
         string errstr = client.getLastErrorString(res);
         if (!errstr.empty()) {
             return Status(ErrorCodes::UnknownError, errstr);
         }
         return Status::OK();
     }
     catch (const DBException& ex) {
         return ex.toStatus();
     }
 }
    Status AuthzManagerExternalStateMongod::updateOne(
            const NamespaceString& collectionName,
            const BSONObj& query,
            const BSONObj& updatePattern,
            bool upsert,
            const BSONObj& writeConcern) {
        try {
            DBDirectClient client;
            {
                Client::GodScope gs;
                // TODO(spencer): Once we're no longer fully rebuilding the user cache on every
                // change to user data we should remove the global lock and uncomment the
                // WriteContext below
                Lock::GlobalWrite w;
                // Client::WriteContext ctx(userNS);
                client.update(collectionName, query, updatePattern, upsert);
            }

            // Handle write concern
            BSONObjBuilder gleBuilder;
            gleBuilder.append("getLastError", 1);
            gleBuilder.appendElements(writeConcern);
            BSONObj res;
            client.runCommand("admin", gleBuilder.done(), res);
            string err = client.getLastErrorString(res);
            if (!err.empty()) {
                return Status(ErrorCodes::UnknownError, err);
            }

            int numUpdated = res["n"].numberInt();
            dassert(numUpdated <= 1 && numUpdated >= 0);
            if (numUpdated == 0) {
                return Status(ErrorCodes::NoMatchingDocument, "No document found");
            }

            return Status::OK();
        } catch (const DBException& e) {
            return e.toStatus();
        }
    }
Beispiel #10
0
    void pretouchN(vector<BSONObj>& v, unsigned a, unsigned b) {
        DEV assert( !dbMutex.isWriteLocked() );

        Client *c = currentClient.get();
        if( c == 0 ) {
            Client::initThread("pretouchN");
            c = &cc();
        }

        readlock lk("");
        for( unsigned i = a; i <= b; i++ ) {
            const BSONObj& op = v[i];
            const char *which = "o";
            const char *opType = op.getStringField("op");
            if ( *opType == 'i' )
                ;
            else if( *opType == 'u' )
                which = "o2";
            else
                continue;
            /* todo : other operations */

            try {
                BSONObj o = op.getObjectField(which);
                BSONElement _id;
                if( o.getObjectID(_id) ) {
                    const char *ns = op.getStringField("ns");
                    BSONObjBuilder b;
                    b.append(_id);
                    BSONObj result;
                    Client::Context ctx( ns );
                    if( Helpers::findById(cc(), ns, b.done(), result) )
                        _dummy_z += result.objsize(); // touch
                }
            }
            catch( DBException& e ) {
                log() << "ignoring assertion in pretouchN() " << a << ' ' << b << ' ' << i << ' ' << e.toString() << endl;
            }
        }
    }
    Status startConfigUpgrade(const string& configServer,
                              int currentVersion,
                              const OID& upgradeID) {
        BSONObjBuilder setUpgradeIdObj;
        setUpgradeIdObj << VersionType::upgradeId(upgradeID);
        setUpgradeIdObj << VersionType::upgradeState(BSONObj());

        Status result = clusterUpdate(VersionType::ConfigNS,
                BSON("_id" << 1 << VersionType::currentVersion(currentVersion)),
                BSON("$set" << setUpgradeIdObj.done()),
                false, // upsert
                false, // multi
                WriteConcernOptions::AllConfigs,
                NULL);

        if ( !result.isOK() ) {
            return Status( result.code(),
                           str::stream() << "could not initialize version info"
                                         << "for upgrade: " << result.reason() );
        }
        return result;
    }
Beispiel #12
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(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;
                }
            }
        }
    }
}
        virtual std::vector<BSONObj> stopIndexBuilds(const std::string& dbname,
                                                     const BSONObj& cmdObj) {
            string source = cmdObj.getStringField( name.c_str() );
            string target = cmdObj.getStringField( "to" );

            BSONObj criteria = BSON("op" << "insert" << "ns" << dbname+".system.indexes" <<
                                    "insert.ns" << source);

            std::vector<BSONObj> prelim = IndexBuilder::killMatchingIndexBuilds(criteria);
            std::vector<BSONObj> indexes;

            for (int i = 0; i < static_cast<int>(prelim.size()); i++) {
                // Change the ns
                BSONObj stripped = prelim[i].removeField("ns");
                BSONObjBuilder builder;
                builder.appendElements(stripped);
                builder.append("ns", target);
                indexes.push_back(builder.done());
            }

            return indexes;
        }
Beispiel #14
0
 void run() {
     create();
     vector< BSONObj > elts;
     BSONObjBuilder s;
     s.append( "foo", 41 );
     elts.push_back( s.obj() );
     for ( int i = 1; i < 4; ++i )
         elts.push_back( simpleBC( i ) );
     BSONObjBuilder b;
     b.append( "a", elts );
     
     BSONObjSetDefaultOrder keys;
     id().getKeysFromObject( b.done(), keys );
     checkSize( 4, keys );
     BSONObjSetDefaultOrder::iterator i = keys.begin();
     assertEquals( nullObj(), *i++ );
     for ( int j = 1; j < 4; ++i, ++j ) {
         BSONObjBuilder b;
         b.append( "", j );
         assertEquals( b.obj(), *i );
     }
 }
    Status AuthzManagerExternalStateMongos::updatePrivilegeDocument(
            const UserName& user, const BSONObj& updateObj, const BSONObj& writeConcern) {
        try {
            const std::string userNS = "admin.system.users";
            scoped_ptr<ScopedDbConnection> conn(getConnectionForAuthzCollection(userNS));

            conn->get()->update(
                    userNS,
                    QUERY(AuthorizationManager::USER_NAME_FIELD_NAME << user.getUser() <<
                          AuthorizationManager::USER_SOURCE_FIELD_NAME << user.getDB()),
                    updateObj);

            // Handle write concern
            BSONObjBuilder gleBuilder;
            gleBuilder.append("getLastError", 1);
            gleBuilder.appendElements(writeConcern);
            BSONObj res;
            conn->get()->runCommand("admin", gleBuilder.done(), res);
            string err = conn->get()->getLastErrorString(res);
            conn->done();

            if (!err.empty()) {
                return Status(ErrorCodes::UserModificationFailed, err);
            }

            int numUpdated = res["n"].numberInt();
            dassert(numUpdated <= 1 && numUpdated >= 0);
            if (numUpdated == 0) {
                return Status(ErrorCodes::UserNotFound,
                              mongoutils::str::stream() << "User " << user.getFullName() <<
                                      " not found");
            }

            return Status::OK();
        } catch (const DBException& e) {
            return e.toStatus();
        }
    }
        bool run(const string& dbname,
                 BSONObj& cmdObj,
                 int options,
                 string& errmsg,
                 BSONObjBuilder& result,
                 bool fromRepl) {

            bool anyDB = false;
            BSONElement usersFilter;
            Status status = auth::parseAndValidateInfoCommands(cmdObj,
                                                               "usersInfo",
                                                               dbname,
                                                               &anyDB,
                                                               &usersFilter);
            if (!status.isOK()) {
                addStatus(status, result);
                return false;
            }

            BSONObjBuilder queryBuilder;
            queryBuilder.appendAs(usersFilter, "name");
            if (!anyDB) {
                queryBuilder.append("source", dbname);
            }

            BSONArrayBuilder usersArrayBuilder;
            BSONArrayBuilder& (BSONArrayBuilder::* appendBSONObj) (const BSONObj&) =
                    &BSONArrayBuilder::append<BSONObj>;
            const boost::function<void(const BSONObj&)> function =
                    boost::bind(appendBSONObj, &usersArrayBuilder, _1);
            AuthorizationManager* authzManager = getGlobalAuthorizationManager();
            authzManager->queryAuthzDocument(NamespaceString("admin.system.users"),
                                             queryBuilder.done(),
                                             function);

            result.append("users", usersArrayBuilder.arr());
            return true;
        }
    Status AuthzManagerExternalStateMongod::insertPrivilegeDocument(const string& dbname,
                                                                    const BSONObj& userObj,
                                                                    const BSONObj& writeConcern) {
        try {
            const std::string userNS = "admin.system.users";
            DBDirectClient client;
            {
                Client::GodScope gs;
                // TODO(spencer): Once we're no longer fully rebuilding the user cache on every
                // change to user data we should remove the global lock and uncomment the
                // WriteContext below
                Lock::GlobalWrite w;
                // Client::WriteContext ctx(userNS);
                client.insert(userNS, userObj);
            }

            // Handle write concern
            BSONObjBuilder gleBuilder;
            gleBuilder.append("getLastError", 1);
            gleBuilder.appendElements(writeConcern);
            BSONObj res;
            client.runCommand("admin", gleBuilder.done(), res);
            string errstr = client.getLastErrorString(res);
            if (errstr.empty()) {
                return Status::OK();
            }
            if (res.hasField("code") && res["code"].Int() == ASSERT_ID_DUPKEY) {
                std::string name = userObj[AuthorizationManager::USER_NAME_FIELD_NAME].String();
                std::string source = userObj[AuthorizationManager::USER_SOURCE_FIELD_NAME].String();
                return Status(ErrorCodes::DuplicateKey,
                              mongoutils::str::stream() << "User \"" << name << "@" << source <<
                                      "\" already exists");
            }
            return Status(ErrorCodes::UserModificationFailed, errstr);
        } catch (const DBException& e) {
            return e.toStatus();
        }
    }
    Status enterConfigUpgradeCriticalSection(const string& configServer, int currentVersion) {
        BSONObjBuilder setUpgradeStateObj;
        setUpgradeStateObj.append(VersionType::upgradeState(), BSON(inCriticalSectionField(true)));

        try {
            ScopedDbConnection conn(configServer, 30);
            conn->update(VersionType::ConfigNS,
                         BSON("_id" << 1 << VersionType::currentVersion(currentVersion)),
                         BSON("$set" << setUpgradeStateObj.done()));
            _checkGLE(conn);
            conn.done();
        }
        catch (const DBException& e) {

            // No cleanup message here since we're not sure if we wrote or not, and
            // not dangerous either way except to prevent further updates (at which point
            // the message is printed)
            return e.toStatus("could not update version info to enter critical update section");
        }

        log() << "entered critical section for config upgrade" << endl;
        return Status::OK();
    }
LegacyReplyBuilder& LegacyReplyBuilder::setCommandReply(Status nonOKStatus,
                                                        BSONObj extraErrorInfo) {
    invariant(!_haveCommandReply);
    if (nonOKStatus == ErrorCodes::StaleConfig) {
        _staleConfigError = true;

        // Need to use the special $err format for StaleConfig errors to be backwards
        // compatible.
        BSONObjBuilder err;

        // $err must be the first field in object.
        err.append("$err", nonOKStatus.reason());
        err.append("code", nonOKStatus.code());
        auto const scex = nonOKStatus.extraInfo<StaleConfigInfo>();
        scex->serialize(&err);
        err.appendElements(extraErrorInfo);
        setRawCommandReply(err.done());
    } else {
        // All other errors proceed through the normal path, which also handles state transitions.
        ReplyBuilderInterface::setCommandReply(std::move(nonOKStatus), std::move(extraErrorInfo));
    }
    return *this;
}
Status ShardingCatalogManager::_dropSessionsCollection(
    OperationContext* opCtx, std::shared_ptr<RemoteCommandTargeter> targeter) {

    BSONObjBuilder builder;
    builder.append("drop", NamespaceString::kLogicalSessionsNamespace.coll());
    {
        BSONObjBuilder wcBuilder(builder.subobjStart("writeConcern"));
        wcBuilder.append("w", "majority");
    }

    auto swCommandResponse = _runCommandForAddShard(
        opCtx, targeter.get(), NamespaceString::kLogicalSessionsNamespace.db(), builder.done());
    if (!swCommandResponse.isOK()) {
        return swCommandResponse.getStatus();
    }

    auto cmdStatus = std::move(swCommandResponse.getValue().commandStatus);
    if (!cmdStatus.isOK() && cmdStatus.code() != ErrorCodes::NamespaceNotFound) {
        return cmdStatus;
    }

    return Status::OK();
}
Beispiel #21
0
    bool CmdAuthenticate::getUserObj(const string& dbname, const string& user, BSONObj& userObj, string& pwd) {
        if (user == internalSecurity.user) {
            uassert(15889, "key file must be used to log in with internal user", cmdLine.keyFile);
            pwd = internalSecurity.pwd;
        }
        else {
            string systemUsers = dbname + ".system.users";
            {
                Client::ReadContext ctx( systemUsers , dbpath, false );

                BSONObjBuilder b;
                b << "user" << user;
                BSONObj query = b.done();
                if( !Helpers::findOne(systemUsers.c_str(), query, userObj) ) {
                    log() << "auth: couldn't find user " << user << ", " << systemUsers << endl;
                    return false;
                }
            }

            pwd = userObj.getStringField("pwd");
        }
        return true;
    }
Beispiel #22
0
// called into by the web server. For now we just translate the parameters
// to their old style equivalents.
void Command::execCommand(OperationContext* txn,
                          Command* command,
                          const rpc::RequestInterface& request,
                          rpc::ReplyBuilderInterface* replyBuilder) {
    int queryFlags = 0;
    BSONObj cmdObj;

    std::tie(cmdObj, queryFlags) = uassertStatusOK(
                                       rpc::downconvertRequestMetadata(request.getCommandArgs(), request.getMetadata()));

    std::string db = request.getDatabase().rawData();
    BSONObjBuilder result;

    execCommandClientBasic(txn,
                           command,
                           *txn->getClient(),
                           queryFlags,
                           request.getDatabase().rawData(),
                           cmdObj,
                           result);

    replyBuilder->setMetadata(rpc::makeEmptyMetadata()).setCommandReply(result.done());
}
Beispiel #23
0
        bool run(
            const string& db,
            BSONObj& cmdObj,
            int options, string& errmsg,
            BSONObjBuilder& result,
            bool fromRepl = false )
        {
            string coll = cmdObj[ "_changePartitionCreateTime" ].valuestrsafe();
            uassert( 17263, "_changePartitionCreateTime must specify a collection", !coll.empty() );
            string ns = db + "." + coll;
            Collection *cl = getCollection( ns );
            uassert( 17264, "no such collection", cl );
            uassert( 17265, "collection must be partitioned", cl->isPartitioned() );

            // change the create time for a partition at a certain index
            PartitionedCollection* pc = cl->as<PartitionedCollection>();
            uint64_t index = cmdObj["index"].numberLong();
            BSONObj refMeta = pc->getPartitionMetadata(index);
            BSONObjBuilder bbb;
            cloneBSONWithFieldChanged(bbb, refMeta, cmdObj["createTime"]);
            pc->updatePartitionMetadata(index, bbb.done(), false);
            return true;
        }
RecordId MMAPV1DatabaseCatalogEntry::_addNamespaceToNamespaceCollection(OperationContext* txn,
                                                                        StringData ns,
                                                                        const BSONObj* options) {
    if (nsToCollectionSubstring(ns) == "system.namespaces") {
        // system.namespaces holds all the others, so it is not explicitly listed in the catalog.
        return {};
    }

    BSONObjBuilder b;
    b.append("name", ns);
    if (options && !options->isEmpty()) {
        b.append("options", *options);
    }

    const BSONObj obj = b.done();

    RecordStoreV1Base* rs = _getNamespaceRecordStore();
    invariant(rs);

    StatusWith<RecordId> loc = rs->insertRecord(txn, obj.objdata(), obj.objsize(), false);
    massertStatusOK(loc.getStatus());
    return loc.getValue();
}
Beispiel #25
0
StatusWith<LegacyCommandAndFlags> downconvertRequestMetadata(BSONObj cmdObj, BSONObj metadata) {
    int legacyQueryFlags = 0;
    BSONObjBuilder auditCommandBob;
    // Ordering is important here - AuditingMetadata must be downconverted first,
    // then ServerSelectionMetadata.
    auto downconvertStatus =
        AuditMetadata::downconvert(cmdObj, metadata, &auditCommandBob, &legacyQueryFlags);

    if (!downconvertStatus.isOK()) {
        return downconvertStatus;
    }


    BSONObjBuilder ssmCommandBob;
    downconvertStatus = ServerSelectionMetadata::downconvert(
        auditCommandBob.done(), metadata, &ssmCommandBob, &legacyQueryFlags);
    if (!downconvertStatus.isOK()) {
        return downconvertStatus;
    }


    return std::make_tuple(ssmCommandBob.obj(), std::move(legacyQueryFlags));
}
Beispiel #26
0
    // TODO: Move this and the other command stuff in newRunQuery outta here and up a level.
    static bool runCommands(const char *ns,
                            BSONObj& jsobj,
                            CurOp& curop,
                            BufBuilder &b,
                            BSONObjBuilder& anObjBuilder,
                            bool fromRepl,
                            int queryOptions) {
        try {
            return _runCommands(ns, jsobj, b, anObjBuilder, fromRepl, queryOptions);
        }
        catch( SendStaleConfigException& ){
            throw;
        }
        catch ( AssertionException& e ) {
            verify( e.getCode() != SendStaleConfigCode && e.getCode() != RecvStaleConfigCode );

            Command::appendCommandStatus(anObjBuilder, e.toStatus());
            curop.debug().exceptionInfo = e.getInfo();
        }
        BSONObj x = anObjBuilder.done();
        b.appendBuf((void*) x.objdata(), x.objsize());
        return true;
    }
Beispiel #27
0
    bool CmdAuthenticate::getUserObj(const string& dbname, const string& user, BSONObj& userObj, string& pwd) {
        if (user == internalSecurity.user) {
            uassert(15889, "key file must be used to log in with internal user", cmdLine.keyFile);
            pwd = internalSecurity.pwd;
        }
        else {
            // static BSONObj userPattern = fromjson("{\"user\":1}");
            string systemUsers = dbname + ".system.users";
            // OCCASIONALLY Helpers::ensureIndex(systemUsers.c_str(), userPattern, false, "user_1");
            {
                BSONObjBuilder b;
                b << "user" << user;
                BSONObj query = b.done();
                if( !Helpers::findOne(systemUsers.c_str(), query, userObj) ) {
                    log() << "auth: couldn't find user " << user << ", " << systemUsers << endl;
                    return false;
                }
            }

            pwd = userObj.getStringField("pwd");
        }
        return true;
    }
    Status AuthzManagerExternalStateMongos::dropIndexes(
            const NamespaceString& collectionName,
            const BSONObj& writeConcern) {

        scoped_ptr<ScopedDbConnection> conn(getConnectionForAuthzCollection(collectionName));
        try {
            conn->get()->dropIndexes(collectionName.ns());
            BSONObjBuilder gleBuilder;
            gleBuilder.append("getLastError", 1);
            gleBuilder.appendElements(writeConcern);
            BSONObj res;
            conn->get()->runCommand("admin", gleBuilder.done(), res);
            string errstr = conn->get()->getLastErrorString(res);
            if (!errstr.empty()) {
                conn->done();
                return Status(ErrorCodes::UnknownError, errstr);
            }
            conn->done();
            return Status::OK();
        }
        catch (const DBException& ex) {
            return ex.toStatus();
        }
    }
StatusWith<long long> CatalogManagerReplicaSet::_runCountCommandOnConfig(OperationContext* txn,
                                                                         const NamespaceString& ns,
                                                                         BSONObj query) {
    BSONObjBuilder countBuilder;
    countBuilder.append("count", ns.coll());
    countBuilder.append("query", query);
    _appendReadConcern(&countBuilder);

    BSONObjBuilder resultBuilder;
    if (!_runReadCommand(
            txn, ns.db().toString(), countBuilder.done(), kConfigReadSelector, &resultBuilder)) {
        return Command::getStatusFromCommandResult(resultBuilder.obj());
    }

    auto responseObj = resultBuilder.obj();

    long long result;
    auto status = bsonExtractIntegerField(responseObj, "n", &result);
    if (!status.isOK()) {
        return status;
    }

    return result;
}
Beispiel #30
0
    /* 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;
    }