BSONArray MongoVersionRange::toBSONArray(const vector<MongoVersionRange>& ranges) {

        BSONArrayBuilder barr;

        for (vector<MongoVersionRange>::const_iterator it = ranges.begin(); it != ranges.end();
                ++it)
        {
            const MongoVersionRange& range = *it;
            range.toBSONElement(&barr);
        }

        return barr.arr();
    }
Example #2
0
    void Pipeline::writeExplainShard(
        BSONObjBuilder &result,
        const intrusive_ptr<DocumentSource> &pInputSource) const {
        BSONArrayBuilder opArray; // where we'll put the pipeline ops

        // first the cursor, which isn't in the opArray
        pInputSource->addToBsonArray(&opArray, true);

        // next, add the pipeline operators
        writeExplainOps(&opArray);

        result.appendArray(serverPipelineName, opArray.arr());
    }
Example #3
0
    static void handleCursorCommand(CursorId id, BSONObj& cmdObj, BSONObjBuilder& result) {
        BSONElement batchSizeElem = cmdObj.getFieldDotted("cursor.batchSize");
        const long long batchSize = batchSizeElem.isNumber()
                                    ? batchSizeElem.numberLong()
                                    : 101; // same as query

        // Using limited cursor API that ignores many edge cases. Should be sufficient for commands.
        ClientCursor::Pin pin(id);
        ClientCursor* cursor = pin.c();

        massert(16958, "Cursor shouldn't have been deleted",
                cursor);

        // Make sure this cursor won't disappear on us
        fassert(16959, !cursor->c()->shouldDestroyOnNSDeletion());
        fassert(16960, !cursor->c()->requiresLock());

        try {
            // can't use result BSONObjBuilder directly since it won't handle exceptions correctly.
            BSONArrayBuilder resultsArray;
            const int byteLimit = MaxBytesToReturnToClientAtOnce;
            for (int objs = 0;
                    objs < batchSize && cursor->ok() && resultsArray.len() <= byteLimit;
                    objs++) {
                // TODO may need special logic if cursor->current() would cause results to be > 16MB
                resultsArray.append(cursor->current());
                cursor->advance();
            }

            // The initial ok() on a cursor may be very expensive so we don't do it when batchSize
            // is 0 since that indicates a desire for a fast return.
            if (batchSize != 0 && !cursor->ok()) {
                // There is no more data. Kill the cursor.
                pin.release();
                ClientCursor::erase(id);
                id = 0;
            }

            BSONObjBuilder cursorObj(result.subobjStart("cursor"));
            cursorObj.append("id", id);
            cursorObj.append("ns", cursor->ns());
            cursorObj.append("firstBatch", resultsArray.arr());
            cursorObj.done();
        }
        catch (...) {
            // Clean up cursor on way out of scope.
            pin.release();
            ClientCursor::erase(id);
            throw;
        }
    }
Example #4
0
StatusWith<LocksType> DistLockCatalogImpl::overtakeLock(OperationContext* opCtx,
                                                        StringData lockID,
                                                        const OID& lockSessionID,
                                                        const OID& currentHolderTS,
                                                        StringData who,
                                                        StringData processId,
                                                        Date_t time,
                                                        StringData why) {
    BSONArrayBuilder orQueryBuilder;
    orQueryBuilder.append(
        BSON(LocksType::name() << lockID << LocksType::state(LocksType::UNLOCKED)));
    orQueryBuilder.append(BSON(LocksType::name() << lockID << LocksType::lockID(currentHolderTS)));

    BSONObj newLockDetails(BSON(
        LocksType::lockID(lockSessionID) << LocksType::state(LocksType::LOCKED) << LocksType::who()
                                         << who
                                         << LocksType::process()
                                         << processId
                                         << LocksType::when(time)
                                         << LocksType::why()
                                         << why));

    auto request = FindAndModifyRequest::makeUpdate(
        _locksNS, BSON("$or" << orQueryBuilder.arr()), BSON("$set" << newLockDetails));
    request.setShouldReturnNew(true);
    request.setWriteConcern(kMajorityWriteConcern);

    auto const shardRegistry = Grid::get(opCtx)->shardRegistry();
    auto resultStatus = shardRegistry->getConfigShard()->runCommandWithFixedRetryAttempts(
        opCtx,
        ReadPreferenceSetting{ReadPreference::PrimaryOnly},
        _locksNS.db().toString(),
        request.toBSON(),
        Shard::kDefaultConfigCommandTimeout,
        Shard::RetryPolicy::kNotIdempotent);

    auto findAndModifyStatus = extractFindAndModifyNewObj(std::move(resultStatus));
    if (!findAndModifyStatus.isOK()) {
        return findAndModifyStatus.getStatus();
    }

    BSONObj doc = findAndModifyStatus.getValue();
    auto locksTypeResult = LocksType::fromBSON(doc);
    if (!locksTypeResult.isOK()) {
        return {ErrorCodes::FailedToParse,
                str::stream() << "failed to parse: " << doc << " : "
                              << locksTypeResult.getStatus().toString()};
    }

    return locksTypeResult.getValue();
}
/* ****************************************************************************
*
* ContextAttribute::valueBson -
*
* Used to render attribute value to BSON, appended into the bsonAttr builder
*/
void ContextAttribute::valueBson(BSONObjBuilder& bsonAttr, const std::string& attrType, bool autocast, bool strings2numbers) const
{
  if (compoundValueP == NULL)
  {
    bsonAppendAttrValue(bsonAttr, attrType, autocast);
  }
  else
  {
    if (compoundValueP->valueType == ValueTypeVector)
    {
      BSONArrayBuilder b;
      compoundValueBson(compoundValueP->childV, b, strings2numbers);
      bsonAttr.append(ENT_ATTRS_VALUE, b.arr());
    }
    else if (compoundValueP->valueType == ValueTypeObject)
    {
      BSONObjBuilder b;

      compoundValueBson(compoundValueP->childV, b, strings2numbers);
      bsonAttr.append(ENT_ATTRS_VALUE, b.obj());
    }
    else if (compoundValueP->valueType == ValueTypeString)
    {
      // FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271
      bsonAttr.append(ENT_ATTRS_VALUE, compoundValueP->stringValue);
    }
    else if (compoundValueP->valueType == ValueTypeNumber)
    {
      // FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271
      bsonAttr.append(ENT_ATTRS_VALUE, compoundValueP->numberValue);
    }
    else if (compoundValueP->valueType == ValueTypeBoolean)
    {
      // FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271
      bsonAttr.append(ENT_ATTRS_VALUE, compoundValueP->boolValue);
    }
    else if (compoundValueP->valueType == ValueTypeNull)
    {
      // FIXME P4: this is somehow redundant. See https://github.com/telefonicaid/fiware-orion/issues/271
      bsonAttr.appendNull(ENT_ATTRS_VALUE);
    }
    else if (compoundValueP->valueType == ValueTypeNotGiven)
    {
      LM_E(("Runtime Error (value not given in compound value)"));
    }
    else
    {
      LM_E(("Runtime Error (Unknown type in compound value)"));
    }
  }
}
Example #6
0
 void run() {
     ShardKeyPattern shardKeyPattern(shardKey());
     ChunkManager chunkManager("", shardKeyPattern, false);
     chunkManager.setSingleChunkForShards( splitPointsVector() );
     
     set<Shard> shards;
     chunkManager.getShardsForQuery( shards, query() );
     
     BSONArrayBuilder b;
     for( set<Shard>::const_iterator i = shards.begin(); i != shards.end(); ++i ) {
         b << i->getName();
     }
     ASSERT_EQUALS( expectedShardNames(), b.arr() );
 }
Example #7
0
    bool Pipeline::run(BSONObjBuilder &result, string &errmsg,
                       const intrusive_ptr<DocumentSource> &pInputSource) {
        /* chain together the sources we found */
        DocumentSource *pSource = pInputSource.get();
        for(SourceVector::iterator iter(sourceVector.begin()),
                listEnd(sourceVector.end()); iter != listEnd; ++iter) {
            intrusive_ptr<DocumentSource> pTemp(*iter);
            pTemp->setSource(pSource);
            pSource = pTemp.get();
        }
        /* pSource is left pointing at the last source in the chain */

        /*
          Iterate through the resulting documents, and add them to the result.
          We do this even if we're doing an explain, in order to capture
          the document counts and other stats.  However, we don't capture
          the result documents for explain.
        */
        if (explain) {
            if (!pCtx->getInRouter())
                writeExplainShard(result, pInputSource);
            else {
                writeExplainMongos(result, pInputSource);
            }
        }
        else {
            // the array in which the aggregation results reside
            // cant use subArrayStart() due to error handling
            BSONArrayBuilder resultArray;
            for(bool hasDoc = !pSource->eof(); hasDoc; hasDoc = pSource->advance()) {
                intrusive_ptr<Document> pDocument(pSource->getCurrent());

                /* add the document to the result set */
                BSONObjBuilder documentBuilder (resultArray.subobjStart());
                pDocument->toBson(&documentBuilder);
                documentBuilder.doneFast();
                // object will be too large, assert. the extra 1KB is for headers
                uassert(16389,
                        str::stream() << "aggregation result exceeds maximum document size ("
                                      << BSONObjMaxUserSize / (1024 * 1024) << "MB)",
                        resultArray.len() < BSONObjMaxUserSize - 1024);
            }

            resultArray.done();
            result.appendArray("result", resultArray.arr());
        }

    return true;
    }
BSONObj ls(const BSONObj& args, void* data) {
    BSONArrayBuilder ret;
    BSONObj o = listFiles(args, data);
    if (!o.isEmpty()) {
        for (BSONObj::iterator i = o.firstElement().Obj().begin(); i.more();) {
            BSONObj f = i.next().Obj();
            string name = f["name"].String();
            if (f["isDirectory"].trueValue()) {
                name += '/';
            }
            ret << name;
        }
    }
    return BSON("" << ret.arr());
}
Example #9
0
 BSONObj rtnCoordDelete::_buildNewDeletor( const BSONObj &deletor,
                                           const CoordSubCLlist &subCLList )
 {
    BSONObjBuilder builder ;
    BSONArrayBuilder babSubCL ;
    CoordSubCLlist::const_iterator iterCL = subCLList.begin();
    while( iterCL != subCLList.end() )
    {
       babSubCL.append( *iterCL ) ;
       ++iterCL ;
    }
    builder.appendElements( deletor ) ;
    builder.appendArray( CAT_SUBCL_NAME, babSubCL.arr() ) ;
    return builder.obj() ;
 }
Example #10
0
        bool run(OperationContext* txn,
                 const string& dbname,
                 BSONObj& cmdObj,
                 int,
                 string& errmsg,
                 BSONObjBuilder& result,
                 bool /*fromRepl*/) {

            BSONElement first = cmdObj.firstElement();
            uassert(
                28528,
                str::stream() << "Argument to listIndexes must be of type String, not "
                              << typeName(first.type()),
                first.type() == String);
            const NamespaceString ns(parseNs(dbname, cmdObj));
            uassert(
                28529,
                str::stream() << "Argument to listIndexes must be a collection name, "
                              << "not the empty string",
                !ns.coll().empty());

            AutoGetCollectionForRead autoColl(txn, ns);
            if (!autoColl.getDb()) {
                return appendCommandStatus( result, Status( ErrorCodes::NamespaceNotFound,
                                                            "no database" ) );
            }

            const Collection* collection = autoColl.getCollection();
            if (!collection) {
                return appendCommandStatus( result, Status( ErrorCodes::NamespaceNotFound,
                                                            "no collection" ) );
            }

            const CollectionCatalogEntry* cce = collection->getCatalogEntry();
            invariant(cce);

            vector<string> indexNames;
            cce->getAllIndexes( txn, &indexNames );

            BSONArrayBuilder arr;
            for ( size_t i = 0; i < indexNames.size(); i++ ) {
                arr.append( cce->getIndexSpec( txn, indexNames[i] ) );
            }

            result.append( "indexes", arr.arr() );

            return true;
        }
Example #11
0
        virtual bool run(OperationContext* txn,
                         const string& dbname,
                         BSONObj& cmdObj,
                         int,
                         string& errmsg,
                         BSONObjBuilder& result) {

            boost::optional<DisableDocumentValidation> maybeDisableValidation;
            if (shouldBypassDocumentValidationforCommand(cmdObj))
                maybeDisableValidation.emplace(txn);

            string from = cmdObj.getStringField("clone");
            if ( from.empty() )
                return false;

            CloneOptions opts;
            opts.fromDB = dbname;
            opts.slaveOk = cmdObj["slaveOk"].trueValue();

            // See if there's any collections we should ignore
            if( cmdObj["collsToIgnore"].type() == Array ){
                BSONObjIterator it( cmdObj["collsToIgnore"].Obj() );

                while( it.more() ){
                    BSONElement e = it.next();
                    if( e.type() == String ){
                        opts.collsToIgnore.insert( e.String() );
                    }
                }
            }

            set<string> clonedColls;

            ScopedTransaction transaction(txn, MODE_IX);
            Lock::DBLock dbXLock(txn->lockState(), dbname, MODE_X);

            Cloner cloner;
            bool rval = cloner.go(txn, dbname, from, opts, &clonedColls, errmsg);

            BSONArrayBuilder barr;
            barr.append( clonedColls );

            result.append( "clonedColls", barr.arr() );

            return rval;

        }
Example #12
0
    bo ReplSetConfig::asBson() const {
        bob b;
        b.append("_id", _id).append("version", version);

        BSONArrayBuilder a;
        for( unsigned i = 0; i < members.size(); i++ )
            a.append( members[i].asBson() );
        b.append("members", a.arr());

        BSONObjBuilder settings;
        bool empty = true;

        if (!rules.empty()) {
            bob modes;
            for (map<string,TagRule*>::const_iterator it = rules.begin(); it != rules.end(); it++) {
                bob clauses;
                vector<TagClause*> r = (*it).second->clauses;
                for (vector<TagClause*>::iterator it2 = r.begin(); it2 < r.end(); it2++) {
                    clauses << (*it2)->name << (*it2)->target;
                }
                modes << (*it).first << clauses.obj();
            }
            settings << "getLastErrorModes" << modes.obj();
            empty = false;
        }

        if (!getLastErrorDefaults.isEmpty()) {
            settings << "getLastErrorDefaults" << getLastErrorDefaults;
            empty = false;
        }

        if (_heartbeatTimeout != DEFAULT_HB_TIMEOUT) {
            settings << "heartbeatTimeoutSecs" << _heartbeatTimeout;
            empty = false;
        }

        if (!_chainingAllowed) {
            settings << "chainingAllowed" << _chainingAllowed;
            empty = false;
        }

        if (!empty) {
            b << "settings" << settings.obj();
        }

        return b.obj();
    }
void SASLServerMechanismRegistry::advertiseMechanismNamesForUser(OperationContext* opCtx,
                                                                 const BSONObj& isMasterCmd,
                                                                 BSONObjBuilder* builder) {
    BSONElement saslSupportedMechs = isMasterCmd["saslSupportedMechs"];
    if (saslSupportedMechs.type() == BSONType::String) {

        const auto userName = uassertStatusOK(UserName::parse(saslSupportedMechs.String()));

        AuthorizationManager* authManager = AuthorizationManager::get(opCtx->getServiceContext());

        UserHandle user;
        const auto swUser = authManager->acquireUser(opCtx, userName);
        if (!swUser.isOK()) {
            auto& status = swUser.getStatus();
            if (status.code() == ErrorCodes::UserNotFound) {
                log() << "Supported SASL mechanisms requested for unknown user '" << userName
                      << "'";
                return;
            }
            uassertStatusOK(status);
        }

        user = std::move(swUser.getValue());
        BSONArrayBuilder mechanismsBuilder;
        const auto& mechList = _getMapRef(userName.getDB());

        for (const auto& factoryIt : mechList) {
            SecurityPropertySet properties = factoryIt->properties();
            if (!properties.hasAllProperties(SecurityPropertySet{SecurityProperty::kNoPlainText,
                                                                 SecurityProperty::kMutualAuth}) &&
                userName.getDB() != "$external") {
                continue;
            }

            auto mechanismEnabled = _mechanismSupportedByConfig(factoryIt->mechanismName());
            if (!mechanismEnabled && userName == internalSecurity.user->getName()) {
                mechanismEnabled = factoryIt->isInternalAuthMech();
            }

            if (mechanismEnabled && factoryIt->canMakeMechanismForUser(user.get())) {
                mechanismsBuilder << factoryIt->mechanismName();
            }
        }

        builder->appendArray("saslSupportedMechs", mechanismsBuilder.arr());
    }
}
StatusWith<LocksType> DistLockCatalogImpl::overtakeLock(StringData lockID,
                                                        const OID& lockSessionID,
                                                        const OID& currentHolderTS,
                                                        StringData who,
                                                        StringData processId,
                                                        Date_t time,
                                                        StringData why) {
    BSONArrayBuilder orQueryBuilder;
    orQueryBuilder.append(
        BSON(LocksType::name() << lockID << LocksType::state(LocksType::UNLOCKED)));
    orQueryBuilder.append(BSON(LocksType::name() << lockID << LocksType::lockID(currentHolderTS)));

    BSONObj newLockDetails(BSON(LocksType::lockID(lockSessionID)
                                << LocksType::state(LocksType::LOCKED) << LocksType::who() << who
                                << LocksType::process() << processId << LocksType::when(time)
                                << LocksType::why() << why));

    auto request = FindAndModifyRequest::makeUpdate(
        _locksNS, BSON("$or" << orQueryBuilder.arr()), BSON("$set" << newLockDetails));
    request.setShouldReturnNew(true);
    request.setWriteConcern(_writeConcern);

    auto resultStatus = _client->runCommandWithNotMasterRetries(
        "config", _locksNS.db().toString(), request.toBSON());

    if (!resultStatus.isOK()) {
        return resultStatus.getStatus();
    }

    BSONObj responseObj(resultStatus.getValue());

    auto findAndModifyStatus = extractFindAndModifyNewObj(responseObj);
    if (!findAndModifyStatus.isOK()) {
        return findAndModifyStatus.getStatus();
    }

    BSONObj doc = findAndModifyStatus.getValue();
    auto locksTypeResult = LocksType::fromBSON(doc);
    if (!locksTypeResult.isOK()) {
        return {ErrorCodes::FailedToParse,
                str::stream() << "failed to parse: " << doc << " : "
                              << locksTypeResult.getStatus().toString()};
    }

    return locksTypeResult.getValue();
}
Example #15
0
// SERVER-15899: test iteration using a path that generates no elements, but traverses a long
// array containing subdocuments with nested arrays.
TEST(Path, NonMatchingLongArrayOfSubdocumentsWithNestedArrays) {
    ElementPath p;
    ASSERT(p.init("a.b.x").isOK());

    // Build the document {a: [{b: []}, {b: []}, {b: []}, ...]}.
    BSONObj subdoc = BSON("b" << BSONArray());
    BSONArrayBuilder builder;
    for (int i = 0; i < 100 * 1000; ++i) {
        builder.append(subdoc);
    }
    BSONObj doc = BSON("a" << builder.arr());

    BSONElementIterator cursor(&p, doc);

    // The path "a.b.x" matches no elements.
    ASSERT(!cursor.more());
}
Example #16
0
BSONArray buildOpPrecond(const string& ns,
                         const string& shardName,
                         const ChunkVersion& shardVersion) {
    BSONArrayBuilder preCond;
    BSONObjBuilder condB;
    condB.append("ns", ChunkType::ConfigNS);
    condB.append("q",
                 BSON("query" << BSON(ChunkType::ns(ns)) << "orderby"
                              << BSON(ChunkType::DEPRECATED_lastmod() << -1)));
    {
        BSONObjBuilder resB(condB.subobjStart("res"));
        shardVersion.addToBSON(resB, ChunkType::DEPRECATED_lastmod());
        resB.done();
    }
    preCond.append(condB.obj());
    return preCond.arr();
}
Example #17
0
    void Projection::transform( const BSONObj& in , BSONObjBuilder& b, const MatchDetails* details ) const {
        const ArrayOpType& arrayOpType = getArrayOpType();

        BSONObjIterator i(in);
        while ( i.more() ) {
            BSONElement e = i.next();
            if ( mongoutils::str::equals( "_id" , e.fieldName() ) ) {
                if ( _includeID )
                    b.append( e );
            }
            else {
                Matchers::const_iterator matcher = _matchers.find( e.fieldName() );
                if ( matcher == _matchers.end() ) {
                    // no array projection matchers for this field
                    append( b, e, details, arrayOpType );
                } else {
                    // field has array projection with $elemMatch specified.
                    massert( 16348, "matchers are only supported for $elemMatch", 
                             arrayOpType == ARRAY_OP_ELEM_MATCH );
                    MatchDetails arrayDetails;
                    arrayDetails.requestElemMatchKey();
                    if ( matcher->second->matches( in, &arrayDetails ) ) {
                        LOG(4) << "Matched array on field: " << matcher->first  << endl
                               << " from array: " << in.getField( matcher->first ) << endl
                               << " in object: " << in << endl
                               << " at position: " << arrayDetails.elemMatchKey() << endl;
                        FieldMap::const_iterator field = _fields.find( e.fieldName()  );
                        massert( 16349, "$elemMatch specified, but projection field not found.",
                            field != _fields.end() );
                        BSONArrayBuilder a;
                        BSONObjBuilder o;
                        massert( 16350, "$elemMatch called on document element with eoo",
                                 ! in.getField( e.fieldName() ).eoo() );
                        massert( 16351, "$elemMatch called on array element with eoo",
                                 ! in.getField( e.fieldName() ).Obj().getField(
                                        arrayDetails.elemMatchKey() ).eoo() );
                        a.append( in.getField( e.fieldName() ).Obj()
                                    .getField( arrayDetails.elemMatchKey() ) );
                        o.appendArray( matcher->first, a.arr() );
                        append( b, o.done().firstElement(), details, arrayOpType );
                    }
                }
            }
        }
    }
Example #18
0
BSONArray storageEngineList() {
    if (!hasGlobalServiceContext())
        return BSONArray();

    std::unique_ptr<StorageFactoriesIterator> sfi(
        getGlobalServiceContext()->makeStorageFactoriesIterator());

    if (!sfi)
        return BSONArray();

    BSONArrayBuilder engineArrayBuilder;

    while (sfi->more()) {
        engineArrayBuilder.append(sfi->next()->getCanonicalName());
    }

    return engineArrayBuilder.arr();
}
Example #19
0
    BSONArray storageEngineList() {
        if (!hasGlobalEnvironment())
            return BSONArray();

        boost::scoped_ptr<StorageFactoriesIterator> sfi(
            getGlobalEnvironment()->makeStorageFactoriesIterator());

        if (!sfi)
            return BSONArray();

        BSONArrayBuilder engineArrayBuilder;

        while (sfi->more()) {
            engineArrayBuilder.append(sfi->next()->getCanonicalName());
        }

        return engineArrayBuilder.arr();
    }
/* ****************************************************************************
*
* compoundValueBson (for objects) -
*/
void compoundValueBson(std::vector<orion::CompoundValueNode*> children, BSONObjBuilder& b)
{
  for (unsigned int ix = 0; ix < children.size(); ++ix)
  {
    orion::CompoundValueNode* child = children[ix];

    std::string effectiveName = dbDotEncode(child->name);

    if (child->valueType == ValueTypeString)
    {
      b.append(effectiveName, child->stringValue);
    }
    else if (child->valueType == ValueTypeNumber)
    {
      b.append(effectiveName, child->numberValue);
    }
    else if (child->valueType == ValueTypeBoolean)
    {
      b.append(effectiveName, child->boolValue);
    }
    else if (child->valueType == ValueTypeNone)
    {
      b.appendNull(effectiveName);
    }
    else if (child->valueType == ValueTypeVector)
    {
      BSONArrayBuilder ba;

      compoundValueBson(child->childV, ba);
      b.append(effectiveName, ba.arr());
    }
    else if (child->valueType == ValueTypeObject)
    {
      BSONObjBuilder bo;

      compoundValueBson(child->childV, bo);
      b.append(effectiveName, bo.obj());
    }
    else
    {
      LM_E(("Runtime Error (Unknown type in compound value)"));
    }
  }
}
Example #21
0
        bool run(OperationContext* txn,
                 const string& dbname,
                 BSONObj& jsobj,
                 int,
                 string& errmsg,
                 BSONObjBuilder& result,
                 bool /*fromRepl*/) {

            Lock::DBRead lk( txn->lockState(), dbname );

            const Database* d = dbHolder().get( txn, dbname );
            const DatabaseCatalogEntry* dbEntry = NULL;

            list<string> names;
            if ( d ) {
                dbEntry = d->getDatabaseCatalogEntry();
                dbEntry->getCollectionNamespaces( &names );
                names.sort();
            }

            BSONArrayBuilder arr;

            for ( list<string>::const_iterator i = names.begin(); i != names.end(); ++i ) {
                string ns = *i;

                StringData collection = nsToCollectionSubstring( ns );
                if ( collection == "system.namespaces" ) {
                    continue;
                }

                BSONObjBuilder b;
                b.append( "name", collection );

                CollectionOptions options =
                    dbEntry->getCollectionCatalogEntry( txn, ns )->getCollectionOptions(txn);
                b.append( "options", options.toBSON() );

                arr.append( b.obj() );
            }

            result.append( "collections", arr.arr() );

            return true;
        }
Example #22
0
    BSONObj IndexBounds::toBSON() const {
        BSONObjBuilder builder;
        if (isSimpleRange) {
            // TODO
        }
        else {
            for (vector<OrderedIntervalList>::const_iterator itField = fields.begin();
                 itField != fields.end();
                 ++itField) {
                BSONArrayBuilder fieldBuilder(builder.subarrayStart(itField->name));
                for (vector<Interval>::const_iterator itInterval = itField->intervals.begin();
                     itInterval != itField->intervals.end();
                     ++itInterval) {
                    BSONArrayBuilder intervalBuilder;

                    // Careful to output $minElement/$maxElement if we don't have bounds.
                    if (itInterval->start.eoo()) {
                        BSONObjBuilder minBuilder;
                        minBuilder.appendMinKey("");
                        BSONObj minKeyObj = minBuilder.obj();
                        intervalBuilder.append(minKeyObj.firstElement());
                    }
                    else {
                        intervalBuilder.append(itInterval->start);
                    }

                    if (itInterval->end.eoo()) {
                        BSONObjBuilder maxBuilder;
                        maxBuilder.appendMaxKey("");
                        BSONObj maxKeyObj = maxBuilder.obj();
                        intervalBuilder.append(maxKeyObj.firstElement());
                    }
                    else {
                        intervalBuilder.append(itInterval->end);
                    }

                    fieldBuilder.append(
                        static_cast<BSONArray>(intervalBuilder.arr().clientReadable()));
                }
            }
        }
        return builder.obj();
    }
Example #23
0
 // elements is a non-geo field.  Add the values literally, expanding arrays.
 void getLiteralKeys(const BSONElementSet &elements, BSONObjSet *out) const {
     if (0 == elements.size()) {
         BSONObjBuilder b;
         b.appendNull("");
         out->insert(b.obj());
     } else if (1 == elements.size()) {
         BSONObjBuilder b;
         b.appendAs(*elements.begin(), "");
         out->insert(b.obj());
     } else {
         BSONArrayBuilder aBuilder;
         for (BSONElementSet::iterator i = elements.begin(); i != elements.end(); ++i) {
             aBuilder.append(*i);
         }
         BSONObjBuilder b;
         b.append("", aBuilder.arr());
         out->insert(b.obj());
     }
 }
Example #24
0
    bo ReplSetConfig::asBson() const {
        bob b;
        b.append("_id", _id).append("version", version);
        if( !ho.isDefault() || !getLastErrorDefaults.isEmpty() ) {
            bob settings;
            if( !ho.isDefault() )
                settings << "heartbeatConnRetries " << ho.heartbeatConnRetries  <<
                         "heartbeatSleep" << ho.heartbeatSleepMillis / 1000.0 <<
                         "heartbeatTimeout" << ho.heartbeatTimeoutMillis / 1000.0;
            if( !getLastErrorDefaults.isEmpty() )
                settings << "getLastErrorDefaults" << getLastErrorDefaults;
            b << "settings" << settings.obj();
        }

        BSONArrayBuilder a;
        for( unsigned i = 0; i < members.size(); i++ )
            a.append( members[i].asBson() );
        b.append("members", a.arr());

        return b.obj();
    }
Example #25
0
void NetworkTestEnv::onFindCommand(OnFindCommandFunction func) {
    onCommand([&func](const RemoteCommandRequest& request) -> StatusWith<BSONObj> {
        const auto& resultStatus = func(request);

        if (!resultStatus.isOK()) {
            return resultStatus.getStatus();
        }

        BSONArrayBuilder arr;
        for (const auto& obj : resultStatus.getValue()) {
            arr.append(obj);
        }

        const NamespaceString nss =
            NamespaceString(request.dbname, request.cmdObj.firstElement().String());
        BSONObjBuilder result;
        appendCursorResponseObject(0LL, nss.toString(), arr.arr(), &result);

        return result.obj();
    });
}
Example #26
0
TEST_F(ViewCatalogFixture, CreateViewWithPipelineExceedingMaxSize) {
    BSONArrayBuilder builder;

    int objsize = BSON("$match" << BSON("x"
                                        << "foo"))
                      .objsize();

    int pipelineSize = 0;

    for (; pipelineSize < ViewGraph::kMaxViewPipelineSizeBytes + 1; pipelineSize += objsize) {
        builder << BSON("$match" << BSON("x"
                                         << "foo"));
    }

    const NamespaceString viewName("db.view");
    const NamespaceString viewOn("db.coll");
    const BSONObj collation;

    auto pipeline = builder.arr();

    ASSERT_NOT_OK(viewCatalog.createView(opCtx.get(), viewName, viewOn, pipeline, collation));
}
TEST(QueryTest, ReadPreferenceTagSets) {
    Query q("{}");
    BSONObj tag_set1 = BSON("datacenter"
                            << "nyc");
    BSONObj tag_set2 = BSON("awesome"
                            << "yeah");
    BSONObjBuilder bob;
    BSONArrayBuilder bab;
    bab.append(tag_set1);
    bab.append(tag_set2);
    q.readPref(mongo::ReadPreference_SecondaryOnly, bab.arr());
    ASSERT_TRUE(q.obj.hasField(Query::ReadPrefField.name()));

    BSONElement read_pref_elem = q.obj[Query::ReadPrefField.name()];
    ASSERT_TRUE(read_pref_elem.isABSONObj());
    BSONObj read_pref_obj = read_pref_elem.Obj();
    ASSERT_EQUALS(read_pref_obj[Query::ReadPrefModeField.name()].String(), "secondary");
    ASSERT_TRUE(read_pref_obj.hasField(Query::ReadPrefTagsField.name()));
    vector<BSONElement> tag_sets = read_pref_obj[Query::ReadPrefTagsField.name()].Array();
    ASSERT_EQUALS(tag_sets[0].Obj(), tag_set1);
    ASSERT_EQUALS(tag_sets[1].Obj(), tag_set2);
}
Example #28
0
        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;
        }
    BSONObj generateSection(OperationContext* txn, const BSONElement& configElement) const {
        RangeDeleter* deleter = getDeleter();
        if (!deleter) {
            return BSONObj();
        }

        BSONObjBuilder result;

        OwnedPointerVector<DeleteJobStats> statsList;
        deleter->getStatsHistory(&statsList.mutableVector());
        BSONArrayBuilder oldStatsBuilder;
        for (OwnedPointerVector<DeleteJobStats>::const_iterator it = statsList.begin();
             it != statsList.end();
             ++it) {
            BSONObjBuilder entryBuilder;
            entryBuilder.append("deletedDocs", (*it)->deletedDocCount);

            if ((*it)->queueEndTS > Date_t()) {
                entryBuilder.append("queueStart", (*it)->queueStartTS);
                entryBuilder.append("queueEnd", (*it)->queueEndTS);
            }

            if ((*it)->deleteEndTS > Date_t()) {
                entryBuilder.append("deleteStart", (*it)->deleteStartTS);
                entryBuilder.append("deleteEnd", (*it)->deleteEndTS);

                if ((*it)->waitForReplEndTS > Date_t()) {
                    entryBuilder.append("waitForReplStart", (*it)->waitForReplStartTS);
                    entryBuilder.append("waitForReplEnd", (*it)->waitForReplEndTS);
                }
            }

            oldStatsBuilder.append(entryBuilder.obj());
        }
        result.append("lastDeleteStats", oldStatsBuilder.arr());

        return result.obj();
    }
Example #30
0
void Pipeline::run(BSONObjBuilder& result) {
    // We should not get here in the explain case.
    verify(!pCtx->isExplain);

    // the array in which the aggregation results reside
    // cant use subArrayStart() due to error handling
    BSONArrayBuilder resultArray;
    while (auto next = getNext()) {
        // Add the document to the result set.
        BSONObjBuilder documentBuilder(resultArray.subobjStart());
        next->toBson(&documentBuilder);
        documentBuilder.doneFast();
        // Object will be too large, assert. The extra 1KB is for headers.
        uassert(16389,
                str::stream() << "aggregation result exceeds maximum document size ("
                              << BSONObjMaxUserSize / (1024 * 1024)
                              << "MB)",
                resultArray.len() < BSONObjMaxUserSize - 1024);
    }

    resultArray.done();
    result.appendArray("result", resultArray.arr());
}