diff --git a/broker/src/main/java/org/apache/rocketmq/broker/controller/ReplicasManager.java b/broker/src/main/java/org/apache/rocketmq/broker/controller/ReplicasManager.java index 93d48de1dd9..e804aed9e30 100644 --- a/broker/src/main/java/org/apache/rocketmq/broker/controller/ReplicasManager.java +++ b/broker/src/main/java/org/apache/rocketmq/broker/controller/ReplicasManager.java @@ -238,29 +238,30 @@ public void changeToMaster(final int newMasterEpoch, final int syncStateSetEpoch synchronized (this) { if (newMasterEpoch > this.masterEpoch) { LOGGER.info("Begin to change to master, brokerName:{}, replicas:{}, new Epoch:{}", this.brokerConfig.getBrokerName(), this.brokerAddress, newMasterEpoch); - this.masterEpoch = newMasterEpoch; if (this.masterBrokerId != null && this.masterBrokerId.equals(this.brokerControllerId) && this.brokerController.getBrokerConfig().getBrokerId() == MixAll.MASTER_ID) { + if (!this.haService.changeToMasterWhenLastRoleIsMaster(newMasterEpoch)) { + throw new IllegalStateException("Store refused master epoch " + newMasterEpoch); + } + this.masterEpoch = newMasterEpoch; // Change SyncStateSet final HashSet newSyncStateSet = new HashSet<>(syncStateSet); changeSyncStateSet(newSyncStateSet, syncStateSetEpoch); - // if master doesn't change - this.haService.changeToMasterWhenLastRoleIsMaster(newMasterEpoch); this.brokerController.getTopicConfigManager().getDataVersion().nextVersion(newMasterEpoch); this.executorService.submit(this::checkSyncStateSetAndDoReport); registerBrokerWhenRoleChange(); return; } - // Change SyncStateSet - final HashSet newSyncStateSet = new HashSet<>(syncStateSet); - changeSyncStateSet(newSyncStateSet, syncStateSetEpoch); - - // Handle the slave synchronise + Set proposed = syncStateSetEpoch > this.syncStateSetEpoch ? new HashSet<>(syncStateSet) : null; + if (!this.haService.changeToMaster(newMasterEpoch, proposed)) { + throw new IllegalStateException("Store refused promotion to master epoch " + newMasterEpoch); + } + if (proposed != null) { + recordSyncStateSet(proposed, syncStateSetEpoch); + } + this.masterEpoch = newMasterEpoch; handleSlaveSynchronize(BrokerRole.SYNC_MASTER); - // Notify ha service, change to master - this.haService.changeToMaster(newMasterEpoch); - this.brokerController.getBrokerConfig().setBrokerId(MixAll.MASTER_ID); this.brokerController.getMessageStoreConfig().setBrokerRole(BrokerRole.SYNC_MASTER); this.brokerController.changeSpecialServiceStatus(true); @@ -337,14 +338,18 @@ public void registerBrokerWhenRoleChange() { private void changeSyncStateSet(final Set newSyncStateSet, final int newSyncStateSetEpoch) { synchronized (this) { if (newSyncStateSetEpoch > this.syncStateSetEpoch) { - LOGGER.info("SyncStateSet changed from {} to {}", this.syncStateSet, newSyncStateSet); - this.syncStateSetEpoch = newSyncStateSetEpoch; - this.syncStateSet = new HashSet<>(newSyncStateSet); + recordSyncStateSet(newSyncStateSet, newSyncStateSetEpoch); this.haService.setSyncStateSet(newSyncStateSet); } } } + private void recordSyncStateSet(Set newSyncStateSet, int newSyncStateSetEpoch) { + LOGGER.info("SyncStateSet changed from {} to {}", this.syncStateSet, newSyncStateSet); + this.syncStateSetEpoch = newSyncStateSetEpoch; + this.syncStateSet = new HashSet<>(newSyncStateSet); + } + private void handleSlaveSynchronize(final BrokerRole role) { if (role == BrokerRole.SLAVE) { if (this.slaveSyncFuture != null) { diff --git a/broker/src/test/java/org/apache/rocketmq/broker/controller/ReplicasManagerRegisterTest.java b/broker/src/test/java/org/apache/rocketmq/broker/controller/ReplicasManagerRegisterTest.java index 39ec0d8d94f..9822a379354 100644 --- a/broker/src/test/java/org/apache/rocketmq/broker/controller/ReplicasManagerRegisterTest.java +++ b/broker/src/test/java/org/apache/rocketmq/broker/controller/ReplicasManagerRegisterTest.java @@ -32,6 +32,7 @@ import org.apache.rocketmq.remoting.protocol.header.controller.register.RegisterBrokerToControllerResponseHeader; import org.apache.rocketmq.store.DefaultMessageStore; import org.apache.rocketmq.store.RunningFlags; +import org.apache.rocketmq.store.config.BrokerRole; import org.apache.rocketmq.store.config.MessageStoreConfig; import org.apache.rocketmq.store.ha.autoswitch.AutoSwitchHAService; import org.apache.rocketmq.store.ha.autoswitch.BrokerMetadata; @@ -51,6 +52,7 @@ import java.util.UUID; import static org.awaitility.Awaitility.await; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; @@ -123,6 +125,7 @@ public void setUp() throws Exception { this.mockedMessageStore = Mockito.mock(DefaultMessageStore.class); this.mockedBrokerOuterAPI = Mockito.mock(BrokerOuterAPI.class); this.mockedAutoSwitchHAService = Mockito.mock(AutoSwitchHAService.class); + when(mockedAutoSwitchHAService.changeToMaster(1, syncStateSet)).thenReturn(true); TopicConfigManager mockedTopicConfigManager = new TopicConfigManager(); when(mockedBrokerController.getBrokerOuterAPI()).thenReturn(mockedBrokerOuterAPI); when(mockedBrokerController.getMessageStore()).thenReturn(mockedMessageStore); @@ -137,6 +140,44 @@ public void setUp() throws Exception { when(mockedBrokerController.getMessageStoreConfig()).thenReturn(buildMessageStoreConfig(0)); } + @Test + public void testRefusedPromotionLeavesRoleAndEpoch() throws Exception { + BrokerConfig config = new BrokerConfig(); + config.setBrokerId(2); + when(mockedBrokerController.getBrokerConfig()).thenReturn(config); + mockedBrokerController.getMessageStoreConfig().setBrokerRole(BrokerRole.SLAVE); + ReplicasManager manager = new ReplicasManager(mockedBrokerController); + try { + assertThatThrownBy(() -> manager.changeToMaster(2, 1, syncStateSet)).isInstanceOf(IllegalStateException.class); + assertEquals(0, manager.getMasterEpoch()); + assertEquals(2, config.getBrokerId()); + assertEquals(0, manager.getSyncStateSet().getSyncStateSetEpoch()); + assertTrue(manager.getSyncStateSet().getSyncStateSet().isEmpty()); + Mockito.verify(mockedAutoSwitchHAService, Mockito.never()).setSyncStateSet(Mockito.anySet()); + assertEquals(BrokerRole.SLAVE, mockedBrokerController.getMessageStoreConfig().getBrokerRole()); + Mockito.verify(mockedAutoSwitchHAService).changeToMaster(2, syncStateSet); + } finally { + manager.shutdown(); + } + } + + @Test + public void testRefusedSameMasterEpochIsRetryable() throws Exception { + BrokerConfig config = new BrokerConfig(); + config.setBrokerId(0); + when(mockedBrokerController.getBrokerConfig()).thenReturn(config); + ReplicasManager manager = new ReplicasManager(mockedBrokerController); + try { + FieldUtils.writeDeclaredField(manager, "masterBrokerId", 2L, true); + FieldUtils.writeDeclaredField(manager, "brokerControllerId", 2L, true); + assertThatThrownBy(() -> manager.changeToMaster(2, 1, syncStateSet)).isInstanceOf(IllegalStateException.class); + assertEquals(0, manager.getMasterEpoch()); + Mockito.verify(mockedAutoSwitchHAService).changeToMasterWhenLastRoleIsMaster(2); + } finally { + manager.shutdown(); + } + } + @Test public void testBrokerRegisterSuccess() throws Exception { diff --git a/docs/cn/controller/replica-history-recovery.md b/docs/cn/controller/replica-history-recovery.md new file mode 100644 index 00000000000..5dfaf157b6f --- /dev/null +++ b/docs/cn/controller/replica-history-recovery.md @@ -0,0 +1,12 @@ +# 恢复因日志历史不一致而隔离的副本 + +健康副本收到完整握手后会将候选截断位点和本地确认位点写入 `ha-history-received`,再执行对应决定。重启时重新执行完整记录中的比较结果。如果日志不完整或无法读取,副本保持隔离。备份时应保留此文件。 + +Controller 模式下,如果握手要求截断到本地确认位点之前,副本会拒绝复制,并在自己的 `storePathRootDir` 下写入 `ha-history-incident`。此后即使主节点在同一个 epoch 继续写入,副本也保留已记录的最小截断位点。带有该记录的副本不能完成主节点提升。允许非正常选主不会自动授权丢弃本地消息。 + +1. 找到**被隔离的副本**,通常是原主节点。保持当选主节点作为复制源。停止被隔离副本,备份其完整 Store、独立配置的 CommitLog 和 epoch 路径,并保留该副本自己的 broker 身份。 +2. 在停止的副本上查看 `ha-history-incident`。六行内容依次为本次事件 ID、截断位点、检测时的确认位点、原本地日志末端、预期主节点 HA 地址及有序的 `epoch@起点` 列表、SHA-256 校验和。独立确认当选主节点的身份,并用可信源的实际 CommitLog 字节核对要保留的前缀。相同的 epoch 和位点无法证明消息内容一致。无法核实前缀或已无法读取截断位点时,应从当选历史的可信快照重建副本。 +3. 授权将丢弃从截断位点到本地末端的全部消息,包括已经确认的消息。例如截断位点为 1580、原确认位点为 3280 时,即使主节点已经写到 4190,副本仍会丢弃 `[1580, 3280)`。确认接受数据损失后,在停止的副本的 Store 根目录运行[英文操作说明](../../en/controller/replica-history-recovery.md)中的授权命令,将已核对的记录原子复制为 `ha-history-approval`,并同步文件与目录。 +4. 将该副本作为当选主节点的从节点重启。握手匹配后,副本先使本次授权失效,再执行截断。检查复制追平情况,并核对新消息内容。若要撤回尚未使用的授权,请停止副本,在 Store 根目录执行英文说明中的撤回命令,删除授权文件并同步目录。保留 `ha-history-incident`,直至恢复过程自行清除它。已执行的截断只能通过备份恢复。 + +目标地址、epoch 历史或截断位点变化时,需要重新核对新事件。健康副本在等待首个握手响应时重启,可以正常重新连接。已隔离的副本再次请求历史前会写入 `ha-history-inspecting`。若此时崩溃或存储失效,副本可能已观察到更小的截断位点,下一次可用握手会使旧授权失效并提出从零截断。请保留两个事件文件。如果恢复中断,检查磁盘状态和新记录后再决定是否重新授权。记录损坏、持久化失败或找不到共同 epoch 时,副本继续保持隔离。 diff --git a/docs/en/controller/replica-history-recovery.md b/docs/en/controller/replica-history-recovery.md new file mode 100644 index 00000000000..5fc1d83fc99 --- /dev/null +++ b/docs/en/controller/replica-history-recovery.md @@ -0,0 +1,54 @@ +# Recover an isolated controller-mode replica + +When a handshake would truncate below the replica's confirmed offset, the replica refuses replication and records the incident in `ha-history-incident` under its `storePathRootDir`. Later handshakes keep the earliest recorded cut even if the elected master writes past the old confirmed offset in the same epoch. Both master-promotion paths check the incident. Enabling unclean election does not authorize local data loss. + +## Accept the elected master's history once + +On receipt of a complete handshake, a healthy replica records its candidate cut and local confirmation in `ha-history-received` before acting on the comparison. A restart replays a completed record. An incomplete or unreadable journal blocks the replica. Include this file in incident backups when present. + +1. Identify the **isolated replica**, often the former master. Keep the elected master as the source. Stop the isolated broker, take a restorable backup of its complete Store (including configured external commit-log and epoch paths), and preserve its broker identity. +2. On the stopped replica inspect `ha-history-incident`. Its lines are the unique incident ID, first byte to discard, confirmed offset at detection, original local end, selected HA endpoint followed by its ordered `epoch@start` entries, and a SHA-256 checksum. Confirm the elected master's identity independently. Verify the retained prefix against a trusted copy of the selected history using actual commit-log bytes. The endpoint, epochs and offsets identify the operator's choice and provide no payload comparison. If the prefix cannot be validated or the cut predates retained data, rebuild the replica from a trusted backup of the elected history. +3. Approving this record discards **every local byte from the cut to the local end**, including confirmed messages. For example, with a recorded cut of 1580 and former confirmed end of 3280, messages in `[1580, 3280)` will be replaced even if the elected master has already reached 4190. Run the following from the stopped replica's Store root after inspecting its record. + +```sh +python3 - <<'PY' +import os +from pathlib import Path +import tempfile +root = Path.cwd() +record = (root / "ha-history-incident").read_bytes() +with tempfile.NamedTemporaryFile(dir=root, delete=False) as staged: + staged.write(record) + staged.flush() + os.fsync(staged.fileno()) +os.replace(staged.name, root / "ha-history-approval") +directory = os.open(root, os.O_RDONLY) +try: + os.fsync(directory) +finally: + os.close(directory) +PY +``` + +4. Restart the isolated replica as a slave of the selected master. A matching handshake changes the nonce, consumes the approval durably, and then truncates the Store. The incident clears after the retained commit-log segment, deleted segment directories, epoch checkpoint and confirmed offset have been persisted. Verify that the replica catches up and compare the replacement messages with the source before returning it to service. + +## Withdraw approval or handle interruption + +To withdraw an unused approval, stop the replica and run the following in its Store root. Restart it as a slave. A consumed approval cannot undo truncation. Preserve the incident file until repair completes. + +```sh +python3 - <<'PY' +import os +from pathlib import Path +approval = Path("ha-history-approval") +if approval.exists(): + approval.unlink() +directory = os.open(".", os.O_RDONLY) +try: + os.fsync(directory) +finally: + os.close(directory) +PY +``` + +If the endpoint, epoch sequence or cut changes, the replica issues a fresh incident ID. A healthy replica can restart while waiting for its first response and reconnect normally. An already-isolated replica creates `ha-history-inspecting` before requesting history again. If it crashes or loses storage while inspecting, it may have seen a smaller cut. Its next usable handshake invalidates the old approval and proposes a cut of **zero**. Preserve both incident files. After an interrupted repair, inspect the current incident and disk state and approve the new record only if the remaining repair is still intended. An unreadable or damaged record, unsupported durable filesystem operation, or lack of a common epoch keeps the replica isolated. Restore a trusted Store snapshot or rebuild when the retained prefix or storage integrity cannot be established. diff --git a/store/src/main/java/org/apache/rocketmq/store/DefaultMessageStore.java b/store/src/main/java/org/apache/rocketmq/store/DefaultMessageStore.java index 88cd5222bf8..a6f9b9ac119 100644 --- a/store/src/main/java/org/apache/rocketmq/store/DefaultMessageStore.java +++ b/store/src/main/java/org/apache/rocketmq/store/DefaultMessageStore.java @@ -852,8 +852,12 @@ public boolean isOffsetAligned(long offset) { return true; } - DispatchRequest dispatchRequest = this.commitLog.checkMessageAndReturnSize(mappedBufferResult.getByteBuffer(), true, false); - return dispatchRequest.isSuccess(); + try { + DispatchRequest dispatchRequest = this.commitLog.checkMessageAndReturnSize(mappedBufferResult.getByteBuffer(), true, false); + return dispatchRequest.isSuccess(); + } finally { + mappedBufferResult.release(); + } } @Override diff --git a/store/src/main/java/org/apache/rocketmq/store/StoreCheckpoint.java b/store/src/main/java/org/apache/rocketmq/store/StoreCheckpoint.java index 774c386dc9c..fe02876030c 100644 --- a/store/src/main/java/org/apache/rocketmq/store/StoreCheckpoint.java +++ b/store/src/main/java/org/apache/rocketmq/store/StoreCheckpoint.java @@ -90,18 +90,22 @@ public void shutdown() { public void flush() { try { - this.mappedByteBuffer.putLong(0, this.physicMsgTimestamp); - this.mappedByteBuffer.putLong(8, this.logicsMsgTimestamp); - this.mappedByteBuffer.putLong(16, this.indexMsgTimestamp); - this.mappedByteBuffer.putLong(24, this.masterFlushedOffset); - this.mappedByteBuffer.putLong(32, this.confirmPhyOffset); - this.mappedByteBuffer.putLong(40, this.logicsPhysicalOffset); - this.mappedByteBuffer.force(); + flushForRecovery(); } catch (Throwable e) { log.error("Failed to flush", e); } } + public synchronized void flushForRecovery() { + this.mappedByteBuffer.putLong(0, this.physicMsgTimestamp); + this.mappedByteBuffer.putLong(8, this.logicsMsgTimestamp); + this.mappedByteBuffer.putLong(16, this.indexMsgTimestamp); + this.mappedByteBuffer.putLong(24, this.masterFlushedOffset); + this.mappedByteBuffer.putLong(32, this.confirmPhyOffset); + this.mappedByteBuffer.putLong(40, this.logicsPhysicalOffset); + this.mappedByteBuffer.force(); + } + public long getPhysicMsgTimestamp() { return physicMsgTimestamp; } diff --git a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java index 665d9aae3b0..91b3fafdb57 100644 --- a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java @@ -23,6 +23,7 @@ import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; @@ -112,6 +113,10 @@ public class AutoSwitchHAClient extends ServiceThread implements HAClient { private final ByteBuffer byteBufferRead = ByteBuffer.allocate(READ_MAX_BUFFER_SIZE); private final DefaultMessageStore messageStore; private final EpochFileCache epochCache; + private final HistoryIncident incident; + private String connectedAddress; + private boolean checkingHistory; + private boolean promotionReserved; private final Long brokerId; @@ -142,11 +147,13 @@ public AutoSwitchHAClient(AutoSwitchHAService haService, DefaultMessageStore def this.haService = haService; this.messageStore = defaultMessageStore; this.epochCache = epochCache; + this.incident = new HistoryIncident(Paths.get(defaultMessageStore.getMessageStoreConfig().getStorePathRootDir())); this.brokerId = brokerId; init(); } public void init() throws IOException { + this.promotionReserved = false; this.selector = NetworkUtil.openSelector(); this.flowMonitor = new FlowMonitor(this.messageStore.getMessageStoreConfig()); this.haReader = new HAClientReader(); @@ -238,6 +245,14 @@ public void closeMasterAndWait() { @Override public void closeMaster() { + if (checkingHistory) { + checkingHistory = false; + try { + incident.finishInspection(); + } catch (IOException e) { + LOGGER.error("Cannot clear unfinished HA connection probe", e); + } + } if (null != this.socketChannel) { try { SelectionKey sk = this.socketChannel.keyFor(this.selector); @@ -306,9 +321,11 @@ private boolean sendHandshakeHeader() throws IOException { } private void handshakeWithMaster() throws IOException { + prepareHistoryCheck(); boolean result = this.sendHandshakeHeader(); if (!result) { closeMasterAndWait(); + return; } this.selector.select(5000); @@ -345,6 +362,7 @@ public boolean connectMaster() throws IOException { SocketAddress socketAddress = NetworkUtil.string2SocketAddress(addr); this.socketChannel = RemotingHelper.connect(socketAddress); if (this.socketChannel != null) { + this.connectedAddress = addr; this.socketChannel.register(this.selector, SelectionKey.OP_READ); LOGGER.info("AutoSwitchHAClient connect to master {}", addr); changeCurrentState(HAConnectionState.HANDSHAKE); @@ -389,7 +407,7 @@ public void run() { return; case READY: // Truncate invalid msg first - final long truncateOffset = AutoSwitchHAClient.this.haService.truncateInvalidMsg(); + final long truncateOffset = incident.isolated() ? -1 : AutoSwitchHAClient.this.haService.truncateInvalidMsg(); if (truncateOffset >= 0) { AutoSwitchHAClient.this.epochCache.truncateSuffixByOffset(truncateOffset); } @@ -429,11 +447,35 @@ public void run() { LOGGER.info(this.getServiceName() + " service end"); } - /** - * Compare the master and slave's epoch file, find consistent point, do truncate. - */ - private boolean doTruncate(List masterEpochEntries, long masterEndOffset) throws Exception { - if (this.epochCache.getEntrySize() == 0) { + synchronized boolean reservePromotion() throws IOException { + if (incident.isolated()) { + return false; + } + promotionReserved = true; + return true; + } + + private synchronized void prepareHistoryCheck() throws IOException { + if (!checkingHistory && !promotionReserved) { + checkingHistory = incident.beginInspection(); + } + } + + private synchronized boolean doTruncate(List masterEpochEntries, long masterEndOffset) throws Exception { + if (promotionReserved) { + return false; + } + prepareHistoryCheck(); + boolean ownsInspection = checkingHistory; + checkingHistory = false; + boolean fresh = !incident.isolated(); + final long localEnd = this.messageStore.getMaxPhyOffset(); + boolean empty = this.epochCache.getEntrySize() == 0; + if (fresh && empty) { + if (localEnd > 0) { + LOGGER.error("Replica has data but no epoch history"); + return false; + } // If epochMap is empty, means the broker is a new replicas LOGGER.info("Slave local epochCache is empty, skip truncate log"); changeCurrentState(HAConnectionState.TRANSFER); @@ -445,26 +487,48 @@ private boolean doTruncate(List masterEpochEntries, long masterEndOf final List localEpochEntries = this.epochCache.getAllEntries(); final EpochFileCache localEpochCache = new EpochFileCache(); localEpochCache.initCacheFromEntries(localEpochEntries); - localEpochCache.setLastEpochEntryEndOffset(this.messageStore.getMaxPhyOffset()); + localEpochCache.setLastEpochEntryEndOffset(localEnd); LOGGER.info("master epoch entries is {}", masterEpochCache.getAllEntries()); LOGGER.info("local epoch entries is {}", localEpochEntries); - final long truncateOffset = localEpochCache.findConsistentPoint(masterEpochCache); + final long point = empty && localEnd == 0 ? 0 : localEpochCache.findConsistentPoint(masterEpochCache); - LOGGER.info("truncateOffset is {}", truncateOffset); + LOGGER.info("Consistent point is {}", point); - if (truncateOffset < 0) { + if (point < 0 || point > masterEndOffset || point > localEnd) { + if (ownsInspection) { + incident.finishInspection(); + } // If truncateOffset < 0, means we can't find a consistent point LOGGER.error("Failed to find a consistent point between masterEpoch:{} and slaveEpoch:{}", masterEpochEntries, localEpochEntries); return false; } - if (!this.messageStore.truncateFiles(truncateOffset)) { + final String source = HistoryIncident.source(String.valueOf(connectedAddress), masterEpochEntries); + final HistoryIncident.Cut cut = fresh + ? incident.firstDecision(point, messageStore::getConfirmOffset, localEnd, source) + : incident.authorize(point, messageStore.getConfirmOffset(), localEnd, source, ownsInspection); + if (!fresh) { + incident.finishInspection(); + } + if (cut == null) { + LOGGER.error("Refuse to truncate isolated replica. Consistent point {}. " + + "masterEpoch:{}, slaveEpoch:{}", point, masterEpochEntries, + localEpochEntries); + return false; + } + final long truncateOffset = cut.offset; + if (!fresh) { + if (connectedAddress == null) { + throw new IOException("Recovery requires a connected master"); + } + DurableHistoryTruncation.apply(messageStore, epochCache, cut); + incident.clear(); + } else if (!this.messageStore.truncateFiles(truncateOffset)) { LOGGER.error("Failed to truncate slave log to {}", truncateOffset); return false; } - final long maxPhyOffset = this.messageStore.getMaxPhyOffset(); - if (truncateOffset < maxPhyOffset) { + if (fresh && truncateOffset < localEnd) { this.epochCache.truncateSuffixByOffset(truncateOffset); LOGGER.info("Truncate slave log to {} success, change to transfer state", truncateOffset); } @@ -517,21 +581,32 @@ protected boolean processReadResult(ByteBuffer byteBufferRead) { boolean isComplete = true; switch (AutoSwitchHAClient.this.currentState) { case HANDSHAKE: { - if (diff < AutoSwitchHAConnection.HANDSHAKE_HEADER_SIZE + bodySize) { + int entrySize = AutoSwitchHAConnection.EPOCH_ENTRY_SIZE; + if (bodySize < 0 || bodySize % entrySize != 0 || masterOffset < 0) { + return false; + } + if (diff - AutoSwitchHAConnection.HANDSHAKE_HEADER_SIZE < bodySize) { // The received HANDSHAKE data is not complete isComplete = false; break; } AutoSwitchHAClient.this.processPosition += AutoSwitchHAConnection.HANDSHAKE_HEADER_SIZE; // Truncate log - int entrySize = AutoSwitchHAConnection.EPOCH_ENTRY_SIZE; final int entryNums = bodySize / entrySize; final ArrayList epochEntries = new ArrayList<>(entryNums); for (int i = 0; i < entryNums; i++) { int epoch = byteBufferRead.getInt(AutoSwitchHAClient.this.processPosition + i * entrySize); long startOffset = byteBufferRead.getLong(AutoSwitchHAClient.this.processPosition + i * entrySize + 4); + if (startOffset < 0 || startOffset > masterOffset + || i > 0 && (epoch <= epochEntries.get(i - 1).getEpoch() + || startOffset <= epochEntries.get(i - 1).getStartOffset())) { + return false; + } epochEntries.add(new EpochEntry(epoch, startOffset)); } + if (entryNums > 0 && epochEntries.get(entryNums - 1).getEpoch() != masterEpoch) { + return false; + } byteBufferRead.position(readSocketPos); AutoSwitchHAClient.this.processPosition += bodySize; LOGGER.info("Receive handshake, masterMaxPosition {}, masterEpochEntries:{}, try truncate log", masterOffset, epochEntries); @@ -599,6 +674,7 @@ protected boolean processReadResult(ByteBuffer byteBufferRead) { } } catch (final Exception e) { LOGGER.error("Error when ha client process read request", e); + return false; } return true; } diff --git a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAService.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAService.java index 7ea988123a2..0a709734efc 100644 --- a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAService.java +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAService.java @@ -19,6 +19,7 @@ import java.io.IOException; import java.nio.channels.SocketChannel; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -71,6 +72,7 @@ public class AutoSwitchHAService extends DefaultHAService { private volatile boolean isSynchronizingSyncStateSet = false; private EpochFileCache epochCache; + private HistoryIncident incident; private AutoSwitchHAClient haClient; private Long localBrokerId = null; @@ -83,6 +85,7 @@ public void init(final DefaultMessageStore defaultMessageStore) throws IOExcepti this.epochCache = new EpochFileCache(defaultMessageStore.getMessageStoreConfig().getStorePathEpochFile()); this.epochCache.initCacheFromFile(); this.defaultMessageStore = defaultMessageStore; + this.incident = new HistoryIncident(Paths.get(defaultMessageStore.getMessageStoreConfig().getStorePathRootDir())); this.acceptSocketService = new AutoSwitchAcceptSocketService(defaultMessageStore.getMessageStoreConfig()); this.groupTransferService = new GroupTransferService(this, defaultMessageStore); this.haConnectionStateNotificationService = new HAConnectionStateNotificationService(this, defaultMessageStore); @@ -120,11 +123,21 @@ public void removeConnection(HAConnection conn) { @Override public boolean changeToMaster(int masterEpoch) throws RocksDBException { + return changeToMaster(masterEpoch, null); + } + + public boolean changeToMaster(int masterEpoch, Set newSyncStateSet) throws RocksDBException { final int lastEpoch = this.epochCache.lastEpoch(); if (masterEpoch < lastEpoch) { LOGGER.warn("newMasterEpoch {} < lastEpoch {}, fail to change to master", masterEpoch, lastEpoch); return false; } + if (!reserveMasterRole()) { + return false; + } + if (newSyncStateSet != null) { + setSyncStateSet(newSyncStateSet); + } destroyConnections(); // Stop ha client if needed if (this.haClient != null) { @@ -204,6 +217,9 @@ public boolean changeToMasterWhenLastRoleIsMaster(int masterEpoch) { LOGGER.warn("newMasterEpoch {} < lastEpoch {}, fail to change to master", masterEpoch, lastEpoch); return false; } + if (!reserveMasterRole()) { + return false; + } // Append new epoch to epochFile final EpochEntry newEpochEntry = appendEpochEntry(masterEpoch); @@ -213,6 +229,21 @@ public boolean changeToMasterWhenLastRoleIsMaster(int masterEpoch) { return true; } + private boolean reserveMasterRole() { + try { + // reservePromotion and doTruncate share the client's monitor. + // After acceptance no handshake can create a new incident while + // shutdown joins the reader outside that monitor. + if (haClient == null ? !incident.isolated() : haClient.reservePromotion()) { + return true; + } + LOGGER.error("Isolated replica cannot become master"); + } catch (IOException e) { + LOGGER.error("Cannot verify local HA history before promotion", e); + } + return false; + } + /** * Append the master epoch to the epoch file. If the epoch already exists locally, keep the original entry * instead of rewriting its start offset with the current max physical offset. A broker that restarts and is diff --git a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/DurableHistoryTruncation.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/DurableHistoryTruncation.java new file mode 100644 index 00000000000..d0789542151 --- /dev/null +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/DurableHistoryTruncation.java @@ -0,0 +1,90 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.rocketmq.store.ha.autoswitch; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import org.apache.rocketmq.common.MixAll; +import org.apache.rocketmq.store.DefaultMessageStore; +import org.apache.rocketmq.store.logfile.MappedFile; +import org.rocksdb.RocksDBException; + +/** Persist a destructive repair before removing the incident. */ +final class DurableHistoryTruncation { + private DurableHistoryTruncation() { + } + + static void apply(DefaultMessageStore store, EpochFileCache epochs, HistoryIncident.Cut cut) throws IOException, RocksDBException { + long offset = cut.offset; + if (offset < store.getMinPhyOffset() || offset > store.getMaxPhyOffset()) { + throw new IOException("Recovery offset outside retained commit log: " + offset); + } + if (!store.truncateFiles(offset) || store.getMaxPhyOffset() != offset) { + throw new IOException("Could not truncate replica to " + offset); + } + // The ordinary truncate only moves in-memory positions inside the + // retained segment. A later load scans its bytes, so even records + // following the next append must be invalidated. + MappedFile last = store.getCommitLog().getMappedFileQueue().getLastMappedFile(); + if (last != null) { + FileChannel channel = last.getFileChannel(); + long position = offset - last.getFileFromOffset(); + ByteBuffer zeros = ByteBuffer.allocate(64 * 1024); + while (position < last.getFileSize()) { + zeros.clear(); + zeros.limit((int) Math.min(zeros.capacity(), last.getFileSize() - position)); + while (zeros.hasRemaining()) { + position += channel.write(zeros, position); + } + } + channel.force(true); + } + Set directories = new HashSet<>(Arrays.asList(store.getMessageStoreConfig().getStorePathCommitLog() + .split(MixAll.MULTI_PATH_SPLITTER))); + String readOnly = store.getMessageStoreConfig().getReadOnlyCommitLogStorePaths(); + if (readOnly != null && !readOnly.trim().isEmpty()) { + directories.addAll(Arrays.asList(readOnly.split(MixAll.MULTI_PATH_SPLITTER))); + } + for (String name : directories) { + Path directory = Paths.get(name.trim()); + try (DirectoryStream files = Files.newDirectoryStream(directory)) { + for (Path file : files) { + String segment = file.getFileName().toString(); + if (segment.matches("[0-9]{20}")) { + long start = Long.parseLong(segment); + if (start > offset && start < cut.originalEnd) { + throw new IOException("Old commit log segment still present: " + file); + } + } + } + } + HistoryIncident.forceDirectory(directory); + } + epochs.truncateForRecovery(offset, Paths.get(store.getMessageStoreConfig().getStorePathEpochFile())); + store.setConfirmOffset(offset); + store.getStoreCheckpoint().flushForRecovery(); + } +} diff --git a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/EpochFileCache.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/EpochFileCache.java index f23e4aa06bf..042c99c52e1 100644 --- a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/EpochFileCache.java +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/EpochFileCache.java @@ -18,6 +18,10 @@ package org.apache.rocketmq.store.ha.autoswitch; import java.io.IOException; +import java.nio.channels.FileChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -260,6 +264,29 @@ public void truncateSuffixByOffset(final long truncateOffset) { doTruncateSuffix(predict); } + void truncateForRecovery(long offset, Path path) throws IOException { + writeLock.lock(); + try { + epochMap.entrySet().removeIf(entry -> entry.getValue().getStartOffset() >= offset); + // The ordinary checkpoint tolerates write errors and reads a backup. + // Neither a failed write nor a stale backup may undo this repair. + CheckpointFile file = new CheckpointFile<>(path.toString(), new EpochEntrySerializer()); + if (epochMap.isEmpty()) { + Files.deleteIfExists(path); + } else { + epochMap.lastEntry().getValue().setEndOffset(Long.MAX_VALUE); + file.write(new ArrayList<>(epochMap.values())); + try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) { + channel.force(true); + } + } + Files.deleteIfExists(path.resolveSibling(path.getFileName() + ".bak")); + HistoryIncident.forceDirectory(path.toAbsolutePath().getParent()); + } finally { + writeLock.unlock(); + } + } + private void doTruncateSuffix(Predicate predict) { this.writeLock.lock(); try { diff --git a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/HistoryIncident.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/HistoryIncident.java new file mode 100644 index 00000000000..530d5fe6976 --- /dev/null +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/HistoryIncident.java @@ -0,0 +1,227 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.rocketmq.store.ha.autoswitch; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.function.LongSupplier; +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.rocketmq.remoting.protocol.EpochEntry; + +/** An operator approves one incident by installing an exact copy as ha-history-approval. */ +final class HistoryIncident { + private static final byte[] CHECKING = "HA history check in progress\n".getBytes(StandardCharsets.UTF_8); + private final Path state; + private final Path approval; + private final Path inspecting; + private final Path received; + + HistoryIncident(Path root) { + this.state = root.resolve("ha-history-incident"); + this.approval = root.resolve("ha-history-approval"); + this.inspecting = root.resolve("ha-history-inspecting"); + this.received = root.resolve("ha-history-received"); + } + + boolean isolated() throws IOException { + replayReceived(); + return read(state) != null || read(inspecting) != null; + } + + private static byte[] read(Path path) throws IOException { + try { + BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!attributes.isRegularFile()) { + throw new IOException("Expected regular HA history file at " + path); + } + } catch (NoSuchFileException absent) { + // A missing or unmounted Store root is not a clean Store. + Files.readAttributes(path.getParent(), BasicFileAttributes.class); + return null; + } + return Files.readAllBytes(path); + } + + boolean beginInspection() throws IOException { + replayReceived(); + if (read(inspecting) != null) { + // A failed force can leave the marker visible only in memory. + // Retry the force without taking ownership of that inspection. + forceDirectory(inspecting.getParent()); + return false; + } + if (read(state) == null) { + return false; + } + // Keep the old incident available to operators, but make its approval + // unusable after a crash until the new observation is accounted for. + Files.createFile(inspecting); + forceDirectory(inspecting.getParent()); + return true; + } + + void finishInspection() throws IOException { + if (Files.deleteIfExists(inspecting)) { + forceDirectory(inspecting.getParent()); + } + } + + static void forceDirectory(Path directory) throws IOException { + try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { + channel.force(true); + } + } + + private byte[] decision(long offset, long confirm, long end, String source) { + String payload = UUID.randomUUID() + "\n" + offset + "\n" + confirm + "\n" + end + "\n" + source + "\n"; + return (payload + DigestUtils.sha256Hex(payload) + "\n").getBytes(StandardCharsets.UTF_8); + } + + private static void writeAndForce(FileChannel channel, byte[] bytes) throws IOException { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + channel.force(true); + } + + private void record(long offset, long confirm, long end, String source) throws IOException { + Path temp = Files.createTempFile(state.getParent(), "ha-incident-", ".tmp"); + try { + try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) { + writeAndForce(channel, decision(offset, confirm, end, source)); + } + Files.move(temp, state, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + forceDirectory(state.getParent()); + } finally { + Files.deleteIfExists(temp); + } + } + + static String source(String peer, List epochs) { + StringBuilder result = new StringBuilder(peer); + for (EpochEntry entry : epochs) { + result.append(' ').append(entry.getEpoch()).append('@').append(entry.getStartOffset()); + } + return result.toString(); + } + + static final class Cut { + final long offset; + final long originalEnd; + + Cut(long offset, long originalEnd) { + this.offset = offset; + this.originalEnd = originalEnd; + } + } + + Cut firstDecision(long point, LongSupplier confirmedOffset, long end, String source) throws IOException { + // Only complete responses reach here. Reserve and force the journal + // entry before consulting confirmation to decide whether to reject. + long confirm; + try (FileChannel channel = FileChannel.open(received, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { + forceDirectory(received.getParent()); + confirm = confirmedOffset.getAsLong(); + writeAndForce(channel, decision(point, confirm, end, source)); + } + boolean refused = point < confirm; + finishReceived(refused); + return refused ? null : new Cut(point, end); + } + + private void replayReceived() throws IOException { + byte[] bytes = read(received); + if (bytes != null) { + String[] fields = checkedFields(bytes); + finishReceived(Long.parseLong(fields[1]) < Long.parseLong(fields[2])); + } + } + + private void finishReceived(boolean refused) throws IOException { + if (refused) { + if (read(state) != null) { + throw new IOException("Conflicting HA history incident and received decision"); + } + Files.move(received, state, StandardCopyOption.ATOMIC_MOVE); + } else { + Files.delete(received); + } + forceDirectory(received.getParent()); + } + + private String[] checkedFields(byte[] bytes) throws IOException { + String[] fields = new String(bytes, StandardCharsets.UTF_8).split("\n", -1); + if (fields.length != 7 || !fields[6].isEmpty() + || !DigestUtils.sha256Hex(String.join("\n", Arrays.copyOf(fields, 5)) + "\n").equals(fields[5])) { + throw new IOException("Invalid HA history record in " + state.getParent()); + } + return fields; + } + + Cut authorize(long point, long confirm, long end, String source, boolean ownsInspection) throws IOException { + byte[] bytes = read(state); + boolean interrupted = !ownsInspection && read(inspecting) != null; + if (bytes == null) { + throw new IOException("HA history incident disappeared"); + } + if (Arrays.equals(bytes, CHECKING)) { + // The last process may have observed a fork without recording + // its boundary. No portion of the local history is assumed safe. + record(0, confirm, end, source); + return null; + } + String[] fields = checkedFields(bytes); + long limit = Long.parseLong(fields[1]); + long originalConfirm = Long.parseLong(fields[2]); + long originalEnd = Long.parseLong(fields[3]); + if (limit < 0 || limit > originalEnd) { + throw new IOException("Invalid HA recovery offset " + limit); + } + if (interrupted || point < limit || end > originalEnd || !fields[4].equals(source)) { + record(interrupted ? 0 : Math.min(limit, point), originalConfirm, Math.max(end, originalEnd), source); + return null; + } + if (!Arrays.equals(bytes, read(approval))) { + return null; + } + // Consume before any destructive work. A crash requires a fresh + // decision and a new copy of the current incident. + record(limit, originalConfirm, originalEnd, source); + Files.delete(approval); + forceDirectory(state.getParent()); + return new Cut(limit, originalEnd); + } + + void clear() throws IOException { + Files.delete(state); + forceDirectory(state.getParent()); + } +} diff --git a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClientTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClientTest.java new file mode 100644 index 00000000000..1b3a8fa91c9 --- /dev/null +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClientTest.java @@ -0,0 +1,228 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.rocketmq.store.ha.autoswitch; + +import java.io.File; +import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import org.apache.rocketmq.common.BrokerConfig; +import org.apache.rocketmq.remoting.protocol.EpochEntry; +import org.apache.rocketmq.store.DefaultMessageStore; +import org.apache.rocketmq.store.config.MessageStoreConfig; +import org.apache.rocketmq.store.ha.HAConnectionState; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class AutoSwitchHAClientTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void testHandshakeMustRetainRefusalAfterClientRestart() throws Exception { + MessageStoreConfig config = new MessageStoreConfig(); + config.setStorePathRootDir(temporaryFolder.newFolder().getAbsolutePath()); + DefaultMessageStore store = mock(DefaultMessageStore.class); + when(store.getMessageStoreConfig()).thenReturn(config); + when(store.getMaxPhyOffset()).thenReturn(3280L); + when(store.getConfirmOffset()).thenReturn(3280L); + when(store.truncateFiles(3280L)).thenReturn(true); + + AutoSwitchHAClient first = createClient(store); + try { + first.changeCurrentState(HAConnectionState.HANDSHAKE); + assertFalse(first.new HAClientReader().processReadResult(handshake(1580L))); + assertEquals(HAConnectionState.HANDSHAKE, first.getCurrentState()); + verify(store, never()).truncateFiles(anyLong()); + } finally { + first.shutdown(); + } + + // Recreate the client against the same storage directory. A higher end offset + // in the same epoch cannot prove that the previously rejected history is safe. + AutoSwitchHAClient restarted = createClient(store); + try { + restarted.changeCurrentState(HAConnectionState.HANDSHAKE); + assertFalse(restarted.new HAClientReader().processReadResult(handshake(4190L))); + assertEquals(HAConnectionState.HANDSHAKE, restarted.getCurrentState()); + verify(store, never()).truncateFiles(anyLong()); + } finally { + restarted.shutdown(); + } + } + + private ByteBuffer handshake(long masterEndOffset) { + ByteBuffer frame = ByteBuffer.allocate(AutoSwitchHAConnection.HANDSHAKE_HEADER_SIZE + + AutoSwitchHAConnection.EPOCH_ENTRY_SIZE); + frame.putInt(HAConnectionState.HANDSHAKE.ordinal()); + frame.putInt(AutoSwitchHAConnection.EPOCH_ENTRY_SIZE); + frame.putLong(masterEndOffset); + frame.putInt(1); + frame.putInt(1); + frame.putLong(0L); + return frame; + } + + @Test + public void testSmallerObservationInvalidatesApprovalEvenIfDiskBecomesUnavailable() throws Exception { + Path root = temporaryFolder.newFolder().toPath(); + Path offline = root.resolveSibling("unmounted"); + MessageStoreConfig config = new MessageStoreConfig(); + config.setStorePathRootDir(root.toString()); + DefaultMessageStore store = mock(DefaultMessageStore.class); + when(store.getMessageStoreConfig()).thenReturn(config); + when(store.getMaxPhyOffset()).thenReturn(200L); + when(store.getConfirmOffset()).thenReturn(200L); + AutoSwitchHAClient first = createClient(store); + try { + first.changeCurrentState(HAConnectionState.HANDSHAKE); + assertFalse(first.new HAClientReader().processReadResult(handshake(100))); + } finally { + first.shutdown(); + } + Files.copy(root.resolve("ha-history-incident"), root.resolve("ha-history-approval")); + AutoSwitchHAClient second = createClient(store); + try { + second.changeCurrentState(HAConnectionState.HANDSHAKE); + // The selected source has regressed further. Lose the filesystem + // between computing the new point and publishing the restriction. + when(store.getConfirmOffset()).thenAnswer(invocation -> { + Files.move(root, offline); + return 200L; + }); + assertFalse(second.new HAClientReader().processReadResult(handshake(60))); + assertTrue(Files.isDirectory(offline)); + } finally { + second.shutdown(); + Files.move(offline, root); + } + HistoryIncident restarted = new HistoryIncident(root); + assertNull(restarted.authorize(200, 200, 200, "null 1@0", false)); + } + + @Test + public void testCrashBeforeFirstReplyAllowsPositiveRetainedMinimum() throws Exception { + MessageStoreConfig config = new MessageStoreConfig(); + config.setStorePathRootDir(temporaryFolder.newFolder().getAbsolutePath()); + DefaultMessageStore store = mock(DefaultMessageStore.class); + when(store.getMessageStoreConfig()).thenReturn(config); + when(store.getMinPhyOffset()).thenReturn(1024L); + when(store.getMaxPhyOffset()).thenReturn(2048L); + when(store.getConfirmOffset()).thenReturn(2048L); + when(store.truncateFiles(2048L)).thenReturn(true); + AutoSwitchHAClient waiting = createClient(store); + AutoSwitchHAClient restarted = createClient(store); + try { + Method prepare = AutoSwitchHAClient.class.getDeclaredMethod("prepareHistoryCheck"); + prepare.setAccessible(true); + prepare.invoke(waiting); + // A fresh process sees only durable state. Never close the first + // connection gracefully before the recreated client has checked. + restarted.changeCurrentState(HAConnectionState.HANDSHAKE); + assertTrue(restarted.new HAClientReader().processReadResult(handshake(2048))); + assertEquals(HAConnectionState.TRANSFER, restarted.getCurrentState()); + } finally { + restarted.shutdown(); + waiting.shutdown(); + } + } + + @Test + public void testCorruptIsolationStateRefusesHandshake() throws Exception { + File directory = temporaryFolder.newFolder(); + Files.write(new File(directory, "ha-history-incident").toPath(), new byte[] {1, 2}); + DefaultMessageStore store = mock(DefaultMessageStore.class); + MessageStoreConfig config = new MessageStoreConfig(); + config.setStorePathRootDir(directory.getAbsolutePath()); + when(store.getMessageStoreConfig()).thenReturn(config); + when(store.getMaxPhyOffset()).thenReturn(100L); + when(store.truncateFiles(100L)).thenReturn(true); + AutoSwitchHAClient client = createClient(store); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + assertFalse(client.new HAClientReader().processReadResult(handshake(100L))); + assertEquals(HAConnectionState.HANDSHAKE, client.getCurrentState()); + verify(store, never()).truncateFiles(anyLong()); + } finally { + client.shutdown(); + } + } + + @Test + public void testDoTruncateRejectsOffsetBelowConfirmOffset() throws Exception { + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + MessageStoreConfig config = new MessageStoreConfig(); + config.setStorePathRootDir(temporaryFolder.newFolder().getAbsolutePath()); + when(messageStore.getMessageStoreConfig()).thenReturn(config); + when(messageStore.getMaxPhyOffset()).thenReturn(200L, 100L); + when(messageStore.getConfirmOffset()).thenReturn(150L); + when(messageStore.truncateFiles(100L)).thenReturn(true); + + AutoSwitchHAClient client = createClient(messageStore); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + assertFalse(client.new HAClientReader().processReadResult(handshake(100L))); + assertEquals(HAConnectionState.HANDSHAKE, client.getCurrentState()); + verify(messageStore, never()).truncateFiles(anyLong()); + } finally { + client.shutdown(); + } + } + + @Test + public void testDoTruncateAllowsOffsetAtConfirmOffset() throws Exception { + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + MessageStoreConfig config = new MessageStoreConfig(); + config.setStorePathRootDir(temporaryFolder.newFolder().getAbsolutePath()); + when(messageStore.getMessageStoreConfig()).thenReturn(config); + when(messageStore.getMaxPhyOffset()).thenReturn(200L, 100L); + when(messageStore.getConfirmOffset()).thenReturn(100L); + when(messageStore.truncateFiles(100L)).thenReturn(true); + + AutoSwitchHAClient client = createClient(messageStore); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + assertTrue(client.new HAClientReader().processReadResult(handshake(100L))); + assertEquals(HAConnectionState.TRANSFER, client.getCurrentState()); + verify(messageStore).truncateFiles(100L); + } finally { + client.shutdown(); + } + } + + private AutoSwitchHAClient createClient(DefaultMessageStore messageStore) throws Exception { + EpochFileCache epochCache = new EpochFileCache(); + assertTrue(epochCache.appendEntry(new EpochEntry(1, 0L))); + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + return new AutoSwitchHAClient(haService, messageStore, epochCache, 1L); + } + +} diff --git a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAServiceTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAServiceTest.java index c33de6af77c..f47a865c271 100644 --- a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAServiceTest.java +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAServiceTest.java @@ -152,6 +152,7 @@ private String epochFilePath() { private DefaultMessageStore mockMessageStore(final String epochFilePath, final long maxPhyOffset) { final DefaultMessageStore messageStore = mock(DefaultMessageStore.class); final MessageStoreConfig messageStoreConfig = new MessageStoreConfig(); + messageStoreConfig.setStorePathRootDir(tempFolder.getRoot().getAbsolutePath()); messageStoreConfig.setStorePathEpochFile(epochFilePath); when(messageStore.getMessageStoreConfig()).thenReturn(messageStoreConfig); when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); @@ -165,4 +166,4 @@ private void assertEpochEntry(final AutoSwitchHAService haService, final int epo assertEquals(epoch, epochEntries.get(0).getEpoch()); assertEquals(startOffset, epochEntries.get(0).getStartOffset()); } -} \ No newline at end of file +} diff --git a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/HistoryIncidentTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/HistoryIncidentTest.java new file mode 100644 index 00000000000..d5fe909d4a5 --- /dev/null +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/HistoryIncidentTest.java @@ -0,0 +1,159 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.rocketmq.store.ha.autoswitch; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class HistoryIncidentTest { + @Rule + public TemporaryFolder temp = new TemporaryFolder(); + + @Test + public void approvalBindsEndpointEpochsCutAndNonce() throws IOException { + Path root = temp.newFolder().toPath(); + HistoryIncident incident = new HistoryIncident(root); + Path state = root.resolve("ha-history-incident"); + Path approval = root.resolve("ha-history-approval"); + assertNull(incident.firstDecision(80, () -> 100, 125, "a 1@0")); + byte[] old = Files.readAllBytes(state); + Files.write(approval, old); + assertNull(incident.authorize(80, 100, 125, "b 1@0", false)); + assertNull(incident.authorize(80, 100, 125, "a 1@0", false)); + Files.write(approval, Files.readAllBytes(state)); + assertNull(incident.authorize(80, 100, 125, "a 1@0 2@80", false)); + Files.write(approval, Files.readAllBytes(state)); + assertNull(incident.authorize(60, 100, 125, "a 1@0 2@80", false)); + assertNull(incident.authorize(100, 100, 125, "a 1@0 2@80", false)); + byte[] accepted = Files.readAllBytes(state); + Files.write(approval, accepted); + HistoryIncident.Cut cut = incident.authorize(100, 100, 125, "a 1@0 2@80", false); + assertEquals(60, cut.offset); + assertEquals(125, cut.originalEnd); + assertFalse(Files.exists(approval)); + // Crash after consuming authorization and before completing repair. + incident = new HistoryIncident(root); + assertTrue(incident.isolated()); + Files.write(approval, accepted); + assertNull(incident.authorize(60, 60, 60, "a 1@0 2@80", false)); + Files.write(approval, Files.readAllBytes(state)); + assertEquals(60, incident.authorize(60, 60, 60, "a 1@0 2@80", false).offset); + incident.clear(); + assertNull(incident.firstDecision(80, () -> 100, 125, "a 1@0")); + Files.write(approval, old); + assertNull(incident.authorize(80, 100, 125, "a 1@0", false)); + } + + @Test + public void healthyWaitHasNoIncidentButInterruptedIsolatedInspectionInvalidatesApproval() throws IOException { + Path root = temp.newFolder().toPath(); + HistoryIncident original = new HistoryIncident(root); + assertFalse(original.beginInspection()); + HistoryIncident restarted = new HistoryIncident(root); + assertEquals(100, restarted.firstDecision(100, () -> 100, 100, "a 1@0").offset); + assertNull(restarted.firstDecision(80, () -> 100, 100, "a 1@0")); + byte[] stale = Files.readAllBytes(root.resolve("ha-history-incident")); + Files.write(root.resolve("ha-history-approval"), stale); + assertTrue(restarted.beginInspection()); + restarted = new HistoryIncident(root); + assertFalse(restarted.beginInspection()); + assertNull(restarted.authorize(100, 100, 100, "a 1@0", false)); + restarted.finishInspection(); + Files.write(root.resolve("ha-history-approval"), stale); + assertNull(restarted.authorize(100, 100, 100, "a 1@0", false)); + Files.write(root.resolve("ha-history-approval"), Files.readAllBytes(root.resolve("ha-history-incident"))); + assertEquals(0, restarted.authorize(100, 100, 100, "a 1@0", false).offset); + } + + @Test + public void restartReplaysReceivedDecisionAfterPublicationFails() throws IOException { + for (long point : new long[] {60, 100}) { + Path root = temp.newFolder().toPath(); + Path offline = root.resolveSibling(root.getFileName() + "-offline"); + HistoryIncident incident = new HistoryIncident(root); + try { + assertThatThrownBy(() -> incident.firstDecision(point, () -> { + try { + Files.move(root, offline); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return 100; + }, 110, "a 1@0")).isInstanceOf(IOException.class); + } finally { + Files.move(offline, root); + } + HistoryIncident restarted = new HistoryIncident(root); + assertEquals(point < 100, restarted.isolated()); + if (point < 100) { + assertNull(restarted.authorize(110, 100, 110, "a 1@0", false)); + Files.copy(root.resolve("ha-history-incident"), root.resolve("ha-history-approval")); + assertEquals(point, restarted.authorize(110, 100, 110, "a 1@0", false).offset); + } + } + } + + @Test + public void retryMustForceAlreadyVisibleInspectionMarker() throws IOException { + Path archive = temp.newFolder().toPath().resolve("store.zip"); + // ZipFS permits creating and reading a file but cannot open its + // directory as a FileChannel for force(true). + try (FileSystem fs = FileSystems.newFileSystem(URI.create("jar:" + archive.toUri()), + Collections.singletonMap("create", "true"))) { + Path root = Files.createDirectory(fs.getPath("/store")); + Files.createFile(root.resolve("ha-history-incident")); + assertThatThrownBy(new HistoryIncident(root)::beginInspection).isInstanceOf(IOException.class); + assertTrue(Files.exists(root.resolve("ha-history-inspecting"))); + assertThatThrownBy(new HistoryIncident(root)::beginInspection).isInstanceOf(IOException.class); + } + } + + @Test + public void invalidApprovalAndUnreadableStateFailClosed() throws IOException { + Path root = temp.newFolder().toPath(); + HistoryIncident incident = new HistoryIncident(root); + assertNull(incident.firstDecision(1, () -> 2, 2, "a 1@0")); + Path approval = root.resolve("ha-history-approval"); + Files.write(approval, "bad".getBytes(StandardCharsets.UTF_8)); + assertNull(incident.authorize(1, 2, 2, "a 1@0", false)); + Files.delete(approval); + Files.createDirectory(approval); + assertThatThrownBy(() -> incident.authorize(1, 2, 2, "a 1@0", false)).isInstanceOf(IOException.class); + assertTrue(incident.isolated()); + Path state = root.resolve("ha-history-incident"); + Files.delete(state); + Files.createDirectory(state); + assertThatThrownBy(incident::isolated).isInstanceOf(IOException.class); + } +} diff --git a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/HistoryRecoveryStoreTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/HistoryRecoveryStoreTest.java new file mode 100644 index 00000000000..7d6bf0457a8 --- /dev/null +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/HistoryRecoveryStoreTest.java @@ -0,0 +1,275 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.rocketmq.store.ha.autoswitch; + +import java.io.DataInputStream; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import org.apache.rocketmq.common.BrokerConfig; +import org.apache.rocketmq.common.message.MessageExtBrokerInner; +import org.apache.rocketmq.store.DefaultMessageStore; +import org.apache.rocketmq.store.SelectMappedBufferResult; +import org.apache.rocketmq.store.config.BrokerRole; +import org.apache.rocketmq.store.config.MessageStoreConfig; +import org.apache.rocketmq.store.ha.HAConnectionState; +import org.apache.rocketmq.store.stats.BrokerStatsManager; +import org.junit.After; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.awaitility.Awaitility.await; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class HistoryRecoveryStoreTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + private DefaultMessageStore source; + private DefaultMessageStore replica; + private AutoSwitchHAClient client; + + @After + public void shutdown() { + if (client != null) { + client.shutdown(); + } + if (replica != null) { + replica.shutdown(); + } + if (source != null) { + source.shutdown(); + } + } + + @Test + public void restartWhileAwaitingFirstReplyRetainsIdenticalNonzeroPrefix() throws Exception { + Path directory = temporaryFolder.newFolder().toPath(); + source = open(temporaryFolder.newFolder().toPath(), 1); + replica = open(directory, 2); + long base = 64 * 1024; + ((AutoSwitchHAService) source.getHaService()).setLocalBrokerId(1L); + ((AutoSwitchHAService) source.getHaService()).setSyncStateSet(Collections.singleton(1L)); + assertTrue(source.getHaService().changeToMaster(1)); + assertTrue(replica.getHaService().changeToMaster(1)); + source.getCommitLog().getMappedFileQueue().getLastMappedFile(base); + replica.getCommitLog().getMappedFileQueue().getLastMappedFile(base); + write(source, "identical"); + byte[] retained = bytes(source, base); + assertTrue(replica.appendToCommitLog(base, retained, 0, retained.length)); + replica.setConfirmOffset(source.getMaxPhyOffset()); + try (ServerSocket silent = new ServerSocket(0)) { + silent.setSoTimeout(15000); + EpochFileCache epochs = new EpochFileCache(replica.getMessageStoreConfig().getStorePathEpochFile()); + assertTrue(epochs.initCacheFromFile()); + client = new AutoSwitchHAClient((AutoSwitchHAService) replica.getHaService(), replica, epochs, 2L); + client.updateHaMasterAddress("127.0.0.1:" + silent.getLocalPort()); + client.start(); + try (Socket socket = silent.accept()) { + socket.setSoTimeout(15000); + new DataInputStream(socket.getInputStream()).readFully(new byte[AutoSwitchHAClient.HANDSHAKE_HEADER_SIZE]); + // Keep the unanswered connection open across Store reload so + // graceful disconnect cleanup cannot hide a durable marker. + replica.shutdown(); + replica = open(directory, 2, BrokerRole.SLAVE); + assertEquals(base, replica.getMinPhyOffset()); + assertTrue(replica.getHaService().changeToSlave("127.0.0.1", 1, 2L)); + replica.getHaService().updateHaMasterAddress("127.0.0.1:" + source.getMessageStoreConfig().getHaListenPort()); + await().atMost(20, TimeUnit.SECONDS).until(() -> + replica.getHaService().getHAClient().getCurrentState() == HAConnectionState.TRANSFER); + assertArrayEquals(retained, bytes(replica, base)); + } + } + } + + @Test + public void sameEpochRewriteAcrossStoreReload() throws Exception { + verifyRecovery(false); + } + + @Test + public void formerMasterAfterUncleanElection() throws Exception { + verifyRecovery(true); + } + + private void verifyRecovery(boolean newEpoch) throws Exception { + Path directory = temporaryFolder.newFolder().toPath(); + source = open(temporaryFolder.newFolder().toPath(), 1); + replica = open(directory, 2); + AutoSwitchHAService master = (AutoSwitchHAService) source.getHaService(); + master.setLocalBrokerId(1L); + master.setSyncStateSet(Collections.singleton(1L)); + assertTrue(master.changeToMaster(1)); + write(source, "common"); + long cut = source.getMaxPhyOffset(); + byte[] common = bytes(source, 0); + assertTrue(((AutoSwitchHAService) replica.getHaService()).changeToMaster(1)); + assertTrue(replica.appendToCommitLog(0, common, 0, common.length)); + write(replica, "former"); + long confirmed = replica.getMaxPhyOffset(); + replica.setConfirmOffset(confirmed); + replica.getMessageStoreConfig().setBrokerRole(BrokerRole.SLAVE); + byte[] former = bytes(replica, cut); + if (newEpoch) { + assertTrue(master.changeToMaster(2)); + write(source, "chosen"); + } + client = connect(); + assertFalse(client.new HAClientReader().processReadResult(handshake(newEpoch, cut))); + assertArrayEquals(former, bytes(replica, cut)); + assertArrayEquals("former".getBytes(StandardCharsets.UTF_8), replica.lookMessageByOffset(cut).getBody()); + assertFalse(replica.getHaService().changeToMasterWhenLastRoleIsMaster(3)); + assertFalse(replica.getHaService().changeToMaster(3)); + client.shutdown(); + client = null; + replica.shutdown(); + replica = open(directory, 2, BrokerRole.SLAVE); + assertEquals(confirmed, replica.getConfirmOffset()); + if (!newEpoch) { + write(source, "chosen"); + } + write(source, "beyond"); + assertTrue(source.getMaxPhyOffset() > confirmed); + byte[] elected = bytes(source, cut); + assertFalse(Arrays.equals(former, Arrays.copyOf(elected, former.length))); + client = connect(); + assertFalse(client.new HAClientReader().processReadResult(handshake(newEpoch, cut))); + assertArrayEquals(former, bytes(replica, cut)); + client.shutdown(); + + if (newEpoch) { + AutoSwitchHAService slave = (AutoSwitchHAService) replica.getHaService(); + slave.setLocalBrokerId(2L); + slave.setSyncStateSet(Collections.singleton(2L)); + assertTrue(slave.changeToSlave("127.0.0.1", 2, 2L)); + slave.updateHaMasterAddress("127.0.0.1:" + source.getMessageStoreConfig().getHaListenPort()); + AutoSwitchHAClient running = (AutoSwitchHAClient) slave.getHAClient(); + await().atMost(20, TimeUnit.SECONDS).until(() -> running.getCurrentState() == HAConnectionState.HANDSHAKE); + assertFalse(slave.changeToMaster(3, Collections.singleton(9L))); + assertFalse(running.isStopped()); + assertEquals(Collections.singleton(2L), slave.getLocalSyncStateSet()); + assertEquals(confirmed, replica.getConfirmOffset()); + assertTrue(slave.changeToSlaveWhenMasterNotChange("127.0.0.1", 4)); + Files.copy(directory.resolve("ha-history-incident"), directory.resolve("ha-history-approval")); + await().atMost(30, TimeUnit.SECONDS).until(() -> replica.getConfirmOffset() == source.getMaxPhyOffset()); + assertArrayEquals(bytes(source, 0), bytes(replica, 0)); + assertArrayEquals("chosen".getBytes(StandardCharsets.UTF_8), replica.lookMessageByOffset(cut).getBody()); + return; + } + + Files.copy(directory.resolve("ha-history-incident"), directory.resolve("ha-history-approval")); + client = connect(); + ByteBuffer frames = handshake(newEpoch, cut); + AutoSwitchHAClient.HAClientReader reader = client.new HAClientReader(); + assertTrue(reader.processReadResult(frames)); + assertEquals(HAConnectionState.TRANSFER, client.getCurrentState()); + assertEquals(cut, replica.getMaxPhyOffset()); + assertEquals(cut, replica.getConfirmOffset()); + assertFalse(Files.exists(directory.resolve("ha-history-approval"))); + // Reload before any replacement writes. Old commit-log bytes cannot + // reappear merely because the authorized session lost its connection. + client.shutdown(); + client = null; + replica.shutdown(); + replica = open(directory, 2, BrokerRole.SLAVE); + assertEquals(cut, replica.getMaxPhyOffset()); + assertTrue(replica.getHaService().changeToSlave("127.0.0.1", newEpoch ? 2 : 1, 2L)); + replica.getHaService().updateHaMasterAddress("127.0.0.1:" + source.getMessageStoreConfig().getHaListenPort()); + await().atMost(30, TimeUnit.SECONDS).until(() -> replica.getConfirmOffset() == source.getMaxPhyOffset()); + assertArrayEquals(bytes(source, 0), bytes(replica, 0)); + assertArrayEquals("chosen".getBytes(StandardCharsets.UTF_8), replica.lookMessageByOffset(cut).getBody()); + } + + private AutoSwitchHAClient connect() throws Exception { + EpochFileCache epochs = new EpochFileCache(replica.getMessageStoreConfig().getStorePathEpochFile()); + assertTrue(epochs.initCacheFromFile()); + AutoSwitchHAClient result = new AutoSwitchHAClient((AutoSwitchHAService) replica.getHaService(), replica, epochs, 2L); + result.updateHaMasterAddress("127.0.0.1:" + source.getMessageStoreConfig().getHaListenPort()); + assertTrue(result.connectMaster()); + return result; + } + + private ByteBuffer handshake(boolean newEpoch, long cut) { + ByteBuffer frame = ByteBuffer.allocate(4096); + frame.putInt(HAConnectionState.HANDSHAKE.ordinal()); + frame.putInt(AutoSwitchHAConnection.EPOCH_ENTRY_SIZE * (newEpoch ? 2 : 1)); + frame.putLong(source.getMaxPhyOffset()).putInt(newEpoch ? 2 : 1); + frame.putInt(1).putLong(0); + if (newEpoch) { + frame.putInt(2).putLong(cut); + } + return frame; + } + + private DefaultMessageStore open(Path directory, int id) throws Exception { + return open(directory, id, BrokerRole.SYNC_MASTER); + } + + private DefaultMessageStore open(Path directory, int id, BrokerRole role) throws Exception { + MessageStoreConfig config = new MessageStoreConfig(); + config.setBrokerRole(role); + config.setStorePathRootDir(directory.toString()); + config.setHaListenPort(0); + config.setHaSendHeartbeatInterval(100); + config.setMappedFileSizeCommitLog(64 * 1024); + config.setMappedFileSizeConsumeQueue(1024 * 20); + config.setMaxHashSlotNum(100); + config.setMaxIndexNum(1000); + BrokerConfig broker = new BrokerConfig(); + broker.setBrokerId(id); + broker.setEnableControllerMode(true); + DefaultMessageStore store = new DefaultMessageStore(config, new BrokerStatsManager("test", true), + null, broker, new ConcurrentHashMap<>()); + assertTrue(store.load()); + store.start(); + return store; + } + + private void write(DefaultMessageStore store, String body) { + MessageExtBrokerInner message = new MessageExtBrokerInner(); + message.setTopic("History"); + message.setQueueId(0); + message.setBody(body.getBytes(StandardCharsets.UTF_8)); + message.setBornHost(new InetSocketAddress("127.0.0.1", 1000)); + message.setStoreHost(new InetSocketAddress("127.0.0.1", 1001)); + message.setWaitStoreMsgOK(false); + assertTrue(store.putMessage(message).isOk()); + } + + private byte[] bytes(DefaultMessageStore store, long start) { + SelectMappedBufferResult result = store.getCommitLogData(start); + try { + byte[] data = new byte[result.getSize()]; + result.getByteBuffer().get(data); + return data; + } finally { + result.release(); + } + } +}