Beispiel #1
0
    nonce Security::getNonce() {
        static mongo::mutex m("getNonce");
        scoped_lock lk(m);

        /* question/todo: /dev/random works on OS X.  is it better
           to use that than random() / srandom()?
        */

        nonce n;
#if defined(__linux__) || defined(__sunos__)
        _devrandom->read((char*)&n, sizeof(n));
        massert( 10355 , "devrandom failed", !_devrandom->fail());
#elif defined(_WIN32)
        unsigned a=0, b=0;
        assert( rand_s(&a) == 0 );
        assert( rand_s(&b) == 0 );
        n = (((unsigned long long)a)<<32) | b;
#else
        n = (((unsigned long long)random())<<32) | random();
#endif
        return n;
    }
Beispiel #2
0
    void ClientInfo::_setupAuth() {
        std::string adminNs = "admin";
        DBConfigPtr config = grid.getDBConfig(adminNs);
        Shard shard = config->getShard(adminNs);
        scoped_ptr<ScopedDbConnection> connPtr(
                ScopedDbConnection::getInternalScopedDbConnection(shard.getConnString(), 30.0));
        ScopedDbConnection& conn = *connPtr;

        //
        // Note: The connection mechanism here is *not* ideal, and should not be used elsewhere.
        // It is safe in this particular case because the admin database is always on the config
        // server and does not move.
        //

        AuthorizationManager* authManager = new AuthorizationManager(new AuthExternalStateImpl());
        Status status = authManager->initialize(conn.get());
        massert(16479,
                mongoutils::str::stream() << "Error initializing AuthorizationManager: "
                                          << status.reason(),
                status == Status::OK());
        setAuthorizationManager(authManager);
    }
Beispiel #3
0
 BtreeCursor::BtreeCursor( NamespaceDetails *_d, int _idxNo, const IndexDetails& _id, const shared_ptr< FieldRangeVector > &_bounds, int _direction, bool useFRVSpec )
     :
     d(_d), idxNo(_idxNo),
     _endKeyInclusive( true ),
     _multikey( d->isMultikey( idxNo ) ),
     indexDetails( _id ),
     _order( _id.keyPattern() ),
     _ordering( Ordering::make( _order ) ),
     _direction( _direction ),
     _bounds( ( assert( _bounds.get() ), _bounds ) ),
     _boundsIterator( new FieldRangeVectorIterator( *_bounds  ) ),
     _spec( useFRVSpec ? _bounds->getSpec() : _id.getSpec() ),
     _independentFieldRanges( true ),
     _nscanned( 0 ) {
     massert( 13384, "BtreeCursor FieldRangeVector constructor doesn't accept special indexes", !_spec.getType() );
     audit();
     startKey = _bounds->startKey();
     _boundsIterator->advance( startKey ); // handles initialization
     _boundsIterator->prepDive();
     bucket = indexDetails.head;
     keyOfs = 0;
 }
Beispiel #4
0
        virtual bool run(OperationContext* txn, const string& dbname , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
            string coll = cmdObj[ "emptycapped" ].valuestrsafe();
            uassert( 13428, "emptycapped must specify a collection", !coll.empty() );
            NamespaceString nss( dbname, coll );

            Client::WriteContext ctx( nss.ns() );
            Database* db = ctx.ctx().db();
            Collection* collection = db->getCollection( nss.ns() );
            massert( 13429, "emptycapped no such collection", collection );

            std::vector<BSONObj> indexes = stopIndexBuilds(db, cmdObj);

            Status status = collection->truncate(txn);
            if ( !status.isOK() )
                return appendCommandStatus( result, status );

            IndexBuilder::restoreIndexes(indexes);

            if (!fromRepl)
                logOp(txn, "c",(dbname + ".$cmd").c_str(), cmdObj);
            return true;
        }
Beispiel #5
0
    void setupSignalHandlers(bool handleControlC) {
        setupSynchronousSignalHandlers();
#ifdef _WIN32
        if (!handleControlC) {
            massert(10297,
                "Couldn't register Windows Ctrl-C handler",
                SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>(CtrlHandler), TRUE));
        }
#else
        // asyncSignals is a global variable listing the signals that should be handled by the
        // interrupt thread, once it is started via startSignalProcessingThread().
        sigemptyset( &asyncSignals );
        sigaddset( &asyncSignals, SIGHUP );
        if (!handleControlC) {
           sigaddset( &asyncSignals, SIGINT );
        }
        sigaddset( &asyncSignals, SIGTERM );
        sigaddset( &asyncSignals, SIGQUIT );
        sigaddset( &asyncSignals, SIGUSR1 );
        sigaddset( &asyncSignals, SIGXCPU );
#endif
    }
    DiskLoc MmapV1ExtentManager::_createExtentInFile( OperationContext* txn,
                                                int fileNo,
                                                DataFile* f,
                                                int size,
                                                bool enforceQuota ) {

        _checkQuota( enforceQuota, fileNo - 1 );

        massert( 10358, "bad new extent size", size >= minSize() && size <= maxSize() );

        DiskLoc loc = f->allocExtentArea( txn, size );
        loc.assertOk();

        Extent *e = getExtent( loc, false );
        verify( e );

        *txn->recoveryUnit()->writing(&e->magic) = Extent::extentSignature;
        *txn->recoveryUnit()->writing(&e->myLoc) = loc;
        *txn->recoveryUnit()->writing(&e->length) = size;

        return loc;
    }
Beispiel #7
0
    int BucketBasics::fullValidate(const DiskLoc& thisLoc, const BSONObj &order) {
        {
            bool f = false;
            assert( f = true );
            massert( 10281 , "assert is misdefined", f);
        }

        killCurrentOp.checkForInterrupt();
        assertValid(order, true);
//	if( bt_fv==0 )
//		return;

        if ( bt_dmp ) {
            out() << thisLoc.toString() << ' ';
            ((BtreeBucket *) this)->dump();
        }

        // keycount
        int kc = 0;

        for ( int i = 0; i < n; i++ ) {
            _KeyNode& kn = k(i);

            if ( kn.isUsed() ) kc++;
            if ( !kn.prevChildBucket.isNull() ) {
                DiskLoc left = kn.prevChildBucket;
                BtreeBucket *b = left.btree();
                wassert( b->parent == thisLoc );
                kc += b->fullValidate(kn.prevChildBucket, order);
            }
        }
        if ( !nextChild.isNull() ) {
            BtreeBucket *b = nextChild.btree();
            wassert( b->parent == thisLoc );
            kc += b->fullValidate(nextChild, order);
        }

        return kc;
    }
Beispiel #8
0
void DBClientCursor::attach(AScopedConnection* conn) {
    verify(_scopedHost.size() == 0);
    verify(conn);
    verify(conn->get());

    if (conn->get()->type() == ConnectionString::SET) {
        if (_lazyHost.size() > 0)
            _scopedHost = _lazyHost;
        else if (_client)
            _scopedHost = _client->getServerAddress();
        else
            massert(14821,
                    "No client or lazy client specified, cannot store multi-host connection.",
                    false);
    } else {
        _scopedHost = conn->getHost();
    }

    conn->done();
    _client = 0;
    _lazyHost = "";
}
Beispiel #9
0
void AutoGetCollectionForRead::_init(const std::string& ns, StringData coll) {
    massert(28535, "need a non-empty collection name", !coll.empty());

    // We have both the DB and collection locked, which the prerequisite to do a stable shard
    // version check.
    ensureShardVersionOKOrThrow(_txn->getClient(), ns);

    auto curOp = CurOp::get(_txn);
    stdx::lock_guard<Client> lk(*_txn->getClient());
    // TODO: OldClientContext legacy, needs to be removed
    curOp->ensureStarted();
    curOp->setNS_inlock(ns);

    // At this point, we are locked in shared mode for the database by the DB lock in the
    // constructor, so it is safe to load the DB pointer.
    if (_db.getDb()) {
        // TODO: OldClientContext legacy, needs to be removed
        curOp->enter_inlock(ns.c_str(), _db.getDb()->getProfilingLevel());

        _coll = _db.getDb()->getCollection(ns);
    }
}
Beispiel #10
0
Lock::DBLock::DBLock(Locker* locker, StringData db, LockMode mode)
    : _id(RESOURCE_DATABASE, db),
      _locker(locker),
      _mode(mode),
      _globalLock(locker, isSharedLockMode(_mode) ? MODE_IS : MODE_IX, UINT_MAX) {
    massert(28539, "need a valid database name", !db.empty() && nsIsDbOnly(db));

    // Need to acquire the flush lock
    _locker->lockMMAPV1Flush();

    if (supportsDocLocking() || enableCollectionLocking) {
        // The check for the admin db is to ensure direct writes to auth collections
        // are serialized (see SERVER-16092).
        if ((_id == resourceIdAdminDB) && !isSharedLockMode(_mode)) {
            _mode = MODE_X;
        }

        invariant(LOCK_OK == _locker->lock(_id, _mode));
    } else {
        invariant(LOCK_OK == _locker->lock(_id, isSharedLockMode(_mode) ? MODE_S : MODE_X));
    }
}
    intrusive_ptr<DocumentSource> DocumentSourceProject::createFromBson(
            BSONElement elem,
            const intrusive_ptr<ExpressionContext> &pExpCtx) {

        /* validate */
        uassert(15969, str::stream() << projectName <<
                " specification must be an object",
                elem.type() == Object);

        Expression::ObjectCtx objectCtx(
              Expression::ObjectCtx::DOCUMENT_OK
            | Expression::ObjectCtx::TOP_LEVEL
            | Expression::ObjectCtx::INCLUSION_OK
            );

        VariablesIdGenerator idGenerator;
        VariablesParseState vps(&idGenerator);
        intrusive_ptr<Expression> parsed = Expression::parseObject(elem.Obj(), &objectCtx, vps);
        ExpressionObject* exprObj = dynamic_cast<ExpressionObject*>(parsed.get());
        massert(16402, "parseObject() returned wrong type of Expression", exprObj);
        uassert(16403, "$projection requires at least one output field", exprObj->getFieldCount());

        intrusive_ptr<DocumentSourceProject> pProject(new DocumentSourceProject(pExpCtx, exprObj));
        pProject->_variables.reset(new Variables(idGenerator.getIdCount()));

        BSONObj projectObj = elem.Obj();
        pProject->_raw = projectObj.getOwned();

#if defined(_DEBUG)
        if (exprObj->isSimple()) {
            DepsTracker deps;
            vector<string> path;
            exprObj->addDependencies(&deps, &path);
            pProject->_simpleProjection.init(deps.toProjection());
        }
#endif

        return pProject;
    }
Beispiel #12
0
    HashedIndexType::HashedIndexType( const IndexPlugin* plugin , const IndexSpec* spec ) :
            IndexType( plugin , spec ) , _keyPattern( spec->keyPattern ) {

        //change these if single-field limitation lifted later
        uassert( 16241 , "Currently only single field hashed index supported." ,
                _keyPattern.toBSON().nFields() == 1 );
        uassert( 16242 , "Currently hashed indexes cannot guarantee uniqueness. Use a regular index." ,
                ! (spec->info).getField("unique").booleanSafe() );

        //Default _seed to 0 if "seed" is not included in the index spec
        //or if the value of "seed" is not a number
        _seed = (spec->info).getField("seed").numberInt();

        //Default _isSparse to false if "sparse" is not included in the index spec
        //or if the value of "sparse" is not a boolean
        _isSparse = (spec->info).getField("sparse").booleanSafe();

        //In case we have hashed indexes based on other hash functions in
        //the future, we store a hashVersion number. If hashVersion changes,
        // "makeSingleKey" will need to change accordingly.
        //Defaults to 0 if "hashVersion" is not included in the index spec
        //or if the value of "hashversion" is not a number
        _hashVersion = (spec->info).getField("hashVersion").numberInt();

        //Get the hashfield name
        BSONElement firstElt = spec->keyPattern.firstElement();
        massert( 16243 , "error: no hashed index field" ,
                firstElt.str().compare( HASHED_INDEX_TYPE_IDENTIFIER ) == 0 );
        _hashedField = firstElt.fieldName();

        // Explicit null valued fields and missing fields are both represented in hashed indexes
        // using the hash value of the null BSONElement.  This is partly for historical reasons
        // (hash of null was used in the initial release of hashed indexes and changing would alter
        // the data format).  Additionally, in certain places the hashed index code and the index
        // bound calculation code assume null and missing are indexed identically.
        BSONObj nullObj = BSON( "" << BSONNULL );
        _missingKey = BSON( "" << makeSingleKey( nullObj.firstElement(), _seed, _hashVersion ) );
    }
Beispiel #13
0
    /** write an op to the oplog that is already built.
        todo : make _logOpRS() call this so we don't repeat ourself?
        */
    void _logOpObjRS(const BSONObj& op) {
        Lock::DBWrite lk("local");

        const OpTime ts = op["ts"]._opTime();
        long long h = op["h"].numberLong();

        {
            const char *logns = rsoplog;
            if ( rsOplogDetails == 0 ) {
                Client::Context ctx(logns , dbpath);
                localDB = ctx.db();
                verify( localDB );
                rsOplogDetails = nsdetails(logns);
                massert(13389, "local.oplog.rs missing. did you drop it? if so restart server", rsOplogDetails);
            }
            Client::Context ctx(logns , localDB);
            {
                int len = op.objsize();
                Record *r = theDataFileMgr.fast_oplog_insert(rsOplogDetails, logns, len);
                memcpy(getDur().writingPtr(r->data(), len), op.objdata(), len);
            }
            /* todo: now() has code to handle clock skew.  but if the skew server to server is large it will get unhappy.
                     this code (or code in now() maybe) should be improved.
                     */
            if( theReplSet ) {
                if( !(theReplSet->lastOpTimeWritten<ts) ) {
                    log() << "replSet error possible failover clock skew issue? " << theReplSet->lastOpTimeWritten.toString() << ' ' << endl;
                }
                theReplSet->lastOpTimeWritten = ts;
                theReplSet->lastH = h;
                ctx.getClient()->setLastOp( ts );

                replset::BackgroundSync::notify();
            }
        }

        OpTime::setLast( ts );
    }
Beispiel #14
0
    HashAccessMethod::HashAccessMethod(IndexDescriptor* descriptor)
        : BtreeBasedAccessMethod(descriptor) {

        const string HASHED_INDEX_TYPE_IDENTIFIER = "hashed";

        //change these if single-field limitation lifted later
        uassert(16763, "Currently only single field hashed index supported." ,
                1 == descriptor->getNumFields());
        uassert(16764, "Currently hashed indexes cannot guarantee uniqueness. Use a regular index.",
                !descriptor->unique());

        // Default _seed to DEFAULT_HASH_SEED if "seed" is not included in the index spec
        // or if the value of "seed" is not a number

        // *** WARNING ***
        // Choosing non-default seeds will invalidate hashed sharding
        // Changing the seed default will break existing indexes and sharded collections

        if ( descriptor->getInfoElement( "seed" ).eoo() ) {
            _seed = BSONElementHasher::DEFAULT_HASH_SEED;
        }
        else {
            _seed = descriptor->getInfoElement("seed").numberInt();
        }

        //In case we have hashed indexes based on other hash functions in
        //the future, we store a hashVersion number. If hashVersion changes,
        // "makeSingleKey" will need to change accordingly.
        //Defaults to 0 if "hashVersion" is not included in the index spec
        //or if the value of "hashversion" is not a number
        _hashVersion = descriptor->getInfoElement("hashVersion").numberInt();

        //Get the hashfield name
        BSONElement firstElt = descriptor->keyPattern().firstElement();
        massert(16765, "error: no hashed index field",
                firstElt.str().compare(HASHED_INDEX_TYPE_IDENTIFIER) == 0);
        _hashedField = firstElt.fieldName();
    }
Beispiel #15
0
 bool SockAddr::operator==(const SockAddr& r) const {
     if (getType() != r.getType())
         return false;
     
     if (getPort() != r.getPort())
         return false;
     
     switch (getType()) {
     case AF_INET:  
         return as<sockaddr_in>().sin_addr.s_addr == r.as<sockaddr_in>().sin_addr.s_addr;
     case AF_INET6: 
         return memcmp(as<sockaddr_in6>().sin6_addr.s6_addr, 
                       r.as<sockaddr_in6>().sin6_addr.s6_addr, 
                       sizeof(in6_addr)) == 0;
     case AF_UNIX:  
         return strcmp(as<sockaddr_un>().sun_path, r.as<sockaddr_un>().sun_path) == 0;
     case AF_UNSPEC: 
         return true; // assume all unspecified addresses are the same
     default: 
         massert(SOCK_FAMILY_UNKNOWN_ERROR, "unsupported address family", false);
     }
     return false;
 }
Beispiel #16
0
double IBMModelOne::distance( const Phrase& hu, const Phrase& en ) const
{
  double val = log(1.0+hu.size()) / en.size() ;

  double huRatio = 1.0 / hu.size();

  for ( int enPos=0; enPos<en.size(); ++enPos )
  {
    double sum = 0;
    const Word& enWord = en[enPos];

    for ( int huPos=0; huPos<hu.size(); ++huPos )
    {
      sum += lookup( hu[huPos], enWord );
    }

    massert( sum>0 );

    val -= log(sum);
  }

  throw "unimplemented";
}
int main(int argc, int argv[])
{
	struct gameState G;
  	struct gameState *p=&G;

  	int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, 
	       sea_hag, tribute, smithy};
  
  	printf ("Testing council_room card.\n");
  
  	int r = initializeGame(2, k, 5, p);
  	massert (r == 0,"initializeGame failed\n");

  	int player = whoseTurn(p);
  	int handPos = 0;
  	int coin_bonus=0;

  	G.handCount[player]=4;
  	G.hand[player][0]=council_room;
  	G.hand[player][1]=village;
  	G.hand[player][2]=minion;
  	G.hand[player][3]=mine;

  	G.numBuys=0;

  	int card = handCard(handPos,p);
  	massert(card>=adventurer&&card<=treasure_map,"invalid card\n");
  	massert(card==council_room,"incorrect card\n");

  	int test=cardEffect(card,-1,-1,-1,p,handPos,&coin_bonus);
  	massert(test==0,"cardEffect failed\n");
  	massert(G.handCount[player]==7,"incorrect had count\n");
  	massert(G.numBuys==1,"numBuys incorrect value\n");
  	massert(G.hand[player][0]!=council_room,"council_room is not discarded\n");

  	if(passed==0)
  		printf("---Test Passed!\n");

  	return 0;
}
    intrusive_ptr<DocumentSource> DocumentSourceProject::createFromBson(
        BSONElement *pBsonElement,
        const intrusive_ptr<ExpressionContext> &pExpCtx) {
        /* validate */
        uassert(15969, str::stream() << projectName <<
                " specification must be an object",
                pBsonElement->type() == Object);

        intrusive_ptr<DocumentSourceProject> pProject(new DocumentSourceProject(pExpCtx));

        BSONObj projectObj(pBsonElement->Obj());
        pProject->_raw = projectObj.getOwned(); // probably not necessary, but better to be safe

        Expression::ObjectCtx objectCtx(
              Expression::ObjectCtx::DOCUMENT_OK
            | Expression::ObjectCtx::TOP_LEVEL
            | Expression::ObjectCtx::INCLUSION_OK
            );

        intrusive_ptr<Expression> parsed = Expression::parseObject(pBsonElement, &objectCtx);
        ExpressionObject* exprObj = dynamic_cast<ExpressionObject*>(parsed.get());
        massert(16402, "parseObject() returned wrong type of Expression", exprObj);
        uassert(16403, "$projection requires at least one output field", exprObj->getFieldCount());

        pProject->pEO = exprObj;

#if defined(_DEBUG)
        if (exprObj->isSimple()) {
            set<string> deps;
            vector<string> path;
            exprObj->addDependencies(deps, &path);
            pProject->_simpleProjection.init(depsToProjection(deps));
        }
#endif

        return pProject;
    }
    Value DocumentSourceCursor::serialize(bool explain) const {
        // we never parse a documentSourceCursor, so we only serialize for explain
        if (!explain)
            return Value();

        // Get planner-level explain info from the underlying PlanExecutor.
        BSONObjBuilder explainBuilder;
        {
            const NamespaceString nss(_ns);
            AutoGetCollectionForRead autoColl(pExpCtx->opCtx, nss);

            massert(17392, "No _exec. Were we disposed before explained?", _exec);

            _exec->restoreState(pExpCtx->opCtx);
            Explain::explainStages(_exec.get(), ExplainCommon::QUERY_PLANNER, &explainBuilder);
            _exec->saveState();
        }

        MutableDocument out;
        out["query"] = Value(_query);

        if (!_sort.isEmpty())
            out["sort"] = Value(_sort);

        if (_limit)
            out["limit"] = Value(_limit->getLimit());

        if (!_projection.isEmpty())
            out["fields"] = Value(_projection);

        // Add explain results from the query system into the agg explain output.
        BSONObj explainObj = explainBuilder.obj();
        invariant(explainObj.hasField("queryPlanner"));
        out["queryPlanner"] = Value(explainObj["queryPlanner"]);

        return Value(DOC(getSourceName() << out.freezeToValue()));
    }
Beispiel #20
0
    Database* DatabaseHolder::getOrCreate( const string& ns , const string& path , bool& justCreated ) {
        string dbname = _todb( ns );
        {
            SimpleMutex::scoped_lock lk(_m);
            Lock::assertAtLeastReadLocked(ns);
            DBs& m = _paths[path];
            {
                DBs::iterator i = m.find(dbname); 
                if( i != m.end() ) {
                    justCreated = false;
                    return i->second;
                }
            }

            // todo: protect against getting sprayed with requests for different db names that DNE - 
            //       that would make the DBs map very large.  not clear what to do to handle though, 
            //       perhaps just log it, which is what we do here with the "> 40" : 
            bool cant = !Lock::isWriteLocked(ns);
            if( logLevel >= 1 || m.size() > 40 || cant || DEBUG_BUILD ) {
                log() << "opening db: " << (path==dbpath?"":path) << ' ' << dbname << endl;
            }
            massert(15927, "can't open database in a read lock. if db was just closed, consider retrying the query. might otherwise indicate an internal error", !cant);
        }

        // this locks _m for defensive checks, so we don't want to be locked right here : 
        Database *db = new Database( dbname.c_str() , justCreated , path );

        {
            SimpleMutex::scoped_lock lk(_m);
            DBs& m = _paths[path];
            assert( m[dbname] == 0 );
            m[dbname] = db;
            _size++;
        }

        return db;
    }
Beispiel #21
0
// Standard Btree implementation below.
BtreeAccessMethod::BtreeAccessMethod(IndexCatalogEntry* btreeState)
    : BtreeBasedAccessMethod(btreeState) {

    // The key generation wants these values.
    vector<const char*> fieldNames;
    vector<BSONElement> fixed;

    BSONObjIterator it(_descriptor->keyPattern());
    while (it.more()) {
        BSONElement elt = it.next();
        fieldNames.push_back(elt.fieldName());
        fixed.push_back(BSONElement());
    }

    if (0 == _descriptor->version()) {
        _keyGenerator.reset(new BtreeKeyGeneratorV0(fieldNames, fixed,
                            _descriptor->isSparse()));
    } else if (1 == _descriptor->version()) {
        _keyGenerator.reset(new BtreeKeyGeneratorV1(fieldNames, fixed,
                            _descriptor->isSparse()));
    } else {
        massert(16745, "Invalid index version for key generation.", false );
    }
}
Beispiel #22
0
    bool SyncSourceFeedback::replHandshake(OperationContext* txn) {
        ReplicationCoordinator* replCoord = getGlobalReplicationCoordinator();
        if (replCoord->getCurrentMemberState().primary()) {
            // primary has no one to handshake to
            return true;
        }
        // construct a vector of handshake obj for us as well as all chained members
        std::vector<BSONObj> handshakeObjs;
        replCoord->prepareReplSetUpdatePositionCommandHandshakes(txn, &handshakeObjs);
        LOG(1) << "handshaking upstream updater";
        for (std::vector<BSONObj>::iterator it = handshakeObjs.begin();
                it != handshakeObjs.end();
                ++it) {
            BSONObj res;
            try {
                LOG(2) << "Sending to " << _connection.get()->toString() << " the replication "
                        "handshake: " << *it;
                if (!_connection->runCommand("admin", *it, res)) {
                    massert(17447, "upstream updater is not supported by the member from which we"
                            " are syncing, please update all nodes to 2.6 or later.",
                            res["errmsg"].str().find("no such cmd") == std::string::npos);
                    log() << "replSet error while handshaking the upstream updater: "
                        << res["errmsg"].valuestrsafe();

                    _resetConnection();
                    return false;
                }
            }
            catch (const DBException& e) {
                log() << "SyncSourceFeedback error sending handshake: " << e.what() << endl;
                _resetConnection();
                return false;
            }
        }
        return true;
    }
Beispiel #23
0
 BtreeCursor::BtreeCursor( NamespaceDetails *_d, int _idxNo, const IndexDetails& _id, const shared_ptr< FieldRangeVector > &_bounds, int _direction )
     :
         d(_d), idxNo(_idxNo), 
         endKeyInclusive_( true ),
         multikey( d->isMultikey( idxNo ) ),
         indexDetails( _id ),
         order( _id.keyPattern() ),
         _ordering( Ordering::make( order ) ),
         direction( _direction ),
         bounds_( ( assert( _bounds.get() ), _bounds ) ),
         _boundsIterator( new FieldRangeVector::Iterator( *bounds_  ) ),
         _spec( _id.getSpec() ),
         _independentFieldRanges( true )
 {
     massert( 13384, "BtreeCursor FieldRangeVector constructor doesn't accept special indexes", !_spec.getType() );
     audit();
     startKey = bounds_->startKey();
     bool found;
     _boundsIterator->advance( startKey ); // handles initialization
     bucket = indexDetails.head.btree()->
     locate(indexDetails, indexDetails.head, startKey, _ordering, keyOfs, found, direction > 0 ? minDiskLoc : maxDiskLoc, direction);
     skipAndCheck();
     DEV assert( dups.size() == 0 );
 }
Beispiel #24
0
RecordId Helpers::findOne(OperationContext* opCtx,
                          Collection* collection,
                          std::unique_ptr<QueryRequest> qr,
                          bool requireIndex) {
    if (!collection)
        return RecordId();

    const ExtensionsCallbackReal extensionsCallback(opCtx, &collection->ns());

    const boost::intrusive_ptr<ExpressionContext> expCtx;
    auto statusWithCQ =
        CanonicalQuery::canonicalize(opCtx,
                                     std::move(qr),
                                     expCtx,
                                     extensionsCallback,
                                     MatchExpressionParser::kAllowAllSpecialFeatures &
                                         ~MatchExpressionParser::AllowedFeatures::kIsolated);

    massertStatusOK(statusWithCQ.getStatus());
    unique_ptr<CanonicalQuery> cq = std::move(statusWithCQ.getValue());

    size_t options = requireIndex ? QueryPlannerParams::NO_TABLE_SCAN : QueryPlannerParams::DEFAULT;
    auto exec = uassertStatusOK(
        getExecutor(opCtx, collection, std::move(cq), PlanExecutor::NO_YIELD, options));

    PlanExecutor::ExecState state;
    BSONObj obj;
    RecordId loc;
    if (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, &loc))) {
        return loc;
    }
    massert(34427,
            "Plan executor error: " + WorkingSetCommon::toStatusString(obj),
            PlanExecutor::IS_EOF == state);
    return RecordId();
}
    HashAccessMethod::HashAccessMethod(IndexDescriptor* descriptor)
        : BtreeBasedAccessMethod(descriptor) {

        const string HASHED_INDEX_TYPE_IDENTIFIER = "hashed";

        //change these if single-field limitation lifted later
        uassert(16763, "Currently only single field hashed index supported." ,
                1 == descriptor->getNumFields());
        uassert(16764, "Currently hashed indexes cannot guarantee uniqueness. Use a regular index.",
                !descriptor->unique());

        //Default _seed to 0 if "seed" is not included in the index spec
        //or if the value of "seed" is not a number
        _seed = descriptor->getInfoElement("seed").numberInt();

        //In case we have hashed indexes based on other hash functions in
        //the future, we store a hashVersion number. If hashVersion changes,
        // "makeSingleKey" will need to change accordingly.
        //Defaults to 0 if "hashVersion" is not included in the index spec
        //or if the value of "hashversion" is not a number
        _hashVersion = descriptor->getInfoElement("hashVersion").numberInt();

        //Get the hashfield name
        BSONElement firstElt = descriptor->keyPattern().firstElement();
        massert(16765, "error: no hashed index field",
                firstElt.str().compare(HASHED_INDEX_TYPE_IDENTIFIER) == 0);
        _hashedField = firstElt.fieldName();

        // Explicit null valued fields and missing fields are both represented in hashed indexes
        // using the hash value of the null BSONElement.  This is partly for historical reasons
        // (hash of null was used in the initial release of hashed indexes and changing would alter
        // the data format).  Additionally, in certain places the hashed index code and the index
        // bound calculation code assume null and missing are indexed identically.
        BSONObj nullObj = BSON("" << BSONNULL);
        _missingKey = BSON("" << makeSingleKey(nullObj.firstElement(), _seed, _hashVersion));
    }
Beispiel #26
0
int main (int argc, char** argv) {
  struct gameState G;

  int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, 
         sea_hag, tribute, smithy};

  printf ("Testing gainCard.\n");
  
  int r = initializeGame(2, k, 5, &G);
  massert(r == 0,"initializeGame failed\n");
  
  int player=whoseTurn(&G);
  int supplyPos=3;
  int flag1=1;
  int flag2=2;
  int flag3=-293587678;
  
  int deck_count=G.deckCount[player]=3;
  int hand_count=G.handCount[player]=4;
  int discard_count=G.discardCount[player]=5;
  
  int gain_card=gainCard(supplyPos,&G,flag1,player);
  massert(gain_card==0,"incorrect value for gainCard\n");
  massert(G.deckCount[player]==deck_count+1,"incorrect value for deckCount\n");

  gain_card=gainCard(++supplyPos,&G,flag2,player);
  massert(gain_card==0,"incorrect value for gainCard\n");
  massert(G.handCount[player]==hand_count+1,"incorrect value for handCount\n");

  gain_card=gainCard(++supplyPos,&G,flag3,player);
  massert(gain_card==0,"incorrect value for gainCard\n");
  massert(G.discardCount[player]==discard_count+1,"incorrect value for discardCount\n");

  if(passed==0)
      printf("---Test Passed!\n");

  return 0;
}
Beispiel #27
0
void buildWordFromDOMTree_En( const DOMNode* parent, Word& word, bool lemma )
{
  massert( toString(parent->getNodeName()) == "w" );

  const DOMNodeList* lst = parent->getChildNodes();

  massert( lst->getLength() > 0 );

  if (!lemma)
  {
    const DOMNode* wordTextNode = lst->item(0);

    massert( wordTextNode->getNodeType() == DOMNode::TEXT_NODE );

    // std::cout << "FOUND WORD: " << wordTextNode->getNodeValue() << std::endl;

    word = toString(wordTextNode->getNodeValue());
  }
  else
  {
    const char lemmaName[] = "l\0e\0m\0m\0a\0\0\0";
    const DOMNamedNodeMap* attrMap = parent->getAttributes();
    const DOMNode* lemmaNode = attrMap->getNamedItem((const unsigned short*)lemmaName);

    massert(lemmaNode);

    const DOMNodeList* lst = lemmaNode->getChildNodes();

    massert( lst->getLength() > 0 );

    const DOMNode* wordTextNode = lst->item(0);

    massert( wordTextNode->getNodeType() == DOMNode::TEXT_NODE );

    // std::cout << "FOUND LEMMA: " << wordTextNode->getNodeValue() << std::endl;

    word = toString(wordTextNode->getNodeValue());
  }
}
Beispiel #28
0
 virtual void connected( AbstractMessagingPort* p ) {
     ClientInfo *c = ClientInfo::get();
     massert(15849, "client info not defined", c);
     if( p->remote().isLocalHost() )
         c->getAuthenticationInfo()->setIsALocalHostConnectionWithSpecialAuthPowers();
 }
Beispiel #29
0
    bool handlePossibleShardedMessage( Message &m, DbResponse* dbresponse ) {
        if ( ! shardingState.enabled() )
            return false;

        int op = m.operation();
        if ( op < 2000
                || op >= 3000
                || op == dbGetMore  // cursors are weird
           )
            return false;

        DbMessage d(m);
        const char *ns = d.getns();
        string errmsg;
        if ( shardVersionOk( ns , opIsWrite( op ) , errmsg ) ) {
            return false;
        }

        log(1) << "connection meta data too old - will retry ns:(" << ns << ") op:(" << opToString(op) << ") " << errmsg << endl;

        if ( doesOpGetAResponse( op ) ) {
            assert( dbresponse );
            BufBuilder b( 32768 );
            b.skip( sizeof( QueryResult ) );
            {
                BSONObj obj = BSON( "$err" << errmsg );
                b.appendBuf( obj.objdata() , obj.objsize() );
            }

            QueryResult *qr = (QueryResult*)b.buf();
            qr->_resultFlags() = ResultFlag_ErrSet | ResultFlag_ShardConfigStale;
            qr->len = b.len();
            qr->setOperation( opReply );
            qr->cursorId = 0;
            qr->startingFrom = 0;
            qr->nReturned = 1;
            b.decouple();

            Message * resp = new Message();
            resp->setData( qr , true );

            dbresponse->response = resp;
            dbresponse->responseTo = m.header()->id;
            return true;
        }

        OID writebackID;
        writebackID.init();
        lastError.getSafe()->writeback( writebackID );

        const OID& clientID = ShardedConnectionInfo::get(false)->getID();
        massert( 10422 ,  "write with bad shard config and no server id!" , clientID.isSet() );

        log(1) << "got write with an old config - writing back ns: " << ns << endl;
        if ( logLevel ) log(1) << debugString( m ) << endl;

        BSONObjBuilder b;
        b.appendBool( "writeBack" , true );
        b.append( "ns" , ns );
        b.append( "id" , writebackID );
        b.append( "connectionId" , cc().getConnectionId() );
        b.appendTimestamp( "version" , shardingState.getVersion( ns ) );
        b.appendTimestamp( "yourVersion" , ShardedConnectionInfo::get( true )->getVersion( ns ) );
        b.appendBinData( "msg" , m.header()->len , bdtCustom , (char*)(m.singleData()) );
        log(2) << "writing back msg with len: " << m.header()->len << " op: " << m.operation() << endl;
        writeBackManager.queueWriteBack( clientID.str() , b.obj() );

        return true;
    }
int main() {
	  int returnValGame, returnValEffect; 
	  int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, 
	       sea_hag, tribute, smithy};

	  int i, j, n, players, player, handCount, deckCount, seed, address;
	  
	  //struct gameState state;
	  struct gameState state;
	  struct gameState stat;
	  struct gameState sta;

	  //printf("Running Random Adventurer Test\n");

	  /*
										--- Author's Note ---
	  So, I had problems running out of memory when I used the same gameState variable more than 12 times, and
	  I honestly don't know why. I momentarily solved this problem by adding more for loops and creating more gamestates;
	  I was still able to get decent coverage, though not up to the amount of tests I originally had in mind.

	  */
	  
	  //Loops 12 times for first set of tests 
	  for (i = 0; i < MAX_TESTS; i++) 
	  {
		  //Picks random # of players between 0 and 3
		  players = rand() % 4;
		  //Pick random sed 
	      seed = rand();		
		  //Initalizes game 
	      returnValGame = initializeGame(players, k, seed, &state);	
		  //Oracle for checking if the game is able to be initialized 
	      massert(returnValGame == 0, "The game was not able to be initialized\n");
	   //Initiate valid state variables
	      //Pick a random deck size between 0 and 499 
		  state.deckCount[player] = rand() % MAX_DECK; 
		  //Pick a random discard size between 0 and 499
		  state.discardCount[player] = rand() % MAX_DECK;
		  //Pick a random hand size between 0 and 499 
		  state.handCount[player] = rand() % MAX_HAND;


		  //Copy state variables
		  handCount = state.handCount[player];
		  deckCount = state.deckCount[player];

		  //1 in 3 chance of making empty deck for coverage
		  if (seed % 3 == 0) 
		  {
			state.deckCount[player] = 0;
		  }
		  //Activates adventurer card effect
		  returnValEffect = cardEffect(adventurer, 1, 1, 1, &state, 1, 1);	
		  //Oracle for checking if adventurer card effect worked 
		  massert(returnValEffect == 0, "The adventurer card effect did not work\n");
	  }

       //Loops 12 times for third set of tests 
	   for (i = 0; i < MAX_TESTS; i++) 
	   {
		  //Picks number of players between 0 and 3 
  		  players = rand() % 4;
		  //Pick random seed 
		  seed = rand();		
		  //Initializes game 
		  returnValGame = initializeGame(players, k, seed, &stat);	
          //Oracle for checking if the game is able to be initialized 
	      massert(returnValGame == 0, "The game was not able to be initialized\n");
		  //Initiate valid state variables
		  //Picks a random deck size between 0 and 499 
		  stat.deckCount[player] = rand() % MAX_DECK; 
		  //Picks a random discard size between 0 and 499 
		  stat.discardCount[player] = rand() % MAX_DECK;
		  //Picks a random hand size between 0 and 499 
		  stat.handCount[player] = rand() % MAX_HAND;


		  //Copy state variables
		  handCount = stat.handCount[player];
		  deckCount = stat.deckCount[player];

		  //1 in 3 chance of making empty deck for coverage
		  if (seed % 3 == 0) 
		  {
			stat.deckCount[player] = 0;
		  }
		  //Activates adventurer card effect 
		  cardEffect(adventurer, 1, 1, 1, &stat, 1, 1);
		  //Oracle for checking if adventurer card effect worked 
		  massert(returnValEffect == 0, "The adventurer card effect did not work\n");
		  //AdventurerCardEffect(&stat, 0);
	   }

       //Loops 12 times for third set of tests 
	   for (i = 0; i < MAX_TESTS; i++) 
	   {
		  //Picks number of players between 0 and 3 
  		  players = rand() % 4;
		  //Pick random seed 
		  seed = rand();		
		  //Initializes game 
		  returnValGame = initializeGame(players, k, seed, &sta);	
          //Oracle for checking if the game is able to be initialized 
	      massert(returnValGame == 0, "The game was not able to be initialized\n");
		  //Initiate valid state variables
		  //Picks a random deck size between 0 and 499 
		  sta.deckCount[player] = rand() % MAX_DECK; 
		  //Picks a random discard size between 0 and 499 
		  sta.discardCount[player] = rand() % MAX_DECK;
		  //Picks a random hand size between 0 and 499 
		  sta.handCount[player] = rand() % MAX_HAND;


		  //Copy state variables
		  handCount = sta.handCount[player];
		  deckCount = sta.deckCount[player];

		  //1 in 3 chance of making empty deck for coverage
		  if (seed % 3 == 0) 
		  {
			sta.deckCount[player] = 0;
		  }
		  //Activates adventurer card effect
		  cardEffect(adventurer, 1, 1, 1, &stat, 1, 1);		
		  //Oracle for checking if adventurer card effect worked 
		  massert(returnValEffect == 0, "The adventurer card effect did not work\n");

	   }

	  //printf("Tests Complete\n");

	  return 0;
}