Repository navigation
Fix subscription replay after leader failover #19535
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,380 @@ | ||
| /* | ||
| * 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.iotdb.subscription.it.consensus.local.tablemodel; | ||
|
|
||
| import org.apache.iotdb.commons.consensus.DataRegionId; | ||
| import org.apache.iotdb.commons.schema.column.ColumnHeaderConstant; | ||
| import org.apache.iotdb.consensus.ConsensusFactory; | ||
| import org.apache.iotdb.isession.ITableSession; | ||
| import org.apache.iotdb.isession.SessionConfig; | ||
| import org.apache.iotdb.it.env.EnvFactory; | ||
| import org.apache.iotdb.it.env.cluster.config.MppBaseConfig; | ||
| import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper; | ||
| import org.apache.iotdb.it.framework.IoTDBTestRunner; | ||
| import org.apache.iotdb.itbase.category.TableClusterIT; | ||
| import org.apache.iotdb.itbase.env.BaseEnv; | ||
| import org.apache.iotdb.rpc.UrlUtils; | ||
| import org.apache.iotdb.session.TableSessionBuilder; | ||
| import org.apache.iotdb.session.subscription.consumer.table.SubscriptionTablePullConsumer; | ||
| import org.apache.iotdb.session.subscription.consumer.table.SubscriptionTablePullConsumerBuilder; | ||
| import org.apache.iotdb.subscription.it.AbstractSubscriptionIT; | ||
|
|
||
| import org.awaitility.Awaitility; | ||
| import org.junit.After; | ||
| import org.junit.Assert; | ||
| import org.junit.Before; | ||
| import org.junit.Test; | ||
| import org.junit.experimental.categories.Category; | ||
| import org.junit.runner.RunWith; | ||
|
|
||
| import java.sql.Connection; | ||
| import java.sql.ResultSet; | ||
| import java.sql.SQLException; | ||
| import java.sql.Statement; | ||
| import java.time.Duration; | ||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.LinkedHashSet; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Properties; | ||
| import java.util.Set; | ||
| import java.util.concurrent.atomic.AtomicReference; | ||
| import java.util.regex.Matcher; | ||
| import java.util.regex.Pattern; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| @RunWith(IoTDBTestRunner.class) | ||
| @Category({TableClusterIT.class}) | ||
| public class IoTDBConsensusSubscriptionLeaderFailoverTableIT extends AbstractSubscriptionIT { | ||
|
|
||
| private static final Pattern IOT_CONSENSUS_METRIC_PATTERN = | ||
| Pattern.compile("iot_consensus\\{([^}]*)}\\s+(\\S+)"); | ||
|
|
||
| @Override | ||
| @Before | ||
| public void setUp() throws Exception { | ||
| super.setUp(); | ||
| EnvFactory.getEnv() | ||
| .getConfig() | ||
| .getCommonConfig() | ||
| .setConfigNodeConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS) | ||
| .setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS) | ||
| .setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS) | ||
| .setSchemaReplicationFactor(1) | ||
| .setDataReplicationFactor(3) | ||
| .setDefaultDataRegionGroupNumPerDatabase(1) | ||
| .setAutoCreateSchemaEnabled(true) | ||
| .setPipeMemoryManagementEnabled(false) | ||
| .setIsPipeEnableMemoryCheck(false); | ||
|
|
||
| final Properties dataNodeProperties = new Properties(); | ||
| dataNodeProperties.setProperty("subscription_enabled", "true"); | ||
| dataNodeProperties.setProperty("subscription_consensus_commit_persist_interval", "1"); | ||
| dataNodeProperties.setProperty("subscription_consensus_commit_fsync_enabled", "true"); | ||
| ((MppBaseConfig) EnvFactory.getEnv().getConfig().getDataNodeCommonConfig()) | ||
| .updateProperties(dataNodeProperties); | ||
| EnvFactory.getEnv() | ||
| .getConfig() | ||
| .getDataNodeConfig() | ||
| .setMetricReporterType(Collections.singletonList("PROMETHEUS")); | ||
| EnvFactory.getEnv().initClusterEnvironment(1, 3); | ||
| } | ||
|
|
||
| @Override | ||
| @After | ||
| public void tearDown() throws Exception { | ||
| try { | ||
| EnvFactory.getEnv().cleanClusterEnvironment(); | ||
| } finally { | ||
| super.tearDown(); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| public void testSubscriptionContinuesAfterRepeatedKill9RegionLeaderFailovers() throws Exception { | ||
| final ConsensusSubscriptionTableITSupport.TestIdentifiers ids = | ||
| ConsensusSubscriptionTableITSupport.newIdentifiers("leader_kill_9"); | ||
| final String tableName = "t1"; | ||
| SubscriptionTablePullConsumer consumer = null; | ||
|
|
||
| try { | ||
| ConsensusSubscriptionTableITSupport.bootstrapDatabaseAndTable( | ||
| ids.getDatabase(), tableName, ConsensusSubscriptionTableITSupport.DEFAULT_TABLE_SCHEMA); | ||
| ConsensusSubscriptionTableITSupport.createConsensusTopic(ids.getTopic(), ".*", ".*"); | ||
| consumer = createConsumer(ids); | ||
| consumer.subscribe(ids.getTopic()); | ||
|
|
||
| final Set<String> baselineRows = | ||
| ConsensusSubscriptionTableITSupport.insertRows( | ||
| ids.getDatabase(), tableName, 1_000L, 16, true); | ||
| ConsensusSubscriptionTableITSupport.pollAndCommitUntilContains(consumer, baselineRows, 90); | ||
|
|
||
| final Set<String> rowsBeforeFailover = | ||
| ConsensusSubscriptionTableITSupport.insertRows( | ||
| ids.getDatabase(), tableName, 2_000L, 32, true); | ||
| final DataNodeWrapper queryNode = EnvFactory.getEnv().getDataNodeWrapperList().get(0); | ||
| final Map<Integer, DataNodeWrapper> regionLeaders = | ||
| awaitDataRegionLeaders(ids.getDatabase(), queryNode); | ||
| final Map.Entry<Integer, DataNodeWrapper> targetRegionLeader = | ||
| regionLeaders.entrySet().iterator().next(); | ||
| final int targetRegionId = targetRegionLeader.getKey(); | ||
| final DataNodeWrapper oldLeader = targetRegionLeader.getValue(); | ||
| awaitRegionReplicationOnSurvivingReplicas(oldLeader, targetRegionId); | ||
| oldLeader.stopForcibly(); | ||
| Assert.assertFalse("The killed DataNode process is still alive", oldLeader.isAlive()); | ||
|
|
||
| final DataNodeWrapper survivingNode = | ||
| EnvFactory.getEnv().getDataNodeWrapperList().stream() | ||
| .filter(DataNodeWrapper::isAlive) | ||
| .findFirst() | ||
| .orElseThrow(() -> new AssertionError("No DataNode survived the forced stop")); | ||
| final DataNodeWrapper newLeader = | ||
| awaitRegionLeaderAfterFailover( | ||
| ids.getDatabase(), survivingNode, targetRegionId, oldLeader); | ||
| final Set<String> rowsAfterFailover = | ||
| insertRows(newLeader, ids.getDatabase(), tableName, 3_000L, 32); | ||
| awaitRegionReplicationOnSurvivingReplicas(newLeader, targetRegionId); | ||
| newLeader.stopForcibly(); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. minor IoTConsensusServerImpl.write returns after the local state-machine write and replicates asynchronously afterwards. rowsAfterFailover (line 141) and rowsBeforeFailover are part of expectedRows, yet stopForcibly() runs immediately after insertRows returns, so entries not yet shipped to a surviving replica are lost and the final containsAll assertion fails intermittently. Fix: Wait until a surviving replica has applied those entries (e.g. poll its subscription progress/search index) before stopForcibly(), or flush and pause before killing.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added a bounded wait before each forced stop. It compares the leader searchIndex with the per-peer currentSyncIndex for every surviving replica, so each pre-stop batch is replicated before the next failover. The targeted 1C3D integration test passes. |
||
| Assert.assertFalse("The killed DataNode process is still alive", newLeader.isAlive()); | ||
|
|
||
| final DataNodeWrapper secondSurvivingNode = | ||
| EnvFactory.getEnv().getDataNodeWrapperList().stream() | ||
| .filter(DataNodeWrapper::isAlive) | ||
| .findFirst() | ||
| .orElseThrow(() -> new AssertionError("No DataNode survived the second forced stop")); | ||
| awaitRegionLeaderAfterFailover( | ||
| ids.getDatabase(), secondSurvivingNode, targetRegionId, newLeader); | ||
|
|
||
| final Set<String> expectedRows = new LinkedHashSet<>(rowsBeforeFailover); | ||
| expectedRows.addAll(rowsAfterFailover); | ||
| final ConsensusSubscriptionTableITSupport.ConsumedRecords replayedRows = | ||
| ConsensusSubscriptionTableITSupport.pollAndCommitUntilContains( | ||
| consumer, expectedRows, 120); | ||
| Assert.assertTrue(replayedRows.getRowKeys().containsAll(expectedRows)); | ||
| } finally { | ||
| ConsensusSubscriptionTableITSupport.cleanup(consumer, ids.getTopic(), ids.getDatabase()); | ||
| } | ||
| } | ||
|
|
||
| private static SubscriptionTablePullConsumer createConsumer( | ||
| final ConsensusSubscriptionTableITSupport.TestIdentifiers ids) throws Exception { | ||
| final List<String> nodeUrls = | ||
| EnvFactory.getEnv().getDataNodeWrapperList().stream() | ||
| .map(DataNodeWrapper::getIpAndPortString) | ||
| .collect(Collectors.toList()); | ||
| final SubscriptionTablePullConsumer consumer = | ||
| (SubscriptionTablePullConsumer) | ||
| new SubscriptionTablePullConsumerBuilder() | ||
| .nodeUrls(nodeUrls) | ||
| .consumerId(ids.getConsumerId()) | ||
| .consumerGroupId(ids.getConsumerGroupId()) | ||
| .heartbeatIntervalMs(1_000L) | ||
| .endpointsSyncIntervalMs(1_000L) | ||
| .autoCommit(false) | ||
| .build(); | ||
| consumer.open(); | ||
| return consumer; | ||
| } | ||
|
|
||
| private static Map<Integer, DataNodeWrapper> awaitDataRegionLeaders( | ||
| final String database, final DataNodeWrapper queryNode) throws SQLException { | ||
| final AtomicReference<Map<Integer, DataNodeWrapper>> leadersReference = new AtomicReference<>(); | ||
| Awaitility.await() | ||
| .pollInSameThread() | ||
| .atMost(Duration.ofSeconds(60)) | ||
| .untilAsserted( | ||
| () -> { | ||
| final List<String> regionRows = new ArrayList<>(); | ||
| final Map<Integer, DataNodeWrapper> leaders = | ||
| getDataRegionLeaders(database, queryNode, regionRows); | ||
| Assert.assertEquals( | ||
| "Expected DataRegion leaders in SHOW REGIONS rows " + regionRows, | ||
| false, | ||
| leaders.isEmpty()); | ||
| leadersReference.set(leaders); | ||
| }); | ||
| return leadersReference.get(); | ||
| } | ||
|
|
||
| private static DataNodeWrapper awaitRegionLeaderAfterFailover( | ||
| final String database, | ||
| final DataNodeWrapper queryNode, | ||
| final int regionId, | ||
| final DataNodeWrapper oldLeader) | ||
| throws SQLException { | ||
| final AtomicReference<DataNodeWrapper> leaderReference = new AtomicReference<>(); | ||
| Awaitility.await() | ||
| .pollInSameThread() | ||
| .atMost(Duration.ofMinutes(2)) | ||
| .untilAsserted( | ||
| () -> { | ||
| final Map<Integer, DataNodeWrapper> leaders = | ||
| getDataRegionLeaders(database, queryNode, new ArrayList<>()); | ||
| final DataNodeWrapper newLeader = leaders.get(regionId); | ||
| Assert.assertNotNull( | ||
| "Expected an elected leader for DataRegion " + regionId, newLeader); | ||
| Assert.assertNotEquals(oldLeader.getPort(), newLeader.getPort()); | ||
| leaderReference.set(newLeader); | ||
| }); | ||
| return leaderReference.get(); | ||
| } | ||
|
|
||
| private static void awaitRegionReplicationOnSurvivingReplicas( | ||
| final DataNodeWrapper leader, final int regionId) { | ||
| final List<DataNodeWrapper> survivingReplicas = | ||
| EnvFactory.getEnv().getDataNodeWrapperList().stream() | ||
| .filter(DataNodeWrapper::isAlive) | ||
| .filter(node -> node != leader) | ||
| .collect(Collectors.toList()); | ||
| Assert.assertFalse( | ||
| "Expected at least one surviving DataRegion replica", survivingReplicas.isEmpty()); | ||
|
|
||
| final String metricsUrl = | ||
| "http://" | ||
| + UrlUtils.formatTEndPointIpv4AndIpv6Url(leader.getIp(), leader.getMetricPort()) | ||
| + "/metrics"; | ||
| final String consensusGroupId = new DataRegionId(regionId).toString(); | ||
| Awaitility.await() | ||
| .pollInterval(Duration.ofMillis(500)) | ||
| .atMost(Duration.ofMinutes(2)) | ||
| .untilAsserted( | ||
| () -> { | ||
| final String metrics = EnvFactory.getEnv().getUrlContent(metricsUrl, null); | ||
| Assert.assertNotNull("Failed to fetch metrics from DataRegion leader", metrics); | ||
| final double searchIndex = | ||
| findIoTConsensusMetricValue( | ||
| metrics, consensusGroupId, "ioTConsensusServerImpl", "searchIndex"); | ||
| Assert.assertFalse( | ||
| "Missing IoTConsensus searchIndex metric for " + consensusGroupId, | ||
| Double.isNaN(searchIndex)); | ||
| for (final DataNodeWrapper replica : survivingReplicas) { | ||
| final String dispatcherName = | ||
| "logDispatcher-" + replica.getIp() + ":" + replica.getDataRegionConsensusPort(); | ||
| final double currentSyncIndex = | ||
| findIoTConsensusMetricValue( | ||
| metrics, consensusGroupId, dispatcherName, "currentSyncIndex"); | ||
| Assert.assertFalse( | ||
| "Missing IoTConsensus replication metric for " + dispatcherName, | ||
| Double.isNaN(currentSyncIndex)); | ||
| Assert.assertTrue( | ||
| "Replica " | ||
| + dispatcherName | ||
| + " is behind the leader search index " | ||
| + searchIndex | ||
| + " at " | ||
| + currentSyncIndex, | ||
| currentSyncIndex >= searchIndex); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| private static double findIoTConsensusMetricValue( | ||
| final String metrics, final String consensusGroupId, final String name, final String type) { | ||
| final Matcher matcher = IOT_CONSENSUS_METRIC_PATTERN.matcher(metrics); | ||
| while (matcher.find()) { | ||
| final String labels = matcher.group(1); | ||
| if (labels.contains("region=\"" + consensusGroupId + "\"") | ||
| && labels.contains("name=\"" + name + "\"") | ||
| && labels.contains("type=\"" + type + "\"")) { | ||
| return Double.parseDouble(matcher.group(2)); | ||
| } | ||
| } | ||
| return Double.NaN; | ||
| } | ||
|
|
||
| private static Map<Integer, DataNodeWrapper> getDataRegionLeaders( | ||
| final String database, final DataNodeWrapper queryNode, final List<String> regionRows) | ||
| throws SQLException { | ||
| final Map<Integer, DataNodeWrapper> leaders = new java.util.LinkedHashMap<>(); | ||
| try (final Connection connection = | ||
| EnvFactory.getEnv() | ||
| .getConnection( | ||
| queryNode, | ||
| SessionConfig.DEFAULT_USER, | ||
| SessionConfig.DEFAULT_PASSWORD, | ||
| BaseEnv.TABLE_SQL_DIALECT); | ||
| final Statement statement = connection.createStatement(); | ||
| final ResultSet resultSet = statement.executeQuery("SHOW REGIONS")) { | ||
| final int typeIndex = resultSet.findColumn(ColumnHeaderConstant.TYPE); | ||
| final int databaseIndex = resultSet.findColumn(ColumnHeaderConstant.DATABASE); | ||
| final int regionIdIndex = resultSet.findColumn(ColumnHeaderConstant.REGION_ID); | ||
| final int rpcAddressIndex = resultSet.findColumn(ColumnHeaderConstant.RPC_ADDRESS); | ||
| final int rpcPortIndex = resultSet.findColumn(ColumnHeaderConstant.RPC_PORT); | ||
| final int roleIndex = resultSet.findColumn(ColumnHeaderConstant.ROLE); | ||
| while (resultSet.next()) { | ||
| final String type = resultSet.getString(typeIndex); | ||
| final String databaseName = resultSet.getString(databaseIndex); | ||
| final String role = resultSet.getString(roleIndex); | ||
| regionRows.add( | ||
| String.format( | ||
| "type=%s,database=%s,role=%s,rpcAddress=%s,rpcPort=%s", | ||
| type, | ||
| databaseName, | ||
| role, | ||
| resultSet.getString(rpcAddressIndex), | ||
| resultSet.getString(rpcPortIndex))); | ||
| if (!"DataRegion".equalsIgnoreCase(type) | ||
| || !database.equals(databaseName) | ||
| || !"Leader".equalsIgnoreCase(role)) { | ||
| continue; | ||
| } | ||
|
|
||
| final String rpcAddress = resultSet.getString(rpcAddressIndex); | ||
| final int rpcPort = resultSet.getInt(rpcPortIndex); | ||
| final DataNodeWrapper leader = | ||
| EnvFactory.getEnv().getDataNodeWrapperList().stream() | ||
| .filter(node -> node.getIp().equals(rpcAddress) && node.getPort() == rpcPort) | ||
| .findFirst() | ||
| .orElseThrow( | ||
| () -> | ||
| new AssertionError( | ||
| "No DataNode wrapper matches the DataRegion leader endpoint")); | ||
| leaders.put(resultSet.getInt(regionIdIndex), leader); | ||
| } | ||
| } | ||
| return leaders; | ||
| } | ||
|
|
||
| private static Set<String> insertRows( | ||
| final DataNodeWrapper node, | ||
| final String database, | ||
| final String tableName, | ||
| final long startTimestamp, | ||
| final int rowCount) | ||
| throws Exception { | ||
| final Set<String> rowKeys = new LinkedHashSet<>(); | ||
| try (final ITableSession session = | ||
| new TableSessionBuilder() | ||
| .nodeUrls(Collections.singletonList(node.getIpAndPortString())) | ||
| .build()) { | ||
| session.executeNonQueryStatement("use " + database); | ||
| for (int row = 0; row < rowCount; row++) { | ||
| final long timestamp = startTimestamp + row; | ||
| session.executeNonQueryStatement( | ||
| String.format( | ||
| "insert into %s(tag1, s1, time) values ('%s', %d, %d)", | ||
| tableName, tableName + "_tag", timestamp * 10L, timestamp)); | ||
| rowKeys.add(ConsensusSubscriptionTableITSupport.rowKey(database, tableName, timestamp)); | ||
| } | ||
| } | ||
| return rowKeys; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6090,7 +6090,12 @@ private static boolean isWriterRuntimeActive( | |
| public void applyRuntimeState(final ConsensusRegionRuntimeState runtimeState) { | ||
| Objects.requireNonNull(runtimeState, DataNodeMiscMessages.EXCEPTION_RUNTIMESTATE_D4D018BA); | ||
| synchronized (runtimeActivationLock) { | ||
| final boolean requiresAuthoritativeActivation = runtimeState.isActive() && !isActive; | ||
| final boolean shouldRefreshAuthoritativeProgress = | ||
| runtimeState.getRuntimeVersion() > runtimeVersion | ||
| && commitManager.isConfigNodeProgressAvailable( | ||
| consumerGroupId, topicName, consensusGroupId); | ||
| final boolean requiresAuthoritativeActivation = | ||
| runtimeState.isActive() && (!isActive || shouldRefreshAuthoritativeProgress); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. major
Fix: Only tear down and re-seek when the fetched ConfigNode progress for this (group, topic, region) actually exceeds the queue's committed frontier, so unrelated node-status pushes do not deactivate and fully rescan every active queue. |
||
| if (requiresAuthoritativeActivation) { | ||
| pendingActivationRuntimeState = runtimeState; | ||
| // Keep the worker dormant until every routing field is installed and the authoritative | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
minor
integration-test/src/test/java/org/apache/iotdb/subscription/it/consensus/local/tablemodel/IoTDBConsensusSubscriptionLeaderFailoverTableIT.java:129— New failover IT never reaches the preferredWriterChanged reset branchThe future leader's queue is bound with initialActive = (lastKnownPreferredWriter == myNodeId), i.e. false, so the first state carrying preferredWriterNodeId == itself already satisfies the pre-existing !isActive term and runs the same authoritative refresh/seek. With only one leader change, the new preferredWriterChanged term is never exercised, so this IT passes with or without the queue change.
Fix: Add a second leader change (e.g. also kill the new leader, or re-elect back to the surviving replica) so an already-active queue observes a preferred-writer change, or drive applyRuntimeState twice on an active queue as the unit test does.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added a second forced DataRegion leader failover. The delivery assertion now covers rows queued before that transition and rows written afterward. Spotless and the integration-test selection check pass; the targeted IT was not run locally.