Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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<Long> 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<Long> newSyncStateSet = new HashSet<>(syncStateSet);
changeSyncStateSet(newSyncStateSet, syncStateSetEpoch);

// Handle the slave synchronise
Set<Long> 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);
Expand Down Expand Up @@ -337,14 +338,18 @@ public void registerBrokerWhenRoleChange() {
private void changeSyncStateSet(final Set<Long> 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<Long> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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 {

Expand Down
12 changes: 12 additions & 0 deletions docs/cn/controller/replica-history-recovery.md
Original file line number Diff line number Diff line change
@@ -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 时,副本继续保持隔离。
54 changes: 54 additions & 0 deletions docs/en/controller/replica-history-recovery.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 11 additions & 7 deletions store/src/main/java/org/apache/rocketmq/store/StoreCheckpoint.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
Loading