• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++ WriteConcernOptions类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中WriteConcernOptions的典型用法代码示例。如果您正苦于以下问题:C++ WriteConcernOptions类的具体用法?C++ WriteConcernOptions怎么用?C++ WriteConcernOptions使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: bsonExtractBooleanField

StatusWith<MigrationSecondaryThrottleOptions>
MigrationSecondaryThrottleOptions::createFromBalancerConfig(const BSONObj& obj) {
    {
        bool isSecondaryThrottle;
        Status status =
            bsonExtractBooleanField(obj, kSecondaryThrottleMongos, &isSecondaryThrottle);
        if (status.isOK()) {
            return MigrationSecondaryThrottleOptions::create(isSecondaryThrottle ? kOn : kOff);
        } else if (status == ErrorCodes::NoSuchKey) {
            return MigrationSecondaryThrottleOptions::create(kDefault);
        } else if (status != ErrorCodes::TypeMismatch) {
            return status;
        }
    }

    // Try to load it as a BSON document
    BSONElement elem;
    Status status = bsonExtractTypedField(obj, kSecondaryThrottleMongos, BSONType::Object, &elem);

    WriteConcernOptions writeConcern;
    Status writeConcernParseStatus = writeConcern.parse(elem.Obj());
    if (!writeConcernParseStatus.isOK()) {
        return writeConcernParseStatus;
    }

    return MigrationSecondaryThrottleOptions::createWithWriteConcern(writeConcern);
}
开发者ID:AlexOreshkevich,项目名称:mongo,代码行数:27,代码来源:migration_secondary_throttle_options.cpp


示例2: bsonExtractTypedField

StatusWith<WriteConcernOptions> WriteConcernOptions::extractWCFromCommand(
    const BSONObj& cmdObj, const std::string& dbName, const WriteConcernOptions& defaultWC) {
    WriteConcernOptions writeConcern = defaultWC;
    writeConcern.usedDefault = true;
    if (writeConcern.wNumNodes == 0 && writeConcern.wMode.empty()) {
        writeConcern.wNumNodes = 1;
    }

    BSONElement writeConcernElement;
    Status wcStatus = bsonExtractTypedField(cmdObj, "writeConcern", Object, &writeConcernElement);
    if (!wcStatus.isOK()) {
        if (wcStatus == ErrorCodes::NoSuchKey) {
            // Return default write concern if no write concern is given.
            return writeConcern;
        }
        return wcStatus;
    }

    BSONObj writeConcernObj = writeConcernElement.Obj();
    // Empty write concern is interpreted to default.
    if (writeConcernObj.isEmpty()) {
        return writeConcern;
    }

    wcStatus = writeConcern.parse(writeConcernObj);
    writeConcern.usedDefault = false;
    if (!wcStatus.isOK()) {
        return wcStatus;
    }

    return writeConcern;
}
开发者ID:CaffeineForCode,项目名称:mongo,代码行数:32,代码来源:write_concern_options.cpp


示例3: WriteConcernOptions

BSONObj CommandHelpers::appendMajorityWriteConcern(const BSONObj& cmdObj) {
    WriteConcernOptions newWC = kMajorityWriteConcern;

    if (cmdObj.hasField(kWriteConcernField)) {
        auto wc = cmdObj.getField(kWriteConcernField);
        // The command has a writeConcern field and it's majority, so we can
        // return it as-is.
        if (wc["w"].ok() && wc["w"].str() == "majority") {
            return cmdObj;
        }

        if (wc["wtimeout"].ok()) {
            // They set a timeout, but aren't using majority WC. We want to use their
            // timeout along with majority WC.
            newWC = WriteConcernOptions(WriteConcernOptions::kMajority,
                                        WriteConcernOptions::SyncMode::UNSET,
                                        wc["wtimeout"].Number());
        }
    }

    // Append all original fields except the writeConcern field to the new command.
    BSONObjBuilder cmdObjWithWriteConcern;
    for (const auto& elem : cmdObj) {
        const auto name = elem.fieldNameStringData();
        if (name != "writeConcern" && !cmdObjWithWriteConcern.hasField(name)) {
            cmdObjWithWriteConcern.append(elem);
        }
    }

    // Finally, add the new write concern.
    cmdObjWithWriteConcern.append(kWriteConcernField, newWC.toBSON());
    return cmdObjWithWriteConcern.obj();
}
开发者ID:kevinAlbs,项目名称:mongo,代码行数:33,代码来源:commands.cpp


示例4: invariant

WriteConcernOptions MigrationSecondaryThrottleOptions::getWriteConcern() const {
    invariant(_secondaryThrottle != kOff);
    invariant(_writeConcernBSON);

    WriteConcernOptions writeConcern;
    fassertStatusOK(34414, writeConcern.parse(*_writeConcernBSON));

    return writeConcern;
}
开发者ID:AlexOreshkevich,项目名称:mongo,代码行数:9,代码来源:migration_secondary_throttle_options.cpp


示例5: validateWriteConcern

Status validateWriteConcern(OperationContext* txn,
                            const WriteConcernOptions& writeConcern,
                            const std::string& dbName) {
    const bool isJournalEnabled = getGlobalServiceContext()->getGlobalStorageEngine()->isDurable();

    if (writeConcern.syncMode == WriteConcernOptions::SyncMode::JOURNAL && !isJournalEnabled) {
        return Status(ErrorCodes::BadValue,
                      "cannot use 'j' option when a host does not have journaling enabled");
    }

    const bool isConfigServer = serverGlobalParams.clusterRole == ClusterRole::ConfigServer;
    const bool isLocalDb(dbName == kLocalDB);
    const repl::ReplicationCoordinator::Mode replMode =
        repl::getGlobalReplicationCoordinator()->getReplicationMode();

    if (isConfigServer) {
        if (!writeConcern.validForConfigServers()) {
            return Status(
                ErrorCodes::BadValue,
                str::stream()
                    << "w:1 and w:'majority' are the only valid write concerns when writing to "
                       "config servers, got: "
                    << writeConcern.toBSON().toString());
        }

        if (replMode == repl::ReplicationCoordinator::modeReplSet &&
            // Allow writes performed within the server to have a write concern of { w: 1 }.
            // This is so commands have the option to skip waiting for replication if they are
            // holding locks (ex. addShardToZone). This also allows commands that perform
            // multiple writes to batch the wait at the end.
            !txn->getClient()->isInDirectClient() &&
            !isLocalDb && writeConcern.wMode.empty()) {
            invariant(writeConcern.wNumNodes == 1);
            return Status(
                ErrorCodes::BadValue,
                str::stream()
                    << "w: 'majority' is the only valid write concern when writing to config "
                       "server replica sets, got: "
                    << writeConcern.toBSON().toString());
        }
    }

    if (replMode == repl::ReplicationCoordinator::modeNone) {
        if (writeConcern.wNumNodes > 1) {
            return Status(ErrorCodes::BadValue, "cannot use 'w' > 1 when a host is not replicated");
        }
    }

    if (replMode != repl::ReplicationCoordinator::modeReplSet && !writeConcern.wMode.empty() &&
        writeConcern.wMode != WriteConcernOptions::kMajority) {
        return Status(ErrorCodes::BadValue,
                      string("cannot use non-majority 'w' mode ") + writeConcern.wMode +
                          " when a host is not a member of a replica set");
    }

    return Status::OK();
}
开发者ID:AshishSanju,项目名称:mongo,代码行数:57,代码来源:write_concern.cpp


示例6: validateWriteConcern

Status validateWriteConcern(const WriteConcernOptions& writeConcern, const std::string& dbName) {
    const bool isJournalEnabled = getGlobalServiceContext()->getGlobalStorageEngine()->isDurable();

    if (writeConcern.syncMode == WriteConcernOptions::JOURNAL && !isJournalEnabled) {
        return Status(ErrorCodes::BadValue,
                      "cannot use 'j' option when a host does not have journaling enabled");
    }

    const bool isConfigServer = serverGlobalParams.configsvr;
    const bool isLocalDb(dbName == kLocalDB);
    const repl::ReplicationCoordinator::Mode replMode =
        repl::getGlobalReplicationCoordinator()->getReplicationMode();

    if (isConfigServer) {
        if (!writeConcern.validForConfigServers()) {
            return Status(
                ErrorCodes::BadValue,
                str::stream()
                    << "w:1 and w:'majority' are the only valid write concerns when writing to "
                       "config servers, got: " << writeConcern.toBSON().toString());
        }
        if (serverGlobalParams.configsvrMode == CatalogManager::ConfigServerMode::CSRS &&
            replMode == repl::ReplicationCoordinator::modeReplSet && !isLocalDb &&
            writeConcern.wMode.empty()) {
            invariant(writeConcern.wNumNodes == 1);
            return Status(
                ErrorCodes::BadValue,
                str::stream()
                    << "w: 'majority' is the only valid write concern when writing to config "
                       "server replica sets, got: " << writeConcern.toBSON().toString());
        }
    }

    if (replMode == repl::ReplicationCoordinator::modeNone) {
        if (writeConcern.wNumNodes > 1) {
            return Status(ErrorCodes::BadValue, "cannot use 'w' > 1 when a host is not replicated");
        }
    }

    if (replMode != repl::ReplicationCoordinator::modeReplSet && !writeConcern.wMode.empty() &&
        writeConcern.wMode != WriteConcernOptions::kMajority) {
        return Status(ErrorCodes::BadValue,
                      string("cannot use non-majority 'w' mode ") + writeConcern.wMode +
                          " when a host is not a member of a replica set");
    }

    return Status::OK();
}
开发者ID:gastongouron,项目名称:mongo,代码行数:48,代码来源:write_concern.cpp


示例7: run

        bool run(const string& dbname, BSONObj& _cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
            LastError *le = lastError.disableForCommand();

            if ( le->nPrev != 1 ) {
                LastError::noError.appendSelf( result , false );
                le->appendSelfStatus( result );
            }
            else {
                le->appendSelf( result , false );
            }

            Client& c = cc();
            c.appendLastOp( result );

            result.appendNumber( "connectionId" , c.getConnectionId() ); // for sharding; also useful in general for debugging

            BSONObj cmdObj = _cmdObj;
            {
                BSONObj::iterator i(_cmdObj);
                i.next();
                if( !i.more() ) {
                    /* empty, use default */
                    BSONObj *def = getLastErrorDefault;
                    if( def )
                        cmdObj = *def;
                }
            }

            WriteConcernOptions writeConcern;
            Status status = writeConcern.parse( cmdObj );
            if ( !status.isOK() ) {
                result.append( "badGLE", cmdObj );
                errmsg = status.toString();
                return false;
            }

            WriteConcernResult res;
            status = waitForWriteConcern( cc(), writeConcern, &res );
            res.appendTo( &result );
            if ( status.code() == ErrorCodes::WriteConcernLegacyOK ) {
                result.append( "wnote", status.toString() );
                return true;
            }
            return appendCommandStatus( result, status );
        }
开发者ID:gabrielhao,项目名称:mongo,代码行数:45,代码来源:get_last_error.cpp


示例8: MigrationSecondaryThrottleOptions

MigrationSecondaryThrottleOptions MigrationSecondaryThrottleOptions::createWithWriteConcern(
    const WriteConcernOptions& writeConcern) {
    // Optimize on write concern, which makes no difference
    if (writeConcern.wNumNodes <= 1 && writeConcern.wMode.empty()) {
        return MigrationSecondaryThrottleOptions(kOff, boost::none);
    }

    return MigrationSecondaryThrottleOptions(kOn, writeConcern.toBSON());
}
开发者ID:AlexOreshkevich,项目名称:mongo,代码行数:9,代码来源:migration_secondary_throttle_options.cpp


示例9: extractWriteConcern

StatusWith<WriteConcernOptions> extractWriteConcern(const BSONObj& cmdObj,
                                                    const std::string& dbName) {
    // The default write concern if empty is w : 1
    // Specifying w : 0 is/was allowed, but is interpreted identically to w : 1
    WriteConcernOptions writeConcern =
        repl::getGlobalReplicationCoordinator()->getGetLastErrorDefault();
    if (writeConcern.wNumNodes == 0 && writeConcern.wMode.empty()) {
        writeConcern.wNumNodes = 1;
    }
    // Upgrade default write concern if necessary.
    addJournalSyncForWMajority(&writeConcern);

    BSONElement writeConcernElement;
    Status wcStatus = bsonExtractTypedField(cmdObj, "writeConcern", Object, &writeConcernElement);
    if (!wcStatus.isOK()) {
        if (wcStatus == ErrorCodes::NoSuchKey) {
            // Return default write concern if no write concern is given.
            return writeConcern;
        }
        return wcStatus;
    }

    BSONObj writeConcernObj = writeConcernElement.Obj();
    // Empty write concern is interpreted to default.
    if (writeConcernObj.isEmpty()) {
        return writeConcern;
    }

    wcStatus = writeConcern.parse(writeConcernObj);
    if (!wcStatus.isOK()) {
        return wcStatus;
    }

    wcStatus = validateWriteConcern(writeConcern, dbName);
    if (!wcStatus.isOK()) {
        return wcStatus;
    }

    // Upgrade parsed write concern if necessary.
    addJournalSyncForWMajority(&writeConcern);

    return writeConcern;
}
开发者ID:gastongouron,项目名称:mongo,代码行数:43,代码来源:write_concern.cpp


示例10: validateWriteConcern

Status validateWriteConcern(OperationContext* txn,
                            const WriteConcernOptions& writeConcern,
                            StringData dbName) {
    if (writeConcern.syncMode == WriteConcernOptions::SyncMode::JOURNAL &&
        !txn->getServiceContext()->getGlobalStorageEngine()->isDurable()) {
        return Status(ErrorCodes::BadValue,
                      "cannot use 'j' option when a host does not have journaling enabled");
    }

    // Remote callers of the config server (as in callers making network calls, not the internal
    // logic) should never be making non-majority writes against the config server, because sharding
    // is not resilient against rollbacks of metadata writes.
    if (serverGlobalParams.clusterRole == ClusterRole::ConfigServer &&
        dbName != NamespaceString::kLocalDb && !writeConcern.validForConfigServers()) {
        // The only cases where we allow non-majority writes are from within the config servers
        // themselves, because these wait for write concern explicitly.
        if (!txn->getClient()->isInDirectClient()) {
            return {ErrorCodes::BadValue,
                    str::stream() << "w:'majority' is the only valid write concern when writing "
                                     "to config servers, got: "
                                  << writeConcern.toBSON()};
        }
    }

    const auto replMode = repl::ReplicationCoordinator::get(txn)->getReplicationMode();

    if (replMode == repl::ReplicationCoordinator::modeNone && writeConcern.wNumNodes > 1) {
        return Status(ErrorCodes::BadValue, "cannot use 'w' > 1 when a host is not replicated");
    }

    if (replMode != repl::ReplicationCoordinator::modeReplSet && !writeConcern.wMode.empty() &&
        writeConcern.wMode != WriteConcernOptions::kMajority) {
        return Status(ErrorCodes::BadValue,
                      string("cannot use non-majority 'w' mode ") + writeConcern.wMode +
                          " when a host is not a member of a replica set");
    }

    return Status::OK();
}
开发者ID:ksuarz,项目名称:mongo,代码行数:39,代码来源:write_concern.cpp


示例11: getDefaultWriteConcernForMigration

StatusWith<WriteConcernOptions> ChunkMoveWriteConcernOptions::getEffectiveWriteConcern(
    OperationContext* opCtx, const MigrationSecondaryThrottleOptions& options) {
    auto secondaryThrottle = options.getSecondaryThrottle();
    if (secondaryThrottle == MigrationSecondaryThrottleOptions::kDefault) {
        if (opCtx->getServiceContext()->getStorageEngine()->supportsDocLocking()) {
            secondaryThrottle = MigrationSecondaryThrottleOptions::kOff;
        } else {
            secondaryThrottle = MigrationSecondaryThrottleOptions::kOn;
        }
    }

    if (secondaryThrottle == MigrationSecondaryThrottleOptions::kOff) {
        return kWriteConcernLocal;
    }

    WriteConcernOptions writeConcern;

    if (options.isWriteConcernSpecified()) {
        writeConcern = options.getWriteConcern();

        repl::ReplicationCoordinator* replCoordinator = repl::ReplicationCoordinator::get(opCtx);

        Status status = replCoordinator->checkIfWriteConcernCanBeSatisfied(writeConcern);
        if (!status.isOK() && status != ErrorCodes::NoReplicationEnabled) {
            return status;
        }
    } else {
        writeConcern = getDefaultWriteConcernForMigration(opCtx);
    }

    if (writeConcern.shouldWaitForOtherNodes() &&
        writeConcern.wTimeout == WriteConcernOptions::kNoTimeout) {
        // Don't allow no timeout
        writeConcern.wTimeout = durationCount<Milliseconds>(kDefaultWriteTimeoutForMigration);
    }

    return writeConcern;
}
开发者ID:louiswilliams,项目名称:mongo,代码行数:38,代码来源:chunk_move_write_concern_options.cpp


示例12: getDefaultWriteConcernForMigration

StatusWith<ChunkMoveWriteConcernOptions> ChunkMoveWriteConcernOptions::initFromCommand(
    const BSONObj& cmdObj) {
    BSONObj secThrottleObj;
    WriteConcernOptions writeConcernOptions;

    Status status = writeConcernOptions.parseSecondaryThrottle(cmdObj, &secThrottleObj);
    if (!status.isOK()) {
        if (status.code() != ErrorCodes::WriteConcernNotDefined) {
            return status;
        }

        writeConcernOptions = getDefaultWriteConcernForMigration();
    } else {
        repl::ReplicationCoordinator* replCoordinator = repl::getGlobalReplicationCoordinator();

        if (replCoordinator->getReplicationMode() ==
                repl::ReplicationCoordinator::modeMasterSlave &&
            writeConcernOptions.shouldWaitForOtherNodes()) {
            warning() << "moveChunk cannot check if secondary throttle setting "
                      << writeConcernOptions.toBSON()
                      << " can be enforced in a master slave configuration";
        }

        Status status = replCoordinator->checkIfWriteConcernCanBeSatisfied(writeConcernOptions);
        if (!status.isOK() && status != ErrorCodes::NoReplicationEnabled) {
            return status;
        }
    }

    if (writeConcernOptions.shouldWaitForOtherNodes() &&
        writeConcernOptions.wTimeout == WriteConcernOptions::kNoTimeout) {
        // Don't allow no timeout
        writeConcernOptions.wTimeout = kDefaultWriteTimeoutForMigrationMs;
    }

    return ChunkMoveWriteConcernOptions(secThrottleObj, writeConcernOptions);
}
开发者ID:hunnymunch,项目名称:mongo,代码行数:37,代码来源:migration_impl.cpp


示例13: warning

StatusWith<WriteConcernOptions> ChunkMoveWriteConcernOptions::getEffectiveWriteConcern(
    const MigrationSecondaryThrottleOptions& options) {
    if (options.getSecondaryThrottle() == MigrationSecondaryThrottleOptions::kOff) {
        return kWriteConcernLocal;
    }

    WriteConcernOptions writeConcern;

    if (options.isWriteConcernSpecified()) {
        writeConcern = options.getWriteConcern();

        repl::ReplicationCoordinator* replCoordinator = repl::getGlobalReplicationCoordinator();

        if (replCoordinator->getReplicationMode() ==
                repl::ReplicationCoordinator::modeMasterSlave &&
            writeConcern.shouldWaitForOtherNodes()) {
            warning() << "moveChunk cannot check if secondary throttle setting "
                      << writeConcern.toBSON()
                      << " can be enforced in a master slave configuration";
        }

        Status status = replCoordinator->checkIfWriteConcernCanBeSatisfied(writeConcern);
        if (!status.isOK() && status != ErrorCodes::NoReplicationEnabled) {
            return status;
        }
    } else {
        writeConcern = getDefaultWriteConcernForMigration();
    }

    if (writeConcern.shouldWaitForOtherNodes() &&
        writeConcern.wTimeout == WriteConcernOptions::kNoTimeout) {
        // Don't allow no timeout
        writeConcern.wTimeout = durationCount<Milliseconds>(kDefaultWriteTimeoutForMigration);
    }

    return writeConcern;
}
开发者ID:AnkyrinRepeat,项目名称:mongo,代码行数:37,代码来源:chunk_move_write_concern_options.cpp


示例14: bsonExtractTypedField

StatusWith<WriteConcernOptions> WriteConcernOptions::extractWCFromCommand(
    const BSONObj& cmdObj, const std::string& dbName, const WriteConcernOptions& defaultWC) {
    WriteConcernOptions writeConcern = defaultWC;
    writeConcern.usedDefault = true;
    if (writeConcern.wNumNodes == 0 && writeConcern.wMode.empty()) {
        writeConcern.wNumNodes = 1;
    }

    // Return the default write concern if no write concern is provided. We check for the existence
    // of the write concern field up front in order to avoid the expense of constructing an error
    // status in bsonExtractTypedField() below.
    if (!cmdObj.hasField(kWriteConcernField)) {
        return writeConcern;
    }

    BSONElement writeConcernElement;
    Status wcStatus =
        bsonExtractTypedField(cmdObj, kWriteConcernField, Object, &writeConcernElement);
    if (!wcStatus.isOK()) {
        return wcStatus;
    }

    BSONObj writeConcernObj = writeConcernElement.Obj();
    // Empty write concern is interpreted to default.
    if (writeConcernObj.isEmpty()) {
        return writeConcern;
    }

    wcStatus = writeConcern.parse(writeConcernObj);
    writeConcern.usedDefault = false;
    if (!wcStatus.isOK()) {
        return wcStatus;
    }

    return writeConcern;
}
开发者ID:pk-karthik,项目名称:mongo,代码行数:36,代码来源:write_concern_options.cpp


示例15: request

StatusWith<bool> ShardingCatalogClientImpl::_updateConfigDocument(
    OperationContext* opCtx,
    const NamespaceString& nss,
    const BSONObj& query,
    const BSONObj& update,
    bool upsert,
    const WriteConcernOptions& writeConcern) {
    invariant(nss.db() == NamespaceString::kConfigDb);

    const BSONElement idField = query.getField("_id");
    invariant(!idField.eoo());

    BatchedCommandRequest request([&] {
        write_ops::Update updateOp(nss);
        updateOp.setUpdates({[&] {
            write_ops::UpdateOpEntry entry;
            entry.setQ(query);
            entry.setU(update);
            entry.setUpsert(upsert);
            entry.setMulti(false);
            return entry;
        }()});
        return updateOp;
    }());
    request.setWriteConcern(writeConcern.toBSON());

    auto configShard = Grid::get(opCtx)->shardRegistry()->getConfigShard();
    auto response = configShard->runBatchWriteCommand(
        opCtx, Shard::kDefaultConfigCommandTimeout, request, Shard::RetryPolicy::kIdempotent);

    Status status = response.toStatus();
    if (!status.isOK()) {
        return status;
    }

    const auto nSelected = response.getN();
    invariant(nSelected == 0 || nSelected == 1);
    return (nSelected == 1);
}
开发者ID:ShaneHarvey,项目名称:mongo,代码行数:39,代码来源:sharding_catalog_client_impl.cpp


示例16: removeConfigDocuments

Status ShardingCatalogClientImpl::removeConfigDocuments(OperationContext* opCtx,
                                                        const NamespaceString& nss,
                                                        const BSONObj& query,
                                                        const WriteConcernOptions& writeConcern) {
    invariant(nss.db() == NamespaceString::kConfigDb);

    BatchedCommandRequest request([&] {
        write_ops::Delete deleteOp(nss);
        deleteOp.setDeletes({[&] {
            write_ops::DeleteOpEntry entry;
            entry.setQ(query);
            entry.setMulti(true);
            return entry;
        }()});
        return deleteOp;
    }());
    request.setWriteConcern(writeConcern.toBSON());

    auto configShard = Grid::get(opCtx)->shardRegistry()->getConfigShard();
    auto response = configShard->runBatchWriteCommand(
        opCtx, Shard::kDefaultConfigCommandTimeout, request, Shard::RetryPolicy::kIdempotent);
    return response.toStatus();
}
开发者ID:ShaneHarvey,项目名称:mongo,代码行数:23,代码来源:sharding_catalog_client_impl.cpp


示例17: run

        bool run(OperationContext* txn, const string& dbname,
                  BSONObj& cmdObj,
                  int,
                  string& errmsg,
                  BSONObjBuilder& result,
                  bool fromRepl ) {

            //
            // Correct behavior here is very finicky.
            //
            // 1.  The first step is to append the error that occurred on the previous operation.
            // This adds an "err" field to the command, which is *not* the command failing.
            //
            // 2.  Next we parse and validate write concern options.  If these options are invalid
            // the command fails no matter what, even if we actually had an error earlier.  The
            // reason for checking here is to match legacy behavior on these kind of failures -
            // we'll still get an "err" field for the write error.
            //
            // 3.  If we had an error on the previous operation, we then return immediately.
            //
            // 4.  Finally, we actually enforce the write concern.  All errors *except* timeout are
            // reported with ok : 0.0, to match legacy behavior.
            //
            // There is a special case when "wOpTime" and "wElectionId" are explicitly provided by 
            // the client (mongos) - in this case we *only* enforce the write concern if it is 
            // valid.
            //
            // We always need to either report "err" (if ok : 1) or "errmsg" (if ok : 0), even if
            // err is null.
            //

            LastError *le = lastError.disableForCommand();

            // Always append lastOp and connectionId
            Client& c = cc();
            c.appendLastOp( result );

            // for sharding; also useful in general for debugging
            result.appendNumber( "connectionId" , c.getConnectionId() );

            OpTime lastOpTime;
            BSONField<OpTime> wOpTimeField("wOpTime");
            FieldParser::FieldState extracted = FieldParser::extract(cmdObj, wOpTimeField, 
                                                                     &lastOpTime, &errmsg);
            if (!extracted) {
                result.append("badGLE", cmdObj);
                appendCommandStatus(result, false, errmsg);
                return false;
            }
            bool lastOpTimePresent = extracted != FieldParser::FIELD_NONE;
            if (!lastOpTimePresent) {
                // Use the client opTime if no wOpTime is specified
                lastOpTime = cc().getLastOp();
            }
            
            OID electionId;
            BSONField<OID> wElectionIdField("wElectionId");
            extracted = FieldParser::extract(cmdObj, wElectionIdField, 
                                             &electionId, &errmsg);
            if (!extracted) {
                result.append("badGLE", cmdObj);
                appendCommandStatus(result, false, errmsg);
                return false;
            }

            bool electionIdPresent = extracted != FieldParser::FIELD_NONE;
            bool errorOccurred = false;

            // Errors aren't reported when wOpTime is used
            if ( !lastOpTimePresent ) {
                if ( le->nPrev != 1 ) {
                    errorOccurred = LastError::noError.appendSelf( result, false );
                    le->appendSelfStatus( result );
                }
                else {
                    errorOccurred = le->appendSelf( result, false );
                }
            }

            BSONObj writeConcernDoc = cmdObj;
            // Use the default options if we have no gle options aside from wOpTime/wElectionId
            const int nFields = cmdObj.nFields();
            bool useDefaultGLEOptions = (nFields == 1) || 
                (nFields == 2 && lastOpTimePresent) ||
                (nFields == 3 && lastOpTimePresent && electionIdPresent);

            if ( useDefaultGLEOptions && getLastErrorDefault ) {
                writeConcernDoc = *getLastErrorDefault;
            }

            //
            // Validate write concern no matter what, this matches 2.4 behavior
            //

            WriteConcernOptions writeConcern;
            Status status = writeConcern.parse( writeConcernDoc );

            if ( status.isOK() ) {
                // Ensure options are valid for this host
                status = validateWriteConcern( writeConcern );
//.........这里部分代码省略.........
开发者ID:AtomRong,项目名称:mongo,代码行数:101,代码来源:get_last_error.cpp


示例18: waitForWriteConcern

Status waitForWriteConcern(OperationContext* txn,
                           const OpTime& replOpTime,
                           const WriteConcernOptions& writeConcern,
                           WriteConcernResult* result) {
    LOG(2) << "Waiting for write concern. OpTime: " << replOpTime
           << ", write concern: " << writeConcern.toBSON();
    auto replCoord = repl::ReplicationCoordinator::get(txn);

    MONGO_FAIL_POINT_PAUSE_WHILE_SET(hangBeforeWaitingForWriteConcern);

    // Next handle blocking on disk
    Timer syncTimer;
    WriteConcernOptions writeConcernWithPopulatedSyncMode =
        replCoord->populateUnsetWriteConcernOptionsSyncMode(writeConcern);

    switch (writeConcernWithPopulatedSyncMode.syncMode) {
        case WriteConcernOptions::SyncMode::UNSET:
            severe() << "Attempting to wait on a WriteConcern with an unset sync option";
            fassertFailed(34410);
        case WriteConcernOptions::SyncMode::NONE:
            break;
        case WriteConcernOptions::SyncMode::FSYNC: {
            StorageEngine* storageEngine = getGlobalServiceContext()->getGlobalStorageEngine();
            if (!storageEngine->isDurable()) {
                result->fsyncFiles = storageEngine->flushAllFiles(true);
            } else {
                // We only need to commit the journal if we're durable
                txn->recoveryUnit()->waitUntilDurable();
            }
            break;
        }
        case WriteConcernOptions::SyncMode::JOURNAL:
            if (replCoord->getReplicationMode() != repl::ReplicationCoordinator::Mode::modeNone) {
                // Wait for ops to become durable then update replication system's
                // knowledge of this.
                OpTime appliedOpTime = replCoord->getMyLastAppliedOpTime();
                txn->recoveryUnit()->waitUntilDurable();
                replCoord->setMyLastDurableOpTimeForward(appliedOpTime);
            } else {
                txn->recoveryUnit()->waitUntilDurable();
            }
            break;
    }

    result->syncMillis = syncTimer.millis();

    // Now wait for replication

    if (replOpTime.isNull()) {
        // no write happened for this client yet
        return Status::OK();
    }

    // needed to avoid incrementing gleWtimeStats SERVER-9005
    if (writeConcernWithPopulatedSyncMode.wNumNodes <= 1 &&
        writeConcernWithPopulatedSyncMode.wMode.empty()) {
        // no desired replication check
        return Status::OK();
    }

    // Replica set stepdowns and gle mode changes are thrown as errors
    repl::ReplicationCoordinator::StatusAndDuration replStatus =
        replCoord->awaitReplication(txn, replOpTime, writeConcernWithPopulatedSyncMode);
    if (replStatus.status == ErrorCodes::WriteConcernFailed) {
        gleWtimeouts.increment();
        result->err = "timeout";
        result->wTimedOut = true;
    }

    // Add stats
    result->writtenTo = repl::getGlobalReplicationCoordinator()->getHostsWrittenTo(
        replOpTime,
        writeConcernWithPopulatedSyncMode.syncMode == WriteConcernOptions::SyncMode::JOURNAL);
    gleWtimeStats.recordMillis(durationCount<Milliseconds>(replStatus.duration));
    result->wTime = durationCount<Milliseconds>(replStatus.duration);

    return replStatus.status;
}
开发者ID:ksuarz,项目名称:mongo,代码行数:78,代码来源:write_concern.cpp


示例19: validateWriteConcern

    void WriteBatchExecutor::executeBatch( const BatchedCommandRequest& request,
                                           BatchedCommandResponse* response ) {

        // TODO: Lift write concern parsing out of this entirely.
        WriteConcernOptions writeConcern;
        Status status = Status::OK();

        BSONObj wcDoc;
        if ( request.isWriteConcernSet() ) {
            wcDoc = request.getWriteConcern();
        }

        if ( wcDoc.isEmpty() ) {
            status = writeConcern.parse( _defaultWriteConcern );
        }
        else {
            status = writeConcern.parse( wcDoc );
        }

        if ( status.isOK() ) {
            status = validateWriteConcern( writeConcern );
        }

        if ( !status.isOK() ) {
            response->setErrCode( status.code() );
            response->setErrMessage( status.reason() );
            response->setOk( false );
            dassert( response->isValid(NULL) );
            return;
        }

        bool silentWC = writeConcern.wMode.empty() && writeConcern.wNumNodes == 0
                        && writeConcern.syncMode == WriteConcernOptions::NONE;

        Timer commandTimer;

        OwnedPointerVector<WriteErrorDetail> writeErrorsOwned;
        vector<WriteErrorDetail*>& writeErrors = writeErrorsOwned.mutableVector();

        OwnedPointerVector<BatchedUpsertDetail> upsertedOwned;
        vector<BatchedUpsertDetail*>& upserted = upsertedOwned.mutableVector();

        //
        // Apply each batch item, possibly bulking some items together in the write lock.
        // Stops on error if batch is ordered.
        //

        bulkExecute( request, &upserted, &writeErrors );

        //
        // Try to enforce the write concern if everything succeeded (unordered or ordered)
        // OR if something succeeded and we're unordered.
        //

        auto_ptr<WCErrorDetail> wcError;
        bool needToEnforceWC = writeErrors.empty()
                               || ( !request.getOrdered()
                                    && writeErrors.size() < request.sizeWriteOps() );

        if ( needToEnforceWC ) {

            _client->curop()->setMessage( "waiting for write concern" );

            WriteConcernResult res;
            status = waitForWriteConcern( writeConcern, _client->getLastOp(), &res );

            if ( !status.isOK() ) {
                wcError.reset( toWriteConcernError( status, res ) );
            }
        }

        //
        // Refresh metadata if needed
        //

        bool staleBatch = !writeErrors.empty()
                          && writeErrors.back()->getErrCode() == ErrorCodes::StaleShardVersion;

        if ( staleBatch ) {

            const BatchedRequestMetadata* requestMetadata = request.getMetadata();
            dassert( requestMetadata );

            // Make sure our shard name is set or is the same as what was set previously
            if ( shardingState.setShardName( requestMetadata->getShardName() ) ) {

                //
                // First, we refresh metadata if we need to based on the requested version.
                //

                ChunkVersion latestShardVersion;
                shardingState.refreshMetadataIfNeeded( request.getTargetingNS(),
                                                       requestMetadata->getShardVersion(),
                                                       &latestShardVersion );

                // Report if we're still changing our metadata
                // TODO: Better reporting per-collection
                if ( shardingState.inCriticalMigrateSection() ) {
                    noteInCriticalSection( writeErrors.back() );
                }
//.........这里部分代码省略.........
开发者ID:EddieWu,项目名称:mongo,代码行数:101,代码来源:batch_executor.cpp


示例20: cmdObjIter

bool ShardingCatalogClientImpl::runUserManagementWriteCommand(OperationContext* opCtx,
                                                              const std::string& commandName,
                                                              const std::string& dbname,
                                                              const BSONObj& cmdObj,
                                                              BSONObjBuilder* result) {
    BSONObj cmdToRun = cmdObj;
    {
        // Make sure that if the command has a write concern that it is w:1 or w:majority, and
        // convert w:1 or no write concern to w:majority before sending.
        WriteConcernOptions writeConcern;
        writeConcern.reset();

        BSONElement writeConcernElement = cmdObj[WriteConcernOptions::kWriteConcernField];
        bool initialCmdHadWriteConcern = !writeConcernElement.eoo();
        if (initialCmdHadWriteConcern) {
            Status status = writeConcern.parse(writeConcernElement.Obj());
            if (!status.isOK()) {
                return CommandHelpers::appen 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ WriteErrorDetail类代码示例发布时间:2022-05-31
下一篇:
C++ WriteBuffer类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap