主頁 > 資料庫 > mongodb 資料塊遷移的原始碼分析

mongodb 資料塊遷移的原始碼分析

2022-07-14 08:58:13 資料庫

1. 簡介

上一篇我們聊到了mongodb資料塊的基本概念,和資料塊遷移的主要流程(詳見mongodb資料塊的遷移流程介紹),這篇文章我們聊聊原始碼實作部分,

2. 遷移序列圖

資料塊遷移的請求是從配置服務器(config server)發給(donor,捐獻方),再有捐獻方發起遷移請求給目標節點(recipient,接收方),后續遷移由捐獻方和接收方配合完成,

資料遷移結束時,捐獻方再提交遷移結果給配置服務器,三方互動序列圖如下:

 

可以看到,序列圖中的5個步驟,是對應前面文章的遷移流程中的5個步驟,其中接收方的流程控制代碼在migration_destination_manager.cpp中的_migrateDriver方法中,捐獻方的流程控制代碼在donor的move_chunk_command.cpp中的_runImpl方法中完成,代碼如下:

static void _runImpl(OperationContext* opCtx, const MoveChunkRequest& moveChunkRequest) {
        const auto writeConcernForRangeDeleter =
            uassertStatusOK(ChunkMoveWriteConcernOptions::getEffectiveWriteConcern(
                opCtx, moveChunkRequest.getSecondaryThrottle()));

        // Resolve the donor and recipient shards and their connection string
        auto const shardRegistry = Grid::get(opCtx)->shardRegistry();
        // 準備donor和recipient的連接
        const auto donorConnStr =
            uassertStatusOK(shardRegistry->getShard(opCtx, moveChunkRequest.getFromShardId()))
                ->getConnString();
        const auto recipientHost = uassertStatusOK([&] {
            auto recipientShard =
                uassertStatusOK(shardRegistry->getShard(opCtx, moveChunkRequest.getToShardId()));

            return recipientShard->getTargeter()->findHost(
                opCtx, ReadPreferenceSetting{ReadPreference::PrimaryOnly});
        }());

        std::string unusedErrMsg;
        // 用于統計每一步的耗時情況
        MoveTimingHelper moveTimingHelper(opCtx,
                                          "from",
                                          moveChunkRequest.getNss().ns(),
                                          moveChunkRequest.getMinKey(),
                                          moveChunkRequest.getMaxKey(),
                                          6,  // Total number of steps
                                          &unusedErrMsg,
                                          moveChunkRequest.getToShardId(),
                                          moveChunkRequest.getFromShardId());

        moveTimingHelper.done(1);
        moveChunkHangAtStep1.pauseWhileSet();

        if (moveChunkRequest.getFromShardId() == moveChunkRequest.getToShardId()) {
            // TODO: SERVER-46669 handle wait for delete.
            return;
        }
        // 構建遷移任務管理器
        MigrationSourceManager migrationSourceManager(
            opCtx, moveChunkRequest, donorConnStr, recipientHost);

        moveTimingHelper.done(2);
        moveChunkHangAtStep2.pauseWhileSet();

        // 向接收方發送遷移命令
        uassertStatusOKWithWarning(migrationSourceManager.startClone());
        moveTimingHelper.done(3);
        moveChunkHangAtStep3.pauseWhileSet();

        // 等待塊資料和變更資料都拷貝完成
        uassertStatusOKWithWarning(migrationSourceManager.awaitToCatchUp());
        moveTimingHelper.done(4);
        moveChunkHangAtStep4.pauseWhileSet();

        // 進入臨界區
        uassertStatusOKWithWarning(migrationSourceManager.enterCriticalSection());

        // 通知接收方
        uassertStatusOKWithWarning(migrationSourceManager.commitChunkOnRecipient());
        moveTimingHelper.done(5);
        moveChunkHangAtStep5.pauseWhileSet();

        // 在配置服務器提交分塊元資料資訊
        uassertStatusOKWithWarning(migrationSourceManager.commitChunkMetadataOnConfig());
        moveTimingHelper.done(6);
        moveChunkHangAtStep6.pauseWhileSet();
    }

下面對每一個步驟的代碼做分析,

3. 各步驟原始碼分析

3.1 啟動遷移( _recvChunkStart)

 

在啟動階段,捐獻方主要做了三件事:

1. 引數檢查,在MigrationSourceManager 建構式中完成,不再贅述,

2. 注冊監聽器,用于記錄在遷移期間該資料塊內發生的變更資料,代碼如下:

3. 向接收方發送遷移命令_recvChunkStart,

步驟2和3的代碼實作在一個方法中,如下:

Status MigrationSourceManager::startClone() {
    ...// 省略了部分代碼

    _cloneAndCommitTimer.reset();

    auto replCoord = repl::ReplicationCoordinator::get(_opCtx);
    auto replEnabled = replCoord->isReplEnabled();

    {
        const auto metadata =https://www.cnblogs.com/xinghebuluo/p/ _getCurrentMetadataAndCheckEpoch();

        // Having the metadata manager registered on the collection sharding state is what indicates
        // that a chunk on that collection is being migrated. With an active migration, write
        // operations require the cloner to be present in order to track changes to the chunk which
        // needs to be transmitted to the recipient.
        // 注冊監聽器,_cloneDriver除了遷移資料外,還會用于記錄在遷移程序中該資料塊增量變化的資料(比如新增的資料)
        _cloneDriver = std::make_unique<MigrationChunkClonerSourceLegacy>(
            _args, metadata.getKeyPattern(), _donorConnStr, _recipientHost);

        AutoGetCollection autoColl(_opCtx,
                                   getNss(),
                                   replEnabled ? MODE_IX : MODE_X,
                                   AutoGetCollectionViewMode::kViewsForbidden,
                                   _opCtx->getServiceContext()->getPreciseClockSource()->now() +
                                       Milliseconds(migrationLockAcquisitionMaxWaitMS.load()));

        auto csr = CollectionShardingRuntime::get(_opCtx, getNss());
        auto lockedCsr = CollectionShardingRuntime::CSRLock::lockExclusive(_opCtx, csr);
        invariant(nullptr == std::exchange(msmForCsr(csr), this));

        _coordinator = std::make_unique<migrationutil::MigrationCoordinator>(
            _cloneDriver->getSessionId(),
            _args.getFromShardId(),
            _args.getToShardId(),
            getNss(),
            *_collectionUUID,
            ChunkRange(_args.getMinKey(), _args.getMaxKey()),
            _chunkVersion,
            _args.getWaitForDelete());

        _state = kCloning;
    }

    if (replEnabled) {
        auto const readConcernArgs = repl::ReadConcernArgs(
            replCoord->getMyLastAppliedOpTime(), repl::ReadConcernLevel::kLocalReadConcern);

        // 檢查當前節點狀態是否滿足repl::ReadConcernLevel::kLocalReadConcern
        auto waitForReadConcernStatus =
            waitForReadConcern(_opCtx, readConcernArgs, StringData(), false);
        if (!waitForReadConcernStatus.isOK()) {
            return waitForReadConcernStatus;
        }
        setPrepareConflictBehaviorForReadConcern(
            _opCtx, readConcernArgs, PrepareConflictBehavior::kEnforce);
    }

    _coordinator->startMigration(_opCtx);

    // 向接收方發送開始拷貝資料的命令(_recvChunkStart)
    Status startCloneStatus = _cloneDriver->startClone(_opCtx,
                                                       _coordinator->getMigrationId(),
                                                       _coordinator->getLsid(),
                                                       _coordinator->getTxnNumber());
    if (!startCloneStatus.isOK()) {
        return startCloneStatus;
    }

    scopedGuard.dismiss();
    return Status::OK();
}

 

接收方在收到遷移請求后,會先檢查本地是否有該表,如果沒有的話,會先建表會創建表的索引:

void MigrationDestinationManager::cloneCollectionIndexesAndOptions(
    OperationContext* opCtx,
    const NamespaceString& nss,
    const CollectionOptionsAndIndexes& collectionOptionsAndIndexes) {
    {
        // 1. Create the collection (if it doesn't already exist) and create any indexes we are
        // missing (auto-heal indexes).

        ...// 省略部分代碼

        {
            AutoGetCollection collection(opCtx, nss, MODE_IS);
            // 如果存在表,且不缺索引,則退出
            if (collection) {
                checkUUIDsMatch(collection.getCollection());
                auto indexSpecs =
                    checkEmptyOrGetMissingIndexesFromDonor(collection.getCollection());
                if (indexSpecs.empty()) {
                    return;
                }
            }
        }

        // Take the exclusive database lock if the collection does not exist or indexes are missing
        // (needs auto-heal).
        // 建表時,需要對資料庫加鎖
        AutoGetDb autoDb(opCtx, nss.db(), MODE_X);
        auto db = autoDb.ensureDbExists();

        auto collection = CollectionCatalog::get(opCtx)->lookupCollectionByNamespace(opCtx, nss);
        if (collection) {
            checkUUIDsMatch(collection);
        } else {
            ...// 省略部分代碼// We do not have a collection by this name. Create the collection with the donor's
            // options.
            // 建表
            OperationShardingState::ScopedAllowImplicitCollectionCreate_UNSAFE
                unsafeCreateCollection(opCtx);
            WriteUnitOfWork wuow(opCtx);
            CollectionOptions collectionOptions = uassertStatusOK(
                CollectionOptions::parse(collectionOptionsAndIndexes.options,
                                         CollectionOptions::ParseKind::parseForStorage));
            const bool createDefaultIndexes = true;
            uassertStatusOK(db->userCreateNS(opCtx,
                                             nss,
                                             collectionOptions,
                                             createDefaultIndexes,
                                             collectionOptionsAndIndexes.idIndexSpec));
            wuow.commit();
            collection = CollectionCatalog::get(opCtx)->lookupCollectionByNamespace(opCtx, nss);
        }
        // 創建對應的索引
        auto indexSpecs = checkEmptyOrGetMissingIndexesFromDonor(collection);
        if (!indexSpecs.empty()) {
            WriteUnitOfWork wunit(opCtx);
            auto fromMigrate = true;
            CollectionWriter collWriter(opCtx, collection->uuid());
            IndexBuildsCoordinator::get(opCtx)->createIndexesOnEmptyCollection(
                opCtx, collWriter, indexSpecs, fromMigrate);
            wunit.commit();
        }
    }
}

 

3.2 接收方拉取存量資料( _migrateClone)

接收方的拉取存量資料時,做了六件事情:

1. 定義了一個批量插入記錄的方法,

2. 定義了一個批量拉取資料的方法,

3. 定義生產者和消費佇列,

4. 啟動資料寫入執行緒,該執行緒會消費佇列中的資料,并呼叫批量插入記錄的方法把記錄保存到本地,

5. 回圈向捐獻方發起拉取資料請求(步驟2的方法),并寫入步驟3的佇列中,

6. 資料拉取結束后(寫入空記錄到佇列中,觸發步驟5結束),則同步等待步驟5的執行緒也結束,

詳細代碼如下:

// 1. 定義批量寫入函式
        auto insertBatchFn = [&](OperationContext* opCtx, BSONObj arr) {
            auto it = arr.begin();
            while (it != arr.end()) {
                int batchNumCloned = 0;
                int batchClonedBytes = 0;
                const int batchMaxCloned = migrateCloneInsertionBatchSize.load();

                assertNotAborted(opCtx);

                write_ops::InsertCommandRequest insertOp(_nss);
                insertOp.getWriteCommandRequestBase().setOrdered(true);
                insertOp.setDocuments([&] {
                    std::vector<BSONObj> toInsert;
                    while (it != arr.end() &&
                           (batchMaxCloned <= 0 || batchNumCloned < batchMaxCloned)) {
                        const auto& doc = *it;
                        BSONObj docToClone = doc.Obj();
                        toInsert.push_back(docToClone);
                        batchNumCloned++;
                        batchClonedBytes += docToClone.objsize();
                        ++it;
                    }
                    return toInsert;
                }());

                const auto reply =
                    write_ops_exec::performInserts(opCtx, insertOp, OperationSource::kFromMigrate);

                for (unsigned long i = 0; i < reply.results.size(); ++i) {
                    uassertStatusOKWithContext(
                        reply.results[i],
                        str::stream() << "Insert of " << insertOp.getDocuments()[i] << " failed.");
                }

                {
                    stdx::lock_guard<Latch> statsLock(_mutex);
                    _numCloned += batchNumCloned;
                    ShardingStatistics::get(opCtx).countDocsClonedOnRecipient.addAndFetch(
                        batchNumCloned);
                    _clonedBytes += batchClonedBytes;
                }
                if (_writeConcern.needToWaitForOtherNodes()) {
                    runWithoutSession(outerOpCtx, [&] {
                        repl::ReplicationCoordinator::StatusAndDuration replStatus =
                            repl::ReplicationCoordinator::get(opCtx)->awaitReplication(
                                opCtx,
                                repl::ReplClientInfo::forClient(opCtx->getClient()).getLastOp(),
                                _writeConcern);
                        if (replStatus.status.code() == ErrorCodes::WriteConcernFailed) {
                            LOGV2_WARNING(
                                22011,
                                "secondaryThrottle on, but doc insert timed out; continuing",
                                "migrationId"_attr = _migrationId->toBSON());
                        } else {
                            uassertStatusOK(replStatus.status);
                        }
                    });
                }

                sleepmillis(migrateCloneInsertionBatchDelayMS.load());
            }
        };
        // 2. 定義批量拉取函式
        auto fetchBatchFn = [&](OperationContext* opCtx) {
            auto res = uassertStatusOKWithContext(
                fromShard->runCommand(opCtx,
                                      ReadPreferenceSetting(ReadPreference::PrimaryOnly),
                                      "admin",
                                      migrateCloneRequest,
                                      Shard::RetryPolicy::kNoRetry),
                "_migrateClone failed: ");

            uassertStatusOKWithContext(Shard::CommandResponse::getEffectiveStatus(res),
                                       "_migrateClone failed: ");

            return res.response;
        };

SingleProducerSingleConsumerQueue<BSONObj>::Options options;
    options.maxQueueDepth = 1;
    // 3. 使用生產者和消費者佇列來把同步的資料寫入到本地
    SingleProducerSingleConsumerQueue<BSONObj> batches(options);
    repl::OpTime lastOpApplied;

    // 4. 定義寫資料執行緒,該執行緒會讀取佇列中的資料并寫入本地節點,直到無需要同步的資料時執行緒退出
    stdx::thread inserterThread{[&] {
        Client::initThread("chunkInserter", opCtx->getServiceContext(), nullptr);
        auto client = Client::getCurrent();
        {
            stdx::lock_guard lk(*client);
            client->setSystemOperationKillableByStepdown(lk);
        }
        auto executor =
            Grid::get(opCtx->getServiceContext())->getExecutorPool()->getFixedExecutor();
        auto inserterOpCtx = CancelableOperationContext(
            cc().makeOperationContext(), opCtx->getCancellationToken(), executor);

        auto consumerGuard = makeGuard([&] {
            batches.closeConsumerEnd();
            lastOpApplied = repl::ReplClientInfo::forClient(inserterOpCtx->getClient()).getLastOp();
        });

        try {
            while (true) {
                auto nextBatch = batches.pop(inserterOpCtx.get());
                auto arr = nextBatch["objects"].Obj();
                if (arr.isEmpty()) {
                    return;
                }
                insertBatchFn(inserterOpCtx.get(), arr);
            }
        } catch (...) {
            stdx::lock_guard<Client> lk(*opCtx->getClient());
            opCtx->getServiceContext()->killOperation(lk, opCtx, ErrorCodes::Error(51008));
            LOGV2(21999,
                  "Batch insertion failed: {error}",
                  "Batch insertion failed",
                  "error"_attr = redact(exceptionToStatus()));
        }
    }};


    {
        //6.  makeGuard的作用是延遲執行inserterThread.join()
        auto inserterThreadJoinGuard = makeGuard([&] {
            batches.closeProducerEnd();
            inserterThread.join();
        });
        // 5. 向捐獻方發起拉取請求,并把資料寫入佇列中
        while (true) {
            auto res = fetchBatchFn(opCtx);
            try {
                batches.push(res.getOwned(), opCtx);
                auto arr = res["objects"].Obj();
                if (arr.isEmpty()) {
                    break;
                }
            } catch (const ExceptionFor<ErrorCodes::ProducerConsumerQueueEndClosed>&) {
                break;
            }
        }
    }  // This scope ensures that the guard is destroyed

3.3 接收方拉取變更資料( _recvChunkStart)

在本步驟,接收方會再拉取變更資料,即在前面遷移程序中,捐獻方上發生的針對該資料塊的寫入、更新和洗掉的記錄,代碼如下:

// 同步變更資料(_transferMods)
    const BSONObj xferModsRequest = createTransferModsRequest(_nss, *_sessionId);

    {
        // 5. Do bulk of mods
        // 5. 批量拉取變更資料,回圈拉取,直至無變更資料
        _setState(CATCHUP);

        while (true) {
            auto res = uassertStatusOKWithContext(
                fromShard->runCommand(opCtx,
                                      ReadPreferenceSetting(ReadPreference::PrimaryOnly),
                                      "admin",
                                      xferModsRequest,
                                      Shard::RetryPolicy::kNoRetry),
                "_transferMods failed: ");

            uassertStatusOKWithContext(Shard::CommandResponse::getEffectiveStatus(res),
                                       "_transferMods failed: ");

            const auto& mods = res.response;

            if (mods["size"].number() == 0) {
                // There are no more pending modifications to be applied. End the catchup phase
                // 無變更資料時,停止回圈
                break;
            }
            // 應用拉取到的變更資料
            if (!_applyMigrateOp(opCtx, mods, &lastOpApplied)) {
                continue;
            }

            const int maxIterations = 3600 * 50;

            // 等待從節點完成資料同步
            int i;
            for (i = 0; i < maxIterations; i++) {
                opCtx->checkForInterrupt();
                outerOpCtx->checkForInterrupt();

                if (getState() == ABORT) {
                    LOGV2(22002,
                          "Migration aborted while waiting for replication at catch up stage",
                          "migrationId"_attr = _migrationId->toBSON());
                    return;
                }

                if (runWithoutSession(outerOpCtx, [&] {
                        return opReplicatedEnough(opCtx, lastOpApplied, _writeConcern);
                    })) {
                    break;
                }

                if (i > 100) {
                    LOGV2(22003,
                          "secondaries having hard time keeping up with migrate",
                          "migrationId"_attr = _migrationId->toBSON());
                }

                sleepmillis(20);
            }

            if (i == maxIterations) {
                _setStateFail("secondary can't keep up with migrate");
                return;
            }
        }

        timing.done(5);
        migrateThreadHangAtStep5.pauseWhileSet();
    }

變更資料拉取結束,就進入等待捐獻方進入臨界區,在臨界區內,捐獻方會阻塞寫入請求,因此在未進入臨界區前,仍然需要拉取變更資料:

        // 6. Wait for commit
        // 6. 等待donor進入臨界區
        _setState(STEADY);

        bool transferAfterCommit = false;
        while (getState() == STEADY || getState() == COMMIT_START) {
            opCtx->checkForInterrupt();
            outerOpCtx->checkForInterrupt();

            // Make sure we do at least one transfer after recv'ing the commit message. If we
            // aren't sure that at least one transfer happens *after* our state changes to
            // COMMIT_START, there could be mods still on the FROM shard that got logged
            // *after* our _transferMods but *before* the critical section.
            if (getState() == COMMIT_START) {
                transferAfterCommit = true;
            }

            auto res = uassertStatusOKWithContext(
                fromShard->runCommand(opCtx,
                                      ReadPreferenceSetting(ReadPreference::PrimaryOnly),
                                      "admin",
                                      xferModsRequest,
                                      Shard::RetryPolicy::kNoRetry),
                "_transferMods failed in STEADY STATE: ");

            uassertStatusOKWithContext(Shard::CommandResponse::getEffectiveStatus(res),
                                       "_transferMods failed in STEADY STATE: ");

            auto mods = res.response;

            // 如果請求到變更資料,則應用到本地,并繼續請求變更資料,直到所有變更資料都遷移結束
            if (mods["size"].number() > 0 && _applyMigrateOp(opCtx, mods, &lastOpApplied)) {
                continue;
            }

            if (getState() == ABORT) {
                LOGV2(22006,
                      "Migration aborted while transferring mods",
                      "migrationId"_attr = _migrationId->toBSON());
                return;
            }

            // We know we're finished when:
            // 1) The from side has told us that it has locked writes (COMMIT_START)
            // 2) We've checked at least one more time for un-transmitted mods
            // 檢查transferAfterCommit的原因:進入COMMIT_START(臨界區)后,需要再拉取一次變更資料
            if (getState() == COMMIT_START && transferAfterCommit == true) {
                // 檢查所有資料同步到從節點后,資料遷移流程結束
                if (runWithoutSession(outerOpCtx,
                                      [&] { return _flushPendingWrites(opCtx, lastOpApplied); })) {
                    break;
                }
            }

            // Only sleep if we aren't committing
            if (getState() == STEADY)
                sleepmillis(10);
        }

 

3.4 進入臨界區( _recvChunkStatus,_recvChunkCommit)

在該步驟,捐獻方主要做了三件事:

1. 等待接收方完成資料同步(_recvChunkStatus),

2. 標記本節點進入臨界區,阻塞寫操作,

3. 通知接收方進入臨界區(_recvChunkCommit),

相關代碼如下:

Status MigrationSourceManager::awaitToCatchUp() {
    invariant(!_opCtx->lockState()->isLocked());
    invariant(_state == kCloning);
    auto scopedGuard = makeGuard([&] { cleanupOnError(); });
    _stats.totalDonorChunkCloneTimeMillis.addAndFetch(_cloneAndCommitTimer.millis());
    _cloneAndCommitTimer.reset();

    // Block until the cloner deems it appropriate to enter the critical section.
    // 等待資料拷貝完成,這里會向接收方發送_recvChunkStatus,檢查接收方的狀態是否是STEADY
    Status catchUpStatus = _cloneDriver->awaitUntilCriticalSectionIsAppropriate(
        _opCtx, kMaxWaitToEnterCriticalSectionTimeout);
    if (!catchUpStatus.isOK()) {
        return catchUpStatus;
    }

    _state = kCloneCaughtUp;
    scopedGuard.dismiss();
    return Status::OK();
}

// 進入臨界區 Status MigrationSourceManager::enterCriticalSection() { ...// 省略部分代碼
// 標記進入臨界區,后續更新類操作會被阻塞(通過ShardingMigrationCriticalSection::getSignal()檢查該標記) _critSec.emplace(_opCtx, _args.getNss(), _critSecReason); _state = kCriticalSection; // Persist a signal to secondaries that we've entered the critical section. This is will cause // secondaries to refresh their routing table when next accessed, which will block behind the // critical section. This ensures causal consistency by preventing a stale mongos with a cluster // time inclusive of the migration config commit update from accessing secondary data. // Note: this write must occur after the critSec flag is set, to ensure the secondary refresh // will stall behind the flag. // 通知從節點此時主節點已進入臨界區,如果有資料訪問時要重繪路由資訊(保證因果一致性) Status signalStatus = shardmetadatautil::updateShardCollectionsEntry( _opCtx, BSON(ShardCollectionType::kNssFieldName << getNss().ns()), BSON("$inc" << BSON(ShardCollectionType::kEnterCriticalSectionCounterFieldName << 1)), false /*upsert*/); if (!signalStatus.isOK()) { return { ErrorCodes::OperationFailed, str::stream() << "Failed to persist critical section signal for secondaries due to: " << signalStatus.toString()}; } LOGV2(22017, "Migration successfully entered critical section", "migrationId"_attr = _coordinator->getMigrationId()); scopedGuard.dismiss(); return Status::OK(); }

Status MigrationSourceManager::commitChunkOnRecipient() {
  invariant(!_opCtx->lockState()->isLocked());
  invariant(_state == kCriticalSection);
  auto scopedGuard = makeGuard([&] { cleanupOnError(); });


  // Tell the recipient shard to fetch the latest changes.
  // 通知接收方進入臨界區,并再次拉取變更資料,
  auto commitCloneStatus = _cloneDriver->commitClone(_opCtx);


  if (MONGO_unlikely(failMigrationCommit.shouldFail()) && commitCloneStatus.isOK()) {
    commitCloneStatus = {ErrorCodes::InternalError,
    "Failing _recvChunkCommit due to failpoint."};
   }


  if (!commitCloneStatus.isOK()) {
    return commitCloneStatus.getStatus().withContext("commit clone failed");
  }


  _recipientCloneCounts = commitCloneStatus.getValue()["counts"].Obj().getOwned();


  _state = kCloneCompleted;
  scopedGuard.dismiss();
  return Status::OK();
}

 

 

3.5 提交遷移結果( _configsvrCommitChunkMigration)

此時,資料已經前部遷移結束,捐獻方將會向配置服務器(config server)提交遷移結果,更新配置服務器上面的分片資訊,代碼如下:

    BSONObjBuilder builder;

    {
        const auto metadata =https://www.cnblogs.com/xinghebuluo/p/ _getCurrentMetadataAndCheckEpoch();

        ChunkType migratedChunkType;
        migratedChunkType.setMin(_args.getMinKey());
        migratedChunkType.setMax(_args.getMaxKey());
        migratedChunkType.setVersion(_chunkVersion);

        // 準備提交更新元資訊的請求
        const auto currentTime = VectorClock::get(_opCtx)->getTime();
        CommitChunkMigrationRequest::appendAsCommand(&builder,
                                                     getNss(),
                                                     _args.getFromShardId(),
                                                     _args.getToShardId(),
                                                     migratedChunkType,
                                                     metadata.getCollVersion(),
                                                     currentTime.clusterTime().asTimestamp());

        builder.append(kWriteConcernField, kMajorityWriteConcern.toBSON());
    }

    // Read operations must begin to wait on the critical section just before we send the commit
    // operation to the config server
    // 進入提交階段時,會阻塞讀請求,其實作和阻塞寫請求類似
    _critSec->enterCommitPhase();

    _state = kCommittingOnConfig;

    Timer t;

    // 向配置服務器提交更新元資料的請求
    auto commitChunkMigrationResponse =
        Grid::get(_opCtx)->shardRegistry()->getConfigShard()->runCommandWithFixedRetryAttempts(
            _opCtx,
            ReadPreferenceSetting{ReadPreference::PrimaryOnly},
            "admin",
            builder.obj(),
            Shard::RetryPolicy::kIdempotent);

    if (MONGO_unlikely(migrationCommitNetworkError.shouldFail())) {
        commitChunkMigrationResponse = Status(
            ErrorCodes::InternalError, "Failpoint 'migrationCommitNetworkError' generated error");
    }

 

4. 小結

至此,mongodb的資料塊遷移的源代碼基本分析完畢,這里補充一下監聽變更資料的代碼實作,

前面有提到監聽變更資料是由_cloneDriver完成的,下面看下_cloneDriver的介面定義:

class MigrationChunkClonerSourceLegacy final : public MigrationChunkClonerSource {
    ...// 省略部分代碼

    StatusWith<BSONObj> commitClone(OperationContext* opCtx) override;

    void cancelClone(OperationContext* opCtx) override;

    bool isDocumentInMigratingChunk(const BSONObj& doc) override;

// 該類定義了三個方法,當捐獻方有寫入、更新和洗掉請求時,會分別呼叫這三個方法
void onInsertOp(OperationContext* opCtx, const BSONObj& insertedDoc, const repl::OpTime& opTime) override; void onUpdateOp(OperationContext* opCtx, boost::optional<BSONObj> preImageDoc, const BSONObj& postImageDoc, const repl::OpTime& opTime, const repl::OpTime& prePostImageOpTime) override; void onDeleteOp(OperationContext* opCtx, const BSONObj& deletedDocId, const repl::OpTime& opTime, const repl::OpTime& preImageOpTime) override;
下面以onInsertOp為例,看下其實作:
  void MigrationChunkClonerSourceLegacy::onInsertOp(OperationContext* opCtx,
                                                  const BSONObj& insertedDoc,
                                                  const repl::OpTime& opTime) {
    dassert(opCtx->lockState()->isCollectionLockedForMode(_args.getNss(), MODE_IX));

    BSONElement idElement = insertedDoc["_id"];
   
    // 檢查該記錄是否在當前遷移資料塊的范圍內,如果不在,直接退出方法
    if (!isInRange(insertedDoc, _args.getMinKey(), _args.getMaxKey(), _shardKeyPattern)) {
        return;
    }

    if (!_addedOperationToOutstandingOperationTrackRequests()) {
        return;
    }

// 將該記錄的_id記錄下面,方便后面拉取變更資料
if (opCtx->getTxnNumber()) { opCtx->recoveryUnit()->registerChange(std::make_unique<LogOpForShardingHandler>( this, idElement.wrap(), 'i', opTime, repl::OpTime())); } else { opCtx->recoveryUnit()->registerChange(std::make_unique<LogOpForShardingHandler>( this, idElement.wrap(), 'i', repl::OpTime(), repl::OpTime())); } }

 

https://github.com/tomliugen

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/499129.html

標籤:NoSQL

上一篇:分布式鎖

下一篇:Oracle學習筆記二十:游標的簡介和使用

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • GPU虛擬機創建時間深度優化

    **?桔妹導讀:**GPU虛擬機實體創建速度慢是公有云面臨的普遍問題,由于通常情況下創建虛擬機屬于低頻操作而未引起業界的重視,實際生產中還是存在對GPU實體創建時間有苛刻要求的業務場景。本文將介紹滴滴云在解決該問題時的思路、方法、并展示最終的優化成果。 從公有云服務商那里購買過虛擬主機的資深用戶,一 ......

    uj5u.com 2020-09-10 06:09:13 more
  • 可編程網卡芯片在滴滴云網路的應用實踐

    **?桔妹導讀:**隨著云規模不斷擴大以及業務層面對延遲、帶寬的要求越來越高,采用DPDK 加速網路報文處理的方式在橫向縱向擴展都出現了局限性。可編程芯片成為業界熱點。本文主要講述了可編程網卡芯片在滴滴云網路中的應用實踐,遇到的問題、帶來的收益以及開源社區貢獻。 #1. 資料中心面臨的問題 隨著滴滴 ......

    uj5u.com 2020-09-10 06:10:21 more
  • 滴滴資料通道服務演進之路

    **?桔妹導讀:**滴滴資料通道引擎承載著全公司的資料同步,為下游實時和離線場景提供了必不可少的源資料。隨著任務量的不斷增加,資料通道的整體架構也隨之發生改變。本文介紹了滴滴資料通道的發展歷程,遇到的問題以及今后的規劃。 #1. 背景 資料,對于任何一家互聯網公司來說都是非常重要的資產,公司的大資料 ......

    uj5u.com 2020-09-10 06:11:05 more
  • 滴滴AI Labs斬獲國際機器翻譯大賽中譯英方向世界第三

    **桔妹導讀:**深耕人工智能領域,致力于探索AI讓出行更美好的滴滴AI Labs再次斬獲國際大獎,這次獲獎的專案是什么呢?一起來看看詳細報道吧! 近日,由國際計算語言學協會ACL(The Association for Computational Linguistics)舉辦的世界最具影響力的機器 ......

    uj5u.com 2020-09-10 06:11:29 more
  • MPP (Massively Parallel Processing)大規模并行處理

    1、什么是mpp? MPP (Massively Parallel Processing),即大規模并行處理,在資料庫非共享集群中,每個節點都有獨立的磁盤存盤系統和記憶體系統,業務資料根據資料庫模型和應用特點劃分到各個節點上,每臺資料節點通過專用網路或者商業通用網路互相連接,彼此協同計算,作為整體提供 ......

    uj5u.com 2020-09-10 06:11:41 more
  • 滴滴資料倉庫指標體系建設實踐

    **桔妹導讀:**指標體系是什么?如何使用OSM模型和AARRR模型搭建指標體系?如何統一流程、規范化、工具化管理指標體系?本文會對建設的方法論結合滴滴資料指標體系建設實踐進行解答分析。 #1. 什么是指標體系 ##1.1 指標體系定義 指標體系是將零散單點的具有相互聯系的指標,系統化的組織起來,通 ......

    uj5u.com 2020-09-10 06:12:52 more
  • 單表千萬行資料庫 LIKE 搜索優化手記

    我們經常在資料庫中使用 LIKE 運算子來完成對資料的模糊搜索,LIKE 運算子用于在 WHERE 子句中搜索列中的指定模式。 如果需要查找客戶表中所有姓氏是“張”的資料,可以使用下面的 SQL 陳述句: SELECT * FROM Customer WHERE Name LIKE '張%' 如果需要 ......

    uj5u.com 2020-09-10 06:13:25 more
  • 滴滴Ceph分布式存盤系統優化之鎖優化

    **桔妹導讀:**Ceph是國際知名的開源分布式存盤系統,在工業界和學術界都有著重要的影響。Ceph的架構和演算法設計發表在國際系統領域頂級會議OSDI、SOSP、SC等上。Ceph社區得到Red Hat、SUSE、Intel等大公司的大力支持。Ceph是國際云計算領域應用最廣泛的開源分布式存盤系統, ......

    uj5u.com 2020-09-10 06:14:51 more
  • es~通過ElasticsearchTemplate進行聚合~嵌套聚合

    之前寫過《es~通過ElasticsearchTemplate進行聚合操作》的文章,這一次主要寫一個嵌套的聚合,例如先對sex集合,再對desc聚合,最后再對age求和,共三層嵌套。 Aggregations的部分特性類似于SQL語言中的group by,avg,sum等函式,Aggregation ......

    uj5u.com 2020-09-10 06:14:59 more
  • 爬蟲日志監控 -- Elastc Stack(ELK)部署

    傻瓜式部署,只需替換IP與用戶 導讀: 現ELK四大組件分別為:Elasticsearch(核心)、logstash(處理)、filebeat(采集)、kibana(可視化) 下載均在https://www.elastic.co/cn/downloads/下tar包,各組件版本最好一致,配合fdm會 ......

    uj5u.com 2020-09-10 06:15:05 more
最新发布
  • day02-2-商鋪查詢快取

    功能02-商鋪查詢快取 3.商鋪詳情快取查詢 3.1什么是快取? 快取就是資料交換的緩沖區(稱作Cache),是存盤資料的臨時地方,一般讀寫性能較高。 快取的作用: 降低后端負載 提高讀寫效率,降低回應時間 快取的成本: 資料一致性成本 代碼維護成本 運維成本 3.2需求說明 如下,當我們點擊商店詳 ......

    uj5u.com 2023-04-20 08:33:24 more
  • MySQL中binlog備份腳本分享

    關于MySQL的二進制日志(binlog),我們都知道二進制日志(binlog)非常重要,尤其當你需要point to point災難恢復的時侯,所以我們要對其進行備份。關于二進制日志(binlog)的備份,可以基于flush logs方式先切換binlog,然后拷貝&壓縮到到遠程服務器或本地服務器 ......

    uj5u.com 2023-04-20 08:28:06 more
  • day02-短信登錄

    功能實作02 2.功能01-短信登錄 2.1基于Session實作登錄 2.1.1思路分析 2.1.2代碼實作 2.1.2.1發送短信驗證碼 發送短信驗證碼: 發送驗證碼的介面為:http://127.0.0.1:8080/api/user/code?phone=xxxxx<手機號> 請求方式:PO ......

    uj5u.com 2023-04-20 08:27:27 more
  • 快取與資料庫雙寫一致性幾種策略分析

    本文將對幾種快取與資料庫保證資料一致性的使用方式進行分析。為保證高并發性能,以下分析場景不考慮執行的原子性及加鎖等強一致性要求的場景,僅追求最終一致性。 ......

    uj5u.com 2023-04-20 08:26:48 more
  • sql陳述句優化

    問題查找及措施 問題查找 需要找到具體的代碼,對其進行一對一優化,而非一直把關注點放在服務器和sql平臺 降低簡化每個事務中處理的問題,盡量不要讓一個事務拖太長的時間 例如檔案上傳時,應將檔案上傳這一步放在事務外面 微軟建議 4.啟動sql定時執行計劃 怎么啟動sqlserver代理服務-百度經驗 ......

    uj5u.com 2023-04-20 08:26:35 more
  • 云時代,MySQL到ClickHouse資料同步產品對比推薦

    ClickHouse 在執行分析查詢時的速度優勢很好的彌補了MySQL的不足,但是對于很多開發者和DBA來說,如何將MySQL穩定、高效、簡單的同步到 ClickHouse 卻很困難。本文對比了 NineData、MaterializeMySQL(ClickHouse自帶)、Bifrost 三款產品... ......

    uj5u.com 2023-04-20 08:26:29 more
  • sql陳述句優化

    問題查找及措施 問題查找 需要找到具體的代碼,對其進行一對一優化,而非一直把關注點放在服務器和sql平臺 降低簡化每個事務中處理的問題,盡量不要讓一個事務拖太長的時間 例如檔案上傳時,應將檔案上傳這一步放在事務外面 微軟建議 4.啟動sql定時執行計劃 怎么啟動sqlserver代理服務-百度經驗 ......

    uj5u.com 2023-04-20 08:25:13 more
  • Redis 報”OutOfDirectMemoryError“(堆外記憶體溢位)

    Redis 報錯“OutOfDirectMemoryError(堆外記憶體溢位) ”問題如下: 一、報錯資訊: 使用 Redis 的業務介面 ,產生 OutOfDirectMemoryError(堆外記憶體溢位),如圖: 格式化后的報錯資訊: { "timestamp": "2023-04-17 22: ......

    uj5u.com 2023-04-20 08:24:54 more
  • day02-2-商鋪查詢快取

    功能02-商鋪查詢快取 3.商鋪詳情快取查詢 3.1什么是快取? 快取就是資料交換的緩沖區(稱作Cache),是存盤資料的臨時地方,一般讀寫性能較高。 快取的作用: 降低后端負載 提高讀寫效率,降低回應時間 快取的成本: 資料一致性成本 代碼維護成本 運維成本 3.2需求說明 如下,當我們點擊商店詳 ......

    uj5u.com 2023-04-20 08:24:03 more
  • day02-短信登錄

    功能實作02 2.功能01-短信登錄 2.1基于Session實作登錄 2.1.1思路分析 2.1.2代碼實作 2.1.2.1發送短信驗證碼 發送短信驗證碼: 發送驗證碼的介面為:http://127.0.0.1:8080/api/user/code?phone=xxxxx<手機號> 請求方式:PO ......

    uj5u.com 2023-04-20 08:23:11 more