本文整理汇总了C++中OID类的典型用法代码示例。如果您正苦于以下问题:C++ OID类的具体用法?C++ OID怎么用?C++ OID使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OID类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: init
void init() {
type = static_cast<char>(jstOID);
strcpy( id, "_id" );
oid.init();
verify( size() == 17 );
}
示例2: mongoUpdateContextSubscription
/* ****************************************************************************
*
* mongoUpdateContextSubscription -
*/
HttpStatusCode mongoUpdateContextSubscription(UpdateContextSubscriptionRequest* requestP, UpdateContextSubscriptionResponse* responseP, Format inFormat, const std::string& tenant)
{
reqSemTake(__FUNCTION__, "ngsi10 update subscription request");
LM_T(LmtMongo, ("Update Context Subscription"));
DBClientBase* connection = getMongoConnection();
/* Look for document */
BSONObj sub;
try
{
OID id = OID(requestP->subscriptionId.get());
mongoSemTake(__FUNCTION__, "findOne in SubscribeContextCollection");
sub = connection->findOne(getSubscribeContextCollectionName(tenant).c_str(), BSON("_id" << id));
mongoSemGive(__FUNCTION__, "findOne in SubscribeContextCollection");
LM_I(("Database Operation Successful (findOne _id: %s)", id.toString().c_str()));
}
catch (const AssertionException &e)
{
/* This happens when OID format is wrong */
// FIXME P4: this checking should be done at the parsing stage, without progressing to
// mongoBackend. For the moment we can leave this here, but we should remove it in the future
// (old issue #95)
mongoSemGive(__FUNCTION__, "findOne in SubscribeContextCollection (mongo assertion exception)");
reqSemGive(__FUNCTION__, "ngsi10 update subscription request (mongo assertion exception)");
responseP->subscribeError.errorCode.fill(SccContextElementNotFound);
LM_W(("Bad Input (invalid OID format)"));
return SccOk;
}
catch (const DBException &e)
{
mongoSemGive(__FUNCTION__, "findOne in SubscribeContextCollection (mongo db exception)");
reqSemGive(__FUNCTION__, "ngsi10 update subscription request (mongo db exception)");
responseP->subscribeError.errorCode.fill(SccReceiverInternalError,
std::string("collection: ") + getSubscribeContextCollectionName(tenant).c_str() +
" - findOne() _id: " + requestP->subscriptionId.get() +
" - exception: " + e.what());
LM_E(("Database Error (%s)", responseP->subscribeError.errorCode.details.c_str()));
return SccOk;
}
catch (...)
{
mongoSemGive(__FUNCTION__, "findOne in SubscribeContextCollection (mongo generic exception)");
reqSemGive(__FUNCTION__, "ngsi10 update subscription request (mongo generic exception)");
responseP->subscribeError.errorCode.fill(SccReceiverInternalError,
std::string("collection: ") + getSubscribeContextCollectionName(tenant).c_str() +
" - findOne() _id: " + requestP->subscriptionId.get() +
" - exception: " + "generic");
LM_E(("Database Error (%s)", responseP->subscribeError.errorCode.details.c_str()));
return SccOk;
}
if (sub.isEmpty()) {
responseP->subscribeError.errorCode.fill(SccContextElementNotFound);
reqSemGive(__FUNCTION__, "ngsi10 update subscription request (no subscriptions found)");
return SccOk;
}
/* We start with an empty BSONObjBuilder and process requestP for all the fields that can
* be updated. I don't like too much this strategy (I would have preferred to start with
* a copy of the original document, then modify as neded, but this doesn't seem to be easy
* using the API provide by the Mongo C++ driver)
*
* FIXME: a better implementation strategy could be doing an findAndModify() query to do the
* update, so detecting if the document was not found, instead of using findOne() + update()
* with $set operation. One operations to MongoDb. vs two operations.
*/
BSONObjBuilder newSub;
/* Entities, attribute list and reference are not updatable, so they are appended directly */
newSub.appendArray(CSUB_ENTITIES, sub.getField(CSUB_ENTITIES).Obj());
newSub.appendArray(CSUB_ATTRS, sub.getField(CSUB_ATTRS).Obj());
newSub.append(CSUB_REFERENCE, STR_FIELD(sub, CSUB_REFERENCE));
/* Duration update */
if (requestP->duration.isEmpty()) {
newSub.append(CSUB_EXPIRATION, sub.getField(CSUB_EXPIRATION).numberLong());
}
else {
long long expiration = getCurrentTime() + requestP->duration.parse();
newSub.append(CSUB_EXPIRATION, expiration);
LM_T(LmtMongo, ("New subscription expiration: %l", expiration));
}
/* Restriction update */
// FIXME: Restrictions not implemented yet
/* Throttling update */
if (!requestP->throttling.isEmpty()) {
/* Throttling equal to 0 removes throttling */
//.........这里部分代码省略.........
示例3: doUpgradeV3ToV4
/**
* Upgrade v3 to v4 described here.
*
* This upgrade takes a config server without collection epochs (potentially) and adds
* epochs to all mongo processes.
*
*/
bool doUpgradeV3ToV4(const ConnectionString& configLoc,
const VersionType& lastVersionInfo,
string* errMsg)
{
string dummy;
if (!errMsg) errMsg = &dummy;
verify(lastVersionInfo.getCurrentVersion() == UpgradeHistory_NoEpochVersion);
if (lastVersionInfo.isUpgradeIdSet() && lastVersionInfo.getUpgradeId().isSet()) {
//
// Another upgrade failed, so cleanup may be necessary
//
BSONObj lastUpgradeState = lastVersionInfo.getUpgradeState();
bool inCriticalSection;
if (!FieldParser::extract(lastUpgradeState,
inCriticalSectionField,
&inCriticalSection,
errMsg))
{
*errMsg = stream() << "problem reading previous upgrade state" << causedBy(errMsg);
return false;
}
if (inCriticalSection) {
// Manual intervention is needed here. Somehow our upgrade didn't get applied
// consistently across config servers.
*errMsg = cannotCleanupMessage;
return false;
}
if (!_cleanupUpgradeState(configLoc, lastVersionInfo.getUpgradeId(), errMsg)) {
// If we can't cleanup the old upgrade state, the user might have done it for us,
// not a fatal problem (we'll just end up with extra collections).
warning() << "could not cleanup previous upgrade state" << causedBy(errMsg) << endl;
*errMsg = "";
}
}
//
// Check the versions of other mongo processes in the cluster before upgrade.
// We can't upgrade if there are active pre-v2.2 processes in the cluster
//
Status mongoVersionStatus = checkClusterMongoVersions(configLoc,
string(minMongoProcessVersion));
if (!mongoVersionStatus.isOK()) {
*errMsg = stream() << "cannot upgrade with pre-v" << minMongoProcessVersion
<< " mongo processes active in the cluster"
<< causedBy(mongoVersionStatus);
return false;
}
VersionType newVersionInfo;
lastVersionInfo.cloneTo(&newVersionInfo);
// Set our upgrade id and state
OID upgradeId = OID::gen();
newVersionInfo.setUpgradeId(upgradeId);
newVersionInfo.setUpgradeState(BSONObj());
// Write our upgrade id and state
{
scoped_ptr<ScopedDbConnection> connPtr;
try {
connPtr.reset(ScopedDbConnection::getInternalScopedDbConnection(configLoc, 30));
ScopedDbConnection& conn = *connPtr;
verify(newVersionInfo.isValid(NULL));
conn->update(VersionType::ConfigNS,
BSON("_id" << 1 << VersionType::version_DEPRECATED(3)),
newVersionInfo.toBSON());
_checkGLE(conn);
}
catch (const DBException& e) {
*errMsg = stream() << "could not initialize version info for upgrade"
<< causedBy(e);
//.........这里部分代码省略.........
示例4: _handlePossibleShardedMessage
bool _handlePossibleShardedMessage( Message &m, DbResponse* dbresponse ) {
DEV assert( shardingState.enabled() );
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;
// We don't care about the version here, since we're returning it later in the writeback
ConfigVersion received, wanted;
if ( shardVersionOk( ns , errmsg, received, wanted ) ) {
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 << "ns" << ns );
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;
}
uassert( 9517 , "writeback" , ( d.reservedField() & DbMessage::Reserved_FromWriteback ) == 0 );
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;
LOG(1) << m.toString() << endl;
BSONObjBuilder b;
b.appendBool( "writeBack" , true );
b.append( "ns" , ns );
b.append( "id" , writebackID );
b.append( "connectionId" , cc().getConnectionId() );
b.append( "instanceIdent" , prettyHostName() );
b.appendTimestamp( "version" , shardingState.getVersion( ns ) );
ShardedConnectionInfo* info = ShardedConnectionInfo::get( false );
b.appendTimestamp( "yourVersion" , info ? info->getVersion(ns) : (ConfigVersion)0 );
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;
}
示例5: getCurrentTime
/* ****************************************************************************
*
* processRegisterContext -
*
* This function has a slightly different behaviour depending on whether the id
* parameter is null (new registration case) or not null (update case), in
* particular:
*
* - In the new registration case, the _id is generated and insert() is used to
* put the document in the DB.
* - In the update case, the _id is set according to the argument 'id' and update() is
* used to put the document in the DB.
*
*/
HttpStatusCode processRegisterContext
(
RegisterContextRequest* requestP,
RegisterContextResponse* responseP,
OID* id,
const std::string& tenant,
const std::string& servicePath,
const std::string& format,
const std::string& fiwareCorrelator
)
{
std::string err;
/* If expiration is not present, then use a default one */
if (requestP->duration.isEmpty())
{
requestP->duration.set(DEFAULT_DURATION);
}
/* Calculate expiration (using the current time and the duration field in the request) */
long long expiration = getCurrentTime() + requestP->duration.parse();
LM_T(LmtMongo, ("Registration expiration: %lu", expiration));
/* Create the mongoDB registration document */
BSONObjBuilder reg;
OID oid;
if (id == NULL)
{
oid.init();
}
else
{
oid = *id;
}
reg.append("_id", oid);
reg.append(REG_EXPIRATION, expiration);
reg.append(REG_SERVICE_PATH, servicePath == "" ? DEFAULT_SERVICE_PATH_UPDATES : servicePath);
reg.append(REG_FORMAT, format);
//
// We accumulate the subscriptions in a map. The key of the map is the string representing
// subscription id
//
std::map<string, TriggeredSubscription*> subsToNotify;
// This vector is used to define which entities to include in notifications
EntityIdVector triggerEntitiesV;
BSONArrayBuilder contextRegistration;
for (unsigned int ix = 0; ix < requestP->contextRegistrationVector.size(); ++ix)
{
ContextRegistration* cr = requestP->contextRegistrationVector[ix];
BSONArrayBuilder entities;
for (unsigned int jx = 0; jx < cr->entityIdVector.size(); ++jx)
{
EntityId* en = cr->entityIdVector[jx];
triggerEntitiesV.push_back(en);
if (en->type == "")
{
entities.append(BSON(REG_ENTITY_ID << en->id));
LM_T(LmtMongo, ("Entity registration: {id: %s}", en->id.c_str()));
}
else
{
entities.append(BSON(REG_ENTITY_ID << en->id << REG_ENTITY_TYPE << en->type));
LM_T(LmtMongo, ("Entity registration: {id: %s, type: %s}", en->id.c_str(), en->type.c_str()));
}
}
BSONArrayBuilder attrs;
for (unsigned int jx = 0; jx < cr->contextRegistrationAttributeVector.size(); ++jx)
{
ContextRegistrationAttribute* cra = cr->contextRegistrationAttributeVector[jx];
attrs.append(BSON(REG_ATTRS_NAME << cra->name << REG_ATTRS_TYPE << cra->type << "isDomain" << cra->isDomain));
LM_T(LmtMongo, ("Attribute registration: {name: %s, type: %s, isDomain: %s}",
cra->name.c_str(),
cra->type.c_str(),
cra->isDomain.c_str()));
for (unsigned int kx = 0;
kx < requestP->contextRegistrationVector[ix]->contextRegistrationAttributeVector[jx]->metadataVector.size();
++kx)
{
//.........这里部分代码省略.........
示例6: invariant
Status MetadataLoader::initChunks(OperationContext* txn,
ShardingCatalogClient* catalogClient,
const string& ns,
const string& shard,
const CollectionMetadata* oldMetadata,
CollectionMetadata* metadata) const {
map<ShardId, ChunkVersion> versionMap; // TODO: use .h defined type
// Preserve the epoch
versionMap[shard] = metadata->_shardVersion;
OID epoch = metadata->getCollVersion().epoch();
bool fullReload = true;
// Check to see if we should use the old version or not.
if (oldMetadata) {
// If our epochs are compatible, it's useful to use the old metadata for diffs: this leads
// to a performance gain because not all the chunks must be reloaded, just the ones this
// shard has not seen -- they will have higher versions than present in oldMetadata.
if (oldMetadata->getCollVersion().hasEqualEpoch(epoch)) {
fullReload = false;
invariant(oldMetadata->isValid());
versionMap[shard] = oldMetadata->_shardVersion;
metadata->_collVersion = oldMetadata->_collVersion;
// TODO: This could be made more efficient if copying not required, but
// not as frequently reloaded as in mongos.
metadata->_chunksMap = oldMetadata->_chunksMap;
LOG(2) << "loading new chunks for collection " << ns
<< " using old metadata w/ version " << oldMetadata->getShardVersion() << " and "
<< metadata->_chunksMap.size() << " chunks";
} else {
warning() << "reloading collection metadata for " << ns << " with new epoch "
<< epoch.toString() << ", the current epoch is "
<< oldMetadata->getCollVersion().epoch().toString();
}
}
// Exposes the new metadata's range map and version to the "differ," who
// would ultimately be responsible of filling them up.
SCMConfigDiffTracker differ(shard);
differ.attach(ns, metadata->_chunksMap, metadata->_collVersion, versionMap);
try {
std::vector<ChunkType> chunks;
const auto diffQuery = differ.configDiffQuery();
Status status = catalogClient->getChunks(
txn, diffQuery.query, diffQuery.sort, boost::none, &chunks, nullptr);
if (!status.isOK()) {
if (status == ErrorCodes::HostUnreachable) {
// Make our metadata invalid
metadata->_collVersion = ChunkVersion(0, 0, OID());
metadata->_chunksMap.clear();
}
return status;
}
//
// The diff tracker should always find at least one chunk (the highest chunk we saw
// last time). If not, something has changed on the config server (potentially between
// when we read the collection data and when we read the chunks data).
//
int diffsApplied = differ.calculateConfigDiff(txn, chunks);
if (diffsApplied > 0) {
// Chunks found, return ok
LOG(2) << "loaded " << diffsApplied << " chunks into new metadata for " << ns
<< " with version " << metadata->_collVersion;
// If the last chunk was moved off of this shard, the shardVersion should be reset to
// zero (if we did not conduct a full reload and oldMetadata was present,
// versionMap[shard] was previously set to the oldMetadata's shardVersion for
// performance gains).
if (!fullReload && metadata->_chunksMap.size() == 0) {
versionMap[shard] = ChunkVersion(0, 0, epoch);
}
metadata->_shardVersion = versionMap[shard];
metadata->fillRanges();
invariant(metadata->isValid());
return Status::OK();
} else if (diffsApplied == 0) {
// No chunks found, the collection is dropping or we're confused
// If this is a full reload, assume it is a drop for backwards compatibility
// TODO: drop the config.collections entry *before* the chunks and eliminate this
// ambiguity
string errMsg = str::stream()
<< "no chunks found when reloading " << ns << ", previous version was "
<< metadata->_collVersion.toString() << (fullReload ? ", this is a drop" : "");
warning() << errMsg;
metadata->_collVersion = ChunkVersion(0, 0, OID());
metadata->_chunksMap.clear();
return fullReload ? Status(ErrorCodes::NamespaceNotFound, errMsg)
: Status(ErrorCodes::RemoteChangeDetected, errMsg);
//.........这里部分代码省略.........
示例7: genWorkingSuffix
string genWorkingSuffix(const OID& lastUpgradeId) {
return "-upgrade-" + lastUpgradeId.toString();
}
示例8: genBackupSuffix
string genBackupSuffix(const OID& lastUpgradeId) {
return "-backup-" + lastUpgradeId.toString();
}
示例9: v8ToMongoElement
void v8ToMongoElement( BSONObjBuilder & b , v8::Handle<v8::String> name , const string sname , v8::Handle<v8::Value> value ){
if ( value->IsString() ){
b.append( sname.c_str() , toSTLString( value ).c_str() );
return;
}
if ( value->IsFunction() ){
b.appendCode( sname.c_str() , toSTLString( value ).c_str() );
return;
}
if ( value->IsNumber() ){
if ( value->IsInt32() )
b.append( sname.c_str(), int( value->ToInt32()->Value() ) );
else
b.append( sname.c_str() , value->ToNumber()->Value() );
return;
}
if ( value->IsArray() ){
BSONObj sub = v8ToMongo( value->ToObject() );
b.appendArray( sname.c_str() , sub );
return;
}
if ( value->IsDate() ){
b.appendDate( sname.c_str() , Date_t(v8::Date::Cast( *value )->NumberValue()) );
return;
}
if ( value->IsExternal() )
return;
if ( value->IsObject() ){
// The user could potentially modify the fields of these special objects,
// wreaking havoc when we attempt to reinterpret them. Not doing any validation
// for now...
Local< v8::Object > obj = value->ToObject();
if ( obj->InternalFieldCount() && obj->GetInternalField( 0 )->IsNumber() ) {
switch( obj->GetInternalField( 0 )->ToInt32()->Value() ) { // NOTE Uint32's Value() gave me a linking error, so going with this instead
case Timestamp:
b.appendTimestamp( sname.c_str(),
Date_t( v8::Date::Cast( *obj->Get( v8::String::New( "time" ) ) )->NumberValue() ),
obj->Get( v8::String::New( "i" ) )->ToInt32()->Value() );
return;
case MinKey:
b.appendMinKey( sname.c_str() );
return;
case MaxKey:
b.appendMaxKey( sname.c_str() );
return;
default:
assert( "invalid internal field" == 0 );
}
}
string s = toSTLString( value );
if ( s.size() && s[0] == '/' ){
s = s.substr( 1 );
string r = s.substr( 0 , s.rfind( "/" ) );
string o = s.substr( s.rfind( "/" ) + 1 );
b.appendRegex( sname.c_str() , r.c_str() , o.c_str() );
}
else if ( value->ToObject()->GetPrototype()->IsObject() &&
value->ToObject()->GetPrototype()->ToObject()->HasRealNamedProperty( v8::String::New( "isObjectId" ) ) ){
OID oid;
oid.init( toSTLString( value ) );
b.appendOID( sname.c_str() , &oid );
}
else if ( !value->ToObject()->GetHiddenValue( v8::String::New( "__NumberLong" ) ).IsEmpty() ) {
// TODO might be nice to potentially speed this up with an indexed internal
// field, but I don't yet know how to use an ObjectTemplate with a
// constructor.
unsigned long long val =
( (unsigned long long)( value->ToObject()->Get( v8::String::New( "top" ) )->ToInt32()->Value() ) << 32 ) +
(unsigned)( value->ToObject()->Get( v8::String::New( "bottom" ) )->ToInt32()->Value() );
b.append( sname.c_str(), (long long)val );
}
else if ( !value->ToObject()->GetHiddenValue( v8::String::New( "__DBPointer" ) ).IsEmpty() ) {
OID oid;
oid.init( toSTLString( value->ToObject()->Get( v8::String::New( "id" ) ) ) );
string ns = toSTLString( value->ToObject()->Get( v8::String::New( "ns" ) ) );
b.appendDBRef( sname.c_str(), ns.c_str(), oid );
}
else if ( !value->ToObject()->GetHiddenValue( v8::String::New( "__BinData" ) ).IsEmpty() ) {
int len = obj->Get( v8::String::New( "len" ) )->ToInt32()->Value();
v8::String::Utf8Value data( obj->Get( v8::String::New( "data" ) ) );
const char *dataArray = *data;
assert( data.length() == len );
b.appendBinData( sname.c_str(),
len,
mongo::BinDataType( obj->Get( v8::String::New( "type" ) )->ToInt32()->Value() ),
dataArray );
} else {
BSONObj sub = v8ToMongo( value->ToObject() );
b.append( sname.c_str() , sub );
}
return;
}
//.........这里部分代码省略.........
示例10: newId
Local< v8::Value > newId( const OID &id ) {
v8::Function * idCons = getObjectIdCons();
v8::Handle<v8::Value> argv[1];
argv[0] = v8::String::New( id.str().c_str() );
return idCons->NewInstance( 1 , argv );
}
示例11: conn
void Model::save( bool safe ) {
scoped_ptr<ScopedDbConnection> conn(
ScopedDbConnection::getScopedDbConnection (modelServer() ) );
BSONObjBuilder b;
serialize( b );
BSONElement myId;
{
BSONObjIterator i = b.iterator();
while ( i.more() ) {
BSONElement e = i.next();
if ( strcmp( e.fieldName() , "_id" ) == 0 ) {
myId = e;
break;
}
}
}
if ( myId.type() ) {
if ( _id.isEmpty() ) {
_id = myId.wrap();
}
else if ( myId.woCompare( _id.firstElement() ) ) {
stringstream ss;
ss << "_id from serialize and stored differ: ";
ss << '[' << myId << "] != ";
ss << '[' << _id.firstElement() << ']';
throw UserException( 13121 , ss.str() );
}
}
if ( _id.isEmpty() ) {
OID oid;
oid.init();
b.appendOID( "_id" , &oid );
BSONObj o = b.obj();
conn->get()->insert( getNS() , o );
_id = o["_id"].wrap().getOwned();
LOG(4) << "inserted new model " << getNS() << " " << o << endl;
}
else {
if ( myId.eoo() ) {
myId = _id["_id"];
b.append( myId );
}
verify( ! myId.eoo() );
BSONObjBuilder qb;
qb.append( myId );
BSONObj q = qb.obj();
BSONObj o = b.obj();
LOG(4) << "updated model" << getNS() << " " << q << " " << o << endl;
conn->get()->update( getNS() , q , o , true );
}
string errmsg = "";
if ( safe )
errmsg = conn->get()->getLastError();
conn->done();
if ( safe && errmsg.size() )
throw UserException( 9003 , (string)"error on Model::save: " + errmsg );
}
示例12: updateShardChunks
Status updateShardChunks(OperationContext* opCtx,
const NamespaceString& nss,
const std::vector<ChunkType>& chunks,
const OID& currEpoch) {
invariant(!chunks.empty());
NamespaceString chunkMetadataNss(ChunkType::ShardNSPrefix + nss.ns());
try {
DBDirectClient client(opCtx);
/**
* Here are examples of the operations that can happen on the config server to update
* the config.chunks collection. 'chunks' only includes the chunks that result from the
* operations, which can be read from the config server, not any that were removed, so
* we must delete any chunks that overlap with the new 'chunks'.
*
* CollectionVersion = 10.3
*
* moveChunk
* {_id: 3, max: 5, version: 10.1} --> {_id: 3, max: 5, version: 11.0}
*
* splitChunk
* {_id: 3, max: 9, version 10.3} --> {_id: 3, max: 5, version 10.4}
* {_id: 5, max: 8, version 10.5}
* {_id: 8, max: 9, version 10.6}
*
* mergeChunk
* {_id: 10, max: 14, version 4.3} --> {_id: 10, max: 22, version 10.4}
* {_id: 14, max: 19, version 7.1}
* {_id: 19, max: 22, version 2.0}
*
*/
for (auto& chunk : chunks) {
// Check for a different epoch.
if (!chunk.getVersion().hasEqualEpoch(currEpoch)) {
return Status{ErrorCodes::ConflictingOperationInProgress,
str::stream() << "Invalid chunks found when reloading '"
<< nss.toString()
<< "'. Previous collection epoch was '"
<< currEpoch.toString()
<< "', but unexpectedly found a new epoch '"
<< chunk.getVersion().epoch().toString()
<< "'. Collection was dropped and recreated."};
}
// Delete any overlapping chunk ranges. Overlapping chunks will have a min value
// ("_id") between (chunk.min, chunk.max].
//
// query: { "_id" : {"$gte": chunk.min, "$lt": chunk.max}}
auto deleteDocs(stdx::make_unique<BatchedDeleteDocument>());
deleteDocs->setQuery(BSON(ChunkType::minShardID << BSON(
"$gte" << chunk.getMin() << "$lt" << chunk.getMax())));
deleteDocs->setLimit(0);
auto deleteRequest(stdx::make_unique<BatchedDeleteRequest>());
deleteRequest->addToDeletes(deleteDocs.release());
BatchedCommandRequest batchedDeleteRequest(deleteRequest.release());
batchedDeleteRequest.setNS(chunkMetadataNss);
const BSONObj deleteCmdObj = batchedDeleteRequest.toBSON();
rpc::UniqueReply deleteCommandResponse =
client.runCommandWithMetadata(chunkMetadataNss.db().toString(),
deleteCmdObj.firstElementFieldName(),
rpc::makeEmptyMetadata(),
deleteCmdObj);
auto deleteStatus =
getStatusFromCommandResult(deleteCommandResponse->getCommandReply());
if (!deleteStatus.isOK()) {
return deleteStatus;
}
// Now the document can be expected to cleanly insert without overlap.
auto insert(stdx::make_unique<BatchedInsertRequest>());
insert->addToDocuments(chunk.toShardBSON());
BatchedCommandRequest insertRequest(insert.release());
insertRequest.setNS(chunkMetadataNss);
const BSONObj insertCmdObj = insertRequest.toBSON();
rpc::UniqueReply commandResponse =
client.runCommandWithMetadata(chunkMetadataNss.db().toString(),
insertCmdObj.firstElementFieldName(),
rpc::makeEmptyMetadata(),
insertCmdObj);
auto insertStatus = getStatusFromCommandResult(commandResponse->getCommandReply());
if (!insertStatus.isOK()) {
return insertStatus;
}
}
return Status::OK();
} catch (const DBException& ex) {
return ex.toStatus();
}
}
示例13: handlePossibleShardedMessage
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 , errmsg ) ){
return false;
}
log() << "shardVersionOk failed 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.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;
queueWriteBack( clientID.str() , b.obj() );
return true;
}
示例14: lua_append_bson
static void lua_append_bson(lua_State *L, const char *key, int stackpos, BSONObjBuilder *builder) {
int type = lua_type(L, stackpos);
if (type == LUA_TTABLE) {
int bsontype_found = luaL_getmetafield(L, stackpos, "__bsontype");
if (!bsontype_found) {
// not a special bsontype
// handle as a regular table, iterating keys
BSONObjBuilder b;
int arraylen = check_array(L, stackpos);
if (arraylen) {
for (int i = 0; i < arraylen; i++) {
lua_rawgeti(L, stackpos, i+1);
stringstream ss;
ss << i;
lua_append_bson(L, ss.str().c_str(), -1, &b);
lua_pop(L, 1);
}
builder->appendArray(key, b.obj());
} else {
lua_pushnil(L);
while (lua_next(L, stackpos-1) != 0) {
if (lua_isnumber(L, -2)) {
stringstream ss;
ss << lua_tonumber(L, -2);
lua_append_bson(L, ss.str().c_str(), -1, &b);
} else {
const char *k = lua_tostring(L, -2);
lua_append_bson(L, k, -1, &b);
}
lua_pop(L, 1);
}
builder->append(key, b.obj());
}
} else {
int bson_type = lua_tointeger(L, -1);
lua_pop(L, 1);
lua_rawgeti(L, -1, 1);
switch (bson_type) {
case mongo::Date:
builder->appendDate(key, lua_tonumber(L, -1));
break;
case mongo::Timestamp:
builder->appendTimestamp(key);
break;
case mongo::RegEx: {
const char* regex = lua_tostring(L, -1);
lua_rawgeti(L, -2, 2); // options
const char* options = lua_tostring(L, -1);
lua_pop(L, 1);
builder->appendRegex(key, regex, options);
break;
}
case mongo::NumberInt:
builder->append(key, static_cast<int32_t>(lua_tointeger(L, -1)));
break;
case mongo::NumberLong:
builder->append(key, static_cast<long long int>(lua_tonumber(L, -1)));
break;
case mongo::Symbol:
builder->appendSymbol(key, lua_tostring(L, -1));
break;
case mongo::jstOID: {
OID oid;
oid.init(lua_tostring(L, -1));
builder->appendOID(key, &oid);
break;
}
case mongo::jstNULL:
builder->appendNull(key);
break;
default:
luaL_error(L, LUAMONGO_UNSUPPORTED_BSON_TYPE, luaL_typename(L, stackpos));
}
lua_pop(L, 1);
}
} else if (type == LUA_TNIL) {
builder->appendNull(key);
} else if (type == LUA_TNUMBER) {
double numval = lua_tonumber(L, stackpos);
if (numval == floor(numval)) {
// The numeric value looks like an integer, treat it as such.
// This is closer to how JSON datatypes behave.
int intval = lua_tointeger(L, stackpos);
builder->append(key, static_cast<int32_t>(intval));
} else {
builder->append(key, numval);
}
} else if (type == LUA_TBOOLEAN) {
builder->appendBool(key, lua_toboolean(L, stackpos));
} else if (type == LUA_TSTRING) {
//.........这里部分代码省略.........
示例15: run
bool run(const char *cmdns, BSONObj& cmdObj, string& errmsg, BSONObjBuilder& result, bool){
string configdb = cmdObj["configdb"].valuestrsafe();
{ // configdb checking
if ( configdb.size() == 0 ){
errmsg = "no configdb";
return false;
}
if ( shardConfigServer.size() == 0 ){
if ( ! cmdObj.getBoolField( "authoritative" ) ){
result.appendBool( "need_authoritative" , true );
errmsg = "first setShardVersion";
return false;
}
shardConfigServer = configdb;
}
else if ( shardConfigServer != configdb ){
errmsg = "specified a different configdb!";
return false;
}
}
{ // setting up ids
if ( cmdObj["serverID"].type() != jstOID ){
// TODO: fix this
//errmsg = "need serverID to be an OID";
//return 0;
}
else {
OID clientId = cmdObj["serverID"].__oid();
if ( ! clientServerIds.get() ){
string s = clientId.str();
OID * nid = new OID();
nid->init( s );
clientServerIds.reset( nid );
if ( ! clientQueues[s] )
clientQueues[s] = new BlockingQueue<BSONObj>();
}
else if ( clientId != *clientServerIds.get() ){
errmsg = "server id has changed!";
return 0;
}
}
}
unsigned long long version = getVersion( cmdObj["version"] , errmsg );
if ( ! version )
return false;
NSVersions * versions = clientShardVersions.get();
if ( ! versions ){
log(1) << "entering shard mode for connection" << endl;
versions = new NSVersions();
clientShardVersions.reset( versions );
}
string ns = cmdObj["setShardVersion"].valuestrsafe();
if ( ns.size() == 0 ){
errmsg = "need to speciy fully namespace";
return false;
}
unsigned long long& oldVersion = (*versions)[ns];
if ( version < oldVersion ){
errmsg = "you already have a newer version";
result.appendTimestamp( "oldVersion" , oldVersion );
result.appendTimestamp( "newVersion" , version );
return false;
}
unsigned long long& myVersion = myVersions[ns];
if ( version < myVersion ){
errmsg = "going to older version for global";
return false;
}
if ( myVersion == 0 && ! cmdObj.getBoolField( "authoritative" ) ){
// need authoritative for first look
result.appendBool( "need_authoritative" , true );
result.append( "ns" , ns );
errmsg = "first time for this ns";
return false;
}
result.appendTimestamp( "oldVersion" , oldVersion );
oldVersion = version;
myVersion = version;
result.append( "ok" , 1 );
return 1;
}