diff --git a/broker/src/main/java/org/apache/rocketmq/broker/controller/BrokerStartupMetadata.java b/broker/src/main/java/org/apache/rocketmq/broker/controller/BrokerStartupMetadata.java new file mode 100644 index 00000000000..500ed45c9b6 --- /dev/null +++ b/broker/src/main/java/org/apache/rocketmq/broker/controller/BrokerStartupMetadata.java @@ -0,0 +1,81 @@ +/* + * 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.broker.controller; + +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.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import org.apache.rocketmq.common.MixAll; +import org.apache.rocketmq.common.UtilAll; + +/** + * Advances once before registering a recovered store. A per-process startup ID, sent alongside the + * generation, prevents a restored metadata file from being mistaken for a registration retry. + */ +final class BrokerStartupMetadata { + private BrokerStartupMetadata() { + } + + static long nextGeneration(Path file) throws IOException { + final Path target = file.toAbsolutePath(); + long previous = 0; + try { + final String[] lines = new String(Files.readAllBytes(target), StandardCharsets.UTF_8).split("\n", -1); + if (lines.length != 4 || !"1".equals(lines[0]) || !lines[3].isEmpty()) { + throw new IOException("Invalid broker startup metadata: " + target); + } + final String payload = lines[0] + "\n" + lines[1] + "\n"; + if (Integer.parseInt(lines[2]) != UtilAll.crc32(payload.getBytes(StandardCharsets.UTF_8))) { + throw new IOException("Broker startup metadata checksum mismatch: " + target); + } + previous = Long.parseLong(lines[1]); + if (previous < 1 || previous == Long.MAX_VALUE) { + throw new IOException("Invalid broker startup generation: " + previous); + } + } catch (NoSuchFileException ignored) { + // First upgraded startup. The controller still checks its own persisted generation. + } catch (NumberFormatException e) { + throw new IOException("Invalid broker startup metadata: " + target, e); + } + + final long next = previous + 1; + final String payload = "1\n" + next + "\n"; + final byte[] data = (payload + UtilAll.crc32(payload.getBytes(StandardCharsets.UTF_8)) + "\n") + .getBytes(StandardCharsets.UTF_8); + final Path temporary = Files.createTempFile(target.getParent(), target.getFileName() + ".", ".tmp"); + try { + try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE)) { + final ByteBuffer buffer = ByteBuffer.wrap(data); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + channel.force(true); + } + Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + MixAll.fsyncDirectory(target.getParent()); + } finally { + Files.deleteIfExists(temporary); + } + return next; + } +} 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..fe1da55864f 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 @@ -17,12 +17,15 @@ package org.apache.rocketmq.broker.controller; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; +import java.util.Objects; import java.util.Random; import java.util.Set; +import java.util.UUID; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -100,6 +103,13 @@ public class ReplicasManager { private int syncStateSetEpoch = 0; private String masterAddress = ""; private int masterEpoch = 0; + private final String brokerStartupId = UUID.randomUUID().toString(); + private Long brokerStartupGeneration; + private volatile boolean startupRegistered; + private int startupMasterEpoch = -1; + private int recoveredEpoch = -1; + private boolean becameMasterThisStartup; + private volatile boolean roleReady; private long lastSyncTimeMs = System.currentTimeMillis(); private Random random = new Random(); @@ -135,6 +145,8 @@ enum RegisterState { } public void start() { + setFenced(true); + this.recoveredEpoch = this.haService.getLastEpoch(); this.state = State.INITIAL; updateControllerAddr(); scanAvailableControllerAddresses(); @@ -197,10 +209,9 @@ private boolean startBasicService() { if (this.state == State.REGISTER_TO_CONTROLLER_DONE) { // The scheduled task for heartbeat sending is not starting now, so we should manually send heartbeat request this.sendHeartbeatToController(); - if (this.masterBrokerId != null || brokerElect()) { + if (brokerElect()) { LOGGER.info("Master in this broker set is elected, masterBrokerId: {}, masterBrokerAddr: {}", this.masterBrokerId, this.masterAddress); this.state = State.RUNNING; - setFenced(false); LOGGER.info("All register process has been done, change state to: {}", this.state); } else { return false; @@ -225,6 +236,12 @@ public void shutdown() { public synchronized void changeBrokerRole(final Long newMasterBrokerId, final String newMasterAddress, final Integer newMasterEpoch, final Integer syncStateSetEpoch, final Set syncStateSet) throws Exception { + // Startup uses the election response; periodic metadata sync reconciles any + // notification that crossed startup before this broker was ready. + if (this.state != State.RUNNING || !this.startupRegistered || newMasterEpoch < this.startupMasterEpoch) { + LOGGER.info("Ignore role notification before startup completes or below its epoch: {}", newMasterEpoch); + return; + } if (newMasterBrokerId != null && newMasterEpoch > this.masterEpoch) { if (newMasterBrokerId.equals(this.brokerControllerId)) { changeToMaster(newMasterEpoch, syncStateSetEpoch, syncStateSet); @@ -236,15 +253,28 @@ public synchronized void changeBrokerRole(final Long newMasterBrokerId, final St public void changeToMaster(final int newMasterEpoch, final int syncStateSetEpoch, final Set syncStateSet) throws Exception { synchronized (this) { + if (!this.startupRegistered || newMasterEpoch < this.startupMasterEpoch) { + throw new IllegalStateException("Master grant does not belong to the registered broker startup"); + } + if (!this.becameMasterThisStartup && newMasterEpoch <= this.recoveredEpoch) { + throw new IllegalStateException("Recovered store requires a master epoch newer than " + this.recoveredEpoch); + } if (newMasterEpoch > this.masterEpoch) { LOGGER.info("Begin to change to master, brokerName:{}, replicas:{}, new Epoch:{}", this.brokerConfig.getBrokerName(), this.brokerAddress, newMasterEpoch); - this.masterEpoch = newMasterEpoch; + this.roleReady = false; + setFenced(true); if (this.masterBrokerId != null && this.masterBrokerId.equals(this.brokerControllerId) && this.brokerController.getBrokerConfig().getBrokerId() == MixAll.MASTER_ID) { // Change SyncStateSet final HashSet newSyncStateSet = new HashSet<>(syncStateSet); changeSyncStateSet(newSyncStateSet, syncStateSetEpoch); // if master doesn't change - this.haService.changeToMasterWhenLastRoleIsMaster(newMasterEpoch); + if (!this.haService.changeToMasterWhenLastRoleIsMaster(newMasterEpoch)) { + throw new IllegalStateException("Failed to persist master epoch " + newMasterEpoch); + } + this.masterEpoch = newMasterEpoch; + this.becameMasterThisStartup = true; + this.roleReady = true; + setFenced(false); this.brokerController.getTopicConfigManager().getDataVersion().nextVersion(newMasterEpoch); this.executorService.submit(this::checkSyncStateSetAndDoReport); registerBrokerWhenRoleChange(); @@ -255,11 +285,12 @@ public void changeToMaster(final int newMasterEpoch, final int syncStateSetEpoch final HashSet newSyncStateSet = new HashSet<>(syncStateSet); changeSyncStateSet(newSyncStateSet, syncStateSetEpoch); - // Handle the slave synchronise - handleSlaveSynchronize(BrokerRole.SYNC_MASTER); - // Notify ha service, change to master - this.haService.changeToMaster(newMasterEpoch); + if (!this.haService.changeToMaster(newMasterEpoch)) { + throw new IllegalStateException("Failed to change HA role to master at epoch " + newMasterEpoch); + } + + handleSlaveSynchronize(BrokerRole.SYNC_MASTER); this.brokerController.getBrokerConfig().setBrokerId(MixAll.MASTER_ID); this.brokerController.getMessageStoreConfig().setBrokerRole(BrokerRole.SYNC_MASTER); @@ -268,6 +299,10 @@ public void changeToMaster(final int newMasterEpoch, final int syncStateSetEpoch // Change record this.masterAddress = this.brokerAddress; this.masterBrokerId = this.brokerControllerId; + this.masterEpoch = newMasterEpoch; + this.becameMasterThisStartup = true; + this.roleReady = true; + setFenced(false); schedulingCheckSyncStateSet(); @@ -280,14 +315,26 @@ public void changeToMaster(final int newMasterEpoch, final int syncStateSetEpoch public void changeToSlave(final String newMasterAddress, final int newMasterEpoch, Long newMasterBrokerId) { synchronized (this) { + if (!this.startupRegistered || newMasterEpoch < this.startupMasterEpoch) { + LOGGER.warn("Ignore slave role before startup registration or below its epoch: {}", newMasterEpoch); + return; + } if (newMasterEpoch > this.masterEpoch) { LOGGER.info("Begin to change to slave, brokerName={}, brokerId={}, newMasterBrokerId={}, newMasterAddress={}, newMasterEpoch={}", this.brokerConfig.getBrokerName(), this.brokerControllerId, newMasterBrokerId, newMasterAddress, newMasterEpoch); - this.masterEpoch = newMasterEpoch; + this.roleReady = false; + setFenced(true); if (newMasterBrokerId.equals(this.masterBrokerId)) { // if master doesn't change - this.haService.changeToSlaveWhenMasterNotChange(newMasterAddress, newMasterEpoch); + if (!this.haService.changeToSlaveWhenMasterNotChange(newMasterAddress, newMasterEpoch)) { + return; + } + this.masterAddress = newMasterAddress; + this.brokerController.getSlaveSynchronize().setMasterAddr(newMasterAddress); + this.masterEpoch = newMasterEpoch; + this.roleReady = true; + setFenced(false); this.brokerController.getTopicConfigManager().getDataVersion().nextVersion(newMasterEpoch); registerBrokerWhenRoleChange(); return; @@ -302,15 +349,17 @@ public void changeToSlave(final String newMasterAddress, final int newMasterEpoc // The brokerId in brokerConfig just means its role(master[0] or slave[>=1]) this.brokerConfig.setBrokerId(brokerControllerId); - // Change record + // Notify ha service, change to slave + if (!this.haService.changeToSlave(newMasterAddress, newMasterEpoch, brokerControllerId)) { + return; + } + this.masterAddress = newMasterAddress; this.masterBrokerId = newMasterBrokerId; - - // Handle the slave synchronise + this.masterEpoch = newMasterEpoch; handleSlaveSynchronize(BrokerRole.SLAVE); - - // Notify ha service, change to slave - this.haService.changeToSlave(newMasterAddress, newMasterEpoch, brokerControllerId); + this.roleReady = true; + setFenced(false); this.brokerController.getTopicConfigManager().getDataVersion().nextVersion(newMasterEpoch); registerBrokerWhenRoleChange(); @@ -391,7 +440,8 @@ private boolean brokerElect() { } else { changeToSlave(masterAddress, tryElectResponse.getMasterEpoch(), tryElectResponse.getMasterBrokerId()); } - return true; + return this.roleReady && Objects.equals(this.masterBrokerId, masterBrokerId) + && this.masterEpoch == tryElectResponse.getMasterEpoch(); } catch (Exception e) { LOGGER.error("Failed to try elect", e); return false; @@ -558,21 +608,30 @@ private boolean createMetadataFileAndDeleteTemp() { */ private boolean registerBrokerToController() { try { - Pair> responsePair = this.brokerOuterAPI.registerBrokerToController(brokerConfig.getBrokerClusterName(), brokerConfig.getBrokerName(), brokerControllerId, brokerAddress, controllerLeaderAddress); + if (this.brokerStartupGeneration == null) { + this.brokerStartupGeneration = BrokerStartupMetadata.nextGeneration(Paths.get( + this.brokerController.getMessageStoreConfig().getStorePathBrokerIdentity() + "-startup")); + } + Pair> responsePair = this.brokerOuterAPI.registerBrokerToController( + brokerConfig.getBrokerClusterName(), brokerConfig.getBrokerName(), brokerControllerId, brokerAddress, + controllerLeaderAddress, this.brokerStartupGeneration, this.brokerStartupId); if (responsePair == null) return false; RegisterBrokerToControllerResponseHeader response = responsePair.getObject1(); - Set syncStateSet = responsePair.getObject2(); - final Long masterBrokerId = response.getMasterBrokerId(); - final String masterAddress = response.getMasterAddress(); - if (masterBrokerId == null) { - return true; - } - if (this.brokerControllerId.equals(masterBrokerId)) { - changeToMaster(response.getMasterEpoch(), response.getSyncStateSetEpoch(), syncStateSet); - } else { - changeToSlave(masterAddress, response.getMasterEpoch(), masterBrokerId); + synchronized (this) { + if (!Objects.equals(this.brokerStartupGeneration, response.getBrokerStartupGeneration()) + || !this.brokerStartupId.equals(response.getBrokerStartupId()) || response.getMasterEpoch() == null) { + LOGGER.error("Controller did not acknowledge this broker startup; upgrade the controller before starting this broker"); + this.startupRegistered = false; + this.roleReady = false; + setFenced(true); + return false; + } + this.startupMasterEpoch = Math.max(this.startupMasterEpoch, response.getMasterEpoch()); + this.startupRegistered = true; } + // The reply acknowledges this process and sets the minimum epoch. It is not + // authorization to publish a role; startup needs the controller's election response. return true; } catch (Exception e) { LOGGER.error("fail to send registerBrokerToController request to controller", e); @@ -673,7 +732,10 @@ private void schedulingSyncBrokerMetadata() { LOGGER.warn("Error happen when get broker {}'s metadata", this.brokerConfig.getBrokerName(), exception); if (exception.getResponseCode() == CONTROLLER_BROKER_METADATA_NOT_EXIST) { try { - registerBrokerToController(); + if (registerBrokerToController()) { + sendHeartbeatToController(); + brokerElect(); + } TimeUnit.SECONDS.sleep(2); } catch (InterruptedException ignore) { diff --git a/broker/src/main/java/org/apache/rocketmq/broker/out/BrokerOuterAPI.java b/broker/src/main/java/org/apache/rocketmq/broker/out/BrokerOuterAPI.java index fb44e8e2234..6ea858e9ee6 100644 --- a/broker/src/main/java/org/apache/rocketmq/broker/out/BrokerOuterAPI.java +++ b/broker/src/main/java/org/apache/rocketmq/broker/out/BrokerOuterAPI.java @@ -1435,7 +1435,16 @@ public ApplyBrokerIdResponseHeader applyBrokerId(final String clusterName, final public Pair> registerBrokerToController( final String clusterName, final String brokerName, final Long brokerId, final String brokerAddress, final String controllerAddress) throws Exception { + return registerBrokerToController(clusterName, brokerName, brokerId, brokerAddress, controllerAddress, + null, null); + } + + public Pair> registerBrokerToController( + final String clusterName, final String brokerName, final Long brokerId, final String brokerAddress, + final String controllerAddress, final Long startupGeneration, final String startupId) throws Exception { final RegisterBrokerToControllerRequestHeader requestHeader = new RegisterBrokerToControllerRequestHeader(clusterName, brokerName, brokerId, brokerAddress); + requestHeader.setBrokerStartupGeneration(startupGeneration); + requestHeader.setBrokerStartupId(startupId); final RemotingCommand request = RemotingCommand.createRequestCommand(RequestCode.CONTROLLER_REGISTER_BROKER, requestHeader); final RemotingCommand response = this.remotingClient.invokeSync(controllerAddress, request, 3000); assert response != null; diff --git a/broker/src/test/java/org/apache/rocketmq/broker/controller/BrokerStartupMetadataTest.java b/broker/src/test/java/org/apache/rocketmq/broker/controller/BrokerStartupMetadataTest.java new file mode 100644 index 00000000000..7c118b5eec3 --- /dev/null +++ b/broker/src/test/java/org/apache/rocketmq/broker/controller/BrokerStartupMetadataTest.java @@ -0,0 +1,58 @@ +/* + * 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.broker.controller; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.junit.Assert.assertEquals; + +public class BrokerStartupMetadataTest { + @Rule + public TemporaryFolder directory = new TemporaryFolder(); + + @Test + public void incrementsPersistedGenerationAcrossStarts() throws Exception { + Path path = directory.getRoot().toPath().resolve("startup"); + assertEquals(1, BrokerStartupMetadata.nextGeneration(path)); + assertEquals(2, BrokerStartupMetadata.nextGeneration(path)); + assertEquals(3, BrokerStartupMetadata.nextGeneration(path)); + } + + @Test(expected = IOException.class) + public void emptyMetadataDoesNotBecomeFirstStartup() throws Exception { + BrokerStartupMetadata.nextGeneration(directory.newFile("startup").toPath()); + } + + @Test(expected = IOException.class) + public void damagedMetadataDoesNotResetGeneration() throws Exception { + Path path = directory.getRoot().toPath().resolve("startup"); + BrokerStartupMetadata.nextGeneration(path); + Files.write(path, "1\n9\n0\n".getBytes(StandardCharsets.UTF_8)); + BrokerStartupMetadata.nextGeneration(path); + } + + @Test(expected = IOException.class) + public void refusesUnwritableMetadataTarget() throws Exception { + BrokerStartupMetadata.nextGeneration(directory.newFolder("startup").toPath()); + } +} 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..84d03aee6c8 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 @@ -142,7 +142,8 @@ public void testBrokerRegisterSuccess() throws Exception { when(mockedBrokerOuterAPI.getNextBrokerId(any(), any(), any())).thenReturn(new GetNextBrokerIdResponseHeader(CLUSTER_NAME, BROKER_NAME, 1L)); when(mockedBrokerOuterAPI.applyBrokerId(any(), any(), anyLong(), any(), any())).thenReturn(new ApplyBrokerIdResponseHeader()); - when(mockedBrokerOuterAPI.registerBrokerToController(any(), any(), anyLong(), any(), any())).thenReturn(new Pair<>(new RegisterBrokerToControllerResponseHeader(), syncStateSet)); + mockRegistrationWithoutMaster(); + when(mockedAutoSwitchHAService.changeToMaster(1)).thenReturn(true); when(mockedBrokerOuterAPI.brokerElect(any(), any(), any(), anyLong())) .thenReturn(new Pair<>(new ElectMasterResponseHeader(1L, "127.0.0.1:13131", 1, 1), syncStateSet)); @@ -159,11 +160,54 @@ public void testBrokerRegisterSuccess() throws Exception { replicasManager0.shutdown(); } + @Test + public void testStartupUsesElectionResponseInsteadOfRegistrationSnapshot() throws Exception { + final long brokerId = 1L; + final String masterAddress = "127.0.0.1:13131"; + when(mockedBrokerOuterAPI.getNextBrokerId(any(), any(), any())) + .thenReturn(new GetNextBrokerIdResponseHeader(CLUSTER_NAME, BROKER_NAME, brokerId)); + when(mockedBrokerOuterAPI.applyBrokerId(any(), any(), anyLong(), any(), any())) + .thenReturn(new ApplyBrokerIdResponseHeader()); + when(mockedBrokerOuterAPI.registerBrokerToController(any(), any(), anyLong(), any(), any(), anyLong(), any())) + .thenAnswer(invocation -> { + RegisterBrokerToControllerResponseHeader response = new RegisterBrokerToControllerResponseHeader(); + response.setBrokerStartupGeneration(invocation.getArgument(5)); + response.setBrokerStartupId(invocation.getArgument(6)); + response.setMasterBrokerId(brokerId); + response.setMasterAddress(masterAddress); + response.setMasterEpoch(2); + response.setSyncStateSetEpoch(1); + return new Pair<>(response, syncStateSet); + }); + when(mockedAutoSwitchHAService.changeToMaster(3)).thenReturn(true); + + ReplicasManager manager = new ReplicasManager(mockedBrokerController); + when(mockedBrokerOuterAPI.brokerElect(any(), any(), any(), anyLong())).thenAnswer(invocation -> { + assertTrue(runningFlags.isFenced()); + assertEquals(0, manager.getMasterEpoch()); + manager.changeBrokerRole(brokerId, masterAddress, 2, 1, syncStateSet); + assertTrue(runningFlags.isFenced()); + return new Pair<>(new ElectMasterResponseHeader(brokerId, masterAddress, 3, 1), syncStateSet); + }); + + try { + manager.start(); + assertEquals(ReplicasManager.State.RUNNING, manager.getState()); + assertEquals(3, manager.getMasterEpoch()); + assertFalse(runningFlags.isFenced()); + Mockito.verify(mockedAutoSwitchHAService, Mockito.never()).changeToMaster(2); + Mockito.verify(mockedAutoSwitchHAService).changeToMaster(3); + } finally { + manager.shutdown(); + } + } + @Test public void testBrokerRegisterSuccessAndRestartWithChangedBrokerConfig() throws Exception { when(mockedBrokerOuterAPI.getNextBrokerId(any(), any(), any())).thenReturn(new GetNextBrokerIdResponseHeader(CLUSTER_NAME, BROKER_NAME, 1L)); when(mockedBrokerOuterAPI.applyBrokerId(any(), any(), anyLong(), any(), any())).thenReturn(new ApplyBrokerIdResponseHeader()); - when(mockedBrokerOuterAPI.registerBrokerToController(any(), any(), anyLong(), any(), any())).thenReturn(new Pair<>(new RegisterBrokerToControllerResponseHeader(), syncStateSet)); + mockRegistrationWithoutMaster(); + when(mockedAutoSwitchHAService.changeToMaster(1)).thenReturn(true); when(mockedBrokerOuterAPI.brokerElect(any(), any(), any(), anyLong())).thenReturn(new Pair<>(new ElectMasterResponseHeader(1L, "127.0.0.1:13131", 1, 1), syncStateSet)); ReplicasManager replicasManager0 = new ReplicasManager(mockedBrokerController); @@ -250,7 +294,8 @@ public void testRegisterFailedAtCreateMetadataFileAndDeleteTemp() throws Excepti ReplicasManager spyReplicasManager = new ReplicasManager(mockedBrokerController); when(mockedBrokerOuterAPI.getNextBrokerId(any(), any(), any())).thenReturn(new GetNextBrokerIdResponseHeader(CLUSTER_NAME, BROKER_NAME, 1L)); when(mockedBrokerOuterAPI.applyBrokerId(any(), any(), anyLong(), any(), any())).thenReturn(new ApplyBrokerIdResponseHeader()); - when(mockedBrokerOuterAPI.registerBrokerToController(any(), any(), anyLong(), any(), any())).thenReturn(new Pair<>(new RegisterBrokerToControllerResponseHeader(), syncStateSet)); + mockRegistrationWithoutMaster(); + when(mockedAutoSwitchHAService.changeToMaster(1)).thenReturn(true); when(mockedBrokerOuterAPI.brokerElect(any(), any(), any(), anyLong())).thenReturn(new Pair<>(new ElectMasterResponseHeader(1L, "127.0.0.1:13131", 1, 1), syncStateSet)); FieldUtils.writeDeclaredField(spyReplicasManager, "brokerMetadata", brokerMetadata, true); @@ -291,7 +336,8 @@ public void testRegisterFailedAtRegisterSuccess() throws Exception { ReplicasManager replicasManager = new ReplicasManager(mockedBrokerController); when(mockedBrokerOuterAPI.getNextBrokerId(any(), any(), any())).thenReturn(new GetNextBrokerIdResponseHeader(CLUSTER_NAME, BROKER_NAME, 1L)); when(mockedBrokerOuterAPI.applyBrokerId(any(), any(), anyLong(), any(), any())).thenReturn(new ApplyBrokerIdResponseHeader()); - when(mockedBrokerOuterAPI.registerBrokerToController(any(), any(), anyLong(), any(), any())).thenThrow(new RuntimeException()); + when(mockedBrokerOuterAPI.registerBrokerToController(any(), any(), anyLong(), any(), any(), anyLong(), any())) + .thenThrow(new RuntimeException()); when(mockedBrokerOuterAPI.brokerElect(any(), any(), any(), anyLong())).thenReturn(new Pair<>(new ElectMasterResponseHeader(1L, "127.0.0.1:13131", 1, 1), syncStateSet)); replicasManager.start(); @@ -319,7 +365,8 @@ public void testRegisterFailedAtRegisterSuccess() throws Exception { // restart, we expect that this replicasManager still keep the metadata and still try to finish its registering ReplicasManager replicasManagerNew = new ReplicasManager(mockedBrokerController); - when(mockedBrokerOuterAPI.registerBrokerToController(any(), any(), anyLong(), any(), any())).thenReturn(new Pair<>(new RegisterBrokerToControllerResponseHeader(), syncStateSet)); + mockRegistrationWithoutMaster(); + when(mockedAutoSwitchHAService.changeToMaster(1)).thenReturn(true); replicasManagerNew.start(); assertEquals(ReplicasManager.State.RUNNING, replicasManagerNew.getState()); @@ -336,6 +383,19 @@ public void testRegisterFailedAtRegisterSuccess() throws Exception { } + private void mockRegistrationWithoutMaster() throws Exception { + when(mockedBrokerOuterAPI.registerBrokerToController(any(), any(), anyLong(), any(), any(), anyLong(), any())) + .thenAnswer(invocation -> { + final RegisterBrokerToControllerResponseHeader response = new RegisterBrokerToControllerResponseHeader(); + response.setBrokerStartupGeneration(invocation.getArgument(5)); + response.setBrokerStartupId(invocation.getArgument(6)); + // Registration succeeds before the initial election has selected a master. + response.setMasterEpoch(0); + response.setSyncStateSetEpoch(0); + return new Pair<>(response, syncStateSet); + }); + } + private void checkMetadataFile(BrokerMetadata brokerMetadata0 ,Long brokerId) throws Exception { assertEquals(brokerId, brokerMetadata0.getBrokerId()); assertTrue(brokerMetadata0.fileExists()); diff --git a/broker/src/test/java/org/apache/rocketmq/broker/controller/ReplicasManagerStartupTest.java b/broker/src/test/java/org/apache/rocketmq/broker/controller/ReplicasManagerStartupTest.java new file mode 100644 index 00000000000..2a2420c7b16 --- /dev/null +++ b/broker/src/test/java/org/apache/rocketmq/broker/controller/ReplicasManagerStartupTest.java @@ -0,0 +1,131 @@ +/* + * 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.broker.controller; + +import java.lang.reflect.Field; +import java.util.Collections; +import java.util.HashSet; +import org.apache.rocketmq.broker.BrokerController; +import org.apache.rocketmq.broker.slave.SlaveSynchronize; +import org.apache.rocketmq.broker.topic.TopicConfigManager; +import org.apache.rocketmq.common.BrokerConfig; +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.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +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 ReplicasManagerStartupTest { + private ReplicasManager manager; + private BrokerController controller; + private AutoSwitchHAService ha; + private RunningFlags flags; + private MessageStoreConfig storeConfig; + + @Before + public void setUp() throws Exception { + controller = mock(BrokerController.class); + DefaultMessageStore store = mock(DefaultMessageStore.class); + ha = mock(AutoSwitchHAService.class); + flags = new RunningFlags(); + storeConfig = new MessageStoreConfig(); + storeConfig.setBrokerRole(BrokerRole.SLAVE); + BrokerConfig config = new BrokerConfig(); + config.setBrokerId(1); + when(controller.getBrokerConfig()).thenReturn(config); + when(controller.getMessageStore()).thenReturn(store); + when(controller.getMessageStoreConfig()).thenReturn(storeConfig); + when(controller.getBrokerAddr()).thenReturn("127.0.0.1:10911"); + when(controller.getSlaveSynchronize()).thenReturn(mock(SlaveSynchronize.class)); + when(controller.getTopicConfigManager()).thenReturn(new TopicConfigManager()); + when(store.getHaService()).thenReturn(ha); + when(store.getRunningFlags()).thenReturn(flags); + when(ha.maybeShrinkSyncStateSet()).thenReturn(new HashSet<>(Collections.singleton(1L))); + manager = new ReplicasManager(controller); + setField("brokerControllerId", 1L); + } + + @After + public void tearDown() { + manager.shutdown(); + } + + @Test + public void refusesMasterNotificationBeforeStartupRegistration() throws Exception { + manager.changeBrokerRole(1L, "127.0.0.1:10911", 2, 1, Collections.singleton(1L)); + verify(ha, never()).changeToMaster(2); + assertEquals(0, manager.getMasterEpoch()); + } + + @Test + public void failedHaTransitionStaysFencedAndSameGrantCanRetry() throws Exception { + setField("startupRegistered", true); + setField("startupMasterEpoch", 2); + when(ha.changeToMaster(2)).thenReturn(false); + try { + manager.changeToMaster(2, 1, Collections.singleton(1L)); + fail("Failed HA transition must not publish the master role"); + } catch (IllegalStateException expected) { + assertTrue(flags.isFenced()); + } + assertEquals(0, manager.getMasterEpoch()); + assertEquals(BrokerRole.SLAVE, storeConfig.getBrokerRole()); + verify(controller, never()).changeSpecialServiceStatus(true); + + when(ha.changeToMaster(2)).thenReturn(true); + manager.changeToMaster(2, 1, Collections.singleton(1L)); + assertEquals(2, manager.getMasterEpoch()); + assertEquals(BrokerRole.SYNC_MASTER, storeConfig.getBrokerRole()); + assertFalse(flags.isFenced()); + verify(controller).changeSpecialServiceStatus(true); + } + + @Test + public void refusesRoleOlderThanRegistrationSnapshot() throws Exception { + setField("startupRegistered", true); + setField("startupMasterEpoch", 3); + manager.changeBrokerRole(1L, "127.0.0.1:10911", 2, 1, Collections.singleton(1L)); + verify(ha, never()).changeToMaster(2); + assertEquals(0, manager.getMasterEpoch()); + } + + @Test(expected = IllegalStateException.class) + public void recoveredStoreCannotReuseItsLastEpoch() throws Exception { + setField("startupRegistered", true); + setField("startupMasterEpoch", 3); + setField("recoveredEpoch", 3); + manager.changeToMaster(3, 1, Collections.singleton(1L)); + } + + private void setField(String name, Object value) throws Exception { + Field field = ReplicasManager.class.getDeclaredField(name); + field.setAccessible(true); + field.set(manager, value); + } +} diff --git a/common/src/main/java/org/apache/rocketmq/common/utils/CheckpointFile.java b/common/src/main/java/org/apache/rocketmq/common/utils/CheckpointFile.java index 8f51d274654..176323d7470 100644 --- a/common/src/main/java/org/apache/rocketmq/common/utils/CheckpointFile.java +++ b/common/src/main/java/org/apache/rocketmq/common/utils/CheckpointFile.java @@ -20,8 +20,15 @@ import java.io.BufferedReader; import java.io.File; 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.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.CollectionUtils; @@ -152,4 +159,91 @@ public List read() throws IOException { return this.read(this.getBackFilePath()); } } + + /** + * Read the primary checkpoint without falling back to an older backup. Callers that use the + * checkpoint as a durable history boundary must not silently restore an earlier boundary. + */ + public synchronized List readStrict() throws IOException { + final Path path = Paths.get(this.filePath); + final List result = new ArrayList<>(); + try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { + final int expectedLines = Integer.parseInt(reader.readLine()); + final int expectedCrc32 = Integer.parseInt(reader.readLine()); + if (expectedLines < 0) { + throw new IOException("Invalid checkpoint entry count: " + this.filePath); + } + final StringBuilder content = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + content.append(line).append(System.lineSeparator()); + final T entry = this.serializer.fromLine(line); + if (entry == null) { + throw new IOException("Invalid checkpoint entry: " + this.filePath); + } + result.add(entry); + } + if (result.size() != expectedLines) { + throw new IOException("Checkpoint entry count does not match: " + this.filePath); + } + final int actualCrc32 = UtilAll.crc32(content.toString().getBytes(StandardCharsets.UTF_8)); + if (actualCrc32 != expectedCrc32) { + throw new IOException("Checkpoint checksum does not match: " + this.filePath); + } + return result; + } catch (NoSuchFileException e) { + if (Files.exists(Paths.get(getBackFilePath()))) { + throw new IOException("Primary checkpoint is missing while a backup exists: " + this.filePath, e); + } + return result; + } catch (RuntimeException e) { + throw new IOException("Invalid checkpoint: " + this.filePath, e); + } + } + + /** + * Replace a checkpoint only after its complete contents have been forced to disk. Empty lists + * are persisted as well, so a removed history cannot reappear from an earlier checkpoint. + */ + public synchronized void writeAtomically(final List entries) throws IOException { + final StringBuilder entryContent = new StringBuilder(); + for (T entry : entries) { + final String line = this.serializer.toLine(entry); + if (line == null || line.isEmpty() || line.indexOf('\n') >= 0 || line.indexOf('\r') >= 0) { + throw new IOException("Invalid checkpoint entry: " + this.filePath); + } + entryContent.append(line).append(System.lineSeparator()); + } + final int crc32 = UtilAll.crc32(entryContent.toString().getBytes(StandardCharsets.UTF_8)); + final byte[] data = (entries.size() + System.lineSeparator() + crc32 + System.lineSeparator() + + entryContent).getBytes(StandardCharsets.UTF_8); + final Path path = Paths.get(this.filePath).toAbsolutePath(); + final Path parent = path.getParent(); + if (path.getFileName() == null || parent == null) { + throw new IOException("Invalid checkpoint path: " + this.filePath); + } + // createDirectories rejects a directory symlink in the last component, such as /tmp on macOS. + if (!Files.isDirectory(parent)) { + Files.createDirectories(parent); + } + final Path temporaryFile = Files.createTempFile(parent, "checkpoint-", ".tmp"); + try { + try (FileChannel channel = FileChannel.open(temporaryFile, StandardOpenOption.WRITE)) { + final ByteBuffer buffer = ByteBuffer.wrap(data); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + channel.force(true); + } + Files.move(temporaryFile, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + MixAll.fsyncDirectory(parent); + } catch (IOException e) { + try { + Files.deleteIfExists(temporaryFile); + } catch (IOException cleanupException) { + e.addSuppressed(cleanupException); + } + throw e; + } + } } diff --git a/controller/src/main/java/org/apache/rocketmq/controller/impl/DLedgerController.java b/controller/src/main/java/org/apache/rocketmq/controller/impl/DLedgerController.java index 3421010340a..aaea0aa9243 100644 --- a/controller/src/main/java/org/apache/rocketmq/controller/impl/DLedgerController.java +++ b/controller/src/main/java/org/apache/rocketmq/controller/impl/DLedgerController.java @@ -25,6 +25,7 @@ import io.openmessaging.storage.dledger.protocol.AppendEntryRequest; import io.openmessaging.storage.dledger.protocol.AppendEntryResponse; import io.openmessaging.storage.dledger.protocol.BatchAppendEntryRequest; +import io.openmessaging.storage.dledger.protocol.DLedgerResponseCode; import io.opentelemetry.api.common.AttributesBuilder; import java.util.ArrayList; import java.util.List; @@ -74,6 +75,7 @@ import org.apache.rocketmq.remoting.protocol.header.controller.register.ApplyBrokerIdRequestHeader; import org.apache.rocketmq.remoting.protocol.header.controller.register.GetNextBrokerIdRequestHeader; import org.apache.rocketmq.remoting.protocol.header.controller.register.RegisterBrokerToControllerRequestHeader; +import org.apache.rocketmq.remoting.protocol.header.controller.register.RegisterBrokerToControllerResponseHeader; import static org.apache.rocketmq.controller.metrics.ControllerMetricsConstant.LABEL_BROKER_SET; import static org.apache.rocketmq.controller.metrics.ControllerMetricsConstant.LABEL_CLUSTER_NAME; @@ -224,7 +226,9 @@ public CompletableFuture applyBrokerId(ApplyBrokerIdRequestHead @Override public CompletableFuture registerBroker(RegisterBrokerToControllerRequestHeader request) { - return this.scheduler.appendEvent("registerSuccess", () -> this.replicasInfoManager.registerBroker(request, brokerAlivePredicate), true); + final Supplier> registration = + () -> this.replicasInfoManager.registerBroker(request, brokerAlivePredicate); + return this.scheduler.appendEvent("registerSuccess", registration, true, registration); } @Override @@ -303,7 +307,13 @@ private boolean appendToDLedgerAndWait(final AppendEntryRequest request) { attributesBuilder.put(LABEL_DLEDGER_OPERATION_STATUS, ControllerMetricsConstant.DLedgerOperationStatus.FAILED.getLowerCaseName()).build()); return false; } - dLedgerFuture.get(5, TimeUnit.SECONDS); + final AppendEntryResponse response = dLedgerFuture.get(5, TimeUnit.SECONDS); + if (response == null || response.getCode() != DLedgerResponseCode.SUCCESS.getCode()) { + log.error("DLedger did not commit the controller event: {}", response); + ControllerMetricsManager.dLedgerOpTotal.add(1, + attributesBuilder.put(LABEL_DLEDGER_OPERATION_STATUS, ControllerMetricsConstant.DLedgerOperationStatus.FAILED.getLowerCaseName()).build()); + return false; + } ControllerMetricsManager.dLedgerOpTotal.add(1, attributesBuilder.put(LABEL_DLEDGER_OPERATION_STATUS, ControllerMetricsConstant.DLedgerOperationStatus.SUCCESS.getLowerCaseName()).build()); ControllerMetricsManager.dLedgerOpLatency.record(stopwatch.elapsed(TimeUnit.MICROSECONDS), @@ -401,6 +411,12 @@ public void run() { public CompletableFuture appendEvent(final String name, final Supplier> supplier, boolean isWriteEvent) { + return appendEvent(name, supplier, isWriteEvent, null); + } + + public CompletableFuture appendEvent(final String name, + final Supplier> supplier, boolean isWriteEvent, + final Supplier> responseSupplier) { if (isStopped() || !DLedgerController.this.roleHandler.isLeaderState()) { final RemotingCommand command = RemotingCommand.createResponseCommand(ResponseCode.CONTROLLER_NOT_LEADER, "The controller is not in leader state"); final CompletableFuture future = new CompletableFuture<>(); @@ -408,7 +424,7 @@ public CompletableFuture appendEvent(final String name, return future; } - final EventHandler event = new ControllerEventHandler<>(name, supplier, isWriteEvent); + final EventHandler event = new ControllerEventHandler<>(name, supplier, isWriteEvent, responseSupplier); int tryTimes = 0; while (true) { try { @@ -433,13 +449,15 @@ public CompletableFuture appendEvent(final String name, class ControllerEventHandler implements EventHandler { private final String name; private final Supplier> supplier; + private final Supplier> responseSupplier; private final CompletableFuture future; private final boolean isWriteEvent; ControllerEventHandler(final String name, final Supplier> supplier, - final boolean isWriteEvent) { + final boolean isWriteEvent, final Supplier> responseSupplier) { this.name = name; this.supplier = supplier; + this.responseSupplier = responseSupplier; this.future = new CompletableFuture<>(); this.isWriteEvent = isWriteEvent; } @@ -481,12 +499,21 @@ public void run() throws Throwable { } if (appendSuccess) { - final RemotingCommand response = RemotingCommand.createResponseCommandWithHeader(result.getResponseCode(), (CommandCustomHeader) result.getResponse()); - if (result.getBody() != null) { - response.setBody(result.getBody()); + ControllerResult responseResult = result; + if (this.responseSupplier != null) { + // A timed-out append can still be applied before this append. Revalidate the + // startup identity and return its committed epoch instead of the predicted epoch. + responseResult = this.responseSupplier.get(); + if (!responseResult.getEvents().isEmpty()) { + throw new IllegalStateException("Broker startup registration has not been applied"); + } + } + final RemotingCommand response = RemotingCommand.createResponseCommandWithHeader(responseResult.getResponseCode(), (CommandCustomHeader) responseResult.getResponse()); + if (responseResult.getBody() != null) { + response.setBody(responseResult.getBody()); } - if (result.getRemark() != null) { - response.setRemark(result.getRemark()); + if (responseResult.getRemark() != null) { + response.setRemark(responseResult.getRemark()); } this.future.complete(response); } else { diff --git a/controller/src/main/java/org/apache/rocketmq/controller/impl/event/EventSerializer.java b/controller/src/main/java/org/apache/rocketmq/controller/impl/event/EventSerializer.java index b5358c7c3ed..d2da5bbae34 100644 --- a/controller/src/main/java/org/apache/rocketmq/controller/impl/event/EventSerializer.java +++ b/controller/src/main/java/org/apache/rocketmq/controller/impl/event/EventSerializer.java @@ -71,6 +71,8 @@ public EventMessage deserialize(byte[] bytes) throws SerializationException { return this.serializer.deserialize(data, CleanBrokerDataEvent.class); case UPDATE_BROKER_ADDRESS: return this.serializer.deserialize(data, UpdateBrokerAddressEvent.class); + case REGISTER_BROKER_STARTUP_EVENT: + return this.serializer.deserialize(data, RegisterBrokerStartupEvent.class); default: break; } diff --git a/controller/src/main/java/org/apache/rocketmq/controller/impl/event/EventType.java b/controller/src/main/java/org/apache/rocketmq/controller/impl/event/EventType.java index 2b4cefb1d73..0fac2c69467 100644 --- a/controller/src/main/java/org/apache/rocketmq/controller/impl/event/EventType.java +++ b/controller/src/main/java/org/apache/rocketmq/controller/impl/event/EventType.java @@ -26,7 +26,8 @@ public enum EventType { READ_EVENT("ReadEvent", (short) 4), CLEAN_BROKER_DATA_EVENT("CleanBrokerDataEvent", (short) 5), - UPDATE_BROKER_ADDRESS("UpdateBrokerAddressEvent", (short) 6); + UPDATE_BROKER_ADDRESS("UpdateBrokerAddressEvent", (short) 6), + REGISTER_BROKER_STARTUP_EVENT("RegisterBrokerStartupEvent", (short) 7); private final String name; private final short id; @@ -50,6 +51,8 @@ public static EventType from(short id) { return CLEAN_BROKER_DATA_EVENT; case 6: return UPDATE_BROKER_ADDRESS; + case 7: + return REGISTER_BROKER_STARTUP_EVENT; } return null; } diff --git a/controller/src/main/java/org/apache/rocketmq/controller/impl/event/ListEventSerializer.java b/controller/src/main/java/org/apache/rocketmq/controller/impl/event/ListEventSerializer.java index ead4895195e..a48939b1e68 100644 --- a/controller/src/main/java/org/apache/rocketmq/controller/impl/event/ListEventSerializer.java +++ b/controller/src/main/java/org/apache/rocketmq/controller/impl/event/ListEventSerializer.java @@ -111,6 +111,9 @@ public static List deserialize(byte[] bytes, Logger log) throws Se case UPDATE_BROKER_ADDRESS: eventMessages.add(SERIALIZER.deserialize(data, UpdateBrokerAddressEvent.class)); break; + case REGISTER_BROKER_STARTUP_EVENT: + eventMessages.add(SERIALIZER.deserialize(data, RegisterBrokerStartupEvent.class)); + break; default: log.error("deserialize event message error, event id: {}, data: {}", eventId, data); break; diff --git a/controller/src/main/java/org/apache/rocketmq/controller/impl/event/RegisterBrokerStartupEvent.java b/controller/src/main/java/org/apache/rocketmq/controller/impl/event/RegisterBrokerStartupEvent.java new file mode 100644 index 00000000000..e99fac7c9ae --- /dev/null +++ b/controller/src/main/java/org/apache/rocketmq/controller/impl/event/RegisterBrokerStartupEvent.java @@ -0,0 +1,59 @@ +/* + * 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.controller.impl.event; + +public class RegisterBrokerStartupEvent implements EventMessage { + private final String brokerName; + private final Long brokerId; + private final String brokerAddress; + private final long brokerStartupGeneration; + private final String brokerStartupId; + + public RegisterBrokerStartupEvent(String brokerName, Long brokerId, String brokerAddress, + long brokerStartupGeneration, String brokerStartupId) { + this.brokerName = brokerName; + this.brokerId = brokerId; + this.brokerAddress = brokerAddress; + this.brokerStartupGeneration = brokerStartupGeneration; + this.brokerStartupId = brokerStartupId; + } + + @Override + public EventType getEventType() { + return EventType.REGISTER_BROKER_STARTUP_EVENT; + } + + public String getBrokerName() { + return brokerName; + } + + public Long getBrokerId() { + return brokerId; + } + + public String getBrokerAddress() { + return brokerAddress; + } + + public long getBrokerStartupGeneration() { + return brokerStartupGeneration; + } + + public String getBrokerStartupId() { + return brokerStartupId; + } +} diff --git a/controller/src/main/java/org/apache/rocketmq/controller/impl/manager/BrokerReplicaInfo.java b/controller/src/main/java/org/apache/rocketmq/controller/impl/manager/BrokerReplicaInfo.java index 1623a05908d..9e8841c1b3a 100644 --- a/controller/src/main/java/org/apache/rocketmq/controller/impl/manager/BrokerReplicaInfo.java +++ b/controller/src/main/java/org/apache/rocketmq/controller/impl/manager/BrokerReplicaInfo.java @@ -40,15 +40,21 @@ public class BrokerReplicaInfo implements Serializable { private final Map> brokerIdInfo; + private Map> brokerStartupInfo; + public BrokerReplicaInfo(String clusterName, String brokerName) { this.clusterName = clusterName; this.brokerName = brokerName; this.nextAssignBrokerId = new AtomicLong(MixAll.FIRST_BROKER_CONTROLLER_ID); this.brokerIdInfo = new ConcurrentHashMap<>(); + this.brokerStartupInfo = new ConcurrentHashMap<>(); } public void removeBrokerId(final Long brokerId) { this.brokerIdInfo.remove(brokerId); + if (this.brokerStartupInfo != null) { + this.brokerStartupInfo.remove(brokerId); + } } public Long getNextAssignBrokerId() { @@ -114,4 +120,22 @@ public void updateBrokerAddress(final Long brokerId, final String brokerAddress) this.brokerIdInfo.put(brokerId, new Pair<>(brokerAddress, oldPair.getObject2())); } } + + public long getBrokerStartupGeneration(final Long brokerId) { + final Pair startup = this.brokerStartupInfo == null ? null : this.brokerStartupInfo.get(brokerId); + return startup == null ? 0 : startup.getObject1(); + } + + public String getBrokerStartupId(final Long brokerId) { + final Pair startup = this.brokerStartupInfo == null ? null : this.brokerStartupInfo.get(brokerId); + return startup == null ? null : startup.getObject2(); + } + + public void updateBrokerStartup(final Long brokerId, final long generation, final String startupId) { + // Older controller snapshots do not contain startup identities. + if (this.brokerStartupInfo == null) { + this.brokerStartupInfo = new ConcurrentHashMap<>(); + } + this.brokerStartupInfo.put(brokerId, new Pair<>(generation, startupId)); + } } diff --git a/controller/src/main/java/org/apache/rocketmq/controller/impl/manager/ReplicasInfoManager.java b/controller/src/main/java/org/apache/rocketmq/controller/impl/manager/ReplicasInfoManager.java index 086058d63a4..509f942f1e1 100644 --- a/controller/src/main/java/org/apache/rocketmq/controller/impl/manager/ReplicasInfoManager.java +++ b/controller/src/main/java/org/apache/rocketmq/controller/impl/manager/ReplicasInfoManager.java @@ -34,6 +34,7 @@ import org.apache.rocketmq.controller.impl.event.ElectMasterEvent; import org.apache.rocketmq.controller.impl.event.EventMessage; import org.apache.rocketmq.controller.impl.event.EventType; +import org.apache.rocketmq.controller.impl.event.RegisterBrokerStartupEvent; import org.apache.rocketmq.controller.impl.event.UpdateBrokerAddressEvent; import org.apache.rocketmq.logging.org.slf4j.Logger; import org.apache.rocketmq.logging.org.slf4j.LoggerFactory; @@ -349,16 +350,49 @@ public ControllerResult registerBroker result.setCodeAndRemark(ResponseCode.CONTROLLER_BROKER_NEED_TO_BE_REGISTERED, String.format("BrokerId: %d hasn't been registered in broker-set: %s", brokerId, brokerName)); return result; } + + final Long startupGeneration = request.getBrokerStartupGeneration(); + final String startupId = request.getBrokerStartupId(); + final long registeredGeneration = brokerReplicaInfo.getBrokerStartupGeneration(brokerId); + final boolean hasStartupIdentity = startupGeneration != null || startupId != null; + boolean newStartup = false; + if (hasStartupIdentity) { + if (startupGeneration == null || startupGeneration <= 0 || StringUtils.isBlank(startupId)) { + result.setCodeAndRemark(ResponseCode.CONTROLLER_INVALID_REQUEST, "Both a positive broker startup generation and a startup id are required"); + return result; + } + if (startupGeneration < registeredGeneration || startupGeneration == registeredGeneration + && !startupId.equals(brokerReplicaInfo.getBrokerStartupId(brokerId))) { + result.setCodeAndRemark(ResponseCode.CONTROLLER_INVALID_REQUEST, "Broker startup identity is stale or conflicts with an accepted startup"); + return result; + } + newStartup = startupGeneration > registeredGeneration; + if (newStartup) { + if (brokerId.equals(syncStateInfo.getMasterBrokerId()) && syncStateInfo.getMasterEpoch() == Integer.MAX_VALUE) { + result.setCodeAndRemark(ResponseCode.CONTROLLER_INVALID_REQUEST, "Master epoch cannot be advanced for the new broker startup"); + return result; + } + result.addEvent(new RegisterBrokerStartupEvent(brokerName, brokerId, brokerAddress, startupGeneration, startupId)); + } + response.setBrokerStartupGeneration(startupGeneration); + response.setBrokerStartupId(startupId); + } else if (registeredGeneration > 0) { + result.setCodeAndRemark(ResponseCode.CONTROLLER_INVALID_REQUEST, "A broker startup identity is required for this broker"); + return result; + } + + final boolean registeringMaster = brokerId.equals(syncStateInfo.getMasterBrokerId()); + response.setMasterEpoch(syncStateInfo.getMasterEpoch() + (newStartup && registeringMaster ? 1 : 0)); + response.setSyncStateSetEpoch(syncStateInfo.getSyncStateSetEpoch()); if (syncStateInfo.isMasterExist() && alivePredicate.check(clusterName, brokerName, syncStateInfo.getMasterBrokerId())) { // if master still exist response.setMasterBrokerId(syncStateInfo.getMasterBrokerId()); - response.setMasterAddress(brokerReplicaInfo.getBrokerAddress(response.getMasterBrokerId())); - response.setMasterEpoch(syncStateInfo.getMasterEpoch()); - response.setSyncStateSetEpoch(syncStateInfo.getSyncStateSetEpoch()); + response.setMasterAddress(hasStartupIdentity && registeringMaster + ? brokerAddress : brokerReplicaInfo.getBrokerAddress(response.getMasterBrokerId())); } result.setBody(new SyncStateSet(syncStateInfo.getSyncStateSet(), syncStateInfo.getSyncStateSetEpoch()).encode()); // if this broker's address has been changed, we need to update it - if (!brokerAddress.equals(brokerReplicaInfo.getBrokerAddress(brokerId))) { + if (!newStartup && !brokerAddress.equals(brokerReplicaInfo.getBrokerAddress(brokerId))) { final UpdateBrokerAddressEvent event = new UpdateBrokerAddressEvent(clusterName, brokerName, brokerAddress, brokerId); result.addEvent(event); } @@ -506,6 +540,9 @@ public void applyEvent(final EventMessage event) { case UPDATE_BROKER_ADDRESS: handleUpdateBrokerAddress((UpdateBrokerAddressEvent) event); break; + case REGISTER_BROKER_STARTUP_EVENT: + handleRegisterBrokerStartup((RegisterBrokerStartupEvent) event); + break; default: break; } @@ -547,6 +584,26 @@ private void handleUpdateBrokerAddress(final UpdateBrokerAddressEvent event) { brokerReplicaInfo.updateBrokerAddress(brokerId, brokerAddress); } + private void handleRegisterBrokerStartup(final RegisterBrokerStartupEvent event) { + final String brokerName = event.getBrokerName(); + final Long brokerId = event.getBrokerId(); + if (!isContainsBroker(brokerName)) { + return; + } + final BrokerReplicaInfo brokerReplicaInfo = this.replicaInfoTable.get(brokerName); + if (!brokerReplicaInfo.isBrokerExist(brokerId) + || event.getBrokerStartupGeneration() <= brokerReplicaInfo.getBrokerStartupGeneration(brokerId)) { + return; + } + brokerReplicaInfo.updateBrokerStartup(brokerId, event.getBrokerStartupGeneration(), event.getBrokerStartupId()); + brokerReplicaInfo.updateBrokerAddress(brokerId, event.getBrokerAddress()); + final SyncStateInfo syncStateInfo = this.syncStateSetInfoTable.get(brokerName); + if (brokerId.equals(syncStateInfo.getMasterBrokerId())) { + // A recovered master needs a new log epoch, without reducing its existing sync state set. + syncStateInfo.updateMasterInfo(brokerId); + } + } + private void handleElectMaster(final ElectMasterEvent event) { final String brokerName = event.getBrokerName(); final Long newMaster = event.getNewMasterBrokerId(); diff --git a/controller/src/test/java/org/apache/rocketmq/controller/impl/DLedgerControllerAppendTest.java b/controller/src/test/java/org/apache/rocketmq/controller/impl/DLedgerControllerAppendTest.java new file mode 100644 index 00000000000..a5bd502d25d --- /dev/null +++ b/controller/src/test/java/org/apache/rocketmq/controller/impl/DLedgerControllerAppendTest.java @@ -0,0 +1,134 @@ +/* + * 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.controller.impl; + +import io.openmessaging.storage.dledger.AppendFuture; +import io.openmessaging.storage.dledger.DLedgerConfig; +import io.openmessaging.storage.dledger.DLedgerServer; +import io.openmessaging.storage.dledger.protocol.AppendEntryRequest; +import io.openmessaging.storage.dledger.protocol.AppendEntryResponse; +import io.openmessaging.storage.dledger.protocol.DLedgerResponseCode; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import org.apache.rocketmq.common.ControllerConfig; +import org.apache.rocketmq.controller.impl.event.ControllerResult; +import org.apache.rocketmq.controller.impl.event.EventSerializer; +import org.apache.rocketmq.controller.impl.event.RegisterBrokerStartupEvent; +import org.apache.rocketmq.remoting.protocol.RemotingCommand; +import org.apache.rocketmq.remoting.protocol.ResponseCode; +import org.apache.rocketmq.remoting.protocol.header.controller.register.RegisterBrokerToControllerResponseHeader; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DLedgerControllerAppendTest { + private DLedgerController controller; + private DLedgerServer server; + + @Before + public void setUp() throws Exception { + // Exercise the real append/response code without starting network or storage services. + controller = mock(DLedgerController.class, CALLS_REAL_METHODS); + server = mock(DLedgerServer.class); + setField("dLedgerServer", server); + DLedgerConfig ledgerConfig = new DLedgerConfig(); + ledgerConfig.setGroup("startup"); + ledgerConfig.setSelfId("n0"); + setField("dLedgerConfig", ledgerConfig); + setField("controllerConfig", new ControllerConfig()); + setField("eventSerializer", new EventSerializer()); + } + + @Test + public void completedErrorResponseIsNotACommittedGrant() throws Exception { + assertFalse(append(DLedgerResponseCode.WAIT_QUORUM_ACK_TIMEOUT)); + assertFalse(append(DLedgerResponseCode.TERM_CHANGED)); + assertTrue(append(DLedgerResponseCode.SUCCESS)); + } + + @Test + public void registrationReturnsCommittedEpochInsteadOfPredictedEpoch() throws Throwable { + ControllerResult predicted = result(2); + predicted.addEvent(new RegisterBrokerStartupEvent("broker", 1L, "127.0.0.1:10911", 3, "third")); + ControllerResult committed = result(3); + completeAppend(DLedgerResponseCode.SUCCESS); + DLedgerController.ControllerEventHandler handler = + controller.new ControllerEventHandler<>("register", () -> predicted, true, () -> committed); + handler.run(); + RemotingCommand response = handler.future().get(); + assertEquals(ResponseCode.SUCCESS, response.getCode()); + RegisterBrokerToControllerResponseHeader header = + (RegisterBrokerToControllerResponseHeader) response.readCustomHeader(); + assertEquals(Integer.valueOf(3), header.getMasterEpoch()); + } + + @Test + public void registrationRevalidatesIdentityAfterCommit() throws Throwable { + ControllerResult predicted = result(2); + predicted.addEvent(new RegisterBrokerStartupEvent("broker", 1L, "127.0.0.1:10911", 2, "second")); + ControllerResult superseded = result(3); + superseded.setCodeAndRemark(ResponseCode.CONTROLLER_INVALID_REQUEST, "Startup was superseded"); + completeAppend(DLedgerResponseCode.SUCCESS); + DLedgerController.ControllerEventHandler handler = + controller.new ControllerEventHandler<>("register", () -> predicted, true, () -> superseded); + handler.run(); + assertEquals(ResponseCode.CONTROLLER_INVALID_REQUEST, handler.future().get().getCode()); + } + + @Test(expected = IllegalStateException.class) + public void unappliedStartupCannotProduceSuccess() throws Throwable { + ControllerResult unapplied = result(2); + unapplied.addEvent(new RegisterBrokerStartupEvent("broker", 1L, "127.0.0.1:10911", 2, "second")); + completeAppend(DLedgerResponseCode.SUCCESS); + controller.new ControllerEventHandler<>("register", () -> unapplied, true, () -> unapplied).run(); + } + + private ControllerResult result(int epoch) { + RegisterBrokerToControllerResponseHeader header = new RegisterBrokerToControllerResponseHeader(); + header.setMasterEpoch(epoch); + return new ControllerResult<>(header); + } + + private boolean append(DLedgerResponseCode code) throws Exception { + completeAppend(code); + Method method = DLedgerController.class.getDeclaredMethod("appendToDLedgerAndWait", AppendEntryRequest.class); + method.setAccessible(true); + return (boolean) method.invoke(controller, new AppendEntryRequest()); + } + + private void completeAppend(DLedgerResponseCode code) throws Exception { + AppendEntryResponse response = new AppendEntryResponse(); + response.setCode(code.getCode()); + AppendFuture future = new AppendFuture<>(); + future.setPos(1); + future.complete(response); + when(server.handleAppend(any(AppendEntryRequest.class))).thenReturn(future); + } + + private void setField(String name, Object value) throws Exception { + Field field = DLedgerController.class.getDeclaredField(name); + field.setAccessible(true); + field.set(controller, value); + } +} diff --git a/controller/src/test/java/org/apache/rocketmq/controller/impl/DLedgerControllerTest.java b/controller/src/test/java/org/apache/rocketmq/controller/impl/DLedgerControllerTest.java index 32e7859a58a..ab64d0c5262 100644 --- a/controller/src/test/java/org/apache/rocketmq/controller/impl/DLedgerControllerTest.java +++ b/controller/src/test/java/org/apache/rocketmq/controller/impl/DLedgerControllerTest.java @@ -33,11 +33,13 @@ import org.apache.rocketmq.remoting.protocol.header.controller.register.GetNextBrokerIdRequestHeader; import org.apache.rocketmq.remoting.protocol.header.controller.register.GetNextBrokerIdResponseHeader; import org.apache.rocketmq.remoting.protocol.header.controller.register.RegisterBrokerToControllerRequestHeader; +import org.apache.rocketmq.remoting.protocol.header.controller.register.RegisterBrokerToControllerResponseHeader; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.File; +import java.net.ServerSocket; import java.time.Duration; import java.util.ArrayList; import java.util.HashSet; @@ -225,6 +227,90 @@ public void setBrokerElectPolicy(DLedgerController controller, Long... deathBrok }, null)); } + @Test + public void testBrokerStartupRegistrationPersistsNewEpoch() throws Exception { + final String group = UUID.randomUUID().toString(); + final String peers; + try (ServerSocket socket = new ServerSocket(0)) { + peers = "n0-127.0.0.1:" + socket.getLocalPort(); + } + controllers.add(launchController(group, peers, "n0", false)); + DLedgerController leader = waitLeader(controllers); + registerNewBroker(leader, DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, DEFAULT_IP[0], 1L); + + final RegisterBrokerToControllerRequestHeader firstStartup = new RegisterBrokerToControllerRequestHeader( + DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, 1L, DEFAULT_IP[0]); + firstStartup.setBrokerStartupGeneration(1L); + firstStartup.setBrokerStartupId(UUID.randomUUID().toString()); + RemotingCommand response = leader.registerBroker(firstStartup).get(10, TimeUnit.SECONDS); + assertEquals(ResponseCode.SUCCESS, response.getCode()); + RegisterBrokerToControllerResponseHeader registration = + (RegisterBrokerToControllerResponseHeader) response.readCustomHeader(); + assertEquals(firstStartup.getBrokerStartupGeneration(), registration.getBrokerStartupGeneration()); + assertEquals(firstStartup.getBrokerStartupId(), registration.getBrokerStartupId()); + brokerTryElectMaster(leader, DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, DEFAULT_IP[0], 1L, true); + + response = leader.getReplicaInfo(new GetReplicaInfoRequestHeader(DEFAULT_BROKER_NAME)).get(10, TimeUnit.SECONDS); + assertEquals(ResponseCode.SUCCESS, response.getCode()); + GetReplicaInfoResponseHeader replicaInfo = (GetReplicaInfoResponseHeader) response.readCustomHeader(); + assertEquals(1, replicaInfo.getMasterEpoch().intValue()); + + final RegisterBrokerToControllerRequestHeader secondStartup = new RegisterBrokerToControllerRequestHeader( + DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, 1L, DEFAULT_IP[0]); + secondStartup.setBrokerStartupGeneration(2L); + secondStartup.setBrokerStartupId(UUID.randomUUID().toString()); + for (int attempt = 0; attempt < 2; attempt++) { + response = leader.registerBroker(secondStartup).get(10, TimeUnit.SECONDS); + assertEquals(ResponseCode.SUCCESS, response.getCode()); + registration = (RegisterBrokerToControllerResponseHeader) response.readCustomHeader(); + assertEquals(1L, registration.getMasterBrokerId().longValue()); + assertEquals(2, registration.getMasterEpoch().intValue()); + assertEquals(secondStartup.getBrokerStartupGeneration(), registration.getBrokerStartupGeneration()); + assertEquals(secondStartup.getBrokerStartupId(), registration.getBrokerStartupId()); + } + + // Restart normally and replay the committed DLedger log from the same store directory. + final String storePath = leader.getControllerConfig().getControllerStorePath(); + leader.shutdown(); + controllers.remove(leader); + controllers.add(launchController(group, peers, "n0", false)); + leader = waitLeader(controllers); + assertEquals(storePath, leader.getControllerConfig().getControllerStorePath()); + + response = leader.getReplicaInfo(new GetReplicaInfoRequestHeader(DEFAULT_BROKER_NAME)).get(10, TimeUnit.SECONDS); + assertEquals(ResponseCode.SUCCESS, response.getCode()); + replicaInfo = (GetReplicaInfoResponseHeader) response.readCustomHeader(); + assertEquals(1L, replicaInfo.getMasterBrokerId().longValue()); + assertEquals(2, replicaInfo.getMasterEpoch().intValue()); + + response = leader.registerBroker(secondStartup).get(10, TimeUnit.SECONDS); + assertEquals(ResponseCode.SUCCESS, response.getCode()); + registration = (RegisterBrokerToControllerResponseHeader) response.readCustomHeader(); + assertEquals(2, registration.getMasterEpoch().intValue()); + assertEquals(secondStartup.getBrokerStartupGeneration(), registration.getBrokerStartupGeneration()); + assertEquals(secondStartup.getBrokerStartupId(), registration.getBrokerStartupId()); + + response = leader.registerBroker(firstStartup).get(10, TimeUnit.SECONDS); + assertEquals(ResponseCode.CONTROLLER_INVALID_REQUEST, response.getCode()); + + final RegisterBrokerToControllerRequestHeader thirdStartup = new RegisterBrokerToControllerRequestHeader( + DEFAULT_CLUSTER_NAME, DEFAULT_BROKER_NAME, 1L, DEFAULT_IP[0]); + thirdStartup.setBrokerStartupGeneration(3L); + thirdStartup.setBrokerStartupId(UUID.randomUUID().toString()); + response = leader.registerBroker(thirdStartup).get(10, TimeUnit.SECONDS); + assertEquals(ResponseCode.SUCCESS, response.getCode()); + registration = (RegisterBrokerToControllerResponseHeader) response.readCustomHeader(); + assertEquals(3, registration.getMasterEpoch().intValue()); + assertEquals(thirdStartup.getBrokerStartupGeneration(), registration.getBrokerStartupGeneration()); + assertEquals(thirdStartup.getBrokerStartupId(), registration.getBrokerStartupId()); + + response = leader.getReplicaInfo(new GetReplicaInfoRequestHeader(DEFAULT_BROKER_NAME)).get(10, TimeUnit.SECONDS); + assertEquals(ResponseCode.SUCCESS, response.getCode()); + replicaInfo = (GetReplicaInfoResponseHeader) response.readCustomHeader(); + assertEquals(1L, replicaInfo.getMasterBrokerId().longValue()); + assertEquals(3, replicaInfo.getMasterEpoch().intValue()); + } + @Test public void testElectMaster() throws Exception { final DLedgerController leader = mockMetaData(false); diff --git a/controller/src/test/java/org/apache/rocketmq/controller/impl/manager/BrokerStartupRegistrationTest.java b/controller/src/test/java/org/apache/rocketmq/controller/impl/manager/BrokerStartupRegistrationTest.java new file mode 100644 index 00000000000..cbf9a322642 --- /dev/null +++ b/controller/src/test/java/org/apache/rocketmq/controller/impl/manager/BrokerStartupRegistrationTest.java @@ -0,0 +1,232 @@ +/* + * 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.controller.impl.manager; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import org.apache.rocketmq.common.ControllerConfig; +import org.apache.rocketmq.controller.elect.impl.DefaultElectPolicy; +import org.apache.rocketmq.controller.helper.BrokerValidPredicate; +import org.apache.rocketmq.controller.impl.event.ControllerResult; +import org.apache.rocketmq.controller.impl.event.EventMessage; +import org.apache.rocketmq.controller.impl.event.EventSerializer; +import org.apache.rocketmq.controller.impl.event.ListEventSerializer; +import org.apache.rocketmq.remoting.protocol.RemotingSerializable; +import org.apache.rocketmq.remoting.protocol.ResponseCode; +import org.apache.rocketmq.remoting.protocol.body.SyncStateSet; +import org.apache.rocketmq.remoting.protocol.header.controller.AlterSyncStateSetRequestHeader; +import org.apache.rocketmq.remoting.protocol.header.controller.ElectMasterRequestHeader; +import org.apache.rocketmq.remoting.protocol.header.controller.GetReplicaInfoRequestHeader; +import org.apache.rocketmq.remoting.protocol.header.controller.GetReplicaInfoResponseHeader; +import org.apache.rocketmq.remoting.protocol.header.controller.register.ApplyBrokerIdRequestHeader; +import org.apache.rocketmq.remoting.protocol.header.controller.register.RegisterBrokerToControllerRequestHeader; +import org.apache.rocketmq.remoting.protocol.header.controller.register.RegisterBrokerToControllerResponseHeader; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +@RunWith(Parameterized.class) +public class BrokerStartupRegistrationTest { + private static final String CLUSTER = "startup-cluster"; + private static final String BROKER = "startup-broker"; + private static final String MASTER_ADDRESS = "127.0.0.1:10911"; + private static final String SLAVE_ADDRESS = "127.0.0.1:20911"; + private static final BrokerValidPredicate ALL_ALIVE = (cluster, broker, id) -> true; + private static final BrokerValidPredicate NONE_ALIVE = (cluster, broker, id) -> false; + + private final boolean raft; + private final EventSerializer serializer = new EventSerializer(); + private ReplicasInfoManager manager; + + @Parameterized.Parameters(name = "raft={0}") + public static Collection controllerTypes() { + return Arrays.asList(new Object[][] {{false}, {true}}); + } + + public BrokerStartupRegistrationTest(boolean raft) { + this.raft = raft; + } + + @Before + public void setUp() { + manager = newManager(); + apply(manager.applyBrokerId(new ApplyBrokerIdRequestHeader(CLUSTER, BROKER, 1L, MASTER_ADDRESS + ";1"))); + apply(manager.applyBrokerId(new ApplyBrokerIdRequestHeader(CLUSTER, BROKER, 2L, SLAVE_ADDRESS + ";1"))); + apply(register(1L, MASTER_ADDRESS, 1L, "first-master", ALL_ALIVE)); + apply(register(2L, SLAVE_ADDRESS, 1L, "first-slave", ALL_ALIVE)); + apply(manager.electMaster(ElectMasterRequestHeader.ofBrokerTrigger(CLUSTER, BROKER, 1L), + new DefaultElectPolicy(ALL_ALIVE, null))); + apply(manager.alterSyncStateSet(new AlterSyncStateSetRequestHeader(BROKER, 1L, 1), + new SyncStateSet(new HashSet<>(Arrays.asList(1L, 2L)), 1), ALL_ALIVE)); + } + + @Test + public void testMasterRestartAdvancesEpochWithoutShrinkingSyncStateSet() { + SyncStateSet before = syncStateSet(); + ControllerResult result = + register(1L, MASTER_ADDRESS, 2L, "second-master", NONE_ALIVE); + + assertEquals(ResponseCode.SUCCESS, result.getResponseCode()); + assertEquals(Long.valueOf(2L), result.getResponse().getBrokerStartupGeneration()); + assertEquals("second-master", result.getResponse().getBrokerStartupId()); + assertNull(result.getResponse().getMasterBrokerId()); + assertEquals(Integer.valueOf(2), result.getResponse().getMasterEpoch()); + assertEquals(Integer.valueOf(1), replicaInfo().getMasterEpoch()); + assertEquals(1, result.getEvents().size()); + + apply(result); + + assertEquals(Integer.valueOf(2), replicaInfo().getMasterEpoch()); + assertEquals(before.getSyncStateSet(), syncStateSet().getSyncStateSet()); + assertEquals(before.getSyncStateSetEpoch(), syncStateSet().getSyncStateSetEpoch()); + // Replaying the same accepted startup cannot grant a second epoch. + apply(result); + assertEquals(Integer.valueOf(2), replicaInfo().getMasterEpoch()); + } + + @Test + public void testRegistrationRetryAndSnapshotRestoreKeepTheSameGrant() throws Throwable { + apply(register(1L, MASTER_ADDRESS, 2L, "second-master", ALL_ALIVE)); + ReplicasInfoManager restored = newManager(); + restored.deserializeFrom(manager.serialize()); + manager = restored; + + ControllerResult retry = + register(1L, MASTER_ADDRESS, 2L, "second-master", NONE_ALIVE); + assertEquals(ResponseCode.SUCCESS, retry.getResponseCode()); + assertTrue(retry.getEvents().isEmpty()); + assertEquals(Integer.valueOf(2), retry.getResponse().getMasterEpoch()); + assertEquals("second-master", retry.getResponse().getBrokerStartupId()); + + apply(register(1L, MASTER_ADDRESS, 3L, "third-master", ALL_ALIVE)); + assertEquals(Integer.valueOf(3), replicaInfo().getMasterEpoch()); + } + + @Test + public void testStaleConflictingAndLegacyRegistrationsCannotReplaceStartup() throws Throwable { + apply(register(1L, MASTER_ADDRESS, 2L, "second-master", ALL_ALIVE)); + ReplicasInfoManager restored = newManager(); + restored.deserializeFrom(manager.serialize()); + manager = restored; + + assertRejected(register(1L, "127.0.0.1:30911", 1L, "first-master", ALL_ALIVE)); + assertRejected(register(1L, "127.0.0.1:30911", 2L, "different-startup", ALL_ALIVE)); + assertRejected(register(1L, "127.0.0.1:30911", null, null, ALL_ALIVE)); + + assertEquals(Integer.valueOf(2), replicaInfo().getMasterEpoch()); + assertEquals(MASTER_ADDRESS, replicaInfo().getMasterAddress()); + assertEquals(ResponseCode.SUCCESS, register(1L, MASTER_ADDRESS, 2L, "second-master", ALL_ALIVE).getResponseCode()); + } + + @Test + public void testFollowerRestartDoesNotAdvanceTheMasterEpoch() { + ControllerResult result = + register(2L, SLAVE_ADDRESS, 2L, "second-slave", ALL_ALIVE); + apply(result); + + assertEquals(Long.valueOf(1L), result.getResponse().getMasterBrokerId()); + assertEquals(Integer.valueOf(1), result.getResponse().getMasterEpoch()); + assertEquals(Integer.valueOf(1), replicaInfo().getMasterEpoch()); + assertEquals(new HashSet<>(Arrays.asList(1L, 2L)), syncStateSet().getSyncStateSet()); + assertTrue(register(2L, SLAVE_ADDRESS, 2L, "second-slave", ALL_ALIVE).getEvents().isEmpty()); + } + + @Test + public void testRegistrationReportsEpochEvenWhenMasterIsInactive() { + ControllerResult result = + register(2L, SLAVE_ADDRESS, 2L, "second-slave", NONE_ALIVE); + apply(result); + + assertNull(result.getResponse().getMasterBrokerId()); + assertEquals(Integer.valueOf(1), result.getResponse().getMasterEpoch()); + assertEquals(Long.valueOf(2L), result.getResponse().getBrokerStartupGeneration()); + assertEquals("second-slave", result.getResponse().getBrokerStartupId()); + } + + @Test + public void testFirstStartupIdentityOnLegacyMasterCreatesNewEpoch() { + manager = newManager(); + apply(manager.applyBrokerId(new ApplyBrokerIdRequestHeader(CLUSTER, BROKER, 1L, MASTER_ADDRESS + ";1"))); + ControllerResult legacy = register(1L, MASTER_ADDRESS, null, null, ALL_ALIVE); + apply(legacy); + assertNull(legacy.getResponse().getBrokerStartupGeneration()); + assertNull(legacy.getResponse().getBrokerStartupId()); + apply(manager.electMaster(ElectMasterRequestHeader.ofBrokerTrigger(CLUSTER, BROKER, 1L), + new DefaultElectPolicy(ALL_ALIVE, null))); + + ControllerResult upgraded = + register(1L, MASTER_ADDRESS, 1L, "first-upgraded-startup", ALL_ALIVE); + apply(upgraded); + + assertEquals(Integer.valueOf(2), upgraded.getResponse().getMasterEpoch()); + assertEquals(Integer.valueOf(2), replicaInfo().getMasterEpoch()); + } + + @Test + public void testMalformedStartupIdentityCannotMutateState() { + assertRejected(register(1L, MASTER_ADDRESS, null, "missing-generation", ALL_ALIVE)); + assertRejected(register(1L, MASTER_ADDRESS, 2L, null, ALL_ALIVE)); + assertRejected(register(1L, MASTER_ADDRESS, 0L, "zero-generation", ALL_ALIVE)); + assertRejected(register(1L, MASTER_ADDRESS, 2L, " ", ALL_ALIVE)); + assertEquals(Integer.valueOf(1), replicaInfo().getMasterEpoch()); + } + + private ReplicasInfoManager newManager() { + ControllerConfig config = new ControllerConfig(); + return raft ? new RaftReplicasInfoManager(config) : new ReplicasInfoManager(config); + } + + private ControllerResult register(long brokerId, String address, + Long generation, String startupId, BrokerValidPredicate alive) { + RegisterBrokerToControllerRequestHeader request = + new RegisterBrokerToControllerRequestHeader(CLUSTER, BROKER, brokerId, address); + request.setBrokerStartupGeneration(generation); + request.setBrokerStartupId(startupId); + return manager.registerBroker(request, alive); + } + + private void apply(ControllerResult result) { + assertEquals(result.getRemark(), ResponseCode.SUCCESS, result.getResponseCode()); + for (EventMessage event : ListEventSerializer.deserialize(ListEventSerializer.serialize(result.getEvents(), null), null)) { + EventMessage decoded = serializer.deserialize(serializer.serialize(event)); + assertNotNull(decoded); + manager.applyEvent(decoded); + } + } + + private void assertRejected(ControllerResult result) { + assertEquals(ResponseCode.CONTROLLER_INVALID_REQUEST, result.getResponseCode()); + assertFalse(result.getRemark().isEmpty()); + assertTrue(result.getEvents().isEmpty()); + } + + private GetReplicaInfoResponseHeader replicaInfo() { + return manager.getReplicaInfo(new GetReplicaInfoRequestHeader(BROKER)).getResponse(); + } + + private SyncStateSet syncStateSet() { + return RemotingSerializable.decode(manager.getReplicaInfo(new GetReplicaInfoRequestHeader(BROKER)).getBody(), SyncStateSet.class); + } +} diff --git a/docs/en/controller/confirmed-data-recovery.md b/docs/en/controller/confirmed-data-recovery.md new file mode 100644 index 00000000000..e3f02f3116d --- /dev/null +++ b/docs/en/controller/confirmed-data-recovery.md @@ -0,0 +1,113 @@ +# Replacing a replica after a confirmed-offset conflict + +In controller mode, a replica refuses a handshake that would truncate its log below its local +`confirmOffset`. The refusal is saved beside `storePathEpochFile`, with the suffix +`.confirmed-offset-guard`. Reconnecting, restarting, changing the master address or receiving a +larger offset does not remove it. A damaged guard record stops initialization instead of enabling +replication. The refusal blocks the follower's HA handshake. It does not freeze the local store +or stop normal retention. Stop the refused replica and preserve its store before attempting +recovery. + +If saving a refusal fails, the running follower still refuses handshakes and retries saving the same +evidence. Resolve the storage failure before restarting it: evidence which never reached durable +storage cannot survive process loss. A nonempty CommitLog without epoch history also fails HA +initialization instead of becoming a source with an invented history. + +A matching physical offset does not establish matching message content. In particular, after a +master loses data and writes replacements under the same epoch, the first refused offset may be +later than the actual divergence. Do not delete the guard or reset the confirmation checkpoint to +force that replica to join. + +## Upgrade order and restart behavior + +Coordinate the upgrade across the controller group and its brokers. Upgrade every controller member, +including controllers embedded in NameServers, before starting an upgraded broker. Do not let an +older controller rejoin the group. A startup acknowledgment comes from the current leader and does +not establish that the other members support the new registration. Upgrade every broker in the +affected group before relying on the new startup-epoch behavior. + +Before upgrading, take consistent backups of the controller snapshots and logs and the corresponding +broker stores and identities. Once the first new startup registration commits, do not downgrade +either component in place over the newer state. A timed-out request may still commit; if the outcome +is unknown, treat it as committed for rollback decisions. Older controllers do not apply the same +startup metadata, and older brokers do not honor the new refusal guard or startup registration. +Rollback requires coordinated recovery from compatible controller and broker backups and +reconciliation of any writes since those backups. + +Each broker startup persists a monotonically increasing generation beside `storePathBrokerIdentity` +with the suffix `-startup`, and uses a fresh startup ID for registration. The controller persists the +accepted pair. A retry with the same pair is idempotent. An older generation, or a reused generation +with another startup ID, is refused. An upgraded broker stays fenced if the controller does not +acknowledge its startup identity. + +When the current master restarts, the controller grants a new master epoch without reducing the +SyncStateSet. The broker records that epoch at the recovered log end before enabling writes. +Thus replacement messages cannot extend the previous epoch. A follower restart does not advance +the group's master epoch. Duplicate grants in one startup retain the original epoch boundary. + +The broker replaces its startup, epoch, and refusal metadata files atomically on filesystems that +support atomic replacement. On Windows, RocketMQ does not sync the parent directory; do not assume +an atomic replacement will survive a power loss. + +Keep the broker identity and its startup metadata together. Restoring an old startup counter is not +a supported way to rejoin an existing broker identity; the controller may correctly refuse it. +Use a new replica identity for a replacement store. + +The new startup behavior does not prove that replicas which diverged before the upgrade contain +identical history. Validate or replace those replicas before returning the group to service. + +## Choose the authoritative history + +First stop the affected writer and preserve every potentially useful store. Record the broker group, +broker identities, master epoch, epoch files, confirmation checkpoints and refusal records. Compare +actual messages where the histories differ. Prefer a healthy replica retaining the acknowledged +messages. If that history can be selected as master, use it as the source for the replacement. + +If the operator deliberately accepts an unclean election, the selected master may not have all +messages acknowledged by the old master. That choice must be explicit. A fresh replica can restore +redundancy for the verified history on the selected master, but it cannot bring across messages that +master no longer has. Preserve the original store and refusal record until any missing confirmed +history is reconciled; a healthy replacement alone does not complete that work. + +The existing election policy is unchanged. The new epoch separates histories and allows replicas to +reject an unsafe rollback; it does not automatically choose the replica containing the most data. +If the available election is unsafe, a group can remain unavailable until the operator selects and +repairs the appropriate history. + +## Restore redundancy using a fresh replica + +Use a fresh replica when a common prefix has not been established. This procedure does not rejoin +the refused member, clear its guard, or infer a rollback point from its first refused handshake. + +1. Stop the refused replica. Retain its complete store, including CommitLog, ConsumeQueue, epoch and + checkpoint files and the refusal record. Do not reuse any of those log or queue files in the new + directory. If paths were configured outside `storePathRootDir`, preserve them as well. +2. Select the authoritative master and check that it retains all data required for recovery. Record + its identity and epoch. Keep that source stable during recovery; pause the operation and reassess + the choice if its history changes. Do not enable unclean elections merely to advance the rebuild. +3. Configure a new, empty store directory and a new broker identity in the same broker group. Set + `syncFromLastFile=false`. Ensure custom CommitLog, ConsumeQueue, epoch and identity paths do not + point back to the preserved store. Follow the existing controller deployment instructions for + registering the new replica; do not copy the old `brokerIdentity` or `-startup` files into it. +4. Start the replacement as a follower of the selected group. It copies the master's retained + CommitLog; it does not reconstruct expired or missing history. Keep the old replica stopped, so its + address and broker identity cannot be reused concurrently. +5. Read and compare actual messages and queue order over the required range, and confirm that new + messages also replicate. Check the epoch history, `maxOffset`, `confirmOffset`, checkpoint and + ConsumeQueue progress separately. A matching maximum offset in runtime stats does not establish + the confirmed offset or the message contents. Recheck after a normal restart of the new replica + before considering the replacement complete. +6. Retire the old stopped identity using the existing controller administration procedure only after + the replacement is healthy. Retiring the identity does not remove the need to retain and reconcile + the preserved data and refusal record. + +The fresh directory is the explicit choice to adopt the selected history. There is no reusable +authorization flag that can silently permit a later loss of confirmed data. Interrupting the copy +leaves the preserved old store unchanged; continue the replacement only while the selected history +remains valid. If the selected source has already expired required log files, restore an appropriate +backup or obtain another retained source before proceeding. + +A healthy holder of protected data can still be promoted. A refusal of another history is not +evidence that this holder's own data is corrupt. When pre-upgrade same-epoch divergence is known, +keep unverified old sources and their descendants isolated until they have been rebuilt; the new +startup epoch mechanism cannot retroactively certify their contents. diff --git a/docs/en/controller/deploy.md b/docs/en/controller/deploy.md index 84849510ef3..a6458db9852 100644 --- a/docs/en/controller/deploy.md +++ b/docs/en/controller/deploy.md @@ -97,6 +97,11 @@ The specific behavior is shown in the following table: ## Upgrade Considerations +If your Controller-mode group already uses persistent BrokerIDs and you are upgrading to a version +with confirmed-offset protection, follow the +[Controller-first upgrade and rollback guide](confirmed-data-recovery.md#upgrade-order-and-restart-behavior). +The older BrokerID migration below does not apply: keep the Controller data and broker epoch files. + From the compatibility statements above, it can be seen that NameServer can be upgraded normally without compatibility issues. In the case where the Nameserver is not to be upgraded, the controller component can be deployed independently to obtain switching capabilities. For broker upgrades, there are two cases: 1. Master-Slave deployment is upgraded to controller switching architecture diff --git a/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/controller/register/RegisterBrokerToControllerRequestHeader.java b/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/controller/register/RegisterBrokerToControllerRequestHeader.java index 38247c3a78e..ab444ef79e3 100644 --- a/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/controller/register/RegisterBrokerToControllerRequestHeader.java +++ b/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/controller/register/RegisterBrokerToControllerRequestHeader.java @@ -37,6 +37,10 @@ public class RegisterBrokerToControllerRequestHeader implements CommandCustomHea private String brokerAddress; + private Long brokerStartupGeneration; + + private String brokerStartupId; + private long invokeTime; public RegisterBrokerToControllerRequestHeader() { @@ -94,4 +98,20 @@ public void setBrokerId(Long brokerId) { public void setBrokerAddress(String brokerAddress) { this.brokerAddress = brokerAddress; } + + public Long getBrokerStartupGeneration() { + return brokerStartupGeneration; + } + + public void setBrokerStartupGeneration(Long brokerStartupGeneration) { + this.brokerStartupGeneration = brokerStartupGeneration; + } + + public String getBrokerStartupId() { + return brokerStartupId; + } + + public void setBrokerStartupId(String brokerStartupId) { + this.brokerStartupId = brokerStartupId; + } } diff --git a/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/controller/register/RegisterBrokerToControllerResponseHeader.java b/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/controller/register/RegisterBrokerToControllerResponseHeader.java index 66bf0e44151..d8b3f6efc93 100644 --- a/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/controller/register/RegisterBrokerToControllerResponseHeader.java +++ b/remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/controller/register/RegisterBrokerToControllerResponseHeader.java @@ -34,6 +34,10 @@ public class RegisterBrokerToControllerResponseHeader implements CommandCustomHe private Integer syncStateSetEpoch; + private Long brokerStartupGeneration; + + private String brokerStartupId; + @Override public void checkFields() throws RemotingCommandException { @@ -94,4 +98,20 @@ public void setClusterName(String clusterName) { public void setBrokerName(String brokerName) { this.brokerName = brokerName; } + + public Long getBrokerStartupGeneration() { + return brokerStartupGeneration; + } + + public void setBrokerStartupGeneration(Long brokerStartupGeneration) { + this.brokerStartupGeneration = brokerStartupGeneration; + } + + public String getBrokerStartupId() { + return brokerStartupId; + } + + public void setBrokerStartupId(String brokerStartupId) { + this.brokerStartupId = brokerStartupId; + } } diff --git a/store/BUILD.bazel b/store/BUILD.bazel index 66af7d6b45c..cfef487b20b 100644 --- a/store/BUILD.bazel +++ b/store/BUILD.bazel @@ -78,6 +78,7 @@ GenTestRules( "src/test/java/org/apache/rocketmq/store/dledger/DLedgerMultiPathTest", ], medium_tests = [ + "src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAHistoryRecoveryTest", "src/test/java/org/apache/rocketmq/store/DefaultMessageStoreTest", "src/test/java/org/apache/rocketmq/store/HATest", "src/test/java/org/apache/rocketmq/store/dledger/DLedgerCommitlogTest", 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..bc2583157eb 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 @@ -40,6 +40,7 @@ import org.apache.rocketmq.store.ha.HAConnectionState; import org.apache.rocketmq.store.ha.io.AbstractHAReader; import org.apache.rocketmq.store.ha.io.HAWriter; +import org.rocksdb.RocksDBException; public class AutoSwitchHAClient extends ServiceThread implements HAClient { @@ -136,6 +137,7 @@ public class AutoSwitchHAClient extends ServiceThread implements HAClient { * Current epoch */ private volatile int currentReceivedEpoch; + private int handshakeMasterEpoch = -1; public AutoSwitchHAClient(AutoSwitchHAService haService, DefaultMessageStore defaultMessageStore, EpochFileCache epochCache, Long brokerId) throws IOException { @@ -388,10 +390,19 @@ public void run() { this.flowMonitor.shutdown(true); return; case READY: + final ConfirmedOffsetGuard guard = this.haService.getConfirmedOffsetGuard(); + if (guard.isBlocked()) { + // Retry the local record without changing the refused follower's history. + guard.ensurePersisted(); + waitForRunning(1000 * 5); + continue; + } // Truncate invalid msg first final long truncateOffset = AutoSwitchHAClient.this.haService.truncateInvalidMsg(); - if (truncateOffset >= 0) { - AutoSwitchHAClient.this.epochCache.truncateSuffixByOffset(truncateOffset); + if (truncateOffset >= 0 && !AutoSwitchHAClient.this.epochCache.truncateSuffixByOffset(truncateOffset)) { + LOGGER.error("Failed to persist recovered epoch history, postpone HA connection"); + waitForRunning(1000 * 5); + continue; } if (!connectMaster()) { LOGGER.warn("AutoSwitchHAClient connect to master {} failed", this.masterHaAddress.get()); @@ -433,7 +444,26 @@ public void run() { * Compare the master and slave's epoch file, find consistent point, do truncate. */ private boolean doTruncate(List masterEpochEntries, long masterEndOffset) throws Exception { + if (this.haService.getConfirmedOffsetGuard().isBlocked()) { + this.haService.getConfirmedOffsetGuard().ensurePersisted(); + LOGGER.error("Refusing HA handshake after a confirmed-offset conflict: {}. Rebuild this replica from an explicitly selected history", + this.haService.getConfirmedOffsetGuard().describe()); + return false; + } + final long localMaxOffset = this.messageStore.getMaxPhyOffset(); + final EpochEntry lastLocalEpoch = this.epochCache.lastEntry(); + // An epoch can be durable before its first message. Remove such a tail using the + // recovered log end before computing a position that we can acknowledge. + if (lastLocalEpoch != null && lastLocalEpoch.getStartOffset() >= localMaxOffset + && !this.epochCache.truncateSuffixByOffset(localMaxOffset)) { + LOGGER.error("Failed to persist recovered replica epoch history at {}", localMaxOffset); + return false; + } if (this.epochCache.getEntrySize() == 0) { + if (this.messageStore.getMaxPhyOffset() != 0 || this.messageStore.getConfirmOffset() > 0) { + LOGGER.error("Refusing HA handshake: a nonempty replica has 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,7 +475,7 @@ 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(localMaxOffset); LOGGER.info("master epoch entries is {}", masterEpochCache.getAllEntries()); LOGGER.info("local epoch entries is {}", localEpochEntries); @@ -459,13 +489,20 @@ private boolean doTruncate(List masterEpochEntries, long masterEndOf LOGGER.error("Failed to find a consistent point between masterEpoch:{} and slaveEpoch:{}", masterEpochEntries, localEpochEntries); return false; } - if (!this.messageStore.truncateFiles(truncateOffset)) { - LOGGER.error("Failed to truncate slave log to {}", truncateOffset); + if (truncateOffset > localMaxOffset || truncateOffset > masterEndOffset) { + LOGGER.error("Refusing impossible consistent offset {}, local end {}, master end {}", + truncateOffset, localMaxOffset, masterEndOffset); return false; } final long maxPhyOffset = this.messageStore.getMaxPhyOffset(); + if (!truncateSlaveLog(truncateOffset)) { + return false; + } + if (!this.epochCache.truncateSuffixByOffset(truncateOffset)) { + LOGGER.error("Failed to persist slave epoch history after truncation to {}", truncateOffset); + return false; + } if (truncateOffset < maxPhyOffset) { - this.epochCache.truncateSuffixByOffset(truncateOffset); LOGGER.info("Truncate slave log to {} success, change to transfer state", truncateOffset); } changeCurrentState(HAConnectionState.TRANSFER); @@ -478,6 +515,25 @@ private boolean doTruncate(List masterEpochEntries, long masterEndOf return true; } + boolean truncateSlaveLog(long truncateOffset) throws RocksDBException, IOException { + final ConfirmedOffsetGuard guard = this.haService.getConfirmedOffsetGuard(); + if (guard.isBlocked()) { + guard.ensurePersisted(); + return false; + } + final long confirmOffset = this.messageStore.getConfirmOffset(); + if (truncateOffset < confirmOffset) { + guard.recordRefusal(getHaMasterAddress(), this.handshakeMasterEpoch, truncateOffset, confirmOffset); + LOGGER.error("Refusing to truncate confirmed data: brokerId={}, {}", this.brokerId, guard.describe()); + return false; + } + if (!this.messageStore.truncateFiles(truncateOffset)) { + LOGGER.error("Failed to truncate slave log to {}", truncateOffset); + return false; + } + return true; + } + class HAClientReader extends AbstractHAReader { @Override @@ -522,6 +578,12 @@ protected boolean processReadResult(ByteBuffer byteBufferRead) { isComplete = false; break; } + final long expectedMasterEpoch = AutoSwitchHAClient.this.messageStore.getStateMachineVersion(); + if (expectedMasterEpoch > 0 && masterEpoch != expectedMasterEpoch) { + LOGGER.error("Refusing handshake from epoch {}, expected controller epoch {}", masterEpoch, expectedMasterEpoch); + return false; + } + AutoSwitchHAClient.this.handshakeMasterEpoch = masterEpoch; AutoSwitchHAClient.this.processPosition += AutoSwitchHAConnection.HANDSHAKE_HEADER_SIZE; // Truncate log int entrySize = AutoSwitchHAConnection.EPOCH_ENTRY_SIZE; @@ -564,12 +626,22 @@ protected boolean processReadResult(ByteBuffer byteBufferRead) { // If epoch changed if (masterEpoch != AutoSwitchHAClient.this.currentReceivedEpoch) { + final EpochEntry existingEntry = AutoSwitchHAClient.this.epochCache.getEntry(masterEpoch); + if (existingEntry == null) { + if (!AutoSwitchHAClient.this.epochCache.appendEntry(new EpochEntry(masterEpoch, masterEpochStartOffset))) { + return false; + } + } else if (existingEntry.getStartOffset() != masterEpochStartOffset) { + LOGGER.error("Received conflicting epoch start: {} at {}", masterEpoch, masterEpochStartOffset); + return false; + } AutoSwitchHAClient.this.currentReceivedEpoch = masterEpoch; - AutoSwitchHAClient.this.epochCache.appendEntry(new EpochEntry(masterEpoch, masterEpochStartOffset)); } if (bodySize > 0) { - AutoSwitchHAClient.this.messageStore.appendToCommitLog(masterOffset, bodyData, 0, bodyData.length); + if (!AutoSwitchHAClient.this.messageStore.appendToCommitLog(masterOffset, bodyData, 0, bodyData.length)) { + return false; + } } haService.getDefaultMessageStore().setConfirmOffset(Math.min(confirmOffset, messageStore.getMaxPhyOffset())); @@ -599,6 +671,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/AutoSwitchHAConnection.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAConnection.java index e67ce46b0c6..4774801cfd2 100644 --- a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAConnection.java +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAConnection.java @@ -612,19 +612,23 @@ private void transferToSlave() throws Exception { } } - // We must ensure that the transmitted logs are within the same epoch - // If currentEpochEndOffset == -1, means that currentTransferEpoch = last epoch, so the endOffset = Long.max - final long currentEpochEndOffset = AutoSwitchHAConnection.this.currentTransferEpochEndOffset; - if (currentEpochEndOffset != -1 && this.nextTransferFromWhere + size > currentEpochEndOffset) { + // Choose the epoch for this batch's first byte. A batch ending at an epoch boundary + // still belongs to the old epoch; only the following batch uses the next epoch. + while (AutoSwitchHAConnection.this.currentTransferEpochEndOffset != -1 + && this.nextTransferFromWhere >= AutoSwitchHAConnection.this.currentTransferEpochEndOffset) { final EpochEntry epochEntry = AutoSwitchHAConnection.this.epochCache.nextEntry(AutoSwitchHAConnection.this.currentTransferEpoch); if (epochEntry == null) { LOGGER.error("Can't find a bigger epochEntry than epoch {}", AutoSwitchHAConnection.this.currentTransferEpoch); + this.releaseData(); waitForRunning(100); return; } - size = (int) (currentEpochEndOffset - this.nextTransferFromWhere); changeTransferEpochToNext(epochEntry); } + final long currentEpochEndOffset = AutoSwitchHAConnection.this.currentTransferEpochEndOffset; + if (currentEpochEndOffset != -1) { + size = (int) Math.min(size, currentEpochEndOffset - this.nextTransferFromWhere); + } this.transferOffset = this.nextTransferFromWhere; this.nextTransferFromWhere += size; 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..15817eb1015 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,9 @@ import java.io.IOException; import java.nio.channels.SocketChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -71,6 +74,7 @@ public class AutoSwitchHAService extends DefaultHAService { private volatile boolean isSynchronizingSyncStateSet = false; private EpochFileCache epochCache; + private ConfirmedOffsetGuard confirmedOffsetGuard; private AutoSwitchHAClient haClient; private Long localBrokerId = null; @@ -80,8 +84,23 @@ public AutoSwitchHAService() { @Override public void init(final DefaultMessageStore defaultMessageStore) throws IOException { - this.epochCache = new EpochFileCache(defaultMessageStore.getMessageStoreConfig().getStorePathEpochFile()); - this.epochCache.initCacheFromFile(); + final Path epochFilePath = Paths.get(defaultMessageStore.getMessageStoreConfig().getStorePathEpochFile()).toAbsolutePath(); + final Path parent = epochFilePath.getParent(); + if (epochFilePath.getFileName() == null || parent == null) { + throw new IOException("Invalid epoch file path: " + epochFilePath); + } + if (!Files.isDirectory(parent)) { + Files.createDirectories(parent); + } + this.epochCache = new EpochFileCache(epochFilePath.toString()); + if (!this.epochCache.initCacheFromFile()) { + throw new IOException("Failed to load epoch history: " + epochFilePath); + } + if (this.epochCache.getEntrySize() == 0 + && (defaultMessageStore.getMaxPhyOffset() != 0 || defaultMessageStore.getConfirmOffset() > 0)) { + throw new IOException("Nonempty commitlog has no epoch history: " + epochFilePath); + } + this.confirmedOffsetGuard = new ConfirmedOffsetGuard(Paths.get(epochFilePath + ".confirmed-offset-guard")); this.defaultMessageStore = defaultMessageStore; this.acceptSocketService = new AutoSwitchAcceptSocketService(defaultMessageStore.getMessageStoreConfig()); this.groupTransferService = new GroupTransferService(this, defaultMessageStore); @@ -134,14 +153,15 @@ public boolean changeToMaster(int masterEpoch) throws RocksDBException { // Truncate dirty file final long truncateOffset = truncateInvalidMsg(); - this.defaultMessageStore.setConfirmOffset(computeConfirmOffset()); - - if (truncateOffset >= 0) { - this.epochCache.truncateSuffixByOffset(truncateOffset); + final EpochEntry newEpochEntry; + try { + // Use the final recovered end, and replace invalid tails and the new boundary together. + newEpochEntry = appendEpochEntry(masterEpoch); + } catch (IOException e) { + LOGGER.error("Failed to persist master epoch {}, keep the broker fenced", masterEpoch, e); + return false; } - - // Append new epoch to epochFile - final EpochEntry newEpochEntry = appendEpochEntry(masterEpoch); + this.defaultMessageStore.setConfirmOffset(computeConfirmOffset()); // Waiting consume queue dispatch while (defaultMessageStore.dispatchBehindBytes() > 0) { @@ -180,7 +200,6 @@ public boolean changeToSlave(String newMasterAddr, int newMasterEpoch, Long slav } this.haClient.updateMasterAddress(newMasterAddr); this.haClient.updateHaMasterAddress(null); - this.haClient.start(); if (defaultMessageStore.isTransientStorePoolEnable()) { waitingForAllCommit(); @@ -188,6 +207,7 @@ public boolean changeToSlave(String newMasterAddr, int newMasterEpoch, Long slav } this.defaultMessageStore.setStateMachineVersion(newMasterEpoch); + this.haClient.start(); LOGGER.info("Change ha to slave success, newMasterAddress:{}, newMasterEpoch:{}", newMasterAddr, newMasterEpoch); return true; @@ -204,8 +224,13 @@ public boolean changeToMasterWhenLastRoleIsMaster(int masterEpoch) { LOGGER.warn("newMasterEpoch {} < lastEpoch {}, fail to change to master", masterEpoch, lastEpoch); return false; } - // Append new epoch to epochFile - final EpochEntry newEpochEntry = appendEpochEntry(masterEpoch); + final EpochEntry newEpochEntry; + try { + newEpochEntry = appendEpochEntry(masterEpoch); + } catch (IOException e) { + LOGGER.error("Failed to persist master epoch {}, keep the broker fenced", masterEpoch, e); + return false; + } this.defaultMessageStore.setStateMachineVersion(masterEpoch); LOGGER.info("Change ha to master success, last role is master, newMasterEpoch:{}, startOffset:{}", @@ -214,34 +239,11 @@ public boolean changeToMasterWhenLastRoleIsMaster(int masterEpoch) { } /** - * 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 - * elected as the master again with the same epoch would otherwise move the start offset of the epoch, and the - * slave holding the original start offset could never find a consistent point, so it would never rejoin the - * sync state set. - *

- * The entry is only reused if its start offset is within the local commitlog. The epoch file is not trimmed - * against the recovered commitlog on startup, so after an unclean shutdown the recorded start offset may be - * greater than the recovered max physical offset. Reusing such an entry would make the slave treat its own - * tail as consistent with the master, and the two replicas would silently diverge. + * Install the granted epoch before writes are enabled. A new broker startup must receive a new + * controller epoch; a duplicate grant within that startup retains its original valid start offset. */ - private EpochEntry appendEpochEntry(final int masterEpoch) { - final int lastEpoch = this.epochCache.lastEpoch(); - if (lastEpoch == masterEpoch) { - final EpochEntry existingEntry = this.epochCache.lastEntry(); - final long maxPhyOffset = this.defaultMessageStore.getMaxPhyOffset(); - if (existingEntry.getStartOffset() <= maxPhyOffset) { - LOGGER.info("Epoch entry already exists locally, keep the original startOffset. epoch:{}, startOffset:{}", - existingEntry.getEpoch(), existingEntry.getStartOffset()); - return existingEntry; - } - LOGGER.warn("Epoch {} startOffset {} exceeds maxPhyOffset {}, rewrite the entry", - masterEpoch, existingEntry.getStartOffset(), maxPhyOffset); - this.epochCache.truncateSuffixByEpoch(masterEpoch); - } - final EpochEntry newEpochEntry = new EpochEntry(masterEpoch, this.defaultMessageStore.getMaxPhyOffset()); - this.epochCache.appendEntry(newEpochEntry); - return newEpochEntry; + private EpochEntry appendEpochEntry(final int masterEpoch) throws IOException { + return this.epochCache.prepareMasterEpoch(masterEpoch, this.defaultMessageStore.getMaxPhyOffset()); } @Override @@ -252,10 +254,25 @@ public boolean changeToSlaveWhenMasterNotChange(String newMasterAddr, int newMas return false; } - this.defaultMessageStore.setStateMachineVersion(newMasterEpoch); - LOGGER.info("Change ha to slave success, master doesn't change, newMasterAddress:{}, newMasterEpoch:{}", - newMasterAddr, newMasterEpoch); - return true; + if (this.haClient == null) { + LOGGER.warn("No HA client for unchanged master {}, fail to change to slave", newMasterAddr); + return false; + } + try { + // The broker ID may be unchanged while its startup and history have changed. Stop the + // old transfer before publishing the new expected epoch and starting another handshake. + this.haClient.reOpen(); + this.haClient.updateMasterAddress(newMasterAddr); + this.haClient.updateHaMasterAddress(null); + this.defaultMessageStore.setStateMachineVersion(newMasterEpoch); + this.haClient.start(); + LOGGER.info("Change ha to slave success, master doesn't change, newMasterAddress:{}, newMasterEpoch:{}", + newMasterAddr, newMasterEpoch); + return true; + } catch (Exception e) { + LOGGER.error("Failed to restart HA client for unchanged master", e); + return false; + } } public void waitingForAllCommit() { @@ -577,6 +594,10 @@ public List getEpochEntries() { return this.epochCache.getAllEntries(); } + public ConfirmedOffsetGuard getConfirmedOffsetGuard() { + return this.confirmedOffsetGuard; + } + public Long getLocalBrokerId() { return localBrokerId; } diff --git a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/ConfirmedOffsetGuard.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/ConfirmedOffsetGuard.java new file mode 100644 index 00000000000..7a3a65e7628 --- /dev/null +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/ConfirmedOffsetGuard.java @@ -0,0 +1,156 @@ +/* + * 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.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import org.apache.rocketmq.common.MixAll; + +/** + * Remembers a refused remote history across HA client and broker restarts. The observed offset is + * diagnostic evidence, not a verified recovery boundary. This guard does not determine whether the + * local replica is eligible to become master. + */ +public class ConfirmedOffsetGuard { + private static final String VERSION = "rocketmq-confirmed-offset-guard-v1"; + private final Path stateFile; + private boolean blocked; + private boolean persisted; + private String source; + private int masterEpoch; + private long observedOffset; + private long confirmOffset; + + public ConfirmedOffsetGuard(Path stateFile) throws IOException { + this.stateFile = stateFile.toAbsolutePath(); + if (this.stateFile.getFileName() == null) { + throw new IOException("Invalid confirmed-offset guard path: " + stateFile); + } + final byte[] data; + try { + data = Files.readAllBytes(this.stateFile); + } catch (NoSuchFileException e) { + return; + } + load(data); + } + + public synchronized boolean isBlocked() { + return this.blocked; + } + + public synchronized void recordRefusal(String source, int masterEpoch, long observedOffset, + long confirmOffset) throws IOException { + if (!this.blocked) { + this.source = source == null ? "" : source; + this.masterEpoch = masterEpoch; + this.observedOffset = observedOffset; + this.confirmOffset = confirmOffset; + this.blocked = true; + } + ensurePersisted(); + } + + public synchronized void ensurePersisted() throws IOException { + if (this.blocked && !this.persisted) { + persist(); + this.persisted = true; + } + } + + public synchronized String describe() { + if (!this.blocked) { + return "No refused remote history"; + } + return "source=" + this.source + ", masterEpoch=" + this.masterEpoch + + ", observedOffset=" + this.observedOffset + ", confirmOffset=" + this.confirmOffset + + ", persisted=" + this.persisted; + } + + private void load(byte[] data) throws IOException { + final String text = decodeUtf8(data); + final String[] fields = text.split("\n", -1); + if (fields.length != 7 || !VERSION.equals(fields[0]) || !fields[6].isEmpty()) { + throw new IOException("Invalid confirmed-offset guard record: " + this.stateFile); + } + final String payload = String.join("\n", fields[0], fields[1], fields[2], fields[3], fields[4]) + "\n"; + try { + final byte[] checksum = Base64.getDecoder().decode(fields[5]); + if (!MessageDigest.isEqual(checksum, digest(payload.getBytes(StandardCharsets.UTF_8)))) { + throw new IOException("Confirmed-offset guard checksum mismatch: " + this.stateFile); + } + this.source = decodeUtf8(Base64.getDecoder().decode(fields[1])); + this.masterEpoch = Integer.parseInt(fields[2]); + this.observedOffset = Long.parseLong(fields[3]); + this.confirmOffset = Long.parseLong(fields[4]); + } catch (IllegalArgumentException e) { + throw new IOException("Invalid confirmed-offset guard record: " + this.stateFile, e); + } + this.blocked = true; + this.persisted = true; + } + + private void persist() throws IOException { + final String encodedSource = Base64.getEncoder().encodeToString(this.source.getBytes(StandardCharsets.UTF_8)); + final String payload = VERSION + "\n" + encodedSource + "\n" + this.masterEpoch + "\n" + + this.observedOffset + "\n" + this.confirmOffset + "\n"; + final String checksum = Base64.getEncoder().encodeToString(digest(payload.getBytes(StandardCharsets.UTF_8))); + final byte[] data = (payload + checksum + "\n").getBytes(StandardCharsets.UTF_8); + final Path parent = this.stateFile.getParent(); + final Path temporaryFile = Files.createTempFile(parent, "confirmed-offset-guard-", ".tmp"); + try { + try (FileChannel channel = FileChannel.open(temporaryFile, StandardOpenOption.WRITE)) { + final ByteBuffer buffer = ByteBuffer.wrap(data); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + channel.force(true); + } + Files.move(temporaryFile, this.stateFile, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + MixAll.fsyncDirectory(parent); + } catch (IOException e) { + try { + Files.deleteIfExists(temporaryFile); + } catch (IOException cleanupException) { + e.addSuppressed(cleanupException); + } + throw e; + } + } + + private static String decodeUtf8(byte[] data) throws IOException { + return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(data)).toString(); + } + + private static byte[] digest(byte[] data) throws IOException { + try { + return MessageDigest.getInstance("SHA-256").digest(data); + } catch (NoSuchAlgorithmException e) { + throw new IOException("SHA-256 is unavailable", e); + } + } +} 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..23c7eae16f7 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,7 @@ package org.apache.rocketmq.store.ha.autoswitch; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -56,8 +57,8 @@ public EpochFileCache(final String path) { public boolean initCacheFromFile() { this.writeLock.lock(); try { - final List entries = this.checkpoint.read(); - initEntries(entries); + final List entries = validatedEntries(this.checkpoint.readStrict()); + publishEntries(entries); return true; } catch (final IOException e) { log.error("Error happen when init epoch entries from epochFile", e); @@ -70,23 +71,49 @@ public boolean initCacheFromFile() { public void initCacheFromEntries(final List entries) { this.writeLock.lock(); try { - initEntries(entries); - flush(); + replaceEntries(entries); + } catch (IOException e) { + throw new UncheckedIOException("Failed to initialize epoch entries", e); } finally { this.writeLock.unlock(); } } - private void initEntries(final List entries) { - this.epochMap.clear(); + private List validatedEntries(final List entries) throws IOException { + final List result = new ArrayList<>(entries.size()); EpochEntry preEntry = null; - for (final EpochEntry entry : entries) { - this.epochMap.put(entry.getEpoch(), entry); + for (final EpochEntry source : entries) { + if (source == null || source.getEpoch() < 0 || source.getStartOffset() < 0 + || source.getEndOffset() < source.getStartOffset()) { + throw new IOException("Invalid epoch entry: " + source); + } + final EpochEntry entry = new EpochEntry(source); if (preEntry != null) { + if (preEntry.getEpoch() >= entry.getEpoch() || preEntry.getStartOffset() >= entry.getStartOffset()) { + throw new IOException("Epoch entries must have increasing epochs and start offsets"); + } preEntry.setEndOffset(entry.getStartOffset()); } + result.add(entry); preEntry = entry; } + return result; + } + + private void publishEntries(final List entries) { + this.epochMap.clear(); + for (final EpochEntry entry : entries) { + this.epochMap.put(entry.getEpoch(), entry); + } + } + + private void replaceEntries(final List entries) throws IOException { + final List replacement = validatedEntries(entries); + if (this.checkpoint != null) { + this.checkpoint.writeAtomically(replacement); + } + // Do not expose a history boundary until its durable replacement has succeeded. + publishEntries(replacement); } public int getEntrySize() { @@ -107,11 +134,41 @@ public boolean appendEntry(final EpochEntry entry) { log.error("The appending entry's lastEpoch or endOffset {} is not bigger than lastEntry {}, append failed", entry, lastEntry); return false; } - lastEntry.setEndOffset(entry.getStartOffset()); } - this.epochMap.put(entry.getEpoch(), new EpochEntry(entry)); - flush(); + final List replacement = getAllEntries(); + replacement.add(entry); + replaceEntries(replacement); return true; + } catch (IOException e) { + log.error("Failed to persist appended epoch entry {}", entry, e); + return false; + } finally { + this.writeLock.unlock(); + } + } + + /** + * Durably close the recovered history and install a controller-granted master epoch. Entries + * starting at or beyond the recovered end have no surviving data and are replaced together + * with the new boundary. Repeated grants within one startup keep an existing valid start. + */ + public EpochEntry prepareMasterEpoch(final int epoch, final long recoveredMax) throws IOException { + this.writeLock.lock(); + try { + if (epoch < 0 || recoveredMax < 0 || epoch < lastEpoch()) { + throw new IOException("Invalid master epoch or recovered offset: " + epoch + ", " + recoveredMax); + } + final EpochEntry lastEntry = lastEntry(); + if (lastEntry != null && lastEntry.getEpoch() == epoch && lastEntry.getStartOffset() <= recoveredMax) { + replaceEntries(getAllEntries()); + return lastEntry; + } + final List replacement = getAllEntries(); + replacement.removeIf(entry -> entry.getStartOffset() >= recoveredMax); + final EpochEntry newEntry = new EpochEntry(epoch, recoveredMax); + replacement.add(newEntry); + replaceEntries(replacement); + return new EpochEntry(newEntry); } finally { this.writeLock.unlock(); } @@ -247,28 +304,32 @@ public long findConsistentPoint(final EpochFileCache compareCache) { /** * Remove epochEntries with epoch >= truncateEpoch. */ - public void truncateSuffixByEpoch(final int truncateEpoch) { + public boolean truncateSuffixByEpoch(final int truncateEpoch) { Predicate predict = entry -> entry.getEpoch() >= truncateEpoch; - doTruncateSuffix(predict); + return doTruncateSuffix(predict); } /** * Remove epochEntries with startOffset >= truncateOffset. */ - public void truncateSuffixByOffset(final long truncateOffset) { + public boolean truncateSuffixByOffset(final long truncateOffset) { Predicate predict = entry -> entry.getStartOffset() >= truncateOffset; - doTruncateSuffix(predict); + return doTruncateSuffix(predict); } - private void doTruncateSuffix(Predicate predict) { + private boolean doTruncateSuffix(Predicate predict) { this.writeLock.lock(); try { - this.epochMap.entrySet().removeIf(entry -> predict.test(entry.getValue())); - final EpochEntry entry = lastEntry(); - if (entry != null) { - entry.setEndOffset(Long.MAX_VALUE); + final List replacement = getAllEntries(); + replacement.removeIf(predict); + if (!replacement.isEmpty()) { + replacement.get(replacement.size() - 1).setEndOffset(Long.MAX_VALUE); } - flush(); + replaceEntries(replacement); + return true; + } catch (IOException e) { + log.error("Failed to persist truncated epoch suffix", e); + return false; } finally { this.writeLock.unlock(); } @@ -277,26 +338,17 @@ private void doTruncateSuffix(Predicate predict) { /** * Remove epochEntries with endOffset <= truncateOffset. */ - public void truncatePrefixByOffset(final long truncateOffset) { + public boolean truncatePrefixByOffset(final long truncateOffset) { Predicate predict = entry -> entry.getEndOffset() <= truncateOffset; this.writeLock.lock(); try { - this.epochMap.entrySet().removeIf(entry -> predict.test(entry.getValue())); - flush(); - } finally { - this.writeLock.unlock(); - } - } - - private void flush() { - this.writeLock.lock(); - try { - if (this.checkpoint != null) { - final ArrayList entries = new ArrayList<>(this.epochMap.values()); - this.checkpoint.write(entries); - } + final List replacement = getAllEntries(); + replacement.removeIf(predict); + replaceEntries(replacement); + return true; } catch (final IOException e) { - log.error("Error happen when flush epochEntries to epochCheckpointFile", e); + log.error("Failed to persist truncated epoch prefix", e); + return false; } finally { this.writeLock.unlock(); } diff --git a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAHistoryRecoveryTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAHistoryRecoveryTest.java new file mode 100644 index 00000000000..8683df1c068 --- /dev/null +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAHistoryRecoveryTest.java @@ -0,0 +1,429 @@ +/* + * 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.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.apache.rocketmq.common.BrokerConfig; +import org.apache.rocketmq.common.message.MessageDecoder; +import org.apache.rocketmq.common.message.MessageExt; +import org.apache.rocketmq.common.message.MessageExtBrokerInner; +import org.apache.rocketmq.store.DefaultMessageStore; +import org.apache.rocketmq.store.GetMessageResult; +import org.apache.rocketmq.store.GetMessageStatus; +import org.apache.rocketmq.store.PutMessageResult; +import org.apache.rocketmq.store.PutMessageStatus; +import org.apache.rocketmq.store.config.BrokerRole; +import org.apache.rocketmq.store.config.FlushDiskType; +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.Before; +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.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Store-level scenarios using real commitlogs and HA sockets. Epoch assignments are explicit inputs; + * these tests do not run a controller or simulate a machine crash. + */ +public class AutoSwitchHAHistoryRecoveryTest { + private static final String TOPIC = "HistoryRecovery"; + private static final int TIMEOUT_SECONDS = 30; + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + private final List stores = new ArrayList<>(); + private BrokerStatsManager brokerStatsManager; + + @Before + public void setUp() { + this.brokerStatsManager = new BrokerStatsManager("HistoryRecovery", true); + } + + @After + public void tearDown() { + try { + for (int i = this.stores.size() - 1; i >= 0; i--) { + final TestStore store = this.stores.get(i); + store.stop(); + store.messageStore.destroy(); + } + } finally { + this.brokerStatsManager.shutdown(); + } + } + + @Test(timeout = 180000) + public void testRefusalSurvivesRegrowthReconnectAndReplicaRestart() throws Exception { + final Path masterPath = newStorePath("master"); + final Path replicaPath = newStorePath("replica"); + final TestStore master = startStore(masterPath, 1); + TestStore replica = startStore(replicaPath, 2); + master.becomeMaster(1); + replica.follow(master, 1); + + final List original = appendMessages(master, "shared", 10); + final long recoveredEnd = master.messageStore.getMaxPhyOffset(); + original.addAll(appendMessages(master, "original", 10)); + awaitReplication(master, replica, original); + final long protectedEnd = replica.messageStore.getMaxPhyOffset(); + replica.stop(); + + // Isolate the store and use its truncation API to provide the shorter source history. + // Keeping epoch 1 deliberately reproduces the unsafe source behavior under review. + truncateIsolatedMaster(master, recoveredEnd); + replica = startStore(replicaPath, 2); + replica.follow(master, 1); + awaitBlocked(replica); + assertPreserved(replica, protectedEnd, original); + + appendMessages(master, "replacement", 30); + assertTrue(master.messageStore.getMaxPhyOffset() > protectedEnd); + replica.follow(master, 1); + assertRemainsRejected(replica, protectedEnd, original); + + replica.stop(); + replica = startStore(replicaPath, 2); + assertTrue(replica.haService().getConfirmedOffsetGuard().isBlocked()); + replica.follow(master, 1); + assertRemainsRejected(replica, protectedEnd, original); + } + + @Test(timeout = 180000) + public void testFirstHandshakeAfterRegrowthUsesNewEpochBoundary() throws Exception { + final Path masterPath = newStorePath("master"); + final Path replicaPath = newStorePath("replica"); + final TestStore master = startStore(masterPath, 1); + TestStore replica = startStore(replicaPath, 2); + master.becomeMaster(1); + replica.follow(master, 1); + + final List original = appendMessages(master, "shared", 10); + final long recoveredEnd = master.messageStore.getMaxPhyOffset(); + original.addAll(appendMessages(master, "original", 10)); + awaitReplication(master, replica, original); + final long protectedEnd = replica.messageStore.getMaxPhyOffset(); + replica.stop(); + + truncateIsolatedMaster(master, recoveredEnd); + // Supply the new epoch before any replacement write, not after regrowth. + master.becomeMaster(2); + assertEquals(recoveredEnd, master.haService().getEpochEntries().get(1).getStartOffset()); + appendMessages(master, "replacement", 30); + assertTrue(master.messageStore.getMaxPhyOffset() > protectedEnd); + + replica = startStore(replicaPath, 2); + assertFalse(replica.haService().getConfirmedOffsetGuard().isBlocked()); + replica.follow(master, 2); + awaitBlocked(replica); + assertRemainsRejected(replica, protectedEnd, original); + } + + @Test(timeout = 180000) + public void testUncleanSelectionRequiresExplicitRebuildAndPreservesOldStore() throws Exception { + final Path oldMasterPath = newStorePath("old-master"); + final Path selectedMasterPath = newStorePath("selected-master"); + TestStore oldMaster = startStore(oldMasterPath, 1); + TestStore selectedMaster = startStore(selectedMasterPath, 2); + oldMaster.becomeMaster(1); + selectedMaster.follow(oldMaster, 1); + + final List common = appendMessages(oldMaster, "shared", 10); + awaitReplication(oldMaster, selectedMaster, common); + final long commonEnd = selectedMaster.messageStore.getMaxPhyOffset(); + selectedMaster.stop(); + + final List abandonedHistory = new ArrayList<>(common); + abandonedHistory.addAll(appendMessages(oldMaster, "old-only", 10)); + oldMaster.haService().setSyncStateSet(Collections.singleton(1L)); + final long protectedEnd = oldMaster.messageStore.getConfirmOffset(); + assertTrue(protectedEnd > commonEnd); + awaitContents(oldMaster, abandonedHistory); + oldMaster.stop(); + + selectedMaster = startStore(selectedMasterPath, 2); + selectedMaster.becomeMaster(2); + final List selectedHistory = new ArrayList<>(common); + selectedHistory.addAll(appendMessages(selectedMaster, "selected", 20)); + + oldMaster = startStore(oldMasterPath, 1); + assertEquals(protectedEnd, oldMaster.messageStore.getConfirmOffset()); + oldMaster.follow(selectedMaster, 2); + awaitBlocked(oldMaster); + assertPreserved(oldMaster, protectedEnd, abandonedHistory); + oldMaster.stop(); + final Map preservedCommitlog = readCommitlogFiles(oldMasterPath); + + // The data frames must carry every epoch themselves. A heartbeat carrying epoch 1 before + // the first data frame could hide a sender that labels the old tail with epoch 2. + selectedMaster.config.setHaSendHeartbeatInterval(60000); + + // The operator explicitly chooses the new master and a fresh store directory. The old + // store and its guard are retained; no offset is guessed from the refused handshake. + TestStore rebuilt = startStore(newStorePath("rebuilt-old-master"), 3); + assertFalse(rebuilt.config.isSyncFromLastFile()); + assertEquals(0, rebuilt.messageStore.getMaxPhyOffset()); + rebuilt.follow(selectedMaster, 2); + awaitReplication(selectedMaster, rebuilt, selectedHistory); + assertEquals(selectedMaster.haService().getEpochEntries(), rebuilt.haService().getEpochEntries()); + assertEquals(0, rebuilt.haService().getEpochEntries().get(0).getStartOffset()); + assertEquals(commonEnd, rebuilt.haService().getEpochEntries().get(0).getEndOffset()); + + selectedHistory.addAll(appendMessages(selectedMaster, "after-rebuild", 5)); + awaitReplication(selectedMaster, rebuilt, selectedHistory); + assertFalse(rebuilt.haService().getConfirmedOffsetGuard().isBlocked()); + assertCommitlogUnchanged(preservedCommitlog, oldMasterPath); + + final Path rebuiltPath = rebuilt.root; + rebuilt.stop(); + rebuilt = startStore(rebuiltPath, 3); + rebuilt.follow(selectedMaster, 2); + awaitReplication(selectedMaster, rebuilt, selectedHistory); + assertEquals(selectedMaster.haService().getEpochEntries(), rebuilt.haService().getEpochEntries()); + + // A fully rebuilt replica must retain enough epoch history to become a source itself. + // Stop the previous source, then supply the next controller grant explicitly to this fixture. + selectedMaster.stop(); + rebuilt.becomeMaster(3); + rebuilt.config.setHaSendHeartbeatInterval(60000); + selectedHistory.addAll(appendMessages(rebuilt, "after-promotion", 5)); + final TestStore nextReplica = startStore(newStorePath("replica-from-rebuilt"), 4); + nextReplica.follow(rebuilt, 3); + awaitReplication(rebuilt, nextReplica, selectedHistory); + assertEquals(rebuilt.haService().getEpochEntries(), nextReplica.haService().getEpochEntries()); + + selectedHistory.addAll(appendMessages(rebuilt, "after-second-copy", 5)); + awaitReplication(rebuilt, nextReplica, selectedHistory); + assertCommitlogUnchanged(preservedCommitlog, oldMasterPath); + } + + private Path newStorePath(String name) throws Exception { + return this.tempFolder.newFolder(name).toPath(); + } + + private TestStore startStore(Path root, long brokerId) throws Exception { + final TestStore store = new TestStore(root, brokerId); + this.stores.add(store); + store.messageStore.getRunningFlags().makeFenced(true); + assertTrue("Store load failed: " + root, store.messageStore.load()); + store.messageStore.start(); + store.haService().setLocalBrokerId(brokerId); + return store; + } + + private void truncateIsolatedMaster(TestStore master, long recoveredEnd) throws Exception { + master.haService().destroyConnections(); + master.haService().setSyncStateSet(Collections.singleton(master.brokerId)); + await().atMost(TIMEOUT_SECONDS, TimeUnit.SECONDS) + .until(() -> master.messageStore.dispatchBehindBytes() == 0); + master.messageStore.getRunningFlags().makeFenced(true); + assertTrue(master.messageStore.truncateFiles(recoveredEnd)); + assertEquals(recoveredEnd, master.messageStore.getMaxPhyOffset()); + assertEquals(recoveredEnd, master.messageStore.getConfirmOffset()); + master.messageStore.getRunningFlags().makeFenced(false); + } + + private List appendMessages(TestStore store, String prefix, int count) { + final List payloads = new ArrayList<>(); + for (int i = 0; i < count; i++) { + final String payload = String.format(Locale.ROOT, "%s-%03d", prefix, i); + final MessageExtBrokerInner message = new MessageExtBrokerInner(); + message.setTopic(TOPIC); + message.setTags("history"); + message.setQueueId(0); + message.setBody(payload.getBytes(StandardCharsets.UTF_8)); + message.setBornTimestamp(System.currentTimeMillis()); + message.setBornHost(new InetSocketAddress("127.0.0.1", 0)); + message.setStoreHost(new InetSocketAddress("127.0.0.1", 10911)); + message.setPropertiesString(MessageDecoder.messageProperties2String(message.getProperties())); + final PutMessageResult result = store.messageStore.putMessage(message); + assertEquals(PutMessageStatus.PUT_OK, result.getPutMessageStatus()); + payloads.add(payload); + } + return payloads; + } + + private void awaitReplication(TestStore master, TestStore replica, List expected) { + await().atMost(TIMEOUT_SECONDS, TimeUnit.SECONDS).untilAsserted(() -> { + assertEquals(master.messageStore.getMaxPhyOffset(), replica.messageStore.getMaxPhyOffset()); + assertEquals(master.messageStore.getConfirmOffset(), replica.messageStore.getConfirmOffset()); + assertContents(master, expected); + assertContents(replica, expected); + }); + } + + private void awaitContents(TestStore store, List expected) { + await().atMost(TIMEOUT_SECONDS, TimeUnit.SECONDS).untilAsserted(() -> assertContents(store, expected)); + } + + private void awaitBlocked(TestStore replica) { + await().atMost(TIMEOUT_SECONDS, TimeUnit.SECONDS) + .until(() -> replica.haService().getConfirmedOffsetGuard().isBlocked()); + } + + private void assertRemainsRejected(TestStore replica, long protectedEnd, List expected) { + // Cover a full rejection/reconnect interval as well as the first response. + await().during(8, TimeUnit.SECONDS).atMost(20, TimeUnit.SECONDS).untilAsserted(() -> { + assertTrue(replica.haService().getConfirmedOffsetGuard().isBlocked()); + assertFalse(HAConnectionState.TRANSFER == replica.haService().getHAClient().getCurrentState()); + assertPreserved(replica, protectedEnd, expected); + }); + } + + private void assertPreserved(TestStore replica, long protectedEnd, List expected) { + assertEquals(protectedEnd, replica.messageStore.getMaxPhyOffset()); + assertEquals(protectedEnd, replica.messageStore.getConfirmOffset()); + assertContents(replica, expected); + } + + private void assertContents(TestStore store, List expected) { + long offset = 0; + int index = 0; + while (index < expected.size()) { + final GetMessageResult result = store.messageStore.getMessage("history-group", TOPIC, 0, offset, 1000, null); + assertNotNull(result); + try { + assertEquals(GetMessageStatus.FOUND, result.getStatus()); + assertTrue(result.getMessageCount() > 0); + assertEquals((long) expected.size(), result.getMaxOffset()); + for (ByteBuffer buffer : result.getMessageBufferList()) { + final MessageExt message = MessageDecoder.decode(buffer.duplicate()); + assertNotNull(message); + assertTrue(index < expected.size()); + assertEquals((long) index, message.getQueueOffset()); + assertEquals(expected.get(index), new String(message.getBody(), StandardCharsets.UTF_8)); + index++; + } + assertTrue(result.getNextBeginOffset() > offset); + offset = result.getNextBeginOffset(); + } finally { + result.release(); + } + } + assertEquals(expected.size(), index); + assertEquals((long) expected.size(), offset); + } + + private Map readCommitlogFiles(Path root) throws Exception { + final Map result = new LinkedHashMap<>(); + try (Stream paths = Files.list(root.resolve("commitlog"))) { + for (Path path : paths.filter(Files::isRegularFile).sorted().collect(Collectors.toList())) { + result.put(path.getFileName(), Files.readAllBytes(path)); + } + } + assertFalse(result.isEmpty()); + return result; + } + + private void assertCommitlogUnchanged(Map expected, Path root) throws Exception { + final Map actual = readCommitlogFiles(root); + assertEquals(expected.keySet(), actual.keySet()); + for (Map.Entry entry : expected.entrySet()) { + assertArrayEquals("Retained commitlog changed: " + entry.getKey(), entry.getValue(), actual.get(entry.getKey())); + } + } + + private class TestStore { + private final Path root; + private final long brokerId; + private final MessageStoreConfig config; + private final DefaultMessageStore messageStore; + private boolean stopped; + + private TestStore(Path root, long brokerId) throws Exception { + this.root = root; + this.brokerId = brokerId; + this.config = new MessageStoreConfig(); + this.config.setStorePathRootDir(root.toString()); + this.config.setMappedFileSizeCommitLog(2048); + this.config.setMappedFileSizeConsumeQueue(20 * 1024); + this.config.setMaxHashSlotNum(1000); + this.config.setMaxIndexNum(1000); + this.config.setMessageIndexEnable(false); + this.config.setEnableCompaction(false); + this.config.setTimerWheelEnable(false); + this.config.setFlushDiskType(FlushDiskType.SYNC_FLUSH); + this.config.setFlushIntervalConsumeQueue(10); + this.config.setBrokerRole(BrokerRole.SLAVE); + this.config.setHaListenPort(0); + this.config.setHaSendHeartbeatInterval(200); + this.config.setSyncFromLastFile(false); + this.config.setTotalReplicas(2); + this.config.setInSyncReplicas(1); + this.config.setMinInSyncReplicas(1); + this.config.setAllAckInSyncStateSet(false); + + final BrokerConfig brokerConfig = new BrokerConfig(); + brokerConfig.setBrokerName("history-recovery"); + brokerConfig.setBrokerId(brokerId); + brokerConfig.setEnableControllerMode(true); + this.messageStore = new DefaultMessageStore(this.config, brokerStatsManager, null, + brokerConfig, new ConcurrentHashMap<>()); + } + + private AutoSwitchHAService haService() { + return (AutoSwitchHAService) this.messageStore.getHaService(); + } + + private void becomeMaster(int epoch) throws Exception { + this.messageStore.getRunningFlags().makeFenced(true); + this.config.setBrokerRole(BrokerRole.SYNC_MASTER); + haService().setSyncStateSet(Collections.singleton(this.brokerId)); + assertTrue(haService().changeToMaster(epoch)); + this.messageStore.getRunningFlags().makeFenced(false); + } + + private void follow(TestStore master, int epoch) { + this.config.setBrokerRole(BrokerRole.SLAVE); + final String address = "127.0.0.1:" + master.config.getHaListenPort(); + assertTrue(master.config.getHaListenPort() > 0); + assertTrue(haService().changeToSlave(address, epoch, this.brokerId)); + haService().updateHaMasterAddress(address); + this.messageStore.getRunningFlags().makeFenced(false); + } + + private void stop() { + if (!this.stopped) { + this.messageStore.shutdown(); + this.stopped = true; + } + } + } +} 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..a47c739ccbf 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 @@ -17,18 +17,30 @@ package org.apache.rocketmq.store.ha.autoswitch; import java.io.File; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; 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.junit.Assume; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import org.mockito.InOrder; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.inOrder; 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 AutoSwitchHAServiceTest { @@ -36,6 +48,27 @@ public class AutoSwitchHAServiceTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); + @Test + public void testEpochCheckpointUnderSymlinkedDirectory() throws Exception { + final Path directory = tempFolder.newFolder("store").toPath(); + final Path link = directory.resolveSibling("link"); + try { + Files.createSymbolicLink(link, directory); + } catch (IOException | UnsupportedOperationException e) { + Assume.assumeNoException("Symbolic links are unavailable on this filesystem", e); + } + final AutoSwitchHAService service = new AutoSwitchHAService(); + service.init(mockMessageStore(link.resolve("epoch").toString(), 0)); + try { + assertTrue(service.changeToMaster(1)); + } finally { + service.shutdown(); + } + final EpochFileCache reloaded = new EpochFileCache(directory.resolve("epoch").toString()); + assertTrue(reloaded.initCacheFromFile()); + assertEquals(new EpochEntry(1, 0), reloaded.lastEntry()); + } + @Test public void testChangeToMasterWithSameEpochKeepsOriginalStartOffset() throws Exception { final String epochFilePath = epochFilePath(); @@ -49,8 +82,8 @@ public void testChangeToMasterWithSameEpochKeepsOriginalStartOffset() throws Exc haService.shutdown(); } - // Simulate the broker restart: the epoch file is recovered from disk and the broker is elected - // as the master again with the same epoch, while the commitlog has grown to 5802. + // Reload the persisted entry and replay its grant after the commitlog has grown. This tests + // the store's idempotence; controller registration must grant a new epoch for a new startup. haService = new AutoSwitchHAService(); haService.init(mockMessageStore(epochFilePath, 5802L)); try { @@ -128,8 +161,8 @@ public void testChangeToMasterRewritesEpochWhenStartOffsetExceedsMaxPhyOffset() haService.shutdown(); } - // Restart after an unclean shutdown: the commitlog recovers to 4800, before the recorded epoch start, - // so the recorded entry must be rewritten instead of being reused. + // An invalid empty tail cannot be reused after commitlog recovery. The controller normally + // supplies a newer epoch; retain coverage of the existing store-level same-epoch behavior. haService = new AutoSwitchHAService(); haService.init(mockMessageStore(epochFilePath, 4800L)); try { @@ -145,6 +178,123 @@ public void testChangeToMasterRewritesEpochWhenStartOffsetExceedsMaxPhyOffset() } } + @Test + public void testBothMasterRolePathsFailWithoutPublishingAnUnpersistedEpoch() throws Exception { + for (boolean alreadyMaster : new boolean[] {false, true}) { + final Path path = tempFolder.getRoot().toPath().resolve("epoch-" + alreadyMaster); + final DefaultMessageStore messageStore = mockMessageStore(path.toString(), 0); + final AutoSwitchHAService haService = new AutoSwitchHAService(); + haService.init(messageStore); + try { + assertTrue(haService.changeToMaster(1)); + when(messageStore.getMaxPhyOffset()).thenReturn(100L); + Files.delete(path); + Files.createDirectory(path); + + final boolean changed = alreadyMaster ? haService.changeToMasterWhenLastRoleIsMaster(2) + : haService.changeToMaster(2); + + assertFalse(changed); + verify(messageStore, never()).setStateMachineVersion(2); + assertEpochEntry(haService, 1, 0); + } finally { + haService.shutdown(); + } + } + } + + @Test + public void testInitRejectsCorruptEpochHistoryEvenWithAValidBackup() throws Exception { + final Path path = new File(epochFilePath()).toPath(); + final EpochFileCache cache = new EpochFileCache(path.toString()); + cache.prepareMasterEpoch(1, 0); + Files.copy(path, path.resolveSibling(path.getFileName() + ".bak")); + Files.write(path, "broken".getBytes(StandardCharsets.UTF_8)); + + try { + new AutoSwitchHAService().init(mockMessageStore(path.toString(), 100)); + fail("Invalid epoch history must prevent HA initialization"); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains("epoch history")); + } + } + + @Test + public void testRefusedRemoteHistorySurvivesLocalPromotionAndRestart() throws Exception { + final Path path = tempFolder.getRoot().toPath().resolve("nested").resolve("epoch"); + final EpochFileCache history = new EpochFileCache(path.toString()); + assertEquals(1, history.prepareMasterEpoch(1, 0).getEpoch()); + AutoSwitchHAService haService = new AutoSwitchHAService(); + haService.init(mockMessageStore(path.toString(), 3280)); + try { + haService.getConfirmedOffsetGuard().recordRefusal("old-master", 2, 1580, 3280); + // A refused remote history does not make this replica's own confirmed data invalid. + assertTrue(haService.changeToMaster(3)); + assertTrue(haService.getConfirmedOffsetGuard().isBlocked()); + } finally { + haService.shutdown(); + } + + haService = new AutoSwitchHAService(); + haService.init(mockMessageStore(path.toString(), 3280)); + try { + assertTrue(haService.getConfirmedOffsetGuard().isBlocked()); + assertTrue(haService.changeToMasterWhenLastRoleIsMaster(4)); + assertTrue(haService.getConfirmedOffsetGuard().isBlocked()); + assertEquals(2, haService.getEpochEntries().size()); + assertEquals(1, haService.getEpochEntries().get(0).getEpoch()); + assertEquals(0, haService.getEpochEntries().get(0).getStartOffset()); + assertEquals(4, haService.getEpochEntries().get(1).getEpoch()); + assertEquals(3280, haService.getEpochEntries().get(1).getStartOffset()); + } finally { + haService.shutdown(); + } + } + + @Test + public void testNonemptyLogWithoutEpochHistoryCannotInitializeHA() throws Exception { + for (boolean emptyCheckpoint : new boolean[] {false, true}) { + final Path path = tempFolder.getRoot().toPath().resolve("missing-history-" + emptyCheckpoint); + if (emptyCheckpoint) { + final EpochFileCache cache = new EpochFileCache(path.toString()); + assertTrue(cache.truncateSuffixByOffset(0)); + } + try { + new AutoSwitchHAService().init(mockMessageStore(path.toString(), 1000)); + fail("A nonempty log without its history must not initialize HA"); + } catch (IOException expected) { + assertTrue(expected.getMessage().contains("no epoch history")); + } + } + } + + @Test + public void testSlaveRolePathsPublishExpectedEpochBeforeStartingTheClient() throws Exception { + for (boolean sameMaster : new boolean[] {false, true}) { + final DefaultMessageStore messageStore = mockMessageStore(epochFilePath(), 0); + final AutoSwitchHAService haService = new AutoSwitchHAService(); + haService.init(messageStore); + final AutoSwitchHAClient client = mock(AutoSwitchHAClient.class); + final Field clientField = AutoSwitchHAService.class.getDeclaredField("haClient"); + clientField.setAccessible(true); + clientField.set(haService, client); + try { + final boolean changed = sameMaster ? haService.changeToSlaveWhenMasterNotChange("new-master", 2) + : haService.changeToSlave("new-master", 2, 1L); + assertTrue(changed); + + final InOrder order = inOrder(client, messageStore); + order.verify(client).reOpen(); + order.verify(client).updateMasterAddress("new-master"); + order.verify(client).updateHaMasterAddress(null); + order.verify(messageStore).setStateMachineVersion(2); + order.verify(client).start(); + } finally { + haService.shutdown(); + } + } + } + private String epochFilePath() { return new File(tempFolder.getRoot(), "EpochFileCache").getAbsolutePath(); } @@ -165,4 +315,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/AutoSwitchHAStateValidationTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAStateValidationTest.java index c7ed78058d3..1178724fef2 100644 --- a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAStateValidationTest.java +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAStateValidationTest.java @@ -16,24 +16,39 @@ */ package org.apache.rocketmq.store.ha.autoswitch; +import java.io.IOException; import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; 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.assertTrue; +import static org.junit.Assert.fail; +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 AutoSwitchHAStateValidationTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void testServerReaderRejectsUnknownSlaveStateOrdinal() throws Exception { @@ -91,6 +106,243 @@ public void testClientReaderHandlesKnownMasterStateOrdinals() throws Exception { HAConnectionState.TRANSFER.ordinal(), AutoSwitchHAConnection.TRANSFER_HEADER_SIZE)); } + @Test + public void testTruncateSlaveLogProtectsConfirmOffset() throws Exception { + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + when(haService.getConfirmedOffsetGuard()).thenReturn(new ConfirmedOffsetGuard( + temporaryFolder.getRoot().toPath().resolve("confirmed-offset-guard"))); + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig()); + when(messageStore.getConfirmOffset()).thenReturn(1024L); + + AutoSwitchHAClient client = new AutoSwitchHAClient(haService, messageStore, new EpochFileCache(), 1L); + try { + assertFalse(client.truncateSlaveLog(1023L)); + verify(messageStore, never()).truncateFiles(anyLong()); + } finally { + client.shutdown(); + } + } + + @Test + public void testClientHandshakeAtConfirmOffset() throws Exception { + long confirmOffset = 1024L; + int epoch = 1; + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + when(haService.getConfirmedOffsetGuard()).thenReturn(new ConfirmedOffsetGuard( + temporaryFolder.getRoot().toPath().resolve("confirmed-offset-guard"))); + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig()); + when(messageStore.getConfirmOffset()).thenReturn(confirmOffset); + when(messageStore.getMaxPhyOffset()).thenReturn(confirmOffset); + when(messageStore.truncateFiles(confirmOffset)).thenReturn(true); + EpochFileCache epochCache = new EpochFileCache(); + epochCache.initCacheFromEntries(Collections.singletonList(new EpochEntry(epoch, 0L))); + + AutoSwitchHAClient client = new AutoSwitchHAClient(haService, messageStore, epochCache, 1L); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + 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(confirmOffset); + frame.putInt(epoch); + frame.putInt(epoch); + frame.putLong(0L); + + assertTrue(client.new HAClientReader().processReadResult(frame)); + assertEquals(HAConnectionState.TRANSFER, client.getCurrentState()); + verify(messageStore).truncateFiles(confirmOffset); + } finally { + client.shutdown(); + } + } + + @Test + public void testHandshakeRefusalSurvivesClientReplacementAndMasterGrowth() throws Exception { + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig()); + when(messageStore.getConfirmOffset()).thenReturn(1024L); + when(messageStore.getMaxPhyOffset()).thenReturn(1024L); + java.nio.file.Path guardFile = temporaryFolder.getRoot().toPath().resolve("confirmed-offset-guard"); + when(haService.getConfirmedOffsetGuard()).thenReturn(new ConfirmedOffsetGuard(guardFile)); + EpochFileCache epochCache = new EpochFileCache(); + epochCache.initCacheFromEntries(Collections.singletonList(new EpochEntry(1, 0L))); + + AutoSwitchHAClient client = new AutoSwitchHAClient(haService, messageStore, epochCache, 1L); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + assertFalse(client.new HAClientReader().processReadResult(handshake(1, 512L))); + assertEquals(HAConnectionState.HANDSHAKE, client.getCurrentState()); + assertEquals(0L, reportedOffset(client)); + verify(messageStore, never()).truncateFiles(anyLong()); + } finally { + client.shutdown(); + } + + when(haService.getConfirmedOffsetGuard()).thenReturn(new ConfirmedOffsetGuard(guardFile)); + client = new AutoSwitchHAClient(haService, messageStore, epochCache, 1L); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + assertFalse(client.new HAClientReader().processReadResult(handshake(1, 2048L))); + assertEquals(HAConnectionState.HANDSHAKE, client.getCurrentState()); + assertEquals(0L, reportedOffset(client)); + verify(messageStore, never()).truncateFiles(anyLong()); + } finally { + client.shutdown(); + } + } + + @Test + public void testEmptyEpochCacheDoesNotBypassPersistedRefusal() throws Exception { + ConfirmedOffsetGuard guard = new ConfirmedOffsetGuard( + temporaryFolder.getRoot().toPath().resolve("confirmed-offset-guard")); + guard.recordRefusal("127.0.0.1:10001", 1, 512, 1024); + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(haService.getConfirmedOffsetGuard()).thenReturn(guard); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig()); + AutoSwitchHAClient client = new AutoSwitchHAClient(haService, messageStore, new EpochFileCache(), 1L); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + assertFalse(client.new HAClientReader().processReadResult(handshake(2, 2048))); + assertEquals(HAConnectionState.HANDSHAKE, client.getCurrentState()); + assertEquals(0L, reportedOffset(client)); + verify(messageStore, never()).truncateFiles(anyLong()); + } finally { + client.shutdown(); + } + } + + private ByteBuffer handshake(int epoch, long maxOffset) { + 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(maxOffset); + frame.putInt(epoch); + frame.putInt(epoch); + frame.putLong(0L); + return frame; + } + + @Test + public void testEmptyReplicaCanJoinAfterAnEmptyMasterEpochWasReplaced() throws Exception { + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(haService.getConfirmedOffsetGuard()).thenReturn(new ConfirmedOffsetGuard( + temporaryFolder.getRoot().toPath().resolve("confirmed-offset-guard"))); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig()); + String epochPath = temporaryFolder.getRoot().toPath().resolve("epoch").toString(); + EpochFileCache cache = new EpochFileCache(epochPath); + assertTrue(cache.appendEntry(new EpochEntry(1, 0))); + AutoSwitchHAClient client = new AutoSwitchHAClient(haService, messageStore, cache, 1L); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + assertTrue(client.new HAClientReader().processReadResult(handshake(2, 1024))); + assertEquals(HAConnectionState.TRANSFER, client.getCurrentState()); + EpochFileCache recovered = new EpochFileCache(epochPath); + assertTrue(recovered.initCacheFromFile()); + assertEquals(0, recovered.getEntrySize()); + } finally { + client.shutdown(); + } + } + + @Test + public void testEpochPersistedAheadOfDataCannotAdvanceAcknowledgedOffset() throws Exception { + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(haService.getConfirmedOffsetGuard()).thenReturn(new ConfirmedOffsetGuard( + temporaryFolder.getRoot().toPath().resolve("guard"))); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig()); + when(messageStore.getMaxPhyOffset()).thenReturn(1000L); + when(messageStore.getConfirmOffset()).thenReturn(1000L); + when(messageStore.truncateFiles(1000L)).thenReturn(true); + String epochPath = temporaryFolder.getRoot().toPath().resolve("epoch").toString(); + EpochFileCache cache = new EpochFileCache(epochPath); + cache.initCacheFromEntries(Arrays.asList(new EpochEntry(1, 0), new EpochEntry(2, 1580))); + AutoSwitchHAClient client = new AutoSwitchHAClient(haService, messageStore, cache, 1L); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + ByteBuffer frame = ByteBuffer.allocate(AutoSwitchHAConnection.HANDSHAKE_HEADER_SIZE + + 2 * AutoSwitchHAConnection.EPOCH_ENTRY_SIZE); + frame.putInt(HAConnectionState.HANDSHAKE.ordinal()); + frame.putInt(2 * AutoSwitchHAConnection.EPOCH_ENTRY_SIZE); + frame.putLong(4190L); + frame.putInt(2); + frame.putInt(1).putLong(0); + frame.putInt(2).putLong(1580); + + assertTrue(client.new HAClientReader().processReadResult(frame)); + assertEquals(HAConnectionState.TRANSFER, client.getCurrentState()); + assertEquals(1000L, reportedOffset(client)); + verify(messageStore).truncateFiles(1000L); + verify(messageStore, never()).truncateFiles(4190L); + EpochFileCache restored = new EpochFileCache(epochPath); + assertTrue(restored.initCacheFromFile()); + assertEquals(1, restored.getEntrySize()); + assertEquals(1, restored.lastEpoch()); + } finally { + client.shutdown(); + } + } + + @Test + public void testBlockedClientRetriesPersistingTheFirstRefusal() throws Exception { + Path parent = temporaryFolder.getRoot().toPath().resolve("guard-parent"); + Path guardPath = parent.resolve("guard"); + ConfirmedOffsetGuard guard = new ConfirmedOffsetGuard(guardPath); + Files.createFile(parent); + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(haService.getConfirmedOffsetGuard()).thenReturn(guard); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig()); + when(messageStore.getConfirmOffset()).thenReturn(1024L); + AutoSwitchHAClient client = new AutoSwitchHAClient(haService, messageStore, new EpochFileCache(), 1L); + try { + try { + client.truncateSlaveLog(512L); + fail("The first refusal cannot be persisted below a regular file"); + } catch (IOException expected) { + assertTrue(guard.isBlocked()); + } + Files.delete(parent); + Files.createDirectory(parent); + + assertFalse(client.truncateSlaveLog(2048L)); + ConfirmedOffsetGuard restored = new ConfirmedOffsetGuard(guardPath); + assertTrue(restored.isBlocked()); + assertTrue(restored.describe().contains("observedOffset=512")); + assertTrue(restored.describe().contains("confirmOffset=1024")); + verify(messageStore, never()).truncateFiles(anyLong()); + } finally { + client.shutdown(); + } + } + + private long reportedOffset(AutoSwitchHAClient client) throws Exception { + Field field = AutoSwitchHAClient.class.getDeclaredField("currentReportedOffset"); + field.setAccessible(true); + return field.getLong(client); + } + private boolean processMasterState(int stateOrdinal, int headerSize) throws Exception { AutoSwitchHAService haService = mock(AutoSwitchHAService.class); DefaultMessageStore messageStore = mock(DefaultMessageStore.class); diff --git a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/ConfirmedOffsetGuardTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/ConfirmedOffsetGuardTest.java new file mode 100644 index 00000000000..b92393d56f1 --- /dev/null +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/ConfirmedOffsetGuardTest.java @@ -0,0 +1,163 @@ +/* + * 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.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class ConfirmedOffsetGuardTest { + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + @Test + public void testMissingRecordDoesNotBlock() throws Exception { + final Path stateFile = stateFile(); + final ConfirmedOffsetGuard guard = new ConfirmedOffsetGuard(stateFile); + + assertFalse(guard.isBlocked()); + assertFalse(Files.exists(stateFile)); + } + + @Test + public void testRefusalSurvivesRestart() throws Exception { + final Path stateFile = stateFile(); + final ConfirmedOffsetGuard guard = new ConfirmedOffsetGuard(stateFile); + guard.recordRefusal("master-\u00e9:10912", 1, 1580, 3280); + + final ConfirmedOffsetGuard restored = new ConfirmedOffsetGuard(stateFile); + assertTrue(guard.isBlocked()); + assertTrue(restored.isBlocked()); + assertEquals(guard.describe(), restored.describe()); + assertTrue(restored.describe().contains("observedOffset=1580")); + assertTrue(restored.describe().contains("confirmOffset=3280")); + } + + @Test + public void testLaterRefusalKeepsFirstEvidence() throws Exception { + final Path stateFile = stateFile(); + final ConfirmedOffsetGuard guard = new ConfirmedOffsetGuard(stateFile); + guard.recordRefusal("first-master:10912", 1, 1580, 3280); + final byte[] originalRecord = Files.readAllBytes(stateFile); + final String originalDescription = guard.describe(); + + guard.recordRefusal("new-master:10912", 2, 4190, 5000); + assertEquals(originalDescription, guard.describe()); + assertArrayEquals(originalRecord, Files.readAllBytes(stateFile)); + + final ConfirmedOffsetGuard restored = new ConfirmedOffsetGuard(stateFile); + restored.recordRefusal("another-master:10912", 3, 6000, 7000); + assertEquals(originalDescription, restored.describe()); + assertArrayEquals(originalRecord, Files.readAllBytes(stateFile)); + } + + @Test + public void testEmptyRecordIsRejected() throws Exception { + final Path stateFile = Files.createFile(stateFile()); + assertInvalidRecord(stateFile); + } + + @Test + public void testCorruptedRecordIsRejected() throws Exception { + final Path stateFile = stateFile(); + final ConfirmedOffsetGuard guard = new ConfirmedOffsetGuard(stateFile); + guard.recordRefusal("master:10912", 1, 1580, 3280); + + final String record = new String(Files.readAllBytes(stateFile), StandardCharsets.UTF_8); + Files.write(stateFile, record.replace("1580", "1581").getBytes(StandardCharsets.UTF_8)); + assertInvalidRecord(stateFile); + } + + @Test + public void testTruncatedRecordIsRejected() throws Exception { + final Path stateFile = stateFile(); + final ConfirmedOffsetGuard guard = new ConfirmedOffsetGuard(stateFile); + guard.recordRefusal("master:10912", 1, 1580, 3280); + + final byte[] record = Files.readAllBytes(stateFile); + Files.write(stateFile, Arrays.copyOf(record, record.length - 5)); + assertInvalidRecord(stateFile); + } + + @Test + public void testUnknownVersionIsRejected() throws Exception { + final Path stateFile = stateFile(); + final ConfirmedOffsetGuard guard = new ConfirmedOffsetGuard(stateFile); + guard.recordRefusal("master:10912", 1, 1580, 3280); + + final String record = new String(Files.readAllBytes(stateFile), StandardCharsets.UTF_8); + Files.write(stateFile, record.replace("guard-v1", "guard-v2").getBytes(StandardCharsets.UTF_8)); + assertInvalidRecord(stateFile); + } + + @Test + public void testFailedWriteKeepsFirstRefusalAndCanRetry() throws Exception { + final Path parent = tempFolder.getRoot().toPath().resolve("parent"); + final Path stateFile = parent.resolve("guard"); + final ConfirmedOffsetGuard guard = new ConfirmedOffsetGuard(stateFile); + Files.createFile(parent); + + try { + guard.recordRefusal("first-master:10912", 1, 1580, 3280); + fail("Writing below a regular file must fail"); + } catch (IOException expected) { + assertTrue(guard.isBlocked()); + } + assertTrue(guard.describe().contains("persisted=false")); + + Files.delete(parent); + Files.createDirectory(parent); + guard.recordRefusal("new-master:10912", 2, 4190, 5000); + + final ConfirmedOffsetGuard restored = new ConfirmedOffsetGuard(stateFile); + assertTrue(restored.isBlocked()); + assertEquals(guard.describe(), restored.describe()); + assertTrue(restored.describe().contains("source=first-master:10912")); + assertTrue(restored.describe().contains("observedOffset=1580")); + assertTrue(restored.describe().contains("confirmOffset=3280")); + } + + @Test + public void testDirectoryIsNotTreatedAsMissingRecord() throws Exception { + final Path stateFile = Files.createDirectory(stateFile()); + assertInvalidRecord(stateFile); + } + + private Path stateFile() { + return tempFolder.getRoot().toPath().resolve("confirmed-offset-guard"); + } + + private void assertInvalidRecord(Path stateFile) throws Exception { + try { + new ConfirmedOffsetGuard(stateFile); + fail("The invalid guard record must prevent loading"); + } catch (IOException expected) { + assertTrue(Files.exists(stateFile)); + } + } +} diff --git a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/EpochFileCacheDurabilityTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/EpochFileCacheDurabilityTest.java new file mode 100644 index 00000000000..19259443c46 --- /dev/null +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/EpochFileCacheDurabilityTest.java @@ -0,0 +1,205 @@ +/* + * 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.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.apache.rocketmq.common.utils.CheckpointFile; +import org.apache.rocketmq.remoting.protocol.EpochEntry; +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.junit.Assert.fail; + +public class EpochFileCacheDurabilityTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void testRecoveredBoundarySurvivesGrowthAndReloadBeforeFirstHandshake() throws Exception { + final Path path = epochPath(); + final EpochFileCache master = new EpochFileCache(path.toString()); + master.prepareMasterEpoch(1, 0); + master.prepareMasterEpoch(2, 1580); + + final EpochFileCache follower = new EpochFileCache(); + follower.initCacheFromEntries(Collections.singletonList(new EpochEntry(1, 0, 3280))); + + // The follower first connects only after the restarted master has written past its old end. + master.setLastEpochEntryEndOffset(4190); + assertEquals(1580, follower.findConsistentPoint(master)); + assertEquals(1580, master.prepareMasterEpoch(2, 4190).getStartOffset()); + + final EpochFileCache reloaded = reload(path); + reloaded.setLastEpochEntryEndOffset(4190); + assertEquals(1580, follower.findConsistentPoint(reloaded)); + assertEquals(1580, reloaded.getEntry(1).getEndOffset()); + } + + @Test + public void testNewEpochReplacesAllLostAndEmptyTailEntries() throws Exception { + final Path path = epochPath(); + final EpochFileCache cache = new EpochFileCache(path.toString()); + cache.initCacheFromEntries(Arrays.asList(new EpochEntry(1, 0), new EpochEntry(2, 100), + new EpochEntry(3, 200))); + + cache.prepareMasterEpoch(4, 100); + + final EpochFileCache reloaded = reload(path); + assertEquals(2, reloaded.getEntrySize()); + assertEquals(100, reloaded.getEntry(1).getEndOffset()); + assertNull(reloaded.getEntry(2)); + assertNull(reloaded.getEntry(3)); + assertEquals(new EpochEntry(4, 100), reloaded.lastEntry()); + } + + @Test + public void testRepeatedZeroWriteStartupsAndRecoveryToZero() throws Exception { + final Path path = epochPath(); + EpochFileCache cache = new EpochFileCache(path.toString()); + cache.prepareMasterEpoch(1, 0); + cache.prepareMasterEpoch(2, 100); + cache.prepareMasterEpoch(3, 0); + cache = reload(path); + assertEquals(Collections.singletonList(new EpochEntry(3, 0)), cache.getAllEntries()); + + cache.prepareMasterEpoch(4, 0); + cache.prepareMasterEpoch(4, 0); + assertEquals(Collections.singletonList(new EpochEntry(4, 0)), reload(path).getAllEntries()); + } + + @Test + public void testStaleMasterGrantCannotChangeTheHistory() throws Exception { + final Path path = epochPath(); + final EpochFileCache cache = new EpochFileCache(path.toString()); + cache.prepareMasterEpoch(3, 0); + try { + cache.prepareMasterEpoch(2, 100); + fail("A stale master epoch must be rejected"); + } catch (IOException expected) { + assertEquals(Collections.singletonList(new EpochEntry(3, 0)), reload(path).getAllEntries()); + } + } + + @Test + public void testFailedPersistenceDoesNotPublishAppendedOrTruncatedHistory() throws Exception { + final Path path = epochPath(); + final EpochFileCache cache = new EpochFileCache(path.toString()); + cache.initCacheFromEntries(Arrays.asList(new EpochEntry(1, 0), new EpochEntry(2, 100))); + final List original = cache.getAllEntries(); + + // Replacing a directory with a file fails even when the tests run with privileged access. + Files.delete(path); + Files.createDirectory(path); + assertFalse(cache.appendEntry(new EpochEntry(3, 200))); + assertEquals(original, cache.getAllEntries()); + assertFalse(cache.truncateSuffixByOffset(100)); + assertEquals(original, cache.getAllEntries()); + assertFalse(cache.truncateSuffixByEpoch(2)); + assertEquals(original, cache.getAllEntries()); + assertFalse(cache.truncatePrefixByOffset(100)); + assertEquals(original, cache.getAllEntries()); + + for (int epoch : new int[] {2, 3}) { + try { + cache.prepareMasterEpoch(epoch, 200); + fail("A master grant cannot succeed without persisting its boundary"); + } catch (IOException expected) { + assertEquals(original, cache.getAllEntries()); + } + } + } + + @Test + public void testPersistedEmptyHistoryDoesNotRestoreAnOlderBackup() throws Exception { + final Path path = epochPath(); + final EpochFileCache cache = new EpochFileCache(path.toString()); + cache.prepareMasterEpoch(1, 0); + Files.copy(path, path.resolveSibling(path.getFileName() + ".bak")); + + assertTrue(cache.truncateSuffixByOffset(0)); + assertEquals(0, reload(path).getEntrySize()); + + Files.delete(path); + assertFalse(new EpochFileCache(path.toString()).initCacheFromFile()); + } + + @Test + public void testCorruptPrimaryDoesNotRestoreAnOlderBackup() throws Exception { + final Path path = epochPath(); + final EpochFileCache cache = new EpochFileCache(path.toString()); + cache.prepareMasterEpoch(1, 0); + Files.copy(path, path.resolveSibling(path.getFileName() + ".bak")); + Files.write(path, "1\n".getBytes(StandardCharsets.UTF_8)); + + assertFalse(cache.initCacheFromFile()); + assertEquals(Collections.singletonList(new EpochEntry(1, 0)), cache.getAllEntries()); + assertFalse(new EpochFileCache(path.toString()).initCacheFromFile()); + } + + @Test + public void testValidChecksumDoesNotAllowInvalidEpochOrdering() throws Exception { + final Path path = epochPath(); + final CheckpointFile checkpoint = new CheckpointFile<>(path.toString(), + new EpochFileCache.EpochEntrySerializer()); + final List> invalidHistories = Arrays.asList( + Arrays.asList(new EpochEntry(1, 0), new EpochEntry(1, 100)), + Arrays.asList(new EpochEntry(2, 0), new EpochEntry(1, 100)), + Arrays.asList(new EpochEntry(1, 100), new EpochEntry(2, 100)), + Arrays.asList(new EpochEntry(1, 100), new EpochEntry(2, 0)), + Collections.singletonList(new EpochEntry(1, -1))); + for (List entries : invalidHistories) { + checkpoint.writeAtomically(entries); + assertFalse(new EpochFileCache(path.toString()).initCacheFromFile()); + } + } + + @Test + public void testZeroChecksumCannotDisableHistoryValidation() throws Exception { + final Path path = epochPath(); + Files.write(path, ("1" + System.lineSeparator() + "0" + System.lineSeparator() + + "1-0" + System.lineSeparator()).getBytes(StandardCharsets.UTF_8)); + assertFalse(new EpochFileCache(path.toString()).initCacheFromFile()); + } + + @Test + public void testMissingHistoryIsAcceptedForANewStore() { + final EpochFileCache cache = new EpochFileCache(epochPath().toString()); + assertTrue(cache.initCacheFromFile()); + assertEquals(0, cache.getEntrySize()); + } + + private Path epochPath() { + return temporaryFolder.getRoot().toPath().resolve("epoch"); + } + + private EpochFileCache reload(Path path) { + final EpochFileCache cache = new EpochFileCache(path.toString()); + assertTrue(cache.initCacheFromFile()); + return cache; + } +}