You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iotdb.apache.org by qi...@apache.org on 2022/05/28 09:37:12 UTC
[iotdb] branch master updated: [IOTDB-3188] Multi leader consensus algorithm implementation (#5939)
This is an automated email from the ASF dual-hosted git repository.
qiaojialin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 8f68e51bbe [IOTDB-3188] Multi leader consensus algorithm implementation (#5939)
8f68e51bbe is described below
commit 8f68e51bbe8df13b1d7227fc7db08b6ff91a3b49
Author: Potato <TX...@gmail.com>
AuthorDate: Sat May 28 17:37:08 2022 +0800
[IOTDB-3188] Multi leader consensus algorithm implementation (#5939)
---
.../resources/conf/iotdb-confignode.properties | 12 +-
.../iotdb/confignode/conf/ConfigNodeConf.java | 27 +-
.../confignode/conf/ConfigNodeDescriptor.java | 9 +-
.../confignode/conf/ConfigNodeStartupCheck.java | 83 ++--
.../iotdb/confignode/manager/ConfigManager.java | 15 +-
.../iotdb/confignode/manager/NodeManager.java | 9 +-
.../consensus/request/ConfigRequestSerDeTest.java | 12 +-
.../iotdb/confignode/persistence/NodeInfoTest.java | 3 +-
.../confignode/persistence/PartitionInfoTest.java | 3 +-
.../thrift/ConfigNodeRPCServiceProcessorTest.java | 19 +-
.../confignode1conf/iotdb-confignode.properties | 4 +-
.../confignode2conf/iotdb-confignode.properties | 3 +-
.../confignode3conf/iotdb-confignode.properties | 3 +-
consensus/README.md | 4 +-
consensus/pom.xml | 5 +
.../apache/iotdb/consensus/ConsensusFactory.java | 6 +
.../org/apache/iotdb/consensus/common/Peer.java | 15 +
.../common/request/IndexedConsensusRequest.java | 88 +++++
.../common/response/ConsensusReadResponse.java | 6 +-
.../common/response/ConsensusResponse.java | 2 +-
.../exception/IllegalPeerEndpointException.java | 9 +-
.../exception/IllegalPeerNumException.java | 4 +-
.../MultiLeaderConsensus.java} | 93 +++--
.../multileader/MultiLeaderServerImpl.java | 186 +++++++++
.../client/AsyncMultiLeaderServiceClient.java | 145 +++++++
.../multileader/client/DispatchLogHandler.java | 100 +++++
.../client/MultiLeaderConsensusClientPool.java | 54 +++
.../conf/MultiLeaderConsensusConfig.java | 40 ++
.../multileader/logdispatcher/IndexController.java | 150 ++++++++
.../multileader/logdispatcher/LogDispatcher.java | 299 +++++++++++++++
.../multileader/logdispatcher/PendingBatch.java | 76 ++++
.../multileader/logdispatcher/SyncStatus.java | 89 +++++
.../multileader/service/MultiLeaderRPCService.java | 95 +++++
.../service/MultiLeaderRPCServiceHandler.java} | 34 +-
.../service/MultiLeaderRPCServiceMBean.java} | 11 +-
.../service/MultiLeaderRPCServiceProcessor.java | 82 ++++
.../{ => multileader}/wal/ConsensusReqReader.java | 6 +-
.../wal/GetConsensusReqReaderPlan.java} | 15 +-
.../apache/iotdb/consensus/ratis/RatisClient.java | 9 +-
.../iotdb/consensus/ratis/RatisConsensus.java | 12 +-
.../iotdb/consensus/ratis/RequestMessage.java | 5 +-
.../org/apache/iotdb/consensus/ratis/Utils.java | 14 +-
.../consensus/standalone/StandAloneConsensus.java | 41 +-
.../multileader/MultiLeaderConsensusTest.java | 419 +++++++++++++++++++++
.../logdispatcher/IndexControllerTest.java | 110 ++++++
.../multileader/logdispatcher/SyncStatusTest.java | 211 +++++++++++
.../iotdb/consensus/ratis/RatisConsensusTest.java | 16 +-
.../apache/iotdb/consensus/ratis/SnapshotTest.java | 1 -
.../apache/iotdb/consensus/ratis/TestUtils.java | 16 +-
.../{ => standalone}/EmptyStateMachine.java | 3 +-
.../iotdb/consensus/standalone/RecoveryTest.java | 9 +-
.../standalone/StandAloneConsensusTest.java | 9 +-
.../iotdb/commons/concurrent/ThreadName.java | 2 +
.../iotdb/commons/consensus/ConsensusGroupId.java | 8 +-
.../apache/iotdb/commons/service/ServiceType.java | 3 +-
.../apache/iotdb/commons/ClientManagerTest.java | 5 +-
.../iotdb/commons/partition/SerializeTest.java | 3 +-
.../commons/utils/ThriftCommonsSerDeUtilsTest.java | 6 +-
pom.xml | 2 +
.../resources/conf/iotdb-engine.properties | 7 +-
.../java/org/apache/iotdb/db/conf/IoTDBConfig.java | 87 ++++-
.../org/apache/iotdb/db/conf/IoTDBDescriptor.java | 16 +-
...ensusImpl.java => DataRegionConsensusImpl.java} | 40 +-
...susImpl.java => SchemaRegionConsensusImpl.java} | 40 +-
.../consensus/statemachine/BaseStateMachine.java | 29 +-
.../statemachine/DataRegionStateMachine.java | 56 ++-
.../statemachine/SchemaRegionStateMachine.java | 23 +-
.../plan/planner/plan/node/write/InsertNode.java | 3 +-
.../scheduler/FragmentInstanceDispatcherImpl.java | 31 +-
.../java/org/apache/iotdb/db/service/DataNode.java | 12 +-
.../service/thrift/impl/InternalServiceImpl.java | 59 ++-
.../org/apache/iotdb/db/wal/node/IWALNode.java | 5 +-
.../java/org/apache/iotdb/db/wal/node/WALNode.java | 6 +-
.../mpp/plan/plan/FragmentInstanceSerdeTest.java | 6 +-
.../iotdb/db/service/InternalServiceImplTest.java | 24 +-
.../iotdb/db/wal/node/ConsensusReqReaderTest.java | 2 +-
.../datanode1conf/iotdb-engine.properties | 3 +-
.../datanode2conf/iotdb-engine.properties | 3 +-
.../datanode3conf/iotdb-engine.properties | 3 +-
thrift-commons/src/main/thrift/common.thrift | 6 +-
.../src/main/thrift/confignode.thrift | 24 +-
.../pom.xml | 56 +--
.../src/main/thrift/mutlileader.thrift | 35 +-
83 files changed, 2863 insertions(+), 433 deletions(-)
diff --git a/confignode/src/assembly/resources/conf/iotdb-confignode.properties b/confignode/src/assembly/resources/conf/iotdb-confignode.properties
index 8fb85749b6..2d8e8e04fd 100644
--- a/confignode/src/assembly/resources/conf/iotdb-confignode.properties
+++ b/confignode/src/assembly/resources/conf/iotdb-confignode.properties
@@ -54,14 +54,20 @@ target_confignode=0.0.0.0:22277
# All parameters in Consensus protocol configuration is unmodifiable after ConfigNode starts for the first time.
# And these parameters should be consistent within the ConfigNodeGroup.
-
-# DataNode consensus protocol type
+# DataRegion consensus protocol type
# These consensus protocols are currently supported:
# 1. org.apache.iotdb.consensus.standalone.StandAloneConsensus(No protocol, only supports stand-alone machine)
# 2. org.apache.iotdb.consensus.ratis.RatisConsensus(Raft protocol)
+# 3. org.apache.iotdb.consensus.multileader.MultiLeaderConsensus(weak consistency, high performance)
# Datatype: String
-# data_node_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
+# data_region_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
+# SchemaRegion consensus protocol type
+# These consensus protocols are currently supported:
+# 1. org.apache.iotdb.consensus.standalone.StandAloneConsensus(No protocol, only supports stand-alone machine)
+# 2. org.apache.iotdb.consensus.ratis.RatisConsensus(Raft protocol)
+# Datatype: String
+# schema_region_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
####################
### PartitionSlot configuration
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeConf.java b/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeConf.java
index 0ca14d6dd5..6ec526de45 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeConf.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeConf.java
@@ -21,6 +21,7 @@ package org.apache.iotdb.confignode.conf;
import org.apache.iotdb.common.rpc.thrift.TConfigNodeLocation;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.conf.IoTDBConstant;
+import org.apache.iotdb.consensus.ConsensusFactory;
import org.apache.iotdb.rpc.RpcUtils;
import java.io.File;
@@ -55,11 +56,13 @@ public class ConfigNodeConf {
private int connectionTimeoutInMS = (int) TimeUnit.SECONDS.toMillis(20);
/** ConfigNodeGroup consensus protocol */
- private final String configNodeConsensusProtocolClass =
- "org.apache.iotdb.consensus.ratis.RatisConsensus";
+ private final String configNodeConsensusProtocolClass = ConsensusFactory.RatisConsensus;
- /** DataNode Regions consensus protocol */
- private String dataNodeConsensusProtocolClass = "org.apache.iotdb.consensus.ratis.RatisConsensus";
+ /** DataNode data region consensus protocol */
+ private String dataRegionConsensusProtocolClass = ConsensusFactory.RatisConsensus;
+
+ /** DataNode schema region consensus protocol */
+ private String schemaRegionConsensusProtocolClass = ConsensusFactory.RatisConsensus;
/**
* ClientManager will have so many selector threads (TAsyncClientManager) to distribute to its
@@ -322,12 +325,20 @@ public class ConfigNodeConf {
return configNodeConsensusProtocolClass;
}
- public String getDataNodeConsensusProtocolClass() {
- return dataNodeConsensusProtocolClass;
+ public String getDataRegionConsensusProtocolClass() {
+ return dataRegionConsensusProtocolClass;
+ }
+
+ public void setDataRegionConsensusProtocolClass(String dataRegionConsensusProtocolClass) {
+ this.dataRegionConsensusProtocolClass = dataRegionConsensusProtocolClass;
+ }
+
+ public String getSchemaRegionConsensusProtocolClass() {
+ return schemaRegionConsensusProtocolClass;
}
- public void setDataNodeConsensusProtocolClass(String dataNodeConsensusProtocolClass) {
- this.dataNodeConsensusProtocolClass = dataNodeConsensusProtocolClass;
+ public void setSchemaRegionConsensusProtocolClass(String schemaRegionConsensusProtocolClass) {
+ this.schemaRegionConsensusProtocolClass = schemaRegionConsensusProtocolClass;
}
public int getThriftServerAwaitTimeForStopService() {
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeDescriptor.java b/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeDescriptor.java
index 2a024dd3b0..4b7c145a0a 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeDescriptor.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeDescriptor.java
@@ -128,9 +128,14 @@ public class ConfigNodeDescriptor {
properties.getProperty(
"series_partition_executor_class", conf.getSeriesPartitionExecutorClass()));
- conf.setDataNodeConsensusProtocolClass(
+ conf.setDataRegionConsensusProtocolClass(
properties.getProperty(
- "data_node_consensus_protocol_class", conf.getDataNodeConsensusProtocolClass()));
+ "data_region_consensus_protocol_class", conf.getDataRegionConsensusProtocolClass()));
+
+ conf.setSchemaRegionConsensusProtocolClass(
+ properties.getProperty(
+ "schema_region_consensus_protocol_class",
+ conf.getSchemaRegionConsensusProtocolClass()));
conf.setRpcAdvancedCompressionEnable(
Boolean.parseBoolean(
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeStartupCheck.java b/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeStartupCheck.java
index 7480d78e0c..999ea0163c 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeStartupCheck.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/conf/ConfigNodeStartupCheck.java
@@ -28,6 +28,7 @@ import org.apache.iotdb.commons.utils.NodeUrlUtils;
import org.apache.iotdb.confignode.client.SyncConfigNodeClientPool;
import org.apache.iotdb.confignode.rpc.thrift.TConfigNodeRegisterReq;
import org.apache.iotdb.confignode.rpc.thrift.TConfigNodeRegisterResp;
+import org.apache.iotdb.consensus.ConsensusFactory;
import org.apache.iotdb.rpc.TSStatusCode;
import org.slf4j.Logger;
@@ -83,8 +84,7 @@ public class ConfigNodeStartupCheck {
private void checkGlobalConfig() throws ConfigurationException {
// When the ConfigNode consensus protocol is set to StandAlone,
// the target_configNode needs to point to itself
- if (conf.getConfigNodeConsensusProtocolClass()
- .equals("org.apache.iotdb.consensus.standalone.StandAloneConsensus")
+ if (conf.getConfigNodeConsensusProtocolClass().equals(ConsensusFactory.StandAloneConsensus)
&& (!conf.getRpcAddress().equals(conf.getTargetConfigNode().getIp())
|| conf.getRpcPort() != conf.getTargetConfigNode().getPort())) {
throw new ConfigurationException(
@@ -93,22 +93,35 @@ public class ConfigNodeStartupCheck {
conf.getRpcAddress() + ":" + conf.getRpcPort());
}
- // When the DataNode consensus protocol is set to StandAlone,
- // the replication factor must be 1
- if (conf.getDataNodeConsensusProtocolClass()
- .equals("org.apache.iotdb.consensus.standalone.StandAloneConsensus")) {
- if (conf.getSchemaReplicationFactor() != 1) {
- throw new ConfigurationException(
- "schema_replication_factor",
- String.valueOf(conf.getSchemaReplicationFactor()),
- String.valueOf(1));
- }
- if (conf.getDataReplicationFactor() != 1) {
- throw new ConfigurationException(
- "data_replication_factor",
- String.valueOf(conf.getDataReplicationFactor()),
- String.valueOf(1));
- }
+ // When the data region consensus protocol is set to StandAlone,
+ // the data replication factor must be 1
+ if (conf.getDataRegionConsensusProtocolClass().equals(ConsensusFactory.StandAloneConsensus)
+ && conf.getDataReplicationFactor() != 1) {
+ throw new ConfigurationException(
+ "data_replication_factor",
+ String.valueOf(conf.getDataReplicationFactor()),
+ String.valueOf(1));
+ }
+
+ // When the schema region consensus protocol is set to StandAlone,
+ // the schema replication factor must be 1
+ if (conf.getSchemaRegionConsensusProtocolClass().equals(ConsensusFactory.StandAloneConsensus)
+ && conf.getSchemaReplicationFactor() != 1) {
+ throw new ConfigurationException(
+ "schema_replication_factor",
+ String.valueOf(conf.getSchemaReplicationFactor()),
+ String.valueOf(1));
+ }
+
+ // When the schema region consensus protocol is set to MultiLeaderConsensus,
+ // we should report an error
+ if (conf.getSchemaRegionConsensusProtocolClass()
+ .equals(ConsensusFactory.MultiLeaderConsensus)) {
+ throw new ConfigurationException(
+ "schema_region_consensus_protocol_class",
+ String.valueOf(conf.getSchemaRegionConsensusProtocolClass()),
+ String.format(
+ "%s or %s", ConsensusFactory.StandAloneConsensus, ConsensusFactory.RatisConsensus));
}
}
@@ -183,7 +196,8 @@ public class ConfigNodeStartupCheck {
new TConfigNodeLocation(
new TEndPoint(conf.getRpcAddress(), conf.getRpcPort()),
new TEndPoint(conf.getRpcAddress(), conf.getConsensusPort())),
- conf.getDataNodeConsensusProtocolClass(),
+ conf.getDataRegionConsensusProtocolClass(),
+ conf.getSchemaRegionConsensusProtocolClass(),
conf.getSeriesPartitionSlotNum(),
conf.getSeriesPartitionExecutorClass(),
CommonDescriptor.getInstance().getConfig().getDefaultTTL(),
@@ -215,7 +229,9 @@ public class ConfigNodeStartupCheck {
systemProperties.setProperty(
"config_node_consensus_protocol_class", conf.getConfigNodeConsensusProtocolClass());
systemProperties.setProperty(
- "data_node_consensus_protocol_class", conf.getDataNodeConsensusProtocolClass());
+ "data_region_consensus_protocol_class", conf.getDataRegionConsensusProtocolClass());
+ systemProperties.setProperty(
+ "schema_region_consensus_protocol_class", conf.getSchemaRegionConsensusProtocolClass());
// PartitionSlot configuration
systemProperties.setProperty(
@@ -282,15 +298,28 @@ public class ConfigNodeStartupCheck {
configNodeConsensusProtocolClass);
}
- String dataNodeConsensusProtocolClass =
- systemProperties.getProperty("data_node_consensus_protocol_class", null);
- if (dataNodeConsensusProtocolClass == null) {
+ String dataRegionConsensusProtocolClass =
+ systemProperties.getProperty("data_region_consensus_protocol_class", null);
+ if (dataRegionConsensusProtocolClass == null) {
+ needReWrite = true;
+ } else if (!dataRegionConsensusProtocolClass.equals(
+ conf.getDataRegionConsensusProtocolClass())) {
+ throw new ConfigurationException(
+ "data_region_consensus_protocol_class",
+ conf.getDataRegionConsensusProtocolClass(),
+ dataRegionConsensusProtocolClass);
+ }
+
+ String schemaRegionConsensusProtocolClass =
+ systemProperties.getProperty("schema_region_consensus_protocol_class", null);
+ if (schemaRegionConsensusProtocolClass == null) {
needReWrite = true;
- } else if (!dataNodeConsensusProtocolClass.equals(conf.getDataNodeConsensusProtocolClass())) {
+ } else if (!schemaRegionConsensusProtocolClass.equals(
+ conf.getSchemaRegionConsensusProtocolClass())) {
throw new ConfigurationException(
- "data_node_consensus_protocol_class",
- conf.getDataNodeConsensusProtocolClass(),
- dataNodeConsensusProtocolClass);
+ "schema_region_consensus_protocol_class",
+ conf.getSchemaRegionConsensusProtocolClass(),
+ schemaRegionConsensusProtocolClass);
}
// PartitionSlot configuration
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java
index 23154f06a0..89ce0e1562 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/ConfigManager.java
@@ -536,11 +536,22 @@ public class ConfigManager implements Manager {
ConfigNodeConf conf = ConfigNodeDescriptor.getInstance().getConf();
TConfigNodeRegisterResp errorResp = new TConfigNodeRegisterResp();
errorResp.setStatus(new TSStatus(TSStatusCode.ERROR_GLOBAL_CONFIG.getStatusCode()));
- if (!req.getDataNodeConsensusProtocolClass().equals(conf.getDataNodeConsensusProtocolClass())) {
+ if (!req.getDataRegionConsensusProtocolClass()
+ .equals(conf.getDataRegionConsensusProtocolClass())) {
errorResp
.getStatus()
.setMessage(
- "Reject register, please ensure that the data_node_consensus_protocol_class are consistent.");
+ "Reject register, please ensure that the data_region_consensus_protocol_class "
+ + "are consistent.");
+ return errorResp;
+ }
+ if (!req.getSchemaRegionConsensusProtocolClass()
+ .equals(conf.getSchemaRegionConsensusProtocolClass())) {
+ errorResp
+ .getStatus()
+ .setMessage(
+ "Reject register, please ensure that the schema_region_consensus_protocol_class "
+ + "are consistent.");
return errorResp;
}
if (req.getSeriesPartitionSlotNum() != conf.getSeriesPartitionSlotNum()) {
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/NodeManager.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/NodeManager.java
index ba046e531a..af436f2fa1 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/NodeManager.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/NodeManager.java
@@ -22,7 +22,6 @@ import org.apache.iotdb.common.rpc.thrift.TConfigNodeLocation;
import org.apache.iotdb.common.rpc.thrift.TDataNodeInfo;
import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
-import org.apache.iotdb.commons.consensus.ConsensusGroupId;
import org.apache.iotdb.confignode.client.AsyncDataNodeClientPool;
import org.apache.iotdb.confignode.conf.ConfigNodeDescriptor;
import org.apache.iotdb.confignode.consensus.request.read.GetDataNodeInfoReq;
@@ -63,8 +62,10 @@ public class NodeManager {
private void setGlobalConfig(DataNodeConfigurationResp dataSet) {
// Set TGlobalConfig
TGlobalConfig globalConfig = new TGlobalConfig();
- globalConfig.setDataNodeConsensusProtocolClass(
- ConfigNodeDescriptor.getInstance().getConf().getDataNodeConsensusProtocolClass());
+ globalConfig.setDataRegionConsensusProtocolClass(
+ ConfigNodeDescriptor.getInstance().getConf().getDataRegionConsensusProtocolClass());
+ globalConfig.setSchemaRegionConsensusProtocolClass(
+ ConfigNodeDescriptor.getInstance().getConf().getSchemaRegionConsensusProtocolClass());
globalConfig.setSeriesPartitionSlotNum(
ConfigNodeDescriptor.getInstance().getConf().getSeriesPartitionSlotNum());
globalConfig.setSeriesPartitionExecutorClass(
@@ -140,7 +141,7 @@ public class NodeManager {
// Return PartitionRegionId
resp.setPartitionRegionId(
- ConsensusGroupId.convertToTConsensusGroupId(getConsensusManager().getConsensusGroupId()));
+ getConsensusManager().getConsensusGroupId().convertToTConsensusGroupId());
// Return online ConfigNodes
resp.setConfigNodeList(nodeInfo.getOnlineConfigNodes());
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/consensus/request/ConfigRequestSerDeTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/consensus/request/ConfigRequestSerDeTest.java
index 55bad48cf3..b11e63c5c4 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/consensus/request/ConfigRequestSerDeTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/consensus/request/ConfigRequestSerDeTest.java
@@ -86,7 +86,8 @@ public class ConfigRequestSerDeTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 7777));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010));
TDataNodeInfo dataNodeInfo = new TDataNodeInfo();
dataNodeInfo.setLocation(dataNodeLocation);
@@ -211,7 +212,8 @@ public class ConfigRequestSerDeTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010));
CreateRegionsReq req0 = new CreateRegionsReq();
TRegionReplicaSet dataRegionSet = new TRegionReplicaSet();
@@ -249,7 +251,8 @@ public class ConfigRequestSerDeTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010));
String storageGroup = "root.sg0";
TSeriesPartitionSlot seriesPartitionSlot = new TSeriesPartitionSlot(10);
@@ -310,7 +313,8 @@ public class ConfigRequestSerDeTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010));
String storageGroup = "root.sg0";
TSeriesPartitionSlot seriesPartitionSlot = new TSeriesPartitionSlot(10);
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/persistence/NodeInfoTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/persistence/NodeInfoTest.java
index 4f37010f1f..d03cc6d5e7 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/persistence/NodeInfoTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/persistence/NodeInfoTest.java
@@ -99,6 +99,7 @@ public class NodeInfoTest {
new TEndPoint("127.0.0.1", 6600 + flag),
new TEndPoint("127.0.0.1", 7700 + flag),
new TEndPoint("127.0.0.1", 8800 + flag),
- new TEndPoint("127.0.0.1", 9900 + flag));
+ new TEndPoint("127.0.0.1", 9900 + flag),
+ new TEndPoint("127.0.0.1", 11000 + flag));
}
}
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/persistence/PartitionInfoTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/persistence/PartitionInfoTest.java
index c1e1eb7a86..49409b0a24 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/persistence/PartitionInfoTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/persistence/PartitionInfoTest.java
@@ -180,7 +180,8 @@ public class PartitionInfoTest {
tDataNodeLocation.setExternalEndPoint(new TEndPoint("127.0.0.1", 6000 + i));
tDataNodeLocation.setInternalEndPoint(new TEndPoint("127.0.0.1", 7000 + i));
tDataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("127.0.0.1", 8000 + i));
- tDataNodeLocation.setConsensusEndPoint(new TEndPoint("127.0.0.1", 9000 + i));
+ tDataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("127.0.0.1", 9000 + i));
+ tDataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("127.0.0.1", 10000 + i));
dataNodeLocations.add(tDataNodeLocation);
}
tRegionReplicaSet.setDataNodeLocations(dataNodeLocations);
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/service/thrift/ConfigNodeRPCServiceProcessorTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/service/thrift/ConfigNodeRPCServiceProcessorTest.java
index 186863a878..263d7a2472 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/service/thrift/ConfigNodeRPCServiceProcessorTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/service/thrift/ConfigNodeRPCServiceProcessorTest.java
@@ -128,8 +128,11 @@ public class ConfigNodeRPCServiceProcessorTest {
private void checkGlobalConfig(TGlobalConfig globalConfig) {
Assert.assertEquals(
- ConfigNodeDescriptor.getInstance().getConf().getDataNodeConsensusProtocolClass(),
- globalConfig.getDataNodeConsensusProtocolClass());
+ ConfigNodeDescriptor.getInstance().getConf().getDataRegionConsensusProtocolClass(),
+ globalConfig.getDataRegionConsensusProtocolClass());
+ Assert.assertEquals(
+ ConfigNodeDescriptor.getInstance().getConf().getSchemaRegionConsensusProtocolClass(),
+ globalConfig.getSchemaRegionConsensusProtocolClass());
Assert.assertEquals(
ConfigNodeDescriptor.getInstance().getConf().getSeriesPartitionSlotNum(),
globalConfig.getSeriesPartitionSlotNum());
@@ -144,7 +147,8 @@ public class ConfigNodeRPCServiceProcessorTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667 + i));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003 + i));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777 + i));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40010 + i));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010 + i));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010 + i));
TDataNodeInfo dataNodeInfo = new TDataNodeInfo();
dataNodeInfo.setLocation(dataNodeLocation);
@@ -169,7 +173,8 @@ public class ConfigNodeRPCServiceProcessorTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6668));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9004));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8778));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40011));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40011));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50011));
TDataNodeInfo dataNodeInfo = new TDataNodeInfo();
dataNodeInfo.setLocation(dataNodeLocation);
@@ -196,7 +201,8 @@ public class ConfigNodeRPCServiceProcessorTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667 + i));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003 + i));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777 + i));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40010 + i));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010 + i));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010 + i));
Assert.assertEquals(dataNodeLocation, infoList.get(i).getValue().getLocation());
}
@@ -210,7 +216,8 @@ public class ConfigNodeRPCServiceProcessorTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6668));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9004));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8778));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40011));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40011));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50011));
Assert.assertEquals(dataNodeLocation, infoMap.get(1).getLocation());
}
diff --git a/confignode/src/test/resources/confignode1conf/iotdb-confignode.properties b/confignode/src/test/resources/confignode1conf/iotdb-confignode.properties
index 2f9245a664..f05a5685ce 100644
--- a/confignode/src/test/resources/confignode1conf/iotdb-confignode.properties
+++ b/confignode/src/test/resources/confignode1conf/iotdb-confignode.properties
@@ -22,8 +22,8 @@ rpc_port=22277
consensus_port=22278
target_confignode=0.0.0.0:22277
config_node_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
-#data_node_consensus_protocol_class=org.apache.iotdb.consensus.standalone.StandAloneConsensus
-data_node_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
+data_region_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
+schema_region_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
# Default number of SchemaRegion replicas
# Datatype: int
diff --git a/confignode/src/test/resources/confignode2conf/iotdb-confignode.properties b/confignode/src/test/resources/confignode2conf/iotdb-confignode.properties
index bcd433ef35..a8961fd689 100644
--- a/confignode/src/test/resources/confignode2conf/iotdb-confignode.properties
+++ b/confignode/src/test/resources/confignode2conf/iotdb-confignode.properties
@@ -22,7 +22,8 @@ rpc_port=22279
consensus_port=22280
target_confignode=0.0.0.0:22277
config_node_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
-data_node_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
+data_region_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
+schema_region_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
system_dir=target/confignode2/system
data_dirs=target/confignode2/data
diff --git a/confignode/src/test/resources/confignode3conf/iotdb-confignode.properties b/confignode/src/test/resources/confignode3conf/iotdb-confignode.properties
index 1adf1d6e54..36ded2eb0d 100644
--- a/confignode/src/test/resources/confignode3conf/iotdb-confignode.properties
+++ b/confignode/src/test/resources/confignode3conf/iotdb-confignode.properties
@@ -22,7 +22,8 @@ rpc_port=22281
consensus_port=22282
target_confignode=0.0.0.0:22277
config_node_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
-data_node_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
+data_region_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
+schema_region_consensus_protocol_class=org.apache.iotdb.consensus.ratis.RatisConsensus
system_dir=target/confignode3/system
data_dirs=target/confignode3/data
diff --git a/consensus/README.md b/consensus/README.md
index c0e77910ed..ecd5c35eae 100644
--- a/consensus/README.md
+++ b/consensus/README.md
@@ -69,7 +69,7 @@ on [Apache Ratis](https://ratis.apache.org/).
```java
IConsensus consensusImpl =
ConsensusFactory.getConsensusImpl(
- "org.apache.iotdb.consensus.ratis.RatisConsensus",
+ ConsensusFactory.RatisConsensus,
new Endpoint(conf.getRpcAddress(), conf.getInternalPort()),
new File(conf.getConsensusDir()),
gid -> new PartitionRegionStateMachine())
@@ -77,7 +77,7 @@ IConsensus consensusImpl =
new IllegalArgumentException(
String.format(
ConsensusFactory.CONSTRUCT_FAILED_MSG,
- "org.apache.iotdb.consensus.ratis.RatisConsensus")));
+ ConsensusFactory.RatisConsensus)));
consensusImpl.start();
```
diff --git a/consensus/pom.xml b/consensus/pom.xml
index e4d873bb19..2853e3326f 100644
--- a/consensus/pom.xml
+++ b/consensus/pom.xml
@@ -52,6 +52,11 @@
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.iotdb</groupId>
+ <artifactId>thrift-multi-leader-consensus</artifactId>
+ <version>${project.version}</version>
+ </dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/ConsensusFactory.java b/consensus/src/main/java/org/apache/iotdb/consensus/ConsensusFactory.java
index efc40e31e6..15e2492b2e 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/ConsensusFactory.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/ConsensusFactory.java
@@ -33,6 +33,12 @@ public class ConsensusFactory {
public static final String CONSTRUCT_FAILED_MSG =
"Construct consensusImpl failed, Please check your consensus className %s";
+ public static final String StandAloneConsensus =
+ "org.apache.iotdb.consensus.standalone.StandAloneConsensus";
+ public static final String RatisConsensus = "org.apache.iotdb.consensus.ratis.RatisConsensus";
+ public static final String MultiLeaderConsensus =
+ "org.apache.iotdb.consensus.multileader.MultiLeaderConsensus";
+
private static final Logger logger = LoggerFactory.getLogger(ConsensusFactory.class);
public static Optional<IConsensus> getConsensusImpl(
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/common/Peer.java b/consensus/src/main/java/org/apache/iotdb/consensus/common/Peer.java
index 99379156fb..df97102dd2 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/common/Peer.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/common/Peer.java
@@ -21,7 +21,9 @@ package org.apache.iotdb.consensus.common;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.consensus.ConsensusGroupId;
+import org.apache.iotdb.commons.utils.ThriftCommonsSerDeUtils;
+import java.nio.ByteBuffer;
import java.util.Objects;
// TODO Use a mature IDL framework such as Protobuf to manage this structure
@@ -43,6 +45,19 @@ public class Peer {
return endpoint;
}
+ public void serialize(ByteBuffer buffer) {
+ ThriftCommonsSerDeUtils.serializeTConsensusGroupId(
+ groupId.convertToTConsensusGroupId(), buffer);
+ ThriftCommonsSerDeUtils.serializeTEndPoint(endpoint, buffer);
+ }
+
+ public static Peer deserialize(ByteBuffer buffer) {
+ return new Peer(
+ ConsensusGroupId.Factory.createFromTConsensusGroupId(
+ ThriftCommonsSerDeUtils.deserializeTConsensusGroupId(buffer)),
+ ThriftCommonsSerDeUtils.deserializeTEndPoint(buffer));
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) {
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequest.java b/consensus/src/main/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequest.java
new file mode 100644
index 0000000000..24ba1ae13f
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/common/request/IndexedConsensusRequest.java
@@ -0,0 +1,88 @@
+/*
+ * 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.consensus.common.request;
+
+import org.apache.iotdb.consensus.multileader.thrift.TLogType;
+
+import java.nio.ByteBuffer;
+import java.util.Objects;
+
+/** only used for multi-leader consensus. */
+public class IndexedConsensusRequest implements IConsensusRequest {
+
+ /** we do not need to serialize these two fields as they are useless in other nodes. */
+ private final long searchIndex;
+
+ private final long safelyDeletedSearchIndex;
+
+ /** we do not need to serialize this field as it will be serialized by TLogBatch. */
+ private final TLogType type;
+
+ private final IConsensusRequest request;
+
+ public IndexedConsensusRequest(
+ long searchIndex, long safelyDeletedSearchIndex, TLogType type, IConsensusRequest request) {
+ this.searchIndex = searchIndex;
+ this.safelyDeletedSearchIndex = safelyDeletedSearchIndex;
+ this.type = type;
+ this.request = request;
+ }
+
+ @Override
+ public void serializeRequest(ByteBuffer buffer) {
+ request.serializeRequest(buffer);
+ }
+
+ public IConsensusRequest getRequest() {
+ return request;
+ }
+
+ public long getSearchIndex() {
+ return searchIndex;
+ }
+
+ public long getSafelyDeletedSearchIndex() {
+ return safelyDeletedSearchIndex;
+ }
+
+ public TLogType getType() {
+ return type;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ IndexedConsensusRequest that = (IndexedConsensusRequest) o;
+ return searchIndex == that.searchIndex
+ && safelyDeletedSearchIndex == that.safelyDeletedSearchIndex
+ && type == that.type
+ && Objects.equals(request, that.request);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(searchIndex, safelyDeletedSearchIndex, type, request);
+ }
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusReadResponse.java b/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusReadResponse.java
index a8bec60d3f..7c3a45bd90 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusReadResponse.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusReadResponse.java
@@ -35,9 +35,13 @@ public class ConsensusReadResponse extends ConsensusResponse {
return dataset;
}
+ public boolean isSuccess() {
+ return exception == null;
+ }
+
@Override
public String toString() {
- return "ConsensusReadResponse{" + "dataset=" + dataset + "} " + super.toString();
+ return "ConsensusReadResponse{" + "dataset=" + dataset + ", exception=" + exception + "}";
}
public static ConsensusReadResponse.Builder newBuilder() {
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusResponse.java b/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusResponse.java
index 355b0d035a..2a14ada29d 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusResponse.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusResponse.java
@@ -22,7 +22,7 @@ package org.apache.iotdb.consensus.common.response;
import org.apache.iotdb.consensus.exception.ConsensusException;
public abstract class ConsensusResponse {
- private final ConsensusException exception;
+ protected final ConsensusException exception;
public ConsensusResponse(ConsensusException exception) {
this.exception = exception;
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerEndpointException.java b/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerEndpointException.java
index 7591345acc..969ed3e38e 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerEndpointException.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerEndpointException.java
@@ -20,13 +20,16 @@
package org.apache.iotdb.consensus.exception;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.consensus.common.Peer;
+
+import java.util.List;
public class IllegalPeerEndpointException extends ConsensusException {
- public IllegalPeerEndpointException(TEndPoint currentNode, TEndPoint newNode) {
+ public IllegalPeerEndpointException(TEndPoint currentNode, List<Peer> peers) {
super(
String.format(
- "Illegal creation for node %s in node %s in StandAloneConsensus Mode",
- newNode, currentNode));
+ "Illegal addConsensusGroup because currentNode %s is not in consensusGroup %s",
+ currentNode, peers));
}
}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java b/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java
index d2026a5515..c08ef05057 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java
@@ -22,8 +22,6 @@ package org.apache.iotdb.consensus.exception;
public class IllegalPeerNumException extends ConsensusException {
public IllegalPeerNumException(int size) {
- super(
- String.format(
- "Illegal Peer num %d, only support one peer in StandAloneConsensus Mode", size));
+ super(String.format("Illegal peer num %d when adding consensus group", size));
}
}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/standalone/StandAloneConsensus.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/MultiLeaderConsensus.java
similarity index 72%
copy from consensus/src/main/java/org/apache/iotdb/consensus/standalone/StandAloneConsensus.java
copy to consensus/src/main/java/org/apache/iotdb/consensus/multileader/MultiLeaderConsensus.java
index 4c2100d1e1..c9393ad642 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/standalone/StandAloneConsensus.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/MultiLeaderConsensus.java
@@ -17,11 +17,12 @@
* under the License.
*/
-package org.apache.iotdb.consensus.standalone;
+package org.apache.iotdb.consensus.multileader;
-import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.consensus.ConsensusGroupId;
+import org.apache.iotdb.commons.exception.StartupException;
+import org.apache.iotdb.commons.service.RegisterManager;
import org.apache.iotdb.consensus.IConsensus;
import org.apache.iotdb.consensus.IStateMachine;
import org.apache.iotdb.consensus.IStateMachine.Registry;
@@ -34,6 +35,8 @@ import org.apache.iotdb.consensus.exception.ConsensusGroupAlreadyExistException;
import org.apache.iotdb.consensus.exception.ConsensusGroupNotExistException;
import org.apache.iotdb.consensus.exception.IllegalPeerEndpointException;
import org.apache.iotdb.consensus.exception.IllegalPeerNumException;
+import org.apache.iotdb.consensus.multileader.service.MultiLeaderRPCService;
+import org.apache.iotdb.consensus.multileader.service.MultiLeaderRPCServiceProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -43,36 +46,41 @@ import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
-/**
- * A simple consensus implementation, which can be used when replicaNum is 1.
- *
- * <p>Notice: The stateMachine needs to implement WAL itself to ensure recovery after a restart
- */
-class StandAloneConsensus implements IConsensus {
+public class MultiLeaderConsensus implements IConsensus {
- private final Logger logger = LoggerFactory.getLogger(StandAloneConsensus.class);
+ private final Logger logger = LoggerFactory.getLogger(MultiLeaderConsensus.class);
private final TEndPoint thisNode;
private final File storageDir;
private final IStateMachine.Registry registry;
- private final Map<ConsensusGroupId, StandAloneServerImpl> stateMachineMap =
+ private final Map<ConsensusGroupId, MultiLeaderServerImpl> stateMachineMap =
new ConcurrentHashMap<>();
+ private final MultiLeaderRPCService service;
+ private final RegisterManager registerManager = new RegisterManager();
- public StandAloneConsensus(TEndPoint thisNode, File storageDir, Registry registry) {
+ public MultiLeaderConsensus(TEndPoint thisNode, File storageDir, Registry registry) {
this.thisNode = thisNode;
this.storageDir = storageDir;
this.registry = registry;
+ this.service = new MultiLeaderRPCService(thisNode);
}
@Override
public void start() throws IOException {
initAndRecover();
+ service.initSyncedServiceImpl(new MultiLeaderRPCServiceProcessor(this));
+ try {
+ registerManager.register(service);
+ } catch (StartupException e) {
+ throw new IOException(e);
+ }
}
private void initAndRecover() throws IOException {
@@ -86,23 +94,29 @@ class StandAloneConsensus implements IConsensus {
String[] items = path.getFileName().toString().split("_");
ConsensusGroupId consensusGroupId =
ConsensusGroupId.Factory.create(
- TConsensusGroupType.valueOf(items[0]).getValue(), Integer.parseInt(items[1]));
- TEndPoint endPoint = new TEndPoint(items[2], Integer.parseInt(items[3]));
- stateMachineMap.put(
- consensusGroupId,
- new StandAloneServerImpl(
- new Peer(consensusGroupId, endPoint), registry.apply(consensusGroupId)));
+ Integer.parseInt(items[0]), Integer.parseInt(items[1]));
+ MultiLeaderServerImpl consensus =
+ new MultiLeaderServerImpl(
+ path.toString(),
+ new Peer(consensusGroupId, thisNode),
+ new ArrayList<>(),
+ registry.apply(consensusGroupId));
+ stateMachineMap.put(consensusGroupId, consensus);
+ consensus.start();
}
}
}
}
@Override
- public void stop() throws IOException {}
+ public void stop() {
+ stateMachineMap.values().parallelStream().forEach(MultiLeaderServerImpl::stop);
+ registerManager.deregisterAll();
+ }
@Override
public ConsensusWriteResponse write(ConsensusGroupId groupId, IConsensusRequest request) {
- StandAloneServerImpl impl = stateMachineMap.get(groupId);
+ MultiLeaderServerImpl impl = stateMachineMap.get(groupId);
if (impl == null) {
return ConsensusWriteResponse.newBuilder()
.setException(new ConsensusGroupNotExistException(groupId))
@@ -113,7 +127,7 @@ class StandAloneConsensus implements IConsensus {
@Override
public ConsensusReadResponse read(ConsensusGroupId groupId, IConsensusRequest request) {
- StandAloneServerImpl impl = stateMachineMap.get(groupId);
+ MultiLeaderServerImpl impl = stateMachineMap.get(groupId);
if (impl == null) {
return ConsensusReadResponse.newBuilder()
.setException(new ConsensusGroupNotExistException(groupId))
@@ -125,29 +139,30 @@ class StandAloneConsensus implements IConsensus {
@Override
public ConsensusGenericResponse addConsensusGroup(ConsensusGroupId groupId, List<Peer> peers) {
int consensusGroupSize = peers.size();
- if (consensusGroupSize != 1) {
+ if (consensusGroupSize == 0) {
return ConsensusGenericResponse.newBuilder()
.setException(new IllegalPeerNumException(consensusGroupSize))
.build();
}
- if (!Objects.equals(thisNode, peers.get(0).getEndpoint())) {
+ if (!peers.contains(new Peer(groupId, thisNode))) {
return ConsensusGenericResponse.newBuilder()
- .setException(new IllegalPeerEndpointException(thisNode, peers.get(0).getEndpoint()))
+ .setException(new IllegalPeerEndpointException(thisNode, peers))
.build();
}
AtomicBoolean exist = new AtomicBoolean(true);
stateMachineMap.computeIfAbsent(
groupId,
- (k) -> {
+ k -> {
exist.set(false);
- StandAloneServerImpl impl =
- new StandAloneServerImpl(peers.get(0), registry.apply(groupId));
- impl.start();
String path = buildPeerDir(groupId);
File file = new File(path);
if (!file.mkdirs()) {
logger.warn("Unable to create consensus dir for group {} at {}", groupId, path);
}
+ MultiLeaderServerImpl impl =
+ new MultiLeaderServerImpl(
+ path, new Peer(groupId, thisNode), peers, registry.apply(groupId));
+ impl.start();
return impl;
});
if (exist.get()) {
@@ -167,9 +182,11 @@ class StandAloneConsensus implements IConsensus {
exist.set(true);
v.stop();
String path = buildPeerDir(groupId);
- File file = new File(path);
- if (!file.delete()) {
- logger.warn("Unable to delete consensus dir for group {} at {}", groupId, path);
+ try {
+ Files.delete(Paths.get(path));
+ } catch (IOException e) {
+ logger.warn(
+ "Unable to delete consensus dir for group {} at {} because {}", groupId, path, e);
}
return null;
});
@@ -220,15 +237,11 @@ class StandAloneConsensus implements IConsensus {
return new Peer(groupId, thisNode);
}
+ public MultiLeaderServerImpl getImpl(ConsensusGroupId groupId) {
+ return stateMachineMap.get(groupId);
+ }
+
private String buildPeerDir(ConsensusGroupId groupId) {
- return storageDir
- + File.separator
- + groupId.getType()
- + "_"
- + groupId.getId()
- + "_"
- + thisNode.getIp()
- + "_"
- + thisNode.getPort();
+ return storageDir + File.separator + groupId.getType().getValue() + "_" + groupId.getId();
}
}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/MultiLeaderServerImpl.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/MultiLeaderServerImpl.java
new file mode 100644
index 0000000000..017fe05a15
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/MultiLeaderServerImpl.java
@@ -0,0 +1,186 @@
+/*
+ * 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.consensus.multileader;
+
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.consensus.IStateMachine;
+import org.apache.iotdb.consensus.common.DataSet;
+import org.apache.iotdb.consensus.common.Peer;
+import org.apache.iotdb.consensus.common.request.ByteBufferConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IndexedConsensusRequest;
+import org.apache.iotdb.consensus.multileader.logdispatcher.IndexController;
+import org.apache.iotdb.consensus.multileader.logdispatcher.LogDispatcher;
+import org.apache.iotdb.consensus.multileader.thrift.TLogType;
+import org.apache.iotdb.consensus.multileader.wal.ConsensusReqReader;
+import org.apache.iotdb.consensus.ratis.Utils;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.List;
+
+public class MultiLeaderServerImpl {
+
+ private static final String CONFIGURATION_FILE_NAME = "configuration.dat";
+ private static final int DEFAULT_CONFIGURATION_BUFFER_SIZE = 1024 * 4;
+
+ private final Logger logger = LoggerFactory.getLogger(MultiLeaderServerImpl.class);
+
+ private final Peer thisNode;
+ private final IStateMachine stateMachine;
+ private final String storageDir;
+ private final List<Peer> configuration;
+ private final IndexController controller;
+ private final LogDispatcher logDispatcher;
+
+ public MultiLeaderServerImpl(
+ String storageDir, Peer thisNode, List<Peer> configuration, IStateMachine stateMachine) {
+ this.storageDir = storageDir;
+ this.thisNode = thisNode;
+ this.stateMachine = stateMachine;
+ this.controller =
+ new IndexController(storageDir, Utils.fromTEndPointToString(thisNode.getEndpoint()), true);
+ this.configuration = configuration;
+ if (configuration.isEmpty()) {
+ recoverConfiguration();
+ } else {
+ persistConfiguration();
+ }
+ logDispatcher = new LogDispatcher(this);
+ }
+
+ public IStateMachine getStateMachine() {
+ return stateMachine;
+ }
+
+ public void start() {
+ stateMachine.start();
+ logDispatcher.start();
+ }
+
+ public void stop() {
+ logDispatcher.stop();
+ stateMachine.stop();
+ }
+
+ /**
+ * records the index of the log and writes locally, and then asynchronous replication is performed
+ */
+ public TSStatus write(IConsensusRequest request) {
+ synchronized (stateMachine) {
+ IndexedConsensusRequest indexedConsensusRequest =
+ buildIndexedConsensusRequestForLocalRequest(request);
+ TSStatus result = stateMachine.write(indexedConsensusRequest);
+ logDispatcher.offer(indexedConsensusRequest);
+ return result;
+ }
+ }
+
+ public DataSet read(IConsensusRequest request) {
+ return stateMachine.read(request);
+ }
+
+ public boolean takeSnapshot(File snapshotDir) {
+ return stateMachine.takeSnapshot(snapshotDir);
+ }
+
+ public void loadSnapshot(File latestSnapshotRootDir) {
+ stateMachine.loadSnapshot(latestSnapshotRootDir);
+ }
+
+ public void persistConfiguration() {
+ ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_CONFIGURATION_BUFFER_SIZE);
+ buffer.putInt(configuration.size());
+ for (Peer peer : configuration) {
+ peer.serialize(buffer);
+ }
+ try {
+ Files.write(
+ Paths.get(new File(storageDir, CONFIGURATION_FILE_NAME).getAbsolutePath()),
+ buffer.array());
+ } catch (IOException e) {
+ logger.error("Unexpected error occurs when persisting configuration", e);
+ }
+ }
+
+ public void recoverConfiguration() {
+ ByteBuffer buffer;
+ try {
+ buffer =
+ ByteBuffer.wrap(
+ Files.readAllBytes(
+ Paths.get(new File(storageDir, CONFIGURATION_FILE_NAME).getAbsolutePath())));
+ int size = buffer.getInt();
+ for (int i = 0; i < size; i++) {
+ configuration.add(Peer.deserialize(buffer));
+ }
+ } catch (IOException e) {
+ logger.error("Unexpected error occurs when recovering configuration", e);
+ }
+ }
+
+ public IndexedConsensusRequest buildIndexedConsensusRequestForLocalRequest(
+ IConsensusRequest request) {
+ return new IndexedConsensusRequest(
+ controller.incrementAndGet(),
+ getCurrentSafelyDeletedSearchIndex(),
+ TLogType.FragmentInstance,
+ request);
+ }
+
+ public IndexedConsensusRequest buildIndexedConsensusRequestForRemoteRequest(
+ ByteBufferConsensusRequest request, TLogType type) {
+ return new IndexedConsensusRequest(
+ ConsensusReqReader.DEFAULT_SEARCH_INDEX,
+ getCurrentSafelyDeletedSearchIndex(),
+ type,
+ request);
+ }
+
+ /**
+ * In the case of multiple copies, the minimum synchronization index is selected. In the case of
+ * single copies, the current index is selected
+ */
+ public long getCurrentSafelyDeletedSearchIndex() {
+ return logDispatcher.getMinSyncIndex().orElseGet(controller::getCurrentIndex);
+ }
+
+ public String getStorageDir() {
+ return storageDir;
+ }
+
+ public Peer getThisNode() {
+ return thisNode;
+ }
+
+ public List<Peer> getConfiguration() {
+ return configuration;
+ }
+
+ public IndexController getController() {
+ return controller;
+ }
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/AsyncMultiLeaderServiceClient.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/AsyncMultiLeaderServiceClient.java
new file mode 100644
index 0000000000..98e2e82b18
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/AsyncMultiLeaderServiceClient.java
@@ -0,0 +1,145 @@
+/*
+ * 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.consensus.multileader.client;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.client.AsyncBaseClientFactory;
+import org.apache.iotdb.commons.client.ClientFactoryProperty;
+import org.apache.iotdb.commons.client.ClientManager;
+import org.apache.iotdb.consensus.multileader.thrift.MultiLeaderConsensusIService;
+import org.apache.iotdb.rpc.TNonblockingSocketWrapper;
+
+import org.apache.commons.pool2.PooledObject;
+import org.apache.commons.pool2.impl.DefaultPooledObject;
+import org.apache.thrift.async.TAsyncClientManager;
+import org.apache.thrift.protocol.TProtocolFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+public class AsyncMultiLeaderServiceClient extends MultiLeaderConsensusIService.AsyncClient {
+
+ private static final Logger logger = LoggerFactory.getLogger(AsyncMultiLeaderServiceClient.class);
+
+ private final TEndPoint endpoint;
+ private final ClientManager<TEndPoint, AsyncMultiLeaderServiceClient> clientManager;
+
+ public AsyncMultiLeaderServiceClient(
+ TProtocolFactory protocolFactory,
+ int connectionTimeout,
+ TEndPoint endpoint,
+ TAsyncClientManager tClientManager,
+ ClientManager<TEndPoint, AsyncMultiLeaderServiceClient> clientManager)
+ throws IOException {
+ super(
+ protocolFactory,
+ tClientManager,
+ TNonblockingSocketWrapper.wrap(endpoint.getIp(), endpoint.getPort(), connectionTimeout));
+ this.endpoint = endpoint;
+ this.clientManager = clientManager;
+ }
+
+ public void close() {
+ ___transport.close();
+ ___currentMethod = null;
+ }
+
+ /**
+ * return self if clientManager is not null, the method doesn't need to call by user, it will
+ * trigger once client transport complete.
+ */
+ private void returnSelf() {
+ if (clientManager != null) {
+ clientManager.returnClient(endpoint, this);
+ }
+ }
+
+ /**
+ * This method will be automatically called by the thrift selector thread, and we'll just simulate
+ * the behavior in our test
+ */
+ @Override
+ public void onComplete() {
+ super.onComplete();
+ returnSelf();
+ }
+
+ /**
+ * This method will be automatically called by the thrift selector thread, and we'll just simulate
+ * the behavior in our test
+ */
+ @Override
+ public void onError(Exception e) {
+ super.onError(e);
+ returnSelf();
+ }
+
+ public boolean isReady() {
+ try {
+ checkReady();
+ return true;
+ } catch (Exception e) {
+ logger.info("Unexpected exception occurs in {} :", this, e);
+ return false;
+ }
+ }
+
+ @Override
+ public String toString() {
+ return String.format("AsyncConfigNodeIServiceClient{%s}", endpoint);
+ }
+
+ public static class Factory
+ extends AsyncBaseClientFactory<TEndPoint, AsyncMultiLeaderServiceClient> {
+
+ public Factory(
+ ClientManager<TEndPoint, AsyncMultiLeaderServiceClient> clientManager,
+ ClientFactoryProperty clientFactoryProperty) {
+ super(clientManager, clientFactoryProperty);
+ }
+
+ @Override
+ public void destroyObject(
+ TEndPoint endPoint, PooledObject<AsyncMultiLeaderServiceClient> pooledObject) {
+ pooledObject.getObject().close();
+ }
+
+ @Override
+ public PooledObject<AsyncMultiLeaderServiceClient> makeObject(TEndPoint endPoint)
+ throws Exception {
+ TAsyncClientManager tManager = tManagers[clientCnt.incrementAndGet() % tManagers.length];
+ tManager = tManager == null ? new TAsyncClientManager() : tManager;
+ return new DefaultPooledObject<>(
+ new AsyncMultiLeaderServiceClient(
+ clientFactoryProperty.getProtocolFactory(),
+ clientFactoryProperty.getConnectionTimeoutMs(),
+ endPoint,
+ tManager,
+ clientManager));
+ }
+
+ @Override
+ public boolean validateObject(
+ TEndPoint endPoint, PooledObject<AsyncMultiLeaderServiceClient> pooledObject) {
+ return pooledObject.getObject() != null && pooledObject.getObject().isReady();
+ }
+ }
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/DispatchLogHandler.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/DispatchLogHandler.java
new file mode 100644
index 0000000000..8cc7d10bef
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/DispatchLogHandler.java
@@ -0,0 +1,100 @@
+/*
+ * 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.consensus.multileader.client;
+
+import org.apache.iotdb.consensus.multileader.conf.MultiLeaderConsensusConfig;
+import org.apache.iotdb.consensus.multileader.logdispatcher.LogDispatcher.LogDispatcherThread;
+import org.apache.iotdb.consensus.multileader.logdispatcher.PendingBatch;
+import org.apache.iotdb.consensus.multileader.thrift.TSyncLogRes;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.apache.thrift.async.AsyncMethodCallback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.CompletableFuture;
+
+public class DispatchLogHandler implements AsyncMethodCallback<TSyncLogRes> {
+
+ private final Logger logger = LoggerFactory.getLogger(DispatchLogHandler.class);
+
+ private final LogDispatcherThread thread;
+ private final PendingBatch batch;
+ private int retryCount;
+
+ public DispatchLogHandler(LogDispatcherThread thread, PendingBatch batch) {
+ this.thread = thread;
+ this.batch = batch;
+ }
+
+ @Override
+ public void onComplete(TSyncLogRes response) {
+ if (response.getStatus().size() == 1
+ && response.getStatus().get(0).getCode()
+ == TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode()) {
+ logger.warn(
+ "Can not send {} to peer {} for {} times because {}",
+ batch,
+ thread.getPeer(),
+ ++retryCount,
+ response.getStatus().get(0).getMessage());
+ sleepCorrespondingTimeAndRetryAsynchronous();
+ } else {
+ thread.getSyncStatus().removeBatch(batch);
+ }
+ }
+
+ @Override
+ public void onError(Exception exception) {
+ logger.warn(
+ "Can not send {} to peer for {} times {} because {}",
+ batch,
+ thread.getPeer(),
+ ++retryCount,
+ exception);
+ sleepCorrespondingTimeAndRetryAsynchronous();
+ }
+
+ private void sleepCorrespondingTimeAndRetryAsynchronous() {
+ // TODO handle forever retry
+ CompletableFuture.runAsync(
+ () -> {
+ try {
+ long defaultSleepTime =
+ (long)
+ (MultiLeaderConsensusConfig.BASIC_RETRY_WAIT_TIME_MS * Math.pow(2, retryCount));
+ Thread.sleep(
+ Math.min(defaultSleepTime, MultiLeaderConsensusConfig.MAX_RETRY_WAIT_TIME_MS));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ logger.warn("Unexpected interruption during retry pending batch");
+ }
+ if (thread.isStopped()) {
+ logger.debug(
+ "LogDispatcherThread {} has been stopped, we will ignore the retry PendingBatch {} after {} times",
+ thread.getPeer(),
+ batch,
+ retryCount);
+ } else {
+ thread.sendBatchAsync(batch, this);
+ }
+ });
+ }
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/MultiLeaderConsensusClientPool.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/MultiLeaderConsensusClientPool.java
new file mode 100644
index 0000000000..a43a979694
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/client/MultiLeaderConsensusClientPool.java
@@ -0,0 +1,54 @@
+/*
+ * 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.consensus.multileader.client;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.client.ClientFactoryProperty;
+import org.apache.iotdb.commons.client.ClientManager;
+import org.apache.iotdb.commons.client.ClientPoolProperty;
+import org.apache.iotdb.commons.client.IClientPoolFactory;
+import org.apache.iotdb.consensus.multileader.conf.MultiLeaderConsensusConfig;
+
+import org.apache.commons.pool2.KeyedObjectPool;
+import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
+
+public class MultiLeaderConsensusClientPool {
+
+ private MultiLeaderConsensusClientPool() {}
+
+ public static class AsyncMultiLeaderServiceClientPoolFactory
+ implements IClientPoolFactory<TEndPoint, AsyncMultiLeaderServiceClient> {
+ @Override
+ public KeyedObjectPool<TEndPoint, AsyncMultiLeaderServiceClient> createClientPool(
+ ClientManager<TEndPoint, AsyncMultiLeaderServiceClient> manager) {
+ return new GenericKeyedObjectPool<>(
+ new AsyncMultiLeaderServiceClient.Factory(
+ manager,
+ new ClientFactoryProperty.Builder()
+ .setConnectionTimeoutMs(MultiLeaderConsensusConfig.CONNECTION_TIMEOUT_IN_MS)
+ .setRpcThriftCompressionEnabled(
+ MultiLeaderConsensusConfig.IS_RPC_THRIFT_COMPRESSION_ENABLED)
+ .setSelectorNumOfAsyncClientManager(
+ MultiLeaderConsensusConfig.SELECTOR_NUM_OF_CLIENT_MANAGER)
+ .build()),
+ new ClientPoolProperty.Builder<AsyncMultiLeaderServiceClient>().build().getConfig());
+ }
+ }
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/conf/MultiLeaderConsensusConfig.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/conf/MultiLeaderConsensusConfig.java
new file mode 100644
index 0000000000..10a547728f
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/conf/MultiLeaderConsensusConfig.java
@@ -0,0 +1,40 @@
+/*
+ * 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.consensus.multileader.conf;
+
+import java.util.concurrent.TimeUnit;
+
+// TODO make it configurable
+public class MultiLeaderConsensusConfig {
+
+ private MultiLeaderConsensusConfig() {}
+
+ public static final int RPC_MAX_CONCURRENT_CLIENT_NUM = 65535;
+ public static final int THRIFT_SERVER_AWAIT_TIME_FOR_STOP_SERVICE = 60;
+ public static final boolean IS_RPC_THRIFT_COMPRESSION_ENABLED = false;
+ public static final int SELECTOR_NUM_OF_CLIENT_MANAGER = 1;
+ public static final int CONNECTION_TIMEOUT_IN_MS = (int) TimeUnit.SECONDS.toMillis(20);
+ public static final int MAX_PENDING_REQUEST_NUM_PER_NODE = 1000;
+ public static final int MAX_REQUEST_PER_BATCH = 100;
+ public static final int MAX_PENDING_BATCH = 50;
+ public static final int MAX_WAITING_TIME_FOR_ACCUMULATE_BATCH_IN_MS = 10;
+ public static final long BASIC_RETRY_WAIT_TIME_MS = TimeUnit.MILLISECONDS.toMillis(100);
+ public static final long MAX_RETRY_WAIT_TIME_MS = TimeUnit.SECONDS.toMillis(20);
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/IndexController.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/IndexController.java
new file mode 100644
index 0000000000..6a7396076d
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/IndexController.java
@@ -0,0 +1,150 @@
+/*
+ * 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.consensus.multileader.logdispatcher;
+
+import org.apache.iotdb.commons.utils.TestOnly;
+
+import org.apache.commons.io.FileUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.concurrent.ThreadSafe;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+
+/** An index controller class to balance the performance degradation of frequent disk I/O. */
+@ThreadSafe
+public class IndexController {
+
+ private final Logger logger = LoggerFactory.getLogger(IndexController.class);
+
+ public static final int FLUSH_INTERVAL = 500;
+
+ private volatile long lastFlushedIndex;
+ private volatile long currentIndex;
+
+ private final String storageDir;
+ private final String prefix;
+ // Indicates whether currentIndex needs to be incremented by FLUSH_INTERVAL interval after restart
+ private final boolean incrementIntervalAfterRestart;
+
+ public IndexController(String storageDir, String prefix, boolean incrementIntervalAfterRestart) {
+ this.storageDir = storageDir;
+ this.prefix = prefix + '-';
+ this.incrementIntervalAfterRestart = incrementIntervalAfterRestart;
+ restore();
+ }
+
+ public synchronized long incrementAndGet() {
+ currentIndex++;
+ checkPersist();
+ return currentIndex;
+ }
+
+ public synchronized long updateAndGet(long index) {
+ long newCurrentIndex = Math.max(currentIndex, index);
+ logger.debug(
+ "update index from currentIndex {} to {} for file prefix {} in {}",
+ currentIndex,
+ newCurrentIndex,
+ prefix,
+ storageDir);
+ currentIndex = newCurrentIndex;
+ checkPersist();
+ return currentIndex;
+ }
+
+ public long getCurrentIndex() {
+ return currentIndex;
+ }
+
+ @TestOnly
+ public long getLastFlushedIndex() {
+ return lastFlushedIndex;
+ }
+
+ private void checkPersist() {
+ if (currentIndex - lastFlushedIndex >= FLUSH_INTERVAL) {
+ persist();
+ }
+ }
+
+ private void persist() {
+ long flushIndex = currentIndex - currentIndex % FLUSH_INTERVAL;
+ File oldFile = new File(storageDir, prefix + lastFlushedIndex);
+ File newFile = new File(storageDir, prefix + flushIndex);
+ try {
+ if (oldFile.exists()) {
+ FileUtils.moveFile(oldFile, newFile);
+ }
+ logger.info(
+ "Version file updated, previous: {}, current: {}",
+ oldFile.getAbsolutePath(),
+ newFile.getAbsolutePath());
+ lastFlushedIndex = flushIndex;
+ } catch (IOException e) {
+ logger.error("Error occurred when flushing next version", e);
+ }
+ }
+
+ private void restore() {
+ File directory = new File(storageDir);
+ File[] versionFiles = directory.listFiles((dir, name) -> name.startsWith(prefix));
+ File versionFile;
+ if (versionFiles != null && versionFiles.length > 0) {
+ long maxVersion = 0;
+ int maxVersionIndex = 0;
+ for (int i = 0; i < versionFiles.length; i++) {
+ long fileVersion = Long.parseLong(versionFiles[i].getName().split("-")[1]);
+ if (fileVersion > maxVersion) {
+ maxVersion = fileVersion;
+ maxVersionIndex = i;
+ }
+ }
+ lastFlushedIndex = maxVersion;
+ for (int i = 0; i < versionFiles.length; i++) {
+ if (i != maxVersionIndex) {
+ try {
+ Files.delete(versionFiles[i].toPath());
+ } catch (IOException e) {
+ logger.error(
+ "Delete outdated version file {} failed", versionFiles[i].getAbsolutePath(), e);
+ }
+ }
+ }
+ if (incrementIntervalAfterRestart) {
+ // prevent overlapping in case of failure
+ currentIndex = lastFlushedIndex + FLUSH_INTERVAL;
+ persist();
+ } else {
+ currentIndex = lastFlushedIndex;
+ }
+ } else {
+ versionFile = new File(directory, prefix + "0");
+ try {
+ Files.createFile(versionFile.toPath());
+ } catch (IOException e) {
+ logger.error("Error occurred when creating new file {}", versionFile.getAbsolutePath(), e);
+ }
+ }
+ }
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/LogDispatcher.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/LogDispatcher.java
new file mode 100644
index 0000000000..3e664ce4e0
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/LogDispatcher.java
@@ -0,0 +1,299 @@
+/*
+ * 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.consensus.multileader.logdispatcher;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.client.IClientManager;
+import org.apache.iotdb.commons.concurrent.IoTDBThreadPoolFactory;
+import org.apache.iotdb.consensus.common.Peer;
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IndexedConsensusRequest;
+import org.apache.iotdb.consensus.multileader.MultiLeaderServerImpl;
+import org.apache.iotdb.consensus.multileader.client.AsyncMultiLeaderServiceClient;
+import org.apache.iotdb.consensus.multileader.client.DispatchLogHandler;
+import org.apache.iotdb.consensus.multileader.client.MultiLeaderConsensusClientPool.AsyncMultiLeaderServiceClientPoolFactory;
+import org.apache.iotdb.consensus.multileader.conf.MultiLeaderConsensusConfig;
+import org.apache.iotdb.consensus.multileader.thrift.TLogBatch;
+import org.apache.iotdb.consensus.multileader.thrift.TLogType;
+import org.apache.iotdb.consensus.multileader.thrift.TSyncLogReq;
+import org.apache.iotdb.consensus.multileader.wal.ConsensusReqReader;
+import org.apache.iotdb.consensus.multileader.wal.GetConsensusReqReaderPlan;
+import org.apache.iotdb.consensus.ratis.Utils;
+
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Objects;
+import java.util.OptionalLong;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+/** Manage all asynchronous replication threads and corresponding async clients */
+public class LogDispatcher {
+
+ private final Logger logger = LoggerFactory.getLogger(LogDispatcher.class);
+
+ private static final int DEFAULT_BUFFER_SIZE = 1024 * 15;
+
+ private final MultiLeaderServerImpl impl;
+ private final List<LogDispatcherThread> threads;
+ private ExecutorService executorService;
+ private IClientManager<TEndPoint, AsyncMultiLeaderServiceClient> clientManager;
+
+ public LogDispatcher(MultiLeaderServerImpl impl) {
+ this.impl = impl;
+ this.threads =
+ impl.getConfiguration().stream()
+ .filter(x -> !Objects.equals(x, impl.getThisNode()))
+ .map(LogDispatcherThread::new)
+ .collect(Collectors.toList());
+ if (!threads.isEmpty()) {
+ this.executorService =
+ IoTDBThreadPoolFactory.newFixedThreadPool(threads.size(), "LogDispatcher");
+ this.clientManager =
+ new IClientManager.Factory<TEndPoint, AsyncMultiLeaderServiceClient>()
+ .createClientManager(new AsyncMultiLeaderServiceClientPoolFactory());
+ }
+ }
+
+ public void start() {
+ if (!threads.isEmpty()) {
+ threads.forEach(executorService::submit);
+ }
+ }
+
+ public void stop() {
+ if (!threads.isEmpty()) {
+ threads.forEach(LogDispatcherThread::stop);
+ executorService.shutdownNow();
+ clientManager.close();
+ int timeout = 10;
+ try {
+ if (!executorService.awaitTermination(timeout, TimeUnit.SECONDS)) {
+ logger.error("Unable to shutdown LogDispatcher service after {} seconds", timeout);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ logger.error("Unexpected Interruption when closing LogDispatcher service ");
+ }
+ }
+ }
+
+ public OptionalLong getMinSyncIndex() {
+ return threads.stream().mapToLong(LogDispatcherThread::getCurrentSyncIndex).min();
+ }
+
+ public void offer(IndexedConsensusRequest request) {
+ threads.forEach(
+ thread -> {
+ if (!thread.offer(request)) {
+ logger.debug("Log queue of {} is full, ignore the log to this node", thread.getPeer());
+ }
+ });
+ }
+
+ public class LogDispatcherThread implements Runnable {
+
+ private volatile boolean stopped = false;
+ private final Peer peer;
+ private final IndexController controller;
+ // A sliding window class that manages asynchronously pendingBatches
+ private final SyncStatus syncStatus;
+ // A queue used to receive asynchronous replication requests
+ private final BlockingQueue<IndexedConsensusRequest> pendingRequest =
+ new ArrayBlockingQueue<>(MultiLeaderConsensusConfig.MAX_PENDING_REQUEST_NUM_PER_NODE);
+ // A container used to cache requests, whose size changes dynamically
+ private final List<IndexedConsensusRequest> bufferedRequest = new LinkedList<>();
+ // A reader management class that gets requests from the DataRegion
+ private final ConsensusReqReader reader =
+ (ConsensusReqReader) impl.getStateMachine().read(new GetConsensusReqReaderPlan());
+
+ public LogDispatcherThread(Peer peer) {
+ this.peer = peer;
+ this.controller =
+ new IndexController(
+ impl.getStorageDir(), Utils.fromTEndPointToString(peer.getEndpoint()), false);
+ this.syncStatus = new SyncStatus(controller);
+ }
+
+ public IndexController getController() {
+ return controller;
+ }
+
+ public long getCurrentSyncIndex() {
+ return controller.getCurrentIndex();
+ }
+
+ public Peer getPeer() {
+ return peer;
+ }
+
+ public boolean offer(IndexedConsensusRequest request) {
+ return pendingRequest.offer(request);
+ }
+
+ public void stop() {
+ stopped = true;
+ }
+
+ public boolean isStopped() {
+ return stopped;
+ }
+
+ @Override
+ public void run() {
+ logger.info("{}: Dispatcher for {} starts", impl.getThisNode(), peer);
+ try {
+ PendingBatch batch;
+ while (!Thread.interrupted() && !stopped) {
+ while ((batch = getBatch()).isEmpty()) {
+ // we may block here if there is no requests in the queue
+ bufferedRequest.add(pendingRequest.take());
+ // If write pressure is low, we simply sleep a little to reduce the number of RPC
+ if (pendingRequest.size() <= MultiLeaderConsensusConfig.MAX_REQUEST_PER_BATCH) {
+ Thread.sleep(MultiLeaderConsensusConfig.MAX_WAITING_TIME_FOR_ACCUMULATE_BATCH_IN_MS);
+ }
+ }
+ // we may block here if the synchronization pipeline is full
+ syncStatus.addNextBatch(batch);
+ // sends batch asynchronously and migrates the retry logic into the callback handler
+ sendBatchAsync(batch, new DispatchLogHandler(this, batch));
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } catch (Exception e) {
+ logger.error("Unexpected error in logDispatcher for peer {}", peer, e);
+ }
+ logger.info("{}: Dispatcher for {} exits", impl.getThisNode(), peer);
+ }
+
+ public PendingBatch getBatch() {
+ PendingBatch batch;
+ List<TLogBatch> logBatches = new ArrayList<>();
+ long startIndex = syncStatus.getNextSendingIndex();
+ long maxIndex = impl.getController().getCurrentIndex();
+ long endIndex;
+ if (bufferedRequest.size() <= MultiLeaderConsensusConfig.MAX_REQUEST_PER_BATCH) {
+ // Use drainTo instead of poll to reduce lock overhead
+ pendingRequest.drainTo(
+ bufferedRequest,
+ MultiLeaderConsensusConfig.MAX_REQUEST_PER_BATCH - bufferedRequest.size());
+ }
+ if (bufferedRequest.isEmpty()) {
+ // only execute this after a restart
+ endIndex = constructBatchFromWAL(startIndex, maxIndex, logBatches);
+ batch = new PendingBatch(startIndex, endIndex, logBatches);
+ logger.debug("accumulated a {} from wal", batch);
+ } else {
+ Iterator<IndexedConsensusRequest> iterator = bufferedRequest.iterator();
+ IndexedConsensusRequest prev = iterator.next();
+ // Prevents gap between logs. For example, some requests are not written into the queue when
+ // the queue is full. In this case, requests need to be loaded from the WAL
+ endIndex = constructBatchFromWAL(startIndex, prev.getSearchIndex(), logBatches);
+ if (logBatches.size() == MultiLeaderConsensusConfig.MAX_REQUEST_PER_BATCH) {
+ batch = new PendingBatch(startIndex, endIndex, logBatches);
+ logger.debug("accumulated a {} from wal", batch);
+ return batch;
+ }
+ constructBatchIndexedFromConsensusRequest(prev, logBatches);
+ endIndex = prev.getSearchIndex();
+ iterator.remove();
+ while (iterator.hasNext()
+ && logBatches.size() <= MultiLeaderConsensusConfig.MAX_REQUEST_PER_BATCH) {
+ IndexedConsensusRequest current = iterator.next();
+ // Prevents gap between logs. For example, some logs are not written into the queue when
+ // the queue is full. In this case, requests need to be loaded from the WAL
+ if (current.getSearchIndex() != prev.getSearchIndex() + 1) {
+ endIndex =
+ constructBatchFromWAL(prev.getSearchIndex(), current.getSearchIndex(), logBatches);
+ if (logBatches.size() == MultiLeaderConsensusConfig.MAX_REQUEST_PER_BATCH) {
+ batch = new PendingBatch(startIndex, endIndex, logBatches);
+ logger.debug("accumulated a {} from queue and wal", batch);
+ return batch;
+ }
+ }
+ constructBatchIndexedFromConsensusRequest(current, logBatches);
+ endIndex = current.getSearchIndex();
+ prev = current;
+ // We might not be able to remove all the elements in the bufferedRequest in the
+ // current function, but that's fine, we'll continue processing these elements in the
+ // bufferedRequest the next time we go into the function, they're never lost
+ iterator.remove();
+ }
+ batch = new PendingBatch(startIndex, endIndex, logBatches);
+ logger.debug("accumulated a {} from queue and wal", batch);
+ }
+ return batch;
+ }
+
+ public void sendBatchAsync(PendingBatch batch, DispatchLogHandler handler) {
+ try {
+ AsyncMultiLeaderServiceClient client = clientManager.borrowClient(peer.getEndpoint());
+ TSyncLogReq req =
+ new TSyncLogReq(peer.getGroupId().convertToTConsensusGroupId(), batch.getBatches());
+ client.syncLog(req, handler);
+ } catch (IOException | TException e) {
+ logger.error("Can not sync logs to peer {} because", peer, e);
+ }
+ }
+
+ public SyncStatus getSyncStatus() {
+ return syncStatus;
+ }
+
+ private long constructBatchFromWAL(
+ long currentIndex, long maxIndex, List<TLogBatch> logBatches) {
+ while (currentIndex < maxIndex
+ && logBatches.size() < MultiLeaderConsensusConfig.MAX_REQUEST_PER_BATCH) {
+ // TODO iterator
+ IConsensusRequest data = reader.getReq(currentIndex++);
+ if (data != null) {
+ // TODO fix byteBuffer overflow
+ ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
+ data.serializeRequest(buffer);
+ buffer.flip();
+ // since WAL can no longer recover FragmentInstance, but only PlanNode, we need to give
+ // special flags to use different deserialization methods in the dataRegion stateMachine
+ logBatches.add(new TLogBatch(TLogType.InsertNode, buffer));
+ }
+ }
+ return currentIndex - 1;
+ }
+
+ private void constructBatchIndexedFromConsensusRequest(
+ IndexedConsensusRequest request, List<TLogBatch> logBatches) {
+ // TODO fix byteBuffer overflow
+ ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
+ request.serializeRequest(buffer);
+ buffer.flip();
+ logBatches.add(new TLogBatch(TLogType.FragmentInstance, buffer));
+ }
+ }
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/PendingBatch.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/PendingBatch.java
new file mode 100644
index 0000000000..b385f73c97
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/PendingBatch.java
@@ -0,0 +1,76 @@
+/*
+ * 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.consensus.multileader.logdispatcher;
+
+import org.apache.iotdb.consensus.multileader.thrift.TLogBatch;
+
+import java.util.List;
+
+public class PendingBatch {
+
+ private final long startIndex;
+ private final long endIndex;
+ private final List<TLogBatch> batches;
+ // indicates whether this batch has been successfully synchronized to another node
+ private boolean synced;
+
+ public PendingBatch(long startIndex, long endIndex, List<TLogBatch> batches) {
+ this.startIndex = startIndex;
+ this.endIndex = endIndex;
+ this.batches = batches;
+ this.synced = false;
+ }
+
+ public long getStartIndex() {
+ return startIndex;
+ }
+
+ public long getEndIndex() {
+ return endIndex;
+ }
+
+ public List<TLogBatch> getBatches() {
+ return batches;
+ }
+
+ public boolean isSynced() {
+ return synced;
+ }
+
+ public void setSynced(boolean synced) {
+ this.synced = synced;
+ }
+
+ public boolean isEmpty() {
+ return batches.isEmpty();
+ }
+
+ @Override
+ public String toString() {
+ return "PendingBatch{"
+ + "startIndex="
+ + startIndex
+ + ", endIndex="
+ + endIndex
+ + ", size="
+ + batches.size()
+ + '}';
+ }
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/SyncStatus.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/SyncStatus.java
new file mode 100644
index 0000000000..fb521b9b07
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/logdispatcher/SyncStatus.java
@@ -0,0 +1,89 @@
+/*
+ * 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.consensus.multileader.logdispatcher;
+
+import org.apache.iotdb.commons.utils.TestOnly;
+import org.apache.iotdb.consensus.multileader.conf.MultiLeaderConsensusConfig;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+public class SyncStatus {
+
+ private final IndexController controller;
+ private final List<PendingBatch> pendingBatches = new LinkedList<>();
+
+ public SyncStatus(IndexController controller) {
+ this.controller = controller;
+ }
+
+ /** we may block here if the synchronization pipeline is full */
+ public void addNextBatch(PendingBatch batch) throws InterruptedException {
+ synchronized (this) {
+ while (pendingBatches.size() >= MultiLeaderConsensusConfig.MAX_PENDING_BATCH) {
+ wait();
+ }
+ pendingBatches.add(batch);
+ }
+ }
+
+ /**
+ * We only set a flag if this batch is not the first one. Notice, We need to confirm that the
+ * batch in the parameter is actually in pendingBatches, rather than a reference to a different
+ * object with equal data, so we do not inherit method equals for PendingBatch
+ */
+ public void removeBatch(PendingBatch batch) {
+ synchronized (this) {
+ batch.setSynced(true);
+ if (pendingBatches.size() > 0 && pendingBatches.get(0).equals(batch)) {
+ Iterator<PendingBatch> iterator = pendingBatches.iterator();
+ PendingBatch current = iterator.next();
+ while (current.isSynced()) {
+ controller.updateAndGet(current.getEndIndex());
+ iterator.remove();
+ if (iterator.hasNext()) {
+ current = iterator.next();
+ } else {
+ break;
+ }
+ }
+ // wake up logDispatcherThread that might be blocked
+ notifyAll();
+ }
+ }
+ }
+
+ /** Gets the first index that is not currently synchronized */
+ public long getNextSendingIndex() {
+ // we do not use ReentrantReadWriteLock because there will be only one thread reading this field
+ synchronized (this) {
+ return 1
+ + (pendingBatches.isEmpty()
+ ? controller.getCurrentIndex()
+ : pendingBatches.get(pendingBatches.size() - 1).getEndIndex());
+ }
+ }
+
+ @TestOnly
+ public List<PendingBatch> getPendingBatches() {
+ return pendingBatches;
+ }
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCService.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCService.java
new file mode 100644
index 0000000000..694a7e038b
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCService.java
@@ -0,0 +1,95 @@
+/*
+ * 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.consensus.multileader.service;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.concurrent.ThreadName;
+import org.apache.iotdb.commons.conf.IoTDBConstant;
+import org.apache.iotdb.commons.exception.runtime.RPCServiceException;
+import org.apache.iotdb.commons.service.ServiceType;
+import org.apache.iotdb.commons.service.ThriftService;
+import org.apache.iotdb.commons.service.ThriftServiceThread;
+import org.apache.iotdb.consensus.multileader.conf.MultiLeaderConsensusConfig;
+import org.apache.iotdb.consensus.multileader.thrift.MultiLeaderConsensusIService;
+
+import java.lang.reflect.InvocationTargetException;
+
+public class MultiLeaderRPCService extends ThriftService implements MultiLeaderRPCServiceMBean {
+
+ private final TEndPoint thisNode;
+ private MultiLeaderRPCServiceProcessor multiLeaderRPCServiceProcessor;
+
+ public MultiLeaderRPCService(TEndPoint thisNode) {
+ this.thisNode = thisNode;
+ }
+
+ @Override
+ public ServiceType getID() {
+ return ServiceType.MULTI_LEADER_CONSENSUS_SERVICE;
+ }
+
+ @Override
+ public void initSyncedServiceImpl(Object multiLeaderRPCServiceProcessor) {
+ this.multiLeaderRPCServiceProcessor =
+ (MultiLeaderRPCServiceProcessor) multiLeaderRPCServiceProcessor;
+ super.mbeanName =
+ String.format(
+ "%s:%s=%s", this.getClass().getPackage(), IoTDBConstant.JMX_TYPE, getID().getJmxName());
+ super.initSyncedServiceImpl(this.multiLeaderRPCServiceProcessor);
+ }
+
+ @Override
+ public void initTProcessor()
+ throws ClassNotFoundException, IllegalAccessException, InstantiationException,
+ NoSuchMethodException, InvocationTargetException {
+ processor = new MultiLeaderConsensusIService.Processor<>(multiLeaderRPCServiceProcessor);
+ }
+
+ @Override
+ public void initThriftServiceThread()
+ throws IllegalAccessException, InstantiationException, ClassNotFoundException {
+ try {
+ thriftServiceThread =
+ new ThriftServiceThread(
+ processor,
+ getID().getName(),
+ ThreadName.MULTI_LEADER_CONSENSUS_RPC_CLIENT.getName(),
+ getBindIP(),
+ getBindPort(),
+ MultiLeaderConsensusConfig.RPC_MAX_CONCURRENT_CLIENT_NUM,
+ MultiLeaderConsensusConfig.THRIFT_SERVER_AWAIT_TIME_FOR_STOP_SERVICE,
+ new MultiLeaderRPCServiceHandler(multiLeaderRPCServiceProcessor),
+ MultiLeaderConsensusConfig.IS_RPC_THRIFT_COMPRESSION_ENABLED);
+ } catch (RPCServiceException e) {
+ throw new IllegalAccessException(e.getMessage());
+ }
+ thriftServiceThread.setName(ThreadName.MULTI_LEADER_CONSENSUS_RPC_SERVER.getName());
+ }
+
+ @Override
+ public String getBindIP() {
+ return thisNode.getIp();
+ }
+
+ @Override
+ public int getBindPort() {
+ return thisNode.getPort();
+ }
+}
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/EmptyStateMachine.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCServiceHandler.java
similarity index 51%
copy from consensus/src/test/java/org/apache/iotdb/consensus/EmptyStateMachine.java
copy to consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCServiceHandler.java
index 01992f472f..889ac7d517 100644
--- a/consensus/src/test/java/org/apache/iotdb/consensus/EmptyStateMachine.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCServiceHandler.java
@@ -17,37 +17,35 @@
* under the License.
*/
-package org.apache.iotdb.consensus;
+package org.apache.iotdb.consensus.multileader.service;
-import org.apache.iotdb.common.rpc.thrift.TSStatus;
-import org.apache.iotdb.consensus.common.DataSet;
-import org.apache.iotdb.consensus.common.request.IConsensusRequest;
+import org.apache.thrift.protocol.TProtocol;
+import org.apache.thrift.server.ServerContext;
+import org.apache.thrift.server.TServerEventHandler;
+import org.apache.thrift.transport.TTransport;
-import java.io.File;
+public class MultiLeaderRPCServiceHandler implements TServerEventHandler {
-public class EmptyStateMachine implements IStateMachine, IStateMachine.EventApi {
+ private final MultiLeaderRPCServiceProcessor processor;
- @Override
- public void start() {}
-
- @Override
- public void stop() {}
+ public MultiLeaderRPCServiceHandler(MultiLeaderRPCServiceProcessor processor) {
+ this.processor = processor;
+ }
@Override
- public TSStatus write(IConsensusRequest IConsensusRequest) {
- return new TSStatus(0);
- }
+ public void preServe() {}
@Override
- public DataSet read(IConsensusRequest IConsensusRequest) {
+ public ServerContext createContext(TProtocol input, TProtocol output) {
return null;
}
@Override
- public boolean takeSnapshot(File snapshotDir) {
- return false;
+ public void deleteContext(ServerContext serverContext, TProtocol input, TProtocol output) {
+ processor.handleClientExit();
}
@Override
- public void loadSnapshot(File latestSnapshotRootDir) {}
+ public void processContext(
+ ServerContext serverContext, TTransport inputTransport, TTransport outputTransport) {}
}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCServiceMBean.java
similarity index 73%
copy from consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java
copy to consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCServiceMBean.java
index d2026a5515..9e354ac204 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCServiceMBean.java
@@ -17,13 +17,6 @@
* under the License.
*/
-package org.apache.iotdb.consensus.exception;
+package org.apache.iotdb.consensus.multileader.service;
-public class IllegalPeerNumException extends ConsensusException {
-
- public IllegalPeerNumException(int size) {
- super(
- String.format(
- "Illegal Peer num %d, only support one peer in StandAloneConsensus Mode", size));
- }
-}
+public interface MultiLeaderRPCServiceMBean {}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCServiceProcessor.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCServiceProcessor.java
new file mode 100644
index 0000000000..05a2c4cb03
--- /dev/null
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/service/MultiLeaderRPCServiceProcessor.java
@@ -0,0 +1,82 @@
+/*
+ * 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.consensus.multileader.service;
+
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.commons.consensus.ConsensusGroupId;
+import org.apache.iotdb.consensus.common.request.ByteBufferConsensusRequest;
+import org.apache.iotdb.consensus.multileader.MultiLeaderConsensus;
+import org.apache.iotdb.consensus.multileader.MultiLeaderServerImpl;
+import org.apache.iotdb.consensus.multileader.thrift.MultiLeaderConsensusIService;
+import org.apache.iotdb.consensus.multileader.thrift.TLogBatch;
+import org.apache.iotdb.consensus.multileader.thrift.TSyncLogReq;
+import org.apache.iotdb.consensus.multileader.thrift.TSyncLogRes;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+public class MultiLeaderRPCServiceProcessor implements MultiLeaderConsensusIService.Iface {
+
+ private final Logger logger = LoggerFactory.getLogger(MultiLeaderRPCServiceProcessor.class);
+
+ private final MultiLeaderConsensus consensus;
+
+ public MultiLeaderRPCServiceProcessor(MultiLeaderConsensus consensus) {
+ this.consensus = consensus;
+ }
+
+ @Override
+ public TSyncLogRes syncLog(TSyncLogReq req) throws TException {
+ ConsensusGroupId groupId =
+ ConsensusGroupId.Factory.createFromTConsensusGroupId(req.getConsensusGroupId());
+ MultiLeaderServerImpl impl = consensus.getImpl(groupId);
+ if (impl == null) {
+ String message =
+ String.format(
+ "Unexpected consensusGroupId %s for TSyncLogReq which size is %s",
+ groupId, req.getBatches().size());
+ logger.error(message);
+ TSStatus status = new TSStatus(TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
+ status.setMessage(message);
+ return new TSyncLogRes(Collections.singletonList(status));
+ }
+ List<TSStatus> statuses = new ArrayList<>();
+ // We use synchronized to ensure atomicity of executing multiple logs
+ synchronized (impl.getStateMachine()) {
+ for (TLogBatch batch : req.getBatches()) {
+ statuses.add(
+ impl.getStateMachine()
+ .write(
+ impl.buildIndexedConsensusRequestForRemoteRequest(
+ new ByteBufferConsensusRequest(batch.data), batch.type)));
+ }
+ }
+ logger.debug("Execute TSyncLogReq for {} with result {}", req.consensusGroupId, statuses);
+ return new TSyncLogRes(statuses);
+ }
+
+ public void handleClientExit() {}
+}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/wal/ConsensusReqReader.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/wal/ConsensusReqReader.java
similarity index 97%
rename from consensus/src/main/java/org/apache/iotdb/consensus/wal/ConsensusReqReader.java
rename to consensus/src/main/java/org/apache/iotdb/consensus/multileader/wal/ConsensusReqReader.java
index d27e9b93e5..5880e5de2d 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/wal/ConsensusReqReader.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/wal/ConsensusReqReader.java
@@ -16,7 +16,8 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.iotdb.consensus.wal;
+
+package org.apache.iotdb.consensus.multileader.wal;
import org.apache.iotdb.consensus.common.request.IConsensusRequest;
@@ -27,6 +28,9 @@ import java.util.concurrent.TimeoutException;
/** This interface provides search interface for consensus requests via index. */
public interface ConsensusReqReader {
+
+ long DEFAULT_SEARCH_INDEX = -1;
+
/**
* Gets the consensus request at the specified position.
*
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/wal/GetConsensusReqReaderPlan.java
similarity index 73%
copy from consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java
copy to consensus/src/main/java/org/apache/iotdb/consensus/multileader/wal/GetConsensusReqReaderPlan.java
index d2026a5515..a9e9f8f34e 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/exception/IllegalPeerNumException.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/multileader/wal/GetConsensusReqReaderPlan.java
@@ -17,13 +17,14 @@
* under the License.
*/
-package org.apache.iotdb.consensus.exception;
+package org.apache.iotdb.consensus.multileader.wal;
-public class IllegalPeerNumException extends ConsensusException {
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
- public IllegalPeerNumException(int size) {
- super(
- String.format(
- "Illegal Peer num %d, only support one peer in StandAloneConsensus Mode", size));
- }
+import java.nio.ByteBuffer;
+
+public class GetConsensusReqReaderPlan implements IConsensusRequest {
+
+ @Override
+ public void serializeRequest(ByteBuffer buffer) {}
}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisClient.java b/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisClient.java
index 8d1643bc0e..1d8c659b62 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisClient.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisClient.java
@@ -28,7 +28,7 @@ import org.apache.ratis.client.RaftClient;
import org.apache.ratis.client.RaftClientRpc;
import org.apache.ratis.conf.RaftProperties;
import org.apache.ratis.protocol.RaftGroup;
-import org.apache.ratis.retry.RetryPolicies;
+import org.apache.ratis.retry.ExponentialBackoffRetry;
import org.apache.ratis.util.TimeDuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -98,8 +98,11 @@ public class RatisClient {
.setProperties(raftProperties)
.setRaftGroup(group)
.setRetryPolicy(
- RetryPolicies.retryForeverWithSleep(
- TimeDuration.valueOf(100, TimeUnit.MILLISECONDS)))
+ ExponentialBackoffRetry.newBuilder()
+ .setBaseSleepTime(TimeDuration.valueOf(100, TimeUnit.MILLISECONDS))
+ .setMaxSleepTime(TimeDuration.valueOf(10, TimeUnit.SECONDS))
+ .setMaxAttempts(10)
+ .build())
.setClientRpc(clientRpc)
.build(),
clientManager));
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisConsensus.java b/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisConsensus.java
index b5a027d0ab..0c96034f7c 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisConsensus.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisConsensus.java
@@ -62,7 +62,6 @@ import org.apache.ratis.protocol.exceptions.NotLeaderException;
import org.apache.ratis.server.DivisionInfo;
import org.apache.ratis.server.RaftServer;
import org.apache.ratis.server.RaftServerConfigKeys;
-import org.apache.ratis.util.NetUtils;
import org.apache.ratis.util.TimeDuration;
import org.apache.thrift.TException;
import org.slf4j.Logger;
@@ -116,11 +115,10 @@ class RatisConsensus implements IConsensus {
*/
public RatisConsensus(TEndPoint endpoint, File ratisStorageDir, IStateMachine.Registry registry)
throws IOException {
- System.setProperty(
- "org.apache.ratis.thirdparty.io.netty.allocator.useCacheForAllThreads", "false");
- String address = Utils.IPAddress(endpoint);
myself = Utils.fromTEndPointAndPriorityToRaftPeer(endpoint, DEFAULT_PRIORITY);
+ System.setProperty(
+ "org.apache.ratis.thirdparty.io.netty.allocator.useCacheForAllThreads", "false");
RaftServerConfigKeys.setStorageDir(properties, Collections.singletonList(ratisStorageDir));
RaftServerConfigKeys.Snapshot.setAutoTriggerEnabled(properties, true);
// TODO make this configurable so that RatisConsensusTest can trigger multiple snapshot process
@@ -130,13 +128,10 @@ class RatisConsensus implements IConsensus {
RaftServerConfigKeys.Rpc.setTimeoutMin(properties, TimeDuration.valueOf(2, TimeUnit.SECONDS));
RaftServerConfigKeys.Rpc.setTimeoutMax(properties, TimeDuration.valueOf(8, TimeUnit.SECONDS));
RaftServerConfigKeys.Rpc.setSleepTime(properties, TimeDuration.valueOf(1, TimeUnit.SECONDS));
-
RaftClientConfigKeys.Rpc.setRequestTimeout(
properties, TimeDuration.valueOf(20, TimeUnit.SECONDS));
- // set the port which server listen to in RaftProperty object
- final int port = NetUtils.createSocketAddr(address).getPort();
- GrpcConfigKeys.Server.setPort(properties, port);
+ GrpcConfigKeys.Server.setPort(properties, endpoint.getPort());
clientRpc = new GrpcFactory(new Parameters()).newRaftClientRpc(ClientId.randomId(), properties);
server =
@@ -478,7 +473,6 @@ class RatisConsensus implements IConsensus {
if (!reply.isSuccess()) {
return failed(new RatisRequestFailedException(reply.getException()));
}
-
} catch (IOException e) {
return failed(new RatisRequestFailedException(e));
} finally {
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RequestMessage.java b/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RequestMessage.java
index 242573e5be..004aae81bb 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RequestMessage.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RequestMessage.java
@@ -30,7 +30,7 @@ public class RequestMessage implements Message {
private final IConsensusRequest actualRequest;
private volatile ByteString serializedContent;
- private static final int DEFAULT_BUFFER_SIZE = 2048 * 10;
+ private static final int DEFAULT_BUFFER_SIZE = 1024 * 30;
public RequestMessage(IConsensusRequest request) {
this.actualRequest = request;
@@ -46,9 +46,8 @@ public class RequestMessage implements Message {
if (serializedContent == null) {
synchronized (this) {
if (serializedContent == null) {
- ByteBufferConsensusRequest req;
if (actualRequest instanceof ByteBufferConsensusRequest) {
- req = (ByteBufferConsensusRequest) actualRequest;
+ ByteBufferConsensusRequest req = (ByteBufferConsensusRequest) actualRequest;
serializedContent = ByteString.copyFrom(req.getContent());
req.getContent().flip();
} else {
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/ratis/Utils.java b/consensus/src/main/java/org/apache/iotdb/consensus/ratis/Utils.java
index 48f8598230..e34ec9d60f 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/ratis/Utils.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/ratis/Utils.java
@@ -42,10 +42,16 @@ public class Utils {
private static final int tempBufferSize = 1024;
private static final byte PADDING_MAGIC = 0x47;
- public static String IPAddress(TEndPoint endpoint) {
+ private Utils() {}
+
+ public static String HostAddress(TEndPoint endpoint) {
return String.format("%s:%d", endpoint.getIp(), endpoint.getPort());
}
+ public static String fromTEndPointToString(TEndPoint endpoint) {
+ return String.format("%s_%d", endpoint.getIp(), endpoint.getPort());
+ }
+
/** Encode the ConsensusGroupId into 6 bytes: 2 Bytes for Group Type and 4 Bytes for Group ID */
public static long groupEncode(ConsensusGroupId consensusGroupId) {
// use abbreviations to prevent overflow
@@ -56,11 +62,11 @@ public class Utils {
}
public static RaftPeerId fromTEndPointToRaftPeerId(TEndPoint endpoint) {
- return RaftPeerId.valueOf(String.format("%s-%d", endpoint.getIp(), endpoint.getPort()));
+ return RaftPeerId.valueOf(fromTEndPointToString(endpoint));
}
public static TEndPoint formRaftPeerIdToTEndPoint(RaftPeerId id) {
- String[] items = id.toString().split("-");
+ String[] items = id.toString().split("_");
return new TEndPoint(items[0], Integer.parseInt(items[1]));
}
@@ -73,7 +79,7 @@ public class Utils {
public static RaftPeer fromTEndPointAndPriorityToRaftPeer(TEndPoint endpoint, int priority) {
return RaftPeer.newBuilder()
.setId(fromTEndPointToRaftPeerId(endpoint))
- .setAddress(IPAddress(endpoint))
+ .setAddress(HostAddress(endpoint))
.setPriority(priority)
.build();
}
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/standalone/StandAloneConsensus.java b/consensus/src/main/java/org/apache/iotdb/consensus/standalone/StandAloneConsensus.java
index 4c2100d1e1..3604d29059 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/standalone/StandAloneConsensus.java
+++ b/consensus/src/main/java/org/apache/iotdb/consensus/standalone/StandAloneConsensus.java
@@ -19,7 +19,6 @@
package org.apache.iotdb.consensus.standalone;
-import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.consensus.ConsensusGroupId;
import org.apache.iotdb.consensus.IConsensus;
@@ -43,9 +42,9 @@ import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -86,19 +85,21 @@ class StandAloneConsensus implements IConsensus {
String[] items = path.getFileName().toString().split("_");
ConsensusGroupId consensusGroupId =
ConsensusGroupId.Factory.create(
- TConsensusGroupType.valueOf(items[0]).getValue(), Integer.parseInt(items[1]));
- TEndPoint endPoint = new TEndPoint(items[2], Integer.parseInt(items[3]));
- stateMachineMap.put(
- consensusGroupId,
+ Integer.parseInt(items[0]), Integer.parseInt(items[1]));
+ StandAloneServerImpl consensus =
new StandAloneServerImpl(
- new Peer(consensusGroupId, endPoint), registry.apply(consensusGroupId)));
+ new Peer(consensusGroupId, thisNode), registry.apply(consensusGroupId));
+ stateMachineMap.put(consensusGroupId, consensus);
+ consensus.start();
}
}
}
}
@Override
- public void stop() throws IOException {}
+ public void stop() throws IOException {
+ stateMachineMap.values().parallelStream().forEach(StandAloneServerImpl::stop);
+ }
@Override
public ConsensusWriteResponse write(ConsensusGroupId groupId, IConsensusRequest request) {
@@ -130,15 +131,15 @@ class StandAloneConsensus implements IConsensus {
.setException(new IllegalPeerNumException(consensusGroupSize))
.build();
}
- if (!Objects.equals(thisNode, peers.get(0).getEndpoint())) {
+ if (!peers.contains(new Peer(groupId, thisNode))) {
return ConsensusGenericResponse.newBuilder()
- .setException(new IllegalPeerEndpointException(thisNode, peers.get(0).getEndpoint()))
+ .setException(new IllegalPeerEndpointException(thisNode, peers))
.build();
}
AtomicBoolean exist = new AtomicBoolean(true);
stateMachineMap.computeIfAbsent(
groupId,
- (k) -> {
+ k -> {
exist.set(false);
StandAloneServerImpl impl =
new StandAloneServerImpl(peers.get(0), registry.apply(groupId));
@@ -167,9 +168,11 @@ class StandAloneConsensus implements IConsensus {
exist.set(true);
v.stop();
String path = buildPeerDir(groupId);
- File file = new File(path);
- if (!file.delete()) {
- logger.warn("Unable to delete consensus dir for group {} at {}", groupId, path);
+ try {
+ Files.delete(Paths.get(path));
+ } catch (IOException e) {
+ logger.warn(
+ "Unable to delete consensus dir for group {} at {} because {}", groupId, path, e);
}
return null;
});
@@ -221,14 +224,6 @@ class StandAloneConsensus implements IConsensus {
}
private String buildPeerDir(ConsensusGroupId groupId) {
- return storageDir
- + File.separator
- + groupId.getType()
- + "_"
- + groupId.getId()
- + "_"
- + thisNode.getIp()
- + "_"
- + thisNode.getPort();
+ return storageDir + File.separator + groupId.getType().getValue() + "_" + groupId.getId();
}
}
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/multileader/MultiLeaderConsensusTest.java b/consensus/src/test/java/org/apache/iotdb/consensus/multileader/MultiLeaderConsensusTest.java
new file mode 100644
index 0000000000..770031bee1
--- /dev/null
+++ b/consensus/src/test/java/org/apache/iotdb/consensus/multileader/MultiLeaderConsensusTest.java
@@ -0,0 +1,419 @@
+/*
+ * 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.consensus.multileader;
+
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.commons.consensus.ConsensusGroupId;
+import org.apache.iotdb.commons.consensus.DataRegionId;
+import org.apache.iotdb.consensus.ConsensusFactory;
+import org.apache.iotdb.consensus.IStateMachine;
+import org.apache.iotdb.consensus.common.ConsensusGroup;
+import org.apache.iotdb.consensus.common.DataSet;
+import org.apache.iotdb.consensus.common.Peer;
+import org.apache.iotdb.consensus.common.request.ByteBufferConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IndexedConsensusRequest;
+import org.apache.iotdb.consensus.multileader.logdispatcher.IndexController;
+import org.apache.iotdb.consensus.multileader.thrift.TLogType;
+import org.apache.iotdb.consensus.multileader.wal.ConsensusReqReader;
+import org.apache.iotdb.consensus.multileader.wal.GetConsensusReqReaderPlan;
+
+import org.apache.ratis.util.FileUtils;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+
+public class MultiLeaderConsensusTest {
+
+ private final Logger logger = LoggerFactory.getLogger(MultiLeaderConsensusTest.class);
+
+ private final ConsensusGroupId gid = new DataRegionId(1);
+
+ private final List<Peer> peers =
+ Arrays.asList(
+ new Peer(gid, new TEndPoint("127.0.0.1", 6000)),
+ new Peer(gid, new TEndPoint("127.0.0.1", 6001)),
+ new Peer(gid, new TEndPoint("127.0.0.1", 6002)));
+
+ private final List<File> peersStorage =
+ Arrays.asList(
+ new File("target" + java.io.File.separator + "1"),
+ new File("target" + java.io.File.separator + "2"),
+ new File("target" + java.io.File.separator + "3"));
+
+ private final ConsensusGroup group = new ConsensusGroup(gid, peers);
+ private final List<MultiLeaderConsensus> servers = new ArrayList<>();
+ private final List<TestStateMachine> stateMachines = new ArrayList<>();
+
+ @Before
+ public void setUp() throws Exception {
+ for (int i = 0; i < 3; i++) {
+ peersStorage.get(i).mkdirs();
+ stateMachines.add(new TestStateMachine());
+ }
+ initServer();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ stopServer();
+ for (File file : peersStorage) {
+ FileUtils.deleteFully(file);
+ }
+ }
+
+ private void initServer() throws IOException {
+ for (int i = 0; i < 3; i++) {
+ int finalI = i;
+ servers.add(
+ (MultiLeaderConsensus)
+ ConsensusFactory.getConsensusImpl(
+ ConsensusFactory.MultiLeaderConsensus,
+ peers.get(i).getEndpoint(),
+ peersStorage.get(i),
+ groupId -> stateMachines.get(finalI))
+ .orElseThrow(
+ () ->
+ new IllegalArgumentException(
+ String.format(
+ ConsensusFactory.CONSTRUCT_FAILED_MSG,
+ ConsensusFactory.MultiLeaderConsensus))));
+ servers.get(i).start();
+ }
+ }
+
+ private void stopServer() {
+ servers.parallelStream().forEach(MultiLeaderConsensus::stop);
+ servers.clear();
+ }
+
+ /**
+ * The three nodes use the requests in the queue to replicate the requests to the other two nodes
+ */
+ @Test
+ public void ReplicateUsingQueueTest() throws IOException, InterruptedException {
+ logger.info("Start ReplicateUsingQueueTest");
+ servers.get(0).addConsensusGroup(group.getGroupId(), group.getPeers());
+ servers.get(1).addConsensusGroup(group.getGroupId(), group.getPeers());
+ servers.get(2).addConsensusGroup(group.getGroupId(), group.getPeers());
+
+ Assert.assertEquals(0, servers.get(0).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(0, servers.get(1).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(0, servers.get(2).getImpl(gid).getController().getCurrentIndex());
+
+ for (int i = 0; i < IndexController.FLUSH_INTERVAL; i++) {
+ servers.get(0).write(gid, new TestEntry(i, peers.get(0)));
+ servers.get(1).write(gid, new TestEntry(i, peers.get(1)));
+ servers.get(2).write(gid, new TestEntry(i, peers.get(2)));
+ Assert.assertEquals(i + 1, servers.get(0).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(i + 1, servers.get(1).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(i + 1, servers.get(2).getImpl(gid).getController().getCurrentIndex());
+ }
+
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(0).getImpl(gid).getController().getLastFlushedIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(1).getImpl(gid).getController().getLastFlushedIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(2).getImpl(gid).getController().getLastFlushedIndex());
+
+ for (int i = 0; i < 3; i++) {
+ long start = System.currentTimeMillis();
+ while (servers.get(i).getImpl(gid).getCurrentSafelyDeletedSearchIndex()
+ < IndexController.FLUSH_INTERVAL) {
+ long current = System.currentTimeMillis();
+ if ((current - start) > 20 * 1000) {
+ Assert.fail("Unable to replicate entries");
+ }
+ Thread.sleep(100);
+ }
+ }
+
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(0).getImpl(gid).getCurrentSafelyDeletedSearchIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(1).getImpl(gid).getCurrentSafelyDeletedSearchIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(2).getImpl(gid).getCurrentSafelyDeletedSearchIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 3, stateMachines.get(0).getRequestSet().size());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 3, stateMachines.get(1).getRequestSet().size());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 3, stateMachines.get(2).getRequestSet().size());
+ Assert.assertEquals(stateMachines.get(0).getData(), stateMachines.get(1).getData());
+ Assert.assertEquals(stateMachines.get(2).getData(), stateMachines.get(1).getData());
+
+ stopServer();
+ initServer();
+
+ Assert.assertEquals(peers, servers.get(0).getImpl(gid).getConfiguration());
+ Assert.assertEquals(peers, servers.get(1).getImpl(gid).getConfiguration());
+ Assert.assertEquals(peers, servers.get(2).getImpl(gid).getConfiguration());
+
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 2,
+ servers.get(0).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 2,
+ servers.get(1).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 2,
+ servers.get(2).getImpl(gid).getController().getCurrentIndex());
+
+ for (int i = 0; i < 3; i++) {
+ long start = System.currentTimeMillis();
+ while (servers.get(i).getImpl(gid).getCurrentSafelyDeletedSearchIndex()
+ < IndexController.FLUSH_INTERVAL) {
+ long current = System.currentTimeMillis();
+ if ((current - start) > 20 * 1000) {
+ Assert.fail("Unable to recover entries");
+ }
+ Thread.sleep(100);
+ }
+ }
+
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(1).getImpl(gid).getCurrentSafelyDeletedSearchIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(1).getImpl(gid).getCurrentSafelyDeletedSearchIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(2).getImpl(gid).getCurrentSafelyDeletedSearchIndex());
+ }
+
+ /**
+ * First, suspend one node to test that the request replication between the two alive nodes is ok,
+ * then restart all nodes to lose state in the queue, and test using WAL replication to make all
+ * nodes finally consistent
+ */
+ @Test
+ public void ReplicateUsingWALTest() throws IOException, InterruptedException {
+ logger.info("Start ReplicateUsingWALTest");
+ servers.get(0).addConsensusGroup(group.getGroupId(), group.getPeers());
+ servers.get(1).addConsensusGroup(group.getGroupId(), group.getPeers());
+
+ Assert.assertEquals(0, servers.get(0).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(0, servers.get(1).getImpl(gid).getController().getCurrentIndex());
+
+ for (int i = 0; i < IndexController.FLUSH_INTERVAL; i++) {
+ servers.get(0).write(gid, new TestEntry(i, peers.get(0)));
+ servers.get(1).write(gid, new TestEntry(i, peers.get(1)));
+ Assert.assertEquals(i + 1, servers.get(0).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(i + 1, servers.get(1).getImpl(gid).getController().getCurrentIndex());
+ }
+
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(0).getImpl(gid).getController().getLastFlushedIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL,
+ servers.get(1).getImpl(gid).getController().getLastFlushedIndex());
+
+ Assert.assertEquals(0, servers.get(0).getImpl(gid).getCurrentSafelyDeletedSearchIndex());
+ Assert.assertEquals(0, servers.get(1).getImpl(gid).getCurrentSafelyDeletedSearchIndex());
+
+ stopServer();
+ initServer();
+
+ servers.get(2).addConsensusGroup(group.getGroupId(), group.getPeers());
+
+ Assert.assertEquals(peers, servers.get(0).getImpl(gid).getConfiguration());
+ Assert.assertEquals(peers, servers.get(1).getImpl(gid).getConfiguration());
+ Assert.assertEquals(peers, servers.get(2).getImpl(gid).getConfiguration());
+
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 2,
+ servers.get(0).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 2,
+ servers.get(1).getImpl(gid).getController().getCurrentIndex());
+ Assert.assertEquals(0, servers.get(2).getImpl(gid).getController().getCurrentIndex());
+
+ for (int i = 0; i < 2; i++) {
+ long start = System.currentTimeMillis();
+ // should be [IndexController.FLUSH_INTERVAL, IndexController.FLUSH_INTERVAL * 2 - 1] after
+ // replicating all entries
+ while (servers.get(i).getImpl(gid).getCurrentSafelyDeletedSearchIndex()
+ < IndexController.FLUSH_INTERVAL) {
+ long current = System.currentTimeMillis();
+ if ((current - start) > 20 * 1000) {
+ logger.error("{}", servers.get(i).getImpl(gid).getCurrentSafelyDeletedSearchIndex());
+ Assert.fail("Unable to replicate entries");
+ }
+ Thread.sleep(100);
+ }
+ }
+
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 2, stateMachines.get(0).getRequestSet().size());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 2, stateMachines.get(1).getRequestSet().size());
+ Assert.assertEquals(
+ IndexController.FLUSH_INTERVAL * 2, stateMachines.get(2).getRequestSet().size());
+
+ Assert.assertEquals(stateMachines.get(0).getData(), stateMachines.get(1).getData());
+ Assert.assertEquals(stateMachines.get(2).getData(), stateMachines.get(1).getData());
+ }
+
+ private static class TestEntry implements IConsensusRequest {
+
+ private final int num;
+ private final Peer peer;
+
+ public TestEntry(int num, Peer peer) {
+ this.num = num;
+ this.peer = peer;
+ }
+
+ @Override
+ public void serializeRequest(ByteBuffer buffer) {
+ buffer.putInt(num);
+ peer.serialize(buffer);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ TestEntry testEntry = (TestEntry) o;
+ return num == testEntry.num && Objects.equals(peer, testEntry.peer);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(num, peer);
+ }
+
+ @Override
+ public String toString() {
+ return "TestEntry{" + "num=" + num + ", peer=" + peer + '}';
+ }
+ }
+
+ private static class TestStateMachine implements IStateMachine, IStateMachine.EventApi {
+
+ private final Set<IndexedConsensusRequest> requestSet = new HashSet<>();
+
+ public Set<IndexedConsensusRequest> getRequestSet() {
+ return requestSet;
+ }
+
+ public Set<TestEntry> getData() {
+ Set<TestEntry> data = new HashSet<>();
+ requestSet.forEach(x -> data.add((TestEntry) x.getRequest()));
+ return data;
+ }
+
+ @Override
+ public void start() {}
+
+ @Override
+ public void stop() {}
+
+ @Override
+ public synchronized TSStatus write(IConsensusRequest request) {
+ IConsensusRequest innerRequest = ((IndexedConsensusRequest) request).getRequest();
+ if (innerRequest instanceof ByteBufferConsensusRequest) {
+ ByteBuffer buffer = ((ByteBufferConsensusRequest) innerRequest).getContent();
+ requestSet.add(
+ new IndexedConsensusRequest(
+ ((IndexedConsensusRequest) request).getSearchIndex(),
+ -1,
+ TLogType.FragmentInstance,
+ new TestEntry(buffer.getInt(), Peer.deserialize(buffer))));
+ } else {
+ requestSet.add(((IndexedConsensusRequest) request));
+ }
+ return new TSStatus();
+ }
+
+ @Override
+ public synchronized DataSet read(IConsensusRequest request) {
+ if (request instanceof GetConsensusReqReaderPlan) {
+ return new FakeConsensusReqReader(new ArrayList<>(requestSet));
+ }
+ return null;
+ }
+
+ @Override
+ public boolean takeSnapshot(File snapshotDir) {
+ return false;
+ }
+
+ @Override
+ public void loadSnapshot(File latestSnapshotRootDir) {}
+ }
+
+ public static class FakeConsensusReqReader implements ConsensusReqReader, DataSet {
+
+ private final List<IndexedConsensusRequest> requestList;
+
+ public FakeConsensusReqReader(List<IndexedConsensusRequest> requestList) {
+ this.requestList = requestList;
+ }
+
+ @Override
+ public IConsensusRequest getReq(long index) {
+ for (IndexedConsensusRequest indexedConsensusRequest : requestList) {
+ if (indexedConsensusRequest.getSearchIndex() == index) {
+ return indexedConsensusRequest;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public List<IConsensusRequest> getReqs(long startIndex, int num) {
+ return null;
+ }
+
+ @Override
+ public ReqIterator getReqIterator(long startIndex) {
+ return null;
+ }
+ }
+}
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/multileader/logdispatcher/IndexControllerTest.java b/consensus/src/test/java/org/apache/iotdb/consensus/multileader/logdispatcher/IndexControllerTest.java
new file mode 100644
index 0000000000..c9bf6051b0
--- /dev/null
+++ b/consensus/src/test/java/org/apache/iotdb/consensus/multileader/logdispatcher/IndexControllerTest.java
@@ -0,0 +1,110 @@
+/*
+ * 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.consensus.multileader.logdispatcher;
+
+import org.apache.ratis.util.FileUtils;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.IOException;
+
+public class IndexControllerTest {
+
+ private static final File storageDir = new File("target" + java.io.File.separator + "test");
+ private static final String prefix = "version";
+
+ @Before
+ public void setUp() throws IOException {
+ FileUtils.createDirectories(storageDir);
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ FileUtils.deleteFully(storageDir);
+ }
+
+ /** test indexController when incrementIntervalAfterRestart == true */
+ @Test
+ public void testTrueIncrementIntervalAfterRestart() {
+ IndexController controller = new IndexController(storageDir.getAbsolutePath(), prefix, true);
+ Assert.assertEquals(0, controller.getCurrentIndex());
+ Assert.assertEquals(0, controller.getLastFlushedIndex());
+
+ for (int i = 0; i < IndexController.FLUSH_INTERVAL - 1; i++) {
+ controller.incrementAndGet();
+ }
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL - 1, controller.getCurrentIndex());
+ Assert.assertEquals(0, controller.getLastFlushedIndex());
+
+ controller = new IndexController(storageDir.getAbsolutePath(), prefix, true);
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL, controller.getCurrentIndex());
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL, controller.getLastFlushedIndex());
+
+ for (int i = 0; i < IndexController.FLUSH_INTERVAL + 1; i++) {
+ controller.incrementAndGet();
+ }
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL * 2 + 1, controller.getCurrentIndex());
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL * 2, controller.getLastFlushedIndex());
+
+ controller = new IndexController(storageDir.getAbsolutePath(), prefix, true);
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL * 3, controller.getCurrentIndex());
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL * 3, controller.getLastFlushedIndex());
+ }
+
+ /** test indexController when incrementIntervalAfterRestart == false */
+ @Test
+ public void testFalseIncrementIntervalAfterRestart() {
+ IndexController controller = new IndexController(storageDir.getAbsolutePath(), prefix, false);
+ Assert.assertEquals(0, controller.getCurrentIndex());
+ Assert.assertEquals(0, controller.getLastFlushedIndex());
+
+ controller.updateAndGet(IndexController.FLUSH_INTERVAL - 1);
+
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL - 1, controller.getCurrentIndex());
+ Assert.assertEquals(0, controller.getLastFlushedIndex());
+
+ controller = new IndexController(storageDir.getAbsolutePath(), prefix, false);
+ Assert.assertEquals(0, controller.getCurrentIndex());
+ Assert.assertEquals(0, controller.getLastFlushedIndex());
+
+ controller.updateAndGet(IndexController.FLUSH_INTERVAL + 1);
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL + 1, controller.getCurrentIndex());
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL, controller.getLastFlushedIndex());
+
+ controller = new IndexController(storageDir.getAbsolutePath(), prefix, false);
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL, controller.getCurrentIndex());
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL, controller.getLastFlushedIndex());
+
+ controller.updateAndGet(IndexController.FLUSH_INTERVAL * 2 - 1);
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL * 2 - 1, controller.getCurrentIndex());
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL, controller.getLastFlushedIndex());
+
+ controller = new IndexController(storageDir.getAbsolutePath(), prefix, false);
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL, controller.getCurrentIndex());
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL, controller.getLastFlushedIndex());
+
+ controller.updateAndGet(IndexController.FLUSH_INTERVAL * 2 + 1);
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL * 2 + 1, controller.getCurrentIndex());
+ Assert.assertEquals(IndexController.FLUSH_INTERVAL * 2, controller.getLastFlushedIndex());
+ }
+}
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/multileader/logdispatcher/SyncStatusTest.java b/consensus/src/test/java/org/apache/iotdb/consensus/multileader/logdispatcher/SyncStatusTest.java
new file mode 100644
index 0000000000..cba5147872
--- /dev/null
+++ b/consensus/src/test/java/org/apache/iotdb/consensus/multileader/logdispatcher/SyncStatusTest.java
@@ -0,0 +1,211 @@
+/*
+ * 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.consensus.multileader.logdispatcher;
+
+import org.apache.iotdb.consensus.multileader.conf.MultiLeaderConsensusConfig;
+
+import org.apache.ratis.util.FileUtils;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+
+public class SyncStatusTest {
+
+ private static final File storageDir = new File("target" + java.io.File.separator + "test");
+ private static final String prefix = "version";
+
+ @Before
+ public void setUp() throws IOException {
+ FileUtils.createDirectories(storageDir);
+ }
+
+ @After
+ public void tearDown() throws IOException {
+ FileUtils.deleteFully(storageDir);
+ }
+
+ /** Confirm success from front to back */
+ @Test
+ public void sequenceTest() throws InterruptedException {
+ IndexController controller = new IndexController(storageDir.getAbsolutePath(), prefix, true);
+ Assert.assertEquals(0, controller.getCurrentIndex());
+
+ SyncStatus status = new SyncStatus(controller);
+ List<PendingBatch> batchList = new ArrayList<>();
+
+ for (long i = 0; i < MultiLeaderConsensusConfig.MAX_PENDING_BATCH; i++) {
+ PendingBatch batch = new PendingBatch(i, i, Collections.emptyList());
+ batchList.add(batch);
+ status.addNextBatch(batch);
+ }
+
+ for (int i = 0; i < MultiLeaderConsensusConfig.MAX_PENDING_BATCH; i++) {
+ status.removeBatch(batchList.get(i));
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH - 1 - i, status.getPendingBatches().size());
+ Assert.assertEquals(i, controller.getCurrentIndex());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH, status.getNextSendingIndex());
+ }
+ }
+
+ /** Confirm success from back to front */
+ @Test
+ public void reverseTest() throws InterruptedException {
+ IndexController controller = new IndexController(storageDir.getAbsolutePath(), prefix, true);
+ Assert.assertEquals(0, controller.getCurrentIndex());
+ Assert.assertEquals(0, controller.getLastFlushedIndex());
+
+ SyncStatus status = new SyncStatus(controller);
+ List<PendingBatch> batchList = new ArrayList<>();
+
+ for (long i = 0; i < MultiLeaderConsensusConfig.MAX_PENDING_BATCH; i++) {
+ PendingBatch batch = new PendingBatch(i, i, Collections.emptyList());
+ batchList.add(batch);
+ status.addNextBatch(batch);
+ }
+
+ for (int i = 0; i < MultiLeaderConsensusConfig.MAX_PENDING_BATCH - 1; i++) {
+ status.removeBatch(batchList.get(MultiLeaderConsensusConfig.MAX_PENDING_BATCH - 1 - i));
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH, status.getPendingBatches().size());
+ Assert.assertEquals(0, controller.getCurrentIndex());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH, status.getNextSendingIndex());
+ }
+
+ status.removeBatch(batchList.get(0));
+ Assert.assertEquals(0, status.getPendingBatches().size());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH - 1, controller.getCurrentIndex());
+ Assert.assertEquals(MultiLeaderConsensusConfig.MAX_PENDING_BATCH, status.getNextSendingIndex());
+ }
+
+ /** Confirm success first from front to back, then back to front */
+ @Test
+ public void mixedTest() throws InterruptedException {
+ IndexController controller = new IndexController(storageDir.getAbsolutePath(), prefix, true);
+ Assert.assertEquals(0, controller.getCurrentIndex());
+ Assert.assertEquals(0, controller.getLastFlushedIndex());
+
+ SyncStatus status = new SyncStatus(controller);
+ List<PendingBatch> batchList = new ArrayList<>();
+
+ for (long i = 0; i < MultiLeaderConsensusConfig.MAX_PENDING_BATCH; i++) {
+ PendingBatch batch = new PendingBatch(i, i, Collections.emptyList());
+ batchList.add(batch);
+ status.addNextBatch(batch);
+ }
+
+ for (int i = 0; i < MultiLeaderConsensusConfig.MAX_PENDING_BATCH / 2; i++) {
+ status.removeBatch(batchList.get(i));
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH - 1 - i, status.getPendingBatches().size());
+ Assert.assertEquals(i, controller.getCurrentIndex());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH, status.getNextSendingIndex());
+ }
+
+ for (int i = MultiLeaderConsensusConfig.MAX_PENDING_BATCH / 2 + 1;
+ i < MultiLeaderConsensusConfig.MAX_PENDING_BATCH;
+ i++) {
+ status.removeBatch(batchList.get(i));
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH / 2, status.getPendingBatches().size());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH, status.getNextSendingIndex());
+ }
+
+ status.removeBatch(batchList.get(MultiLeaderConsensusConfig.MAX_PENDING_BATCH / 2));
+ Assert.assertEquals(0, status.getPendingBatches().size());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH - 1, controller.getCurrentIndex());
+ Assert.assertEquals(MultiLeaderConsensusConfig.MAX_PENDING_BATCH, status.getNextSendingIndex());
+ }
+
+ /** Test Blocking while addNextBatch */
+ @Test
+ public void waitTest() throws InterruptedException, ExecutionException {
+ IndexController controller = new IndexController(storageDir.getAbsolutePath(), prefix, true);
+ Assert.assertEquals(0, controller.getCurrentIndex());
+
+ SyncStatus status = new SyncStatus(controller);
+ List<PendingBatch> batchList = new ArrayList<>();
+
+ for (long i = 0; i < MultiLeaderConsensusConfig.MAX_PENDING_BATCH; i++) {
+ PendingBatch batch = new PendingBatch(i, i, Collections.emptyList());
+ batchList.add(batch);
+ status.addNextBatch(batch);
+ }
+
+ for (int i = 0; i < MultiLeaderConsensusConfig.MAX_PENDING_BATCH - 1; i++) {
+ status.removeBatch(batchList.get(MultiLeaderConsensusConfig.MAX_PENDING_BATCH - 1 - i));
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH, status.getPendingBatches().size());
+ Assert.assertEquals(0, controller.getCurrentIndex());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH, status.getNextSendingIndex());
+ }
+
+ CompletableFuture<Boolean> future =
+ CompletableFuture.supplyAsync(
+ () -> {
+ PendingBatch batch =
+ new PendingBatch(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH,
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH,
+ Collections.emptyList());
+ batchList.add(batch);
+ try {
+ status.addNextBatch(batch);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ return false;
+ }
+ return true;
+ });
+
+ Thread.sleep(1000);
+ Assert.assertFalse(future.isDone());
+
+ status.removeBatch(batchList.get(0));
+ Assert.assertTrue(future.get());
+ Assert.assertEquals(1, status.getPendingBatches().size());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH - 1, controller.getCurrentIndex());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH + 1, status.getNextSendingIndex());
+
+ status.removeBatch(batchList.get(MultiLeaderConsensusConfig.MAX_PENDING_BATCH));
+ Assert.assertEquals(0, status.getPendingBatches().size());
+ Assert.assertEquals(MultiLeaderConsensusConfig.MAX_PENDING_BATCH, controller.getCurrentIndex());
+ Assert.assertEquals(
+ MultiLeaderConsensusConfig.MAX_PENDING_BATCH + 1, status.getNextSendingIndex());
+ }
+}
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RatisConsensusTest.java b/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RatisConsensusTest.java
index 839de7fe96..b114c2305a 100644
--- a/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RatisConsensusTest.java
+++ b/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RatisConsensusTest.java
@@ -48,8 +48,6 @@ import java.util.concurrent.TimeUnit;
public class RatisConsensusTest {
- private static final String RATIS_CLASS_NAME = "org.apache.iotdb.consensus.ratis.RatisConsensus";
-
private ConsensusGroupId gid;
private List<Peer> peers;
private List<File> peersStorage;
@@ -64,14 +62,16 @@ public class RatisConsensusTest {
int finalI = i;
servers.add(
ConsensusFactory.getConsensusImpl(
- RATIS_CLASS_NAME,
+ ConsensusFactory.RatisConsensus,
peers.get(i).getEndpoint(),
peersStorage.get(i),
groupId -> stateMachines.get(finalI))
.orElseThrow(
() ->
new IllegalArgumentException(
- String.format(ConsensusFactory.CONSTRUCT_FAILED_MSG, RATIS_CLASS_NAME))));
+ String.format(
+ ConsensusFactory.CONSTRUCT_FAILED_MSG,
+ ConsensusFactory.RatisConsensus))));
servers.get(i).start();
}
}
@@ -84,9 +84,9 @@ public class RatisConsensusTest {
peers.add(new Peer(gid, new TEndPoint("127.0.0.1", 6001)));
peers.add(new Peer(gid, new TEndPoint("127.0.0.1", 6002)));
peersStorage = new ArrayList<>();
- peersStorage.add(new File("./target/1/"));
- peersStorage.add(new File("./target/2/"));
- peersStorage.add(new File("./target/3/"));
+ peersStorage.add(new File("target" + java.io.File.separator + "1"));
+ peersStorage.add(new File("target" + java.io.File.separator + "2"));
+ peersStorage.add(new File("target" + java.io.File.separator + "3"));
for (File dir : peersStorage) {
dir.mkdirs();
}
@@ -229,7 +229,7 @@ public class RatisConsensusTest {
IConsensus leader = null;
while (leader == null) {
long current = System.currentTimeMillis();
- if ((current - start) > 60 * 1000 * 1000) {
+ if ((current - start) > 60 * 1000) {
break;
}
for (int i = 0; i < 3; i++) {
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/ratis/SnapshotTest.java b/consensus/src/test/java/org/apache/iotdb/consensus/ratis/SnapshotTest.java
index 9a741a5332..45b4d6ee6b 100644
--- a/consensus/src/test/java/org/apache/iotdb/consensus/ratis/SnapshotTest.java
+++ b/consensus/src/test/java/org/apache/iotdb/consensus/ratis/SnapshotTest.java
@@ -75,7 +75,6 @@ public class SnapshotTest {
@Before
public void setUp() throws IOException {
- FileUtils.deleteFully(testDir);
FileUtils.createDirectories(testDir);
}
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/ratis/TestUtils.java b/consensus/src/test/java/org/apache/iotdb/consensus/ratis/TestUtils.java
index 0e36ea878e..3aad1fd504 100644
--- a/consensus/src/test/java/org/apache/iotdb/consensus/ratis/TestUtils.java
+++ b/consensus/src/test/java/org/apache/iotdb/consensus/ratis/TestUtils.java
@@ -41,7 +41,7 @@ import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;
public class TestUtils {
- static class TestDataSet implements DataSet {
+ public static class TestDataSet implements DataSet {
private int number;
public void setNumber(int number) {
@@ -53,7 +53,7 @@ public class TestUtils {
}
}
- static class TestRequest {
+ public static class TestRequest {
private final int cmd;
public TestRequest(ByteBuffer buffer) {
@@ -65,7 +65,7 @@ public class TestUtils {
}
}
- static class IntegerCounter implements IStateMachine, IStateMachine.EventApi {
+ public static class IntegerCounter implements IStateMachine, IStateMachine.EventApi {
private AtomicInteger integer;
private final Logger logger = LoggerFactory.getLogger(IntegerCounter.class);
private TEndPoint leaderEndpoint;
@@ -80,9 +80,13 @@ public class TestUtils {
public void stop() {}
@Override
- public TSStatus write(IConsensusRequest IConsensusRequest) {
- ByteBufferConsensusRequest request = (ByteBufferConsensusRequest) IConsensusRequest;
- TestRequest testRequest = new TestRequest(request.getContent());
+ public TSStatus write(IConsensusRequest request) {
+ TestRequest testRequest;
+ if (request instanceof ByteBufferConsensusRequest) {
+ testRequest = new TestRequest(((ByteBufferConsensusRequest) request).getContent());
+ } else {
+ testRequest = (TestRequest) request;
+ }
if (testRequest.isIncr()) {
integer.incrementAndGet();
}
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/EmptyStateMachine.java b/consensus/src/test/java/org/apache/iotdb/consensus/standalone/EmptyStateMachine.java
similarity index 94%
rename from consensus/src/test/java/org/apache/iotdb/consensus/EmptyStateMachine.java
rename to consensus/src/test/java/org/apache/iotdb/consensus/standalone/EmptyStateMachine.java
index 01992f472f..3428f5abff 100644
--- a/consensus/src/test/java/org/apache/iotdb/consensus/EmptyStateMachine.java
+++ b/consensus/src/test/java/org/apache/iotdb/consensus/standalone/EmptyStateMachine.java
@@ -17,9 +17,10 @@
* under the License.
*/
-package org.apache.iotdb.consensus;
+package org.apache.iotdb.consensus.standalone;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.consensus.IStateMachine;
import org.apache.iotdb.consensus.common.DataSet;
import org.apache.iotdb.consensus.common.request.IConsensusRequest;
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/standalone/RecoveryTest.java b/consensus/src/test/java/org/apache/iotdb/consensus/standalone/RecoveryTest.java
index a166893b6b..de4442ed79 100644
--- a/consensus/src/test/java/org/apache/iotdb/consensus/standalone/RecoveryTest.java
+++ b/consensus/src/test/java/org/apache/iotdb/consensus/standalone/RecoveryTest.java
@@ -22,7 +22,6 @@ import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.consensus.ConsensusGroupId;
import org.apache.iotdb.commons.consensus.SchemaRegionId;
import org.apache.iotdb.consensus.ConsensusFactory;
-import org.apache.iotdb.consensus.EmptyStateMachine;
import org.apache.iotdb.consensus.IConsensus;
import org.apache.iotdb.consensus.common.Peer;
import org.apache.iotdb.consensus.common.response.ConsensusGenericResponse;
@@ -41,22 +40,20 @@ import java.util.Collections;
public class RecoveryTest {
private final ConsensusGroupId schemaRegionId = new SchemaRegionId(1);
private IConsensus consensusImpl;
- private static final String STANDALONE_CONSENSUS_CLASS_NAME =
- "org.apache.iotdb.consensus.standalone.StandAloneConsensus";
public void constructConsensus() throws IOException {
consensusImpl =
ConsensusFactory.getConsensusImpl(
- STANDALONE_CONSENSUS_CLASS_NAME,
+ ConsensusFactory.StandAloneConsensus,
new TEndPoint("0.0.0.0", 9000),
- new File("./target/recovery"),
+ new File("target" + java.io.File.separator + "recovery"),
gid -> new EmptyStateMachine())
.orElseThrow(
() ->
new IllegalArgumentException(
String.format(
ConsensusFactory.CONSTRUCT_FAILED_MSG,
- STANDALONE_CONSENSUS_CLASS_NAME)));
+ ConsensusFactory.StandAloneConsensus)));
consensusImpl.start();
}
diff --git a/consensus/src/test/java/org/apache/iotdb/consensus/standalone/StandAloneConsensusTest.java b/consensus/src/test/java/org/apache/iotdb/consensus/standalone/StandAloneConsensusTest.java
index 776257e2f8..5c3ae96453 100644
--- a/consensus/src/test/java/org/apache/iotdb/consensus/standalone/StandAloneConsensusTest.java
+++ b/consensus/src/test/java/org/apache/iotdb/consensus/standalone/StandAloneConsensusTest.java
@@ -26,7 +26,6 @@ import org.apache.iotdb.commons.consensus.DataRegionId;
import org.apache.iotdb.commons.consensus.PartitionRegionId;
import org.apache.iotdb.commons.consensus.SchemaRegionId;
import org.apache.iotdb.consensus.ConsensusFactory;
-import org.apache.iotdb.consensus.EmptyStateMachine;
import org.apache.iotdb.consensus.IConsensus;
import org.apache.iotdb.consensus.IStateMachine;
import org.apache.iotdb.consensus.common.DataSet;
@@ -58,8 +57,6 @@ import static org.junit.Assert.assertTrue;
public class StandAloneConsensusTest {
- private static final String STANDALONE_CONSENSUS_CLASS_NAME =
- "org.apache.iotdb.consensus.standalone.StandAloneConsensus";
private IConsensus consensusImpl;
private final TestEntry entry1 = new TestEntry(0);
private final ByteBufferConsensusRequest entry2 =
@@ -125,9 +122,9 @@ public class StandAloneConsensusTest {
public void setUp() throws Exception {
consensusImpl =
ConsensusFactory.getConsensusImpl(
- STANDALONE_CONSENSUS_CLASS_NAME,
+ ConsensusFactory.StandAloneConsensus,
new TEndPoint("0.0.0.0", 6667),
- new File("./target/standalone"),
+ new File("target" + java.io.File.separator + "standalone"),
gid -> {
switch (gid.getType()) {
case SchemaRegion:
@@ -142,7 +139,7 @@ public class StandAloneConsensusTest {
new IllegalArgumentException(
String.format(
ConsensusFactory.CONSTRUCT_FAILED_MSG,
- STANDALONE_CONSENSUS_CLASS_NAME)));
+ ConsensusFactory.StandAloneConsensus)));
consensusImpl.start();
}
diff --git a/node-commons/src/main/java/org/apache/iotdb/commons/concurrent/ThreadName.java b/node-commons/src/main/java/org/apache/iotdb/commons/concurrent/ThreadName.java
index b6c3317a5b..c3feb250f8 100644
--- a/node-commons/src/main/java/org/apache/iotdb/commons/concurrent/ThreadName.java
+++ b/node-commons/src/main/java/org/apache/iotdb/commons/concurrent/ThreadName.java
@@ -74,6 +74,8 @@ public enum ThreadName {
CLUSTER_MONITOR("ClusterMonitor"),
CONFIG_NODE_RPC_SERVER("ConfigNodeRpcServer"),
CONFIG_NODE_RPC_CLIENT("ConfigNodeRPC-Client"),
+ MULTI_LEADER_CONSENSUS_RPC_CLIENT("MultiLeaderConsensusRPC-Client"),
+ MULTI_LEADER_CONSENSUS_RPC_SERVER("MultiLeaderConsensusRPC-Server"),
DATA_NODE_MANAGEMENT_RPC_SERVER("DataNodeManagementRPC"),
DATA_NODE_MANAGEMENT_RPC_CLIENT("DataNodeManagementRPC-Client"),
Cluster_Monitor("ClusterMonitor"),
diff --git a/node-commons/src/main/java/org/apache/iotdb/commons/consensus/ConsensusGroupId.java b/node-commons/src/main/java/org/apache/iotdb/commons/consensus/ConsensusGroupId.java
index 0bc5556c15..2a5ab281f2 100644
--- a/node-commons/src/main/java/org/apache/iotdb/commons/consensus/ConsensusGroupId.java
+++ b/node-commons/src/main/java/org/apache/iotdb/commons/consensus/ConsensusGroupId.java
@@ -37,6 +37,10 @@ public abstract class ConsensusGroupId {
// return specific type
public abstract TConsensusGroupType getType();
+ public TConsensusGroupId convertToTConsensusGroupId() {
+ return new TConsensusGroupId(getType(), getId());
+ }
+
@Override
public int hashCode() {
return Objects.hash(getType(), getId());
@@ -82,10 +86,6 @@ public abstract class ConsensusGroupId {
}
}
- public static TConsensusGroupId convertToTConsensusGroupId(ConsensusGroupId consensusGroupId) {
- return new TConsensusGroupId(consensusGroupId.getType(), consensusGroupId.getId());
- }
-
public static String formatTConsensusGroupId(TConsensusGroupId groupId) {
StringBuilder format = new StringBuilder();
diff --git a/node-commons/src/main/java/org/apache/iotdb/commons/service/ServiceType.java b/node-commons/src/main/java/org/apache/iotdb/commons/service/ServiceType.java
index 02ca71b26c..283f2b87c5 100644
--- a/node-commons/src/main/java/org/apache/iotdb/commons/service/ServiceType.java
+++ b/node-commons/src/main/java/org/apache/iotdb/commons/service/ServiceType.java
@@ -72,7 +72,8 @@ public enum ServiceType {
DATA_NODE_MANAGEMENT_SERVICE("Data Node management service", "DataNodeManagementServer"),
FRAGMENT_INSTANCE_MANAGER_SERVICE("Fragment instance manager", "FragmentInstanceManager"),
DATA_BLOCK_MANAGER_SERVICE("Data block manager", "DataBlockManager"),
- INTERNAL_SERVICE("Internal Service", "InternalService");
+ INTERNAL_SERVICE("Internal Service", "InternalService"),
+ MULTI_LEADER_CONSENSUS_SERVICE("Multi Leader consensus Service", "MultiLeaderRPCService");
private final String name;
private final String jmxName;
diff --git a/node-commons/src/test/java/org/apache/iotdb/commons/ClientManagerTest.java b/node-commons/src/test/java/org/apache/iotdb/commons/ClientManagerTest.java
index 44a4e3f777..f760082c26 100644
--- a/node-commons/src/test/java/org/apache/iotdb/commons/ClientManagerTest.java
+++ b/node-commons/src/test/java/org/apache/iotdb/commons/ClientManagerTest.java
@@ -423,7 +423,8 @@ public class ClientManagerTest {
// reuse the port to avoid `Bind Address already in use` which is caused by TIME_WAIT state
// because port won't be usable immediately after we close it.
metaServer.setReuseAddress(true);
- metaServer.bind(new InetSocketAddress(9003));
+ metaServer.bind(new InetSocketAddress(endPoint.getIp(), endPoint.getPort()), 0);
+
metaServerListeningThread =
new Thread(
() -> {
@@ -441,10 +442,12 @@ public class ClientManagerTest {
public void stopServer() throws InterruptedException, IOException {
if (metaServer != null) {
metaServer.close();
+ metaServer = null;
}
if (metaServerListeningThread != null) {
metaServerListeningThread.interrupt();
metaServerListeningThread.join();
+ metaServerListeningThread = null;
}
}
diff --git a/node-commons/src/test/java/org/apache/iotdb/commons/partition/SerializeTest.java b/node-commons/src/test/java/org/apache/iotdb/commons/partition/SerializeTest.java
index 1e032efc62..1f4f3152d6 100644
--- a/node-commons/src/test/java/org/apache/iotdb/commons/partition/SerializeTest.java
+++ b/node-commons/src/test/java/org/apache/iotdb/commons/partition/SerializeTest.java
@@ -68,7 +68,8 @@ public abstract class SerializeTest {
tDataNodeLocation.setExternalEndPoint(new TEndPoint("127.0.0.1", 6000 + i));
tDataNodeLocation.setInternalEndPoint(new TEndPoint("127.0.0.1", 7000 + i));
tDataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("127.0.0.1", 8000 + i));
- tDataNodeLocation.setConsensusEndPoint(new TEndPoint("127.0.0.1", 9000 + i));
+ tDataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("127.0.0.1", 9000 + i));
+ tDataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("127.0.0.1", 10000 + i));
dataNodeLocations.add(tDataNodeLocation);
}
tRegionReplicaSet.setDataNodeLocations(dataNodeLocations);
diff --git a/node-commons/src/test/java/org/apache/iotdb/commons/utils/ThriftCommonsSerDeUtilsTest.java b/node-commons/src/test/java/org/apache/iotdb/commons/utils/ThriftCommonsSerDeUtilsTest.java
index 0abde8a0fa..94a2a81427 100644
--- a/node-commons/src/test/java/org/apache/iotdb/commons/utils/ThriftCommonsSerDeUtilsTest.java
+++ b/node-commons/src/test/java/org/apache/iotdb/commons/utils/ThriftCommonsSerDeUtilsTest.java
@@ -58,7 +58,8 @@ public class ThriftCommonsSerDeUtilsTest {
dataNodeLocation0.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667));
dataNodeLocation0.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003));
dataNodeLocation0.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777));
- dataNodeLocation0.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation0.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation0.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010));
ThriftCommonsSerDeUtils.serializeTDataNodeLocation(dataNodeLocation0, buffer);
buffer.flip();
TDataNodeLocation dataNodeLocation1 =
@@ -108,7 +109,8 @@ public class ThriftCommonsSerDeUtilsTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667 + i));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003 + i));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777 + i));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40010 + i));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010 + i));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010 + i));
regionReplicaSet0.getDataNodeLocations().add(dataNodeLocation);
}
ThriftCommonsSerDeUtils.serializeTRegionReplicaSet(regionReplicaSet0, buffer);
diff --git a/pom.xml b/pom.xml
index a16909c1be..d20058c39d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -84,6 +84,7 @@
<module>thrift</module>
<module>thrift-commons</module>
<module>thrift-confignode</module>
+ <module>thrift-multi-leader-consensus</module>
<module>thrift-cluster</module>
<module>thrift-sync</module>
<module>thrift-influxdb</module>
@@ -796,6 +797,7 @@
<sourceDirectory>thrift/target/generated-sources/thrift</sourceDirectory>
<sourceDirectory>thrift-commons/target/generated-sources/thrift</sourceDirectory>
<sourceDirectory>thrift-confignode/target/generated-sources/thrift</sourceDirectory>
+ <sourceDirectory>thrift-multi-leader-consensus/target/generated-sources/thrift</sourceDirectory>
<sourceDirectory>thrift-sync/target/generated-sources/thrift</sourceDirectory>
<sourceDirectory>thrift-cluster/target/generated-sources/thrift</sourceDirectory>
<sourceDirectory>thrift-influxdb/target/generated-sources/thrift</sourceDirectory>
diff --git a/server/src/assembly/resources/conf/iotdb-engine.properties b/server/src/assembly/resources/conf/iotdb-engine.properties
index 66c86c5ee3..d551acf77d 100644
--- a/server/src/assembly/resources/conf/iotdb-engine.properties
+++ b/server/src/assembly/resources/conf/iotdb-engine.properties
@@ -51,10 +51,13 @@ internal_ip=127.0.0.1
# port for coordinator's communication between cluster nodes.
internal_port=9003
+# Datatype: int
+# port for consensus's communication for data region between cluster nodes.
+data_region_consensus_port=40010
# Datatype: int
-# port for consensus's communication between cluster nodes.
-consensus_port=40010
+# port for consensus's communication for schema region between cluster nodes.
+schema_region_consensus_port=50010
# comma-separated {IP/DOMAIN}:internal_port pairs
# Data nodes store config nodes ip and port to communicate with config nodes.
diff --git a/server/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java b/server/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
index adf1e404a9..4d3be15291 100644
--- a/server/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
+++ b/server/src/main/java/org/apache/iotdb/db/conf/IoTDBConfig.java
@@ -20,6 +20,7 @@ package org.apache.iotdb.db.conf;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.conf.IoTDBConstant;
+import org.apache.iotdb.consensus.ConsensusFactory;
import org.apache.iotdb.db.conf.directories.DirectoryManager;
import org.apache.iotdb.db.engine.compaction.constant.CompactionPriority;
import org.apache.iotdb.db.engine.compaction.constant.CrossCompactionPerformer;
@@ -279,6 +280,20 @@ public class IoTDBConfig {
/** Consensus directory. */
private String consensusDir = IoTDBConstant.DEFAULT_BASE_DIR + File.separator + "consensus";
+ private String dataRegionConsensusDir =
+ IoTDBConstant.DEFAULT_BASE_DIR
+ + File.separator
+ + "consensus"
+ + File.separator
+ + "data_region";
+
+ private String schemaRegionConsensusDir =
+ IoTDBConstant.DEFAULT_BASE_DIR
+ + File.separator
+ + "consensus"
+ + File.separator
+ + "schema_region";
+
/** Maximum MemTable number. Invalid when enableMemControl is true. */
private int maxMemtableNumber = 0;
@@ -825,8 +840,11 @@ public class IoTDBConfig {
/** Internal port for coordinator */
private int internalPort = 9003;
- /** Internal port for consensus protocol */
- private int consensusPort = 40010;
+ /** Internal port for dataRegion consensus protocol */
+ private int dataRegionConsensusPort = 40010;
+
+ /** Internal port for schemaRegion consensus protocol */
+ private int schemaRegionConsensusPort = 50010;
/** Ip and port of config nodes. */
private List<TEndPoint> configNodeList =
@@ -836,11 +854,18 @@ public class IoTDBConfig {
private long joinClusterTimeOutMs = TimeUnit.SECONDS.toMillis(5);
/**
- * The consensus protocol class. The Datanode should communicate with ConfigNode on startup and
- * set this variable so that the correct class name can be obtained later when the consensus layer
- * singleton is initialized
+ * The consensus protocol class for data region. The Datanode should communicate with ConfigNode
+ * on startup and set this variable so that the correct class name can be obtained later when the
+ * data region consensus layer singleton is initialized
*/
- private String consensusProtocolClass = "org.apache.iotdb.consensus.ratis.RatisConsensus";
+ private String dataRegionConsensusProtocolClass = ConsensusFactory.RatisConsensus;
+
+ /**
+ * The consensus protocol class for schema region. The Datanode should communicate with ConfigNode
+ * on startup and set this variable so that the correct class name can be obtained later when the
+ * schema region consensus layer singleton is initialized
+ */
+ private String schemaRegionConsensusProtocolClass = ConsensusFactory.RatisConsensus;
/**
* The series partition executor class. The Datanode should communicate with ConfigNode on startup
@@ -1182,6 +1207,24 @@ public class IoTDBConfig {
public void setConsensusDir(String consensusDir) {
this.consensusDir = consensusDir;
+ setDataRegionConsensusDir(consensusDir + File.separator + "data_region");
+ setSchemaRegionConsensusDir(consensusDir + File.separator + "schema_region");
+ }
+
+ public String getDataRegionConsensusDir() {
+ return dataRegionConsensusDir;
+ }
+
+ public void setDataRegionConsensusDir(String dataRegionConsensusDir) {
+ this.dataRegionConsensusDir = dataRegionConsensusDir;
+ }
+
+ public String getSchemaRegionConsensusDir() {
+ return schemaRegionConsensusDir;
+ }
+
+ public void setSchemaRegionConsensusDir(String schemaRegionConsensusDir) {
+ this.schemaRegionConsensusDir = schemaRegionConsensusDir;
}
public String getExtDir() {
@@ -2645,12 +2688,20 @@ public class IoTDBConfig {
this.internalPort = internalPort;
}
- public int getConsensusPort() {
- return consensusPort;
+ public int getDataRegionConsensusPort() {
+ return dataRegionConsensusPort;
+ }
+
+ public void setDataRegionConsensusPort(int dataRegionConsensusPort) {
+ this.dataRegionConsensusPort = dataRegionConsensusPort;
+ }
+
+ public int getSchemaRegionConsensusPort() {
+ return schemaRegionConsensusPort;
}
- public void setConsensusPort(int consensusPort) {
- this.consensusPort = consensusPort;
+ public void setSchemaRegionConsensusPort(int schemaRegionConsensusPort) {
+ this.schemaRegionConsensusPort = schemaRegionConsensusPort;
}
public List<TEndPoint> getConfigNodeList() {
@@ -2669,12 +2720,20 @@ public class IoTDBConfig {
this.joinClusterTimeOutMs = joinClusterTimeOutMs;
}
- public String getConsensusProtocolClass() {
- return consensusProtocolClass;
+ public String getDataRegionConsensusProtocolClass() {
+ return dataRegionConsensusProtocolClass;
+ }
+
+ public void setDataRegionConsensusProtocolClass(String dataRegionConsensusProtocolClass) {
+ this.dataRegionConsensusProtocolClass = dataRegionConsensusProtocolClass;
+ }
+
+ public String getSchemaRegionConsensusProtocolClass() {
+ return schemaRegionConsensusProtocolClass;
}
- public void setConsensusProtocolClass(String consensusProtocolClass) {
- this.consensusProtocolClass = consensusProtocolClass;
+ public void setSchemaRegionConsensusProtocolClass(String schemaRegionConsensusProtocolClass) {
+ this.schemaRegionConsensusProtocolClass = schemaRegionConsensusProtocolClass;
}
public String getSeriesPartitionExecutorClass() {
diff --git a/server/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java b/server/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
index 3bca1c387e..f93f78331d 100644
--- a/server/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
+++ b/server/src/main/java/org/apache/iotdb/db/conf/IoTDBDescriptor.java
@@ -1563,9 +1563,17 @@ public class IoTDBDescriptor {
Integer.parseInt(
properties.getProperty("internal_port", Integer.toString(conf.getInternalPort()))));
- conf.setConsensusPort(
+ conf.setDataRegionConsensusPort(
Integer.parseInt(
- properties.getProperty("consensus_port", Integer.toString(conf.getConsensusPort()))));
+ properties.getProperty(
+ "data_region_consensus_port",
+ Integer.toString(conf.getDataRegionConsensusPort()))));
+
+ conf.setSchemaRegionConsensusPort(
+ Integer.parseInt(
+ properties.getProperty(
+ "schema_region_consensus_port",
+ Integer.toString(conf.getSchemaRegionConsensusPort()))));
}
public void loadShuffleProps(Properties properties) {
@@ -1616,7 +1624,9 @@ public class IoTDBDescriptor {
// These configurations are received from config node when registering
public void loadGlobalConfig(TGlobalConfig globalConfig) {
conf.setSeriesPartitionExecutorClass(globalConfig.getSeriesPartitionExecutorClass());
- conf.setConsensusProtocolClass(globalConfig.getDataNodeConsensusProtocolClass());
+ conf.setDataRegionConsensusProtocolClass(globalConfig.getDataRegionConsensusProtocolClass());
+ conf.setSchemaRegionConsensusProtocolClass(
+ globalConfig.getSchemaRegionConsensusProtocolClass());
conf.setSeriesPartitionSlotNum(globalConfig.getSeriesPartitionSlotNum());
conf.setPartitionInterval(globalConfig.timePartitionInterval);
}
diff --git a/server/src/main/java/org/apache/iotdb/db/consensus/ConsensusImpl.java b/server/src/main/java/org/apache/iotdb/db/consensus/DataRegionConsensusImpl.java
similarity index 56%
copy from server/src/main/java/org/apache/iotdb/db/consensus/ConsensusImpl.java
copy to server/src/main/java/org/apache/iotdb/db/consensus/DataRegionConsensusImpl.java
index 96fd26af89..2007f1af59 100644
--- a/server/src/main/java/org/apache/iotdb/db/consensus/ConsensusImpl.java
+++ b/server/src/main/java/org/apache/iotdb/db/consensus/DataRegionConsensusImpl.java
@@ -21,57 +21,45 @@ package org.apache.iotdb.db.consensus;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.consensus.DataRegionId;
-import org.apache.iotdb.commons.consensus.SchemaRegionId;
import org.apache.iotdb.consensus.ConsensusFactory;
import org.apache.iotdb.consensus.IConsensus;
import org.apache.iotdb.db.conf.IoTDBConfig;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.consensus.statemachine.DataRegionStateMachine;
-import org.apache.iotdb.db.consensus.statemachine.SchemaRegionStateMachine;
import org.apache.iotdb.db.engine.StorageEngineV2;
-import org.apache.iotdb.db.metadata.schemaregion.SchemaEngine;
import java.io.File;
/**
- * We can use ConsensusImpl.getInstance() to obtain a consensus layer reference for reading and
- * writing
+ * We can use DataRegionConsensusImpl.getInstance() to obtain a consensus layer reference for
+ * dataRegion's reading and writing
*/
-public class ConsensusImpl {
+public class DataRegionConsensusImpl {
- private ConsensusImpl() {}
+ private DataRegionConsensusImpl() {}
public static IConsensus getInstance() {
- return ConsensusImplHolder.INSTANCE;
+ return DataRegionConsensusImplHolder.INSTANCE;
}
- private static class ConsensusImplHolder {
+ private static class DataRegionConsensusImplHolder {
private static final IoTDBConfig conf = IoTDBDescriptor.getInstance().getConfig();
private static final IConsensus INSTANCE =
ConsensusFactory.getConsensusImpl(
- conf.getConsensusProtocolClass(),
- new TEndPoint(conf.getInternalIp(), conf.getConsensusPort()),
- new File(conf.getConsensusDir()),
- gid -> {
- switch (gid.getType()) {
- case SchemaRegion:
- return new SchemaRegionStateMachine(
- SchemaEngine.getInstance().getSchemaRegion((SchemaRegionId) gid));
- case DataRegion:
- return new DataRegionStateMachine(
- StorageEngineV2.getInstance().getDataRegion((DataRegionId) gid));
- }
- throw new IllegalArgumentException(
- String.format("Unexpected consensusGroup %s", gid));
- })
+ conf.getDataRegionConsensusProtocolClass(),
+ new TEndPoint(conf.getInternalIp(), conf.getDataRegionConsensusPort()),
+ new File(conf.getDataRegionConsensusDir()),
+ gid ->
+ new DataRegionStateMachine(
+ StorageEngineV2.getInstance().getDataRegion((DataRegionId) gid)))
.orElseThrow(
() ->
new IllegalArgumentException(
String.format(
ConsensusFactory.CONSTRUCT_FAILED_MSG,
- conf.getConsensusProtocolClass())));
+ conf.getDataRegionConsensusProtocolClass())));
- private ConsensusImplHolder() {}
+ private DataRegionConsensusImplHolder() {}
}
}
diff --git a/server/src/main/java/org/apache/iotdb/db/consensus/ConsensusImpl.java b/server/src/main/java/org/apache/iotdb/db/consensus/SchemaRegionConsensusImpl.java
similarity index 57%
rename from server/src/main/java/org/apache/iotdb/db/consensus/ConsensusImpl.java
rename to server/src/main/java/org/apache/iotdb/db/consensus/SchemaRegionConsensusImpl.java
index 96fd26af89..1bde912992 100644
--- a/server/src/main/java/org/apache/iotdb/db/consensus/ConsensusImpl.java
+++ b/server/src/main/java/org/apache/iotdb/db/consensus/SchemaRegionConsensusImpl.java
@@ -20,58 +20,46 @@
package org.apache.iotdb.db.consensus;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
-import org.apache.iotdb.commons.consensus.DataRegionId;
import org.apache.iotdb.commons.consensus.SchemaRegionId;
import org.apache.iotdb.consensus.ConsensusFactory;
import org.apache.iotdb.consensus.IConsensus;
import org.apache.iotdb.db.conf.IoTDBConfig;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
-import org.apache.iotdb.db.consensus.statemachine.DataRegionStateMachine;
import org.apache.iotdb.db.consensus.statemachine.SchemaRegionStateMachine;
-import org.apache.iotdb.db.engine.StorageEngineV2;
import org.apache.iotdb.db.metadata.schemaregion.SchemaEngine;
import java.io.File;
/**
- * We can use ConsensusImpl.getInstance() to obtain a consensus layer reference for reading and
- * writing
+ * We can use SchemaRegionConsensusImpl.getInstance() to obtain a consensus layer reference for
+ * schemaRegion's reading and writing
*/
-public class ConsensusImpl {
+public class SchemaRegionConsensusImpl {
- private ConsensusImpl() {}
+ private SchemaRegionConsensusImpl() {}
public static IConsensus getInstance() {
- return ConsensusImplHolder.INSTANCE;
+ return SchemaRegionConsensusImplHolder.INSTANCE;
}
- private static class ConsensusImplHolder {
+ private static class SchemaRegionConsensusImplHolder {
private static final IoTDBConfig conf = IoTDBDescriptor.getInstance().getConfig();
private static final IConsensus INSTANCE =
ConsensusFactory.getConsensusImpl(
- conf.getConsensusProtocolClass(),
- new TEndPoint(conf.getInternalIp(), conf.getConsensusPort()),
- new File(conf.getConsensusDir()),
- gid -> {
- switch (gid.getType()) {
- case SchemaRegion:
- return new SchemaRegionStateMachine(
- SchemaEngine.getInstance().getSchemaRegion((SchemaRegionId) gid));
- case DataRegion:
- return new DataRegionStateMachine(
- StorageEngineV2.getInstance().getDataRegion((DataRegionId) gid));
- }
- throw new IllegalArgumentException(
- String.format("Unexpected consensusGroup %s", gid));
- })
+ conf.getSchemaRegionConsensusProtocolClass(),
+ new TEndPoint(conf.getInternalIp(), conf.getSchemaRegionConsensusPort()),
+ new File(conf.getSchemaRegionConsensusDir()),
+ gid ->
+ new SchemaRegionStateMachine(
+ SchemaEngine.getInstance().getSchemaRegion((SchemaRegionId) gid)))
.orElseThrow(
() ->
new IllegalArgumentException(
String.format(
ConsensusFactory.CONSTRUCT_FAILED_MSG,
- conf.getConsensusProtocolClass())));
+ conf.getSchemaRegionConsensusProtocolClass())));
- private ConsensusImplHolder() {}
+ private SchemaRegionConsensusImplHolder() {}
}
}
diff --git a/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/BaseStateMachine.java b/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/BaseStateMachine.java
index 51616c30bd..0387022154 100644
--- a/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/BaseStateMachine.java
+++ b/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/BaseStateMachine.java
@@ -19,13 +19,10 @@
package org.apache.iotdb.db.consensus.statemachine;
-import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.consensus.IStateMachine;
-import org.apache.iotdb.consensus.common.DataSet;
import org.apache.iotdb.consensus.common.request.ByteBufferConsensusRequest;
import org.apache.iotdb.consensus.common.request.IConsensusRequest;
import org.apache.iotdb.db.mpp.plan.planner.plan.FragmentInstance;
-import org.apache.iotdb.rpc.TSStatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -34,31 +31,7 @@ public abstract class BaseStateMachine implements IStateMachine, IStateMachine.E
private static final Logger logger = LoggerFactory.getLogger(BaseStateMachine.class);
- @Override
- public TSStatus write(IConsensusRequest request) {
- try {
- return write(getFragmentInstance(request));
- } catch (IllegalArgumentException e) {
- logger.error(e.getMessage(), e);
- return new TSStatus(TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
- }
- }
-
- protected abstract TSStatus write(FragmentInstance fragmentInstance);
-
- @Override
- public DataSet read(IConsensusRequest request) {
- try {
- return read(getFragmentInstance(request));
- } catch (IllegalArgumentException e) {
- logger.error(e.getMessage());
- return null;
- }
- }
-
- protected abstract DataSet read(FragmentInstance fragmentInstance);
-
- private FragmentInstance getFragmentInstance(IConsensusRequest request) {
+ protected FragmentInstance getFragmentInstance(IConsensusRequest request) {
FragmentInstance instance;
if (request instanceof ByteBufferConsensusRequest) {
instance =
diff --git a/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/DataRegionStateMachine.java b/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/DataRegionStateMachine.java
index 1decc0b84d..8387d98aeb 100644
--- a/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/DataRegionStateMachine.java
+++ b/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/DataRegionStateMachine.java
@@ -22,6 +22,11 @@ package org.apache.iotdb.db.consensus.statemachine;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.consensus.DataRegionId;
import org.apache.iotdb.consensus.common.DataSet;
+import org.apache.iotdb.consensus.common.request.ByteBufferConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IndexedConsensusRequest;
+import org.apache.iotdb.consensus.multileader.thrift.TLogType;
+import org.apache.iotdb.consensus.multileader.wal.GetConsensusReqReaderPlan;
import org.apache.iotdb.db.consensus.statemachine.visitor.DataExecutionVisitor;
import org.apache.iotdb.db.engine.StorageEngineV2;
import org.apache.iotdb.db.engine.snapshot.SnapshotLoader;
@@ -30,6 +35,9 @@ import org.apache.iotdb.db.engine.storagegroup.DataRegion;
import org.apache.iotdb.db.mpp.execution.fragment.FragmentInstanceManager;
import org.apache.iotdb.db.mpp.plan.planner.plan.FragmentInstance;
import org.apache.iotdb.db.mpp.plan.planner.plan.node.PlanNode;
+import org.apache.iotdb.db.mpp.plan.planner.plan.node.PlanNodeType;
+import org.apache.iotdb.db.mpp.plan.planner.plan.node.write.InsertNode;
+import org.apache.iotdb.rpc.TSStatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -92,13 +100,53 @@ public class DataRegionStateMachine extends BaseStateMachine {
}
@Override
- protected TSStatus write(FragmentInstance fragmentInstance) {
- PlanNode planNode = fragmentInstance.getFragment().getRoot();
+ public TSStatus write(IConsensusRequest request) {
+ PlanNode planNode;
+ try {
+ if (request instanceof IndexedConsensusRequest) {
+ IndexedConsensusRequest indexedConsensusRequest = (IndexedConsensusRequest) request;
+ if (indexedConsensusRequest.getType() == TLogType.InsertNode) {
+ planNode =
+ PlanNodeType.deserialize(
+ ((ByteBufferConsensusRequest) indexedConsensusRequest.getRequest()).getContent());
+ } else {
+ planNode =
+ getFragmentInstance(indexedConsensusRequest.getRequest()).getFragment().getRoot();
+ }
+ if (planNode instanceof InsertNode) {
+ ((InsertNode) planNode)
+ .setSearchIndex(((IndexedConsensusRequest) request).getSearchIndex());
+ ((InsertNode) planNode)
+ .setSafelyDeletedSearchIndex(
+ ((IndexedConsensusRequest) request).getSafelyDeletedSearchIndex());
+ }
+ } else {
+ planNode = getFragmentInstance(request).getFragment().getRoot();
+ }
+ return write(planNode);
+ } catch (IllegalArgumentException e) {
+ logger.error(e.getMessage(), e);
+ return new TSStatus(TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
+ }
+ }
+
+ protected TSStatus write(PlanNode planNode) {
return planNode.accept(new DataExecutionVisitor(), region);
}
@Override
- protected DataSet read(FragmentInstance fragmentInstance) {
- return QUERY_INSTANCE_MANAGER.execDataQueryFragmentInstance(fragmentInstance, region);
+ public DataSet read(IConsensusRequest request) {
+ if (request instanceof GetConsensusReqReaderPlan) {
+ return region.getWALNode();
+ } else {
+ FragmentInstance fragmentInstance;
+ try {
+ fragmentInstance = getFragmentInstance(request);
+ } catch (IllegalArgumentException e) {
+ logger.error(e.getMessage());
+ return null;
+ }
+ return QUERY_INSTANCE_MANAGER.execDataQueryFragmentInstance(fragmentInstance, region);
+ }
}
}
diff --git a/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/SchemaRegionStateMachine.java b/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/SchemaRegionStateMachine.java
index 37e7f7f591..930093f7a6 100644
--- a/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/SchemaRegionStateMachine.java
+++ b/server/src/main/java/org/apache/iotdb/db/consensus/statemachine/SchemaRegionStateMachine.java
@@ -21,11 +21,13 @@ package org.apache.iotdb.db.consensus.statemachine;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.consensus.common.DataSet;
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
import org.apache.iotdb.db.metadata.schemaregion.ISchemaRegion;
import org.apache.iotdb.db.metadata.visitor.SchemaExecutionVisitor;
import org.apache.iotdb.db.mpp.execution.fragment.FragmentInstanceManager;
import org.apache.iotdb.db.mpp.plan.planner.plan.FragmentInstance;
import org.apache.iotdb.db.mpp.plan.planner.plan.node.PlanNode;
+import org.apache.iotdb.rpc.TSStatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -61,15 +63,26 @@ public class SchemaRegionStateMachine extends BaseStateMachine {
}
@Override
- protected TSStatus write(FragmentInstance fragmentInstance) {
+ public TSStatus write(IConsensusRequest request) {
logger.info("Execute write plan in SchemaRegionStateMachine");
- PlanNode planNode = fragmentInstance.getFragment().getRoot();
- TSStatus status = planNode.accept(new SchemaExecutionVisitor(), schemaRegion);
- return status;
+ try {
+ PlanNode planNode = getFragmentInstance(request).getFragment().getRoot();
+ return planNode.accept(new SchemaExecutionVisitor(), schemaRegion);
+ } catch (IllegalArgumentException e) {
+ logger.error(e.getMessage(), e);
+ return new TSStatus(TSStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
+ }
}
@Override
- protected DataSet read(FragmentInstance fragmentInstance) {
+ public DataSet read(IConsensusRequest request) {
+ FragmentInstance fragmentInstance;
+ try {
+ fragmentInstance = getFragmentInstance(request);
+ } catch (IllegalArgumentException e) {
+ logger.error(e.getMessage());
+ return null;
+ }
logger.info(
"SchemaRegionStateMachine[{}]: Execute read plan: FragmentInstance-{}",
schemaRegion.getSchemaRegionId(),
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/planner/plan/node/write/InsertNode.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/planner/plan/node/write/InsertNode.java
index f5b15139e5..4050db50fb 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/planner/plan/node/write/InsertNode.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/planner/plan/node/write/InsertNode.java
@@ -83,7 +83,7 @@ public abstract class InsertNode extends WritePlanNode implements IConsensusRequ
protected long safelyDeletedSearchIndex = DEFAULT_SAFELY_DELETED_SEARCH_INDEX;
/** Physical address of data region after splitting */
- TRegionReplicaSet dataRegionReplicaSet;
+ protected TRegionReplicaSet dataRegionReplicaSet;
protected InsertNode(PlanNodeId id) {
super(id);
@@ -178,6 +178,7 @@ public abstract class InsertNode extends WritePlanNode implements IConsensusRequ
@Override
public void serializeRequest(ByteBuffer buffer) {
serializeAttributes(buffer);
+ getPlanNodeId().serialize(buffer);
}
@Override
diff --git a/server/src/main/java/org/apache/iotdb/db/mpp/plan/scheduler/FragmentInstanceDispatcherImpl.java b/server/src/main/java/org/apache/iotdb/db/mpp/plan/scheduler/FragmentInstanceDispatcherImpl.java
index 4e446bf085..a6da556732 100644
--- a/server/src/main/java/org/apache/iotdb/db/mpp/plan/scheduler/FragmentInstanceDispatcherImpl.java
+++ b/server/src/main/java/org/apache/iotdb/db/mpp/plan/scheduler/FragmentInstanceDispatcherImpl.java
@@ -24,9 +24,12 @@ import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.commons.client.IClientManager;
import org.apache.iotdb.commons.client.sync.SyncDataNodeInternalServiceClient;
import org.apache.iotdb.commons.consensus.ConsensusGroupId;
+import org.apache.iotdb.commons.consensus.DataRegionId;
+import org.apache.iotdb.consensus.common.response.ConsensusReadResponse;
import org.apache.iotdb.consensus.common.response.ConsensusWriteResponse;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
-import org.apache.iotdb.db.consensus.ConsensusImpl;
+import org.apache.iotdb.db.consensus.DataRegionConsensusImpl;
+import org.apache.iotdb.db.consensus.SchemaRegionConsensusImpl;
import org.apache.iotdb.db.exception.mpp.FragmentInstanceDispatchException;
import org.apache.iotdb.db.exception.sql.SemanticException;
import org.apache.iotdb.db.mpp.execution.fragment.FragmentInstanceInfo;
@@ -169,9 +172,20 @@ public class FragmentInstanceDispatcherImpl implements IFragInstanceDispatcher {
instance.getRegionReplicaSet().getRegionId());
switch (instance.getType()) {
case READ:
- FragmentInstanceInfo info =
- (FragmentInstanceInfo) ConsensusImpl.getInstance().read(groupId, instance).getDataset();
- return !info.getState().isFailed();
+ ConsensusReadResponse readResponse;
+ if (groupId instanceof DataRegionId) {
+ readResponse = DataRegionConsensusImpl.getInstance().read(groupId, instance);
+ } else {
+ readResponse = SchemaRegionConsensusImpl.getInstance().read(groupId, instance);
+ }
+ if (!readResponse.isSuccess()) {
+ logger.error(
+ "dispatch FragmentInstance {} locally failed because {}",
+ instance,
+ readResponse.getException());
+ return false;
+ }
+ return !((FragmentInstanceInfo) readResponse.getDataset()).getState().isFailed();
case WRITE:
PlanNode planNode = instance.getFragment().getRoot();
if (planNode instanceof InsertNode) {
@@ -181,8 +195,13 @@ public class FragmentInstanceDispatcherImpl implements IFragInstanceDispatcher {
throw new FragmentInstanceDispatchException(e);
}
}
- ConsensusWriteResponse resp = ConsensusImpl.getInstance().write(groupId, instance);
- return TSStatusCode.SUCCESS_STATUS.getStatusCode() == resp.getStatus().getCode();
+ ConsensusWriteResponse writeResponse;
+ if (groupId instanceof DataRegionId) {
+ writeResponse = DataRegionConsensusImpl.getInstance().write(groupId, instance);
+ } else {
+ writeResponse = SchemaRegionConsensusImpl.getInstance().write(groupId, instance);
+ }
+ return TSStatusCode.SUCCESS_STATUS.getStatusCode() == writeResponse.getStatus().getCode();
}
throw new UnsupportedOperationException(
String.format("unknown query type [%s]", instance.getType()));
diff --git a/server/src/main/java/org/apache/iotdb/db/service/DataNode.java b/server/src/main/java/org/apache/iotdb/db/service/DataNode.java
index b523b8749e..e2b62e687d 100644
--- a/server/src/main/java/org/apache/iotdb/db/service/DataNode.java
+++ b/server/src/main/java/org/apache/iotdb/db/service/DataNode.java
@@ -40,7 +40,8 @@ import org.apache.iotdb.db.conf.IoTDBConfig;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.conf.IoTDBStartCheck;
import org.apache.iotdb.db.conf.rest.IoTDBRestServiceDescriptor;
-import org.apache.iotdb.db.consensus.ConsensusImpl;
+import org.apache.iotdb.db.consensus.DataRegionConsensusImpl;
+import org.apache.iotdb.db.consensus.SchemaRegionConsensusImpl;
import org.apache.iotdb.db.engine.StorageEngineV2;
import org.apache.iotdb.db.engine.cache.CacheHitRatioMonitor;
import org.apache.iotdb.db.engine.compaction.CompactionTaskManager;
@@ -172,8 +173,10 @@ public class DataNode implements DataNodeMBean {
new TEndPoint(config.getInternalIp(), config.getInternalPort()));
location.setDataBlockManagerEndPoint(
new TEndPoint(config.getInternalIp(), config.getDataBlockManagerPort()));
- location.setConsensusEndPoint(
- new TEndPoint(config.getInternalIp(), config.getConsensusPort()));
+ location.setDataRegionConsensusEndPoint(
+ new TEndPoint(config.getInternalIp(), config.getDataRegionConsensusPort()));
+ location.setSchemaRegionConsensusEndPoint(
+ new TEndPoint(config.getInternalIp(), config.getSchemaRegionConsensusPort()));
// Set DataNodeInfo
TDataNodeInfo info = new TDataNodeInfo();
@@ -244,7 +247,8 @@ public class DataNode implements DataNodeMBean {
try {
// TODO: Start consensus layer in some where else
- ConsensusImpl.getInstance().start();
+ SchemaRegionConsensusImpl.getInstance().start();
+ DataRegionConsensusImpl.getInstance().start();
} catch (IOException e) {
throw new StartupException(e);
}
diff --git a/server/src/main/java/org/apache/iotdb/db/service/thrift/impl/InternalServiceImpl.java b/server/src/main/java/org/apache/iotdb/db/service/thrift/impl/InternalServiceImpl.java
index 62157d6ecb..eff3a3ffa0 100644
--- a/server/src/main/java/org/apache/iotdb/db/service/thrift/impl/InternalServiceImpl.java
+++ b/server/src/main/java/org/apache/iotdb/db/service/thrift/impl/InternalServiceImpl.java
@@ -40,7 +40,8 @@ import org.apache.iotdb.consensus.common.response.ConsensusGenericResponse;
import org.apache.iotdb.consensus.common.response.ConsensusReadResponse;
import org.apache.iotdb.consensus.common.response.ConsensusWriteResponse;
import org.apache.iotdb.db.auth.AuthorizerManager;
-import org.apache.iotdb.db.consensus.ConsensusImpl;
+import org.apache.iotdb.db.consensus.DataRegionConsensusImpl;
+import org.apache.iotdb.db.consensus.SchemaRegionConsensusImpl;
import org.apache.iotdb.db.engine.StorageEngineV2;
import org.apache.iotdb.db.exception.DataRegionException;
import org.apache.iotdb.db.exception.sql.SemanticException;
@@ -118,14 +119,28 @@ public class InternalServiceImpl implements InternalService.Iface {
ConsensusGroupId.Factory.createFromTConsensusGroupId(req.getConsensusGroupId());
switch (type) {
case READ:
- ConsensusReadResponse readResp =
- ConsensusImpl.getInstance()
- .read(groupId, new ByteBufferConsensusRequest(req.fragmentInstance.body));
- FragmentInstanceInfo info = (FragmentInstanceInfo) readResp.getDataset();
+ ConsensusReadResponse readResponse;
+ if (groupId instanceof DataRegionId) {
+ readResponse =
+ DataRegionConsensusImpl.getInstance()
+ .read(groupId, new ByteBufferConsensusRequest(req.fragmentInstance.body));
+ } else {
+ readResponse =
+ SchemaRegionConsensusImpl.getInstance()
+ .read(groupId, new ByteBufferConsensusRequest(req.fragmentInstance.body));
+ }
+ if (!readResponse.isSuccess()) {
+ LOGGER.error(
+ "execute FragmentInstance in ConsensusGroup {} failed because {}",
+ req.getConsensusGroupId(),
+ readResponse.getException());
+ return new TSendFragmentInstanceResp(false);
+ }
+ FragmentInstanceInfo info = (FragmentInstanceInfo) readResponse.getDataset();
return new TSendFragmentInstanceResp(!info.getState().isFailed());
case WRITE:
TSendFragmentInstanceResp response = new TSendFragmentInstanceResp();
- ConsensusWriteResponse resp;
+ ConsensusWriteResponse writeResponse;
FragmentInstance fragmentInstance =
FragmentInstance.deserializeFrom(req.fragmentInstance.body);
@@ -139,11 +154,15 @@ public class InternalServiceImpl implements InternalService.Iface {
return response;
}
}
- resp = ConsensusImpl.getInstance().write(groupId, fragmentInstance);
+ if (groupId instanceof DataRegionId) {
+ writeResponse = DataRegionConsensusImpl.getInstance().write(groupId, fragmentInstance);
+ } else {
+ writeResponse = SchemaRegionConsensusImpl.getInstance().write(groupId, fragmentInstance);
+ }
// TODO need consider more status
response.setAccepted(
- TSStatusCode.SUCCESS_STATUS.getStatusCode() == resp.getStatus().getCode());
- response.setMessage(resp.getStatus().message);
+ TSStatusCode.SUCCESS_STATUS.getStatusCode() == writeResponse.getStatus().getCode());
+ response.setMessage(writeResponse.getStatus().message);
return response;
}
return null;
@@ -196,12 +215,12 @@ public class InternalServiceImpl implements InternalService.Iface {
for (TDataNodeLocation dataNodeLocation : regionReplicaSet.getDataNodeLocations()) {
TEndPoint endpoint =
new TEndPoint(
- dataNodeLocation.getConsensusEndPoint().getIp(),
- dataNodeLocation.getConsensusEndPoint().getPort());
+ dataNodeLocation.getSchemaRegionConsensusEndPoint().getIp(),
+ dataNodeLocation.getSchemaRegionConsensusEndPoint().getPort());
peers.add(new Peer(schemaRegionId, endpoint));
}
ConsensusGenericResponse consensusGenericResponse =
- ConsensusImpl.getInstance().addConsensusGroup(schemaRegionId, peers);
+ SchemaRegionConsensusImpl.getInstance().addConsensusGroup(schemaRegionId, peers);
if (consensusGenericResponse.isSuccess()) {
tsStatus = new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
} else {
@@ -234,12 +253,12 @@ public class InternalServiceImpl implements InternalService.Iface {
for (TDataNodeLocation dataNodeLocation : regionReplicaSet.getDataNodeLocations()) {
TEndPoint endpoint =
new TEndPoint(
- dataNodeLocation.getConsensusEndPoint().getIp(),
- dataNodeLocation.getConsensusEndPoint().getPort());
+ dataNodeLocation.getDataRegionConsensusEndPoint().getIp(),
+ dataNodeLocation.getDataRegionConsensusEndPoint().getPort());
peers.add(new Peer(dataRegionId, endpoint));
}
ConsensusGenericResponse consensusGenericResponse =
- ConsensusImpl.getInstance().addConsensusGroup(dataRegionId, peers);
+ DataRegionConsensusImpl.getInstance().addConsensusGroup(dataRegionId, peers);
if (consensusGenericResponse.isSuccess()) {
tsStatus = new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
} else {
@@ -351,7 +370,15 @@ public class InternalServiceImpl implements InternalService.Iface {
PlanFragment planFragment = new PlanFragment(planFragmentId, deleteRegionNode);
FragmentInstance fragmentInstance =
new FragmentInstance(planFragment, fragmentInstanceId, null, QueryType.WRITE);
- return ConsensusImpl.getInstance().write(consensusGroupId, fragmentInstance).getStatus();
+ if (consensusGroupId instanceof DataRegionId) {
+ return DataRegionConsensusImpl.getInstance()
+ .write(consensusGroupId, fragmentInstance)
+ .getStatus();
+ } else {
+ return SchemaRegionConsensusImpl.getInstance()
+ .write(consensusGroupId, fragmentInstance)
+ .getStatus();
+ }
}
@Override
diff --git a/server/src/main/java/org/apache/iotdb/db/wal/node/IWALNode.java b/server/src/main/java/org/apache/iotdb/db/wal/node/IWALNode.java
index 9925015dda..4482b1b3f9 100644
--- a/server/src/main/java/org/apache/iotdb/db/wal/node/IWALNode.java
+++ b/server/src/main/java/org/apache/iotdb/db/wal/node/IWALNode.java
@@ -18,7 +18,8 @@
*/
package org.apache.iotdb.db.wal.node;
-import org.apache.iotdb.consensus.wal.ConsensusReqReader;
+import org.apache.iotdb.consensus.common.DataSet;
+import org.apache.iotdb.consensus.multileader.wal.ConsensusReqReader;
import org.apache.iotdb.db.engine.flush.FlushListener;
import org.apache.iotdb.db.engine.memtable.IMemTable;
import org.apache.iotdb.db.mpp.plan.planner.plan.node.write.InsertRowNode;
@@ -29,7 +30,7 @@ import org.apache.iotdb.db.qp.physical.crud.InsertTabletPlan;
import org.apache.iotdb.db.wal.utils.listener.WALFlushListener;
/** This interface provides uniform interface for writing wal and making checkpoints. */
-public interface IWALNode extends FlushListener, AutoCloseable, ConsensusReqReader {
+public interface IWALNode extends FlushListener, AutoCloseable, ConsensusReqReader, DataSet {
/** Log InsertRowPlan */
WALFlushListener log(int memTableId, InsertRowPlan insertRowPlan);
diff --git a/server/src/main/java/org/apache/iotdb/db/wal/node/WALNode.java b/server/src/main/java/org/apache/iotdb/db/wal/node/WALNode.java
index 7b4d9dba8c..d0002cafd1 100644
--- a/server/src/main/java/org/apache/iotdb/db/wal/node/WALNode.java
+++ b/server/src/main/java/org/apache/iotdb/db/wal/node/WALNode.java
@@ -411,7 +411,9 @@ public class WALNode implements IWALNode {
return null;
}
if (size == 1) {
- return insertNodes.get(0);
+ InsertNode insertNode = insertNodes.get(0);
+ insertNode.setPlanNodeId(new PlanNodeId(""));
+ return insertNode;
}
InsertNode result;
@@ -445,7 +447,7 @@ public class WALNode implements IWALNode {
: new InsertRowsNode(new PlanNodeId(""), index, insertRowNodes);
}
result.setSearchIndex(insertNodes.get(0).getSearchIndex());
-
+ result.setDevicePath(insertNodes.get(0).getDevicePath());
return result;
}
diff --git a/server/src/test/java/org/apache/iotdb/db/mpp/plan/plan/FragmentInstanceSerdeTest.java b/server/src/test/java/org/apache/iotdb/db/mpp/plan/plan/FragmentInstanceSerdeTest.java
index 3e32852dfd..fdb2c1924a 100644
--- a/server/src/test/java/org/apache/iotdb/db/mpp/plan/plan/FragmentInstanceSerdeTest.java
+++ b/server/src/test/java/org/apache/iotdb/db/mpp/plan/plan/FragmentInstanceSerdeTest.java
@@ -57,7 +57,8 @@ public class FragmentInstanceSerdeTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010));
PlanFragmentId planFragmentId = new PlanFragmentId("test", -1);
FragmentInstance fragmentInstance =
@@ -86,7 +87,8 @@ public class FragmentInstanceSerdeTest {
dataNodeLocation.setExternalEndPoint(new TEndPoint("0.0.0.0", 6667));
dataNodeLocation.setInternalEndPoint(new TEndPoint("0.0.0.0", 9003));
dataNodeLocation.setDataBlockManagerEndPoint(new TEndPoint("0.0.0.0", 8777));
- dataNodeLocation.setConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setDataRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 40010));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(new TEndPoint("0.0.0.0", 50010));
PlanFragmentId planFragmentId = new PlanFragmentId("test2", 1);
FragmentInstance fragmentInstance =
diff --git a/server/src/test/java/org/apache/iotdb/db/service/InternalServiceImplTest.java b/server/src/test/java/org/apache/iotdb/db/service/InternalServiceImplTest.java
index 9abb8a5805..6399891c42 100644
--- a/server/src/test/java/org/apache/iotdb/db/service/InternalServiceImplTest.java
+++ b/server/src/test/java/org/apache/iotdb/db/service/InternalServiceImplTest.java
@@ -31,7 +31,8 @@ import org.apache.iotdb.commons.path.PartialPath;
import org.apache.iotdb.consensus.common.Peer;
import org.apache.iotdb.db.conf.IoTDBConfig;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
-import org.apache.iotdb.db.consensus.ConsensusImpl;
+import org.apache.iotdb.db.consensus.DataRegionConsensusImpl;
+import org.apache.iotdb.db.consensus.SchemaRegionConsensusImpl;
import org.apache.iotdb.db.exception.StorageEngineException;
import org.apache.iotdb.db.localconfignode.LocalConfigNode;
import org.apache.iotdb.db.metadata.utils.TimeseriesVersionUtil;
@@ -79,23 +80,24 @@ public class InternalServiceImplTest {
IoTDB.configManager.init();
configNode = LocalConfigNode.getInstance();
configNode.getBelongedSchemaRegionIdWithAutoCreate(new PartialPath("root.ln"));
- ConsensusImpl.getInstance().start();
+ DataRegionConsensusImpl.getInstance().start();
+ SchemaRegionConsensusImpl.getInstance().start();
}
@Before
public void setUp() throws Exception {
TRegionReplicaSet regionReplicaSet = genRegionReplicaSet();
- ConsensusImpl.getInstance()
+ SchemaRegionConsensusImpl.getInstance()
.addConsensusGroup(
ConsensusGroupId.Factory.createFromTConsensusGroupId(regionReplicaSet.getRegionId()),
- genPeerList(regionReplicaSet));
+ genSchemaRegionPeerList(regionReplicaSet));
internalServiceImpl = new InternalServiceImpl();
}
@After
public void tearDown() throws Exception {
TRegionReplicaSet regionReplicaSet = genRegionReplicaSet();
- ConsensusImpl.getInstance()
+ SchemaRegionConsensusImpl.getInstance()
.removeConsensusGroup(
ConsensusGroupId.Factory.createFromTConsensusGroupId(regionReplicaSet.getRegionId()));
FileUtils.deleteFully(new File(conf.getConsensusDir()));
@@ -103,7 +105,8 @@ public class InternalServiceImplTest {
@AfterClass
public static void tearDownAfterClass() throws IOException, StorageEngineException {
- ConsensusImpl.getInstance().stop();
+ DataRegionConsensusImpl.getInstance().stop();
+ SchemaRegionConsensusImpl.getInstance().stop();
IoTDB.configManager.clear();
EnvironmentUtils.cleanEnv();
}
@@ -374,20 +377,23 @@ public class InternalServiceImplTest {
.setInternalEndPoint(new TEndPoint(conf.getInternalIp(), conf.getInternalPort()))
.setDataBlockManagerEndPoint(
new TEndPoint(conf.getInternalIp(), conf.getDataBlockManagerPort()))
- .setConsensusEndPoint(new TEndPoint(conf.getInternalIp(), conf.getConsensusPort())));
+ .setDataRegionConsensusEndPoint(
+ new TEndPoint(conf.getInternalIp(), conf.getDataRegionConsensusPort()))
+ .setSchemaRegionConsensusEndPoint(
+ new TEndPoint(conf.getInternalIp(), conf.getSchemaRegionConsensusPort())));
// construct fragmentInstance
return new TRegionReplicaSet(
new TConsensusGroupId(TConsensusGroupType.SchemaRegion, 0), dataNodeList);
}
- private List<Peer> genPeerList(TRegionReplicaSet regionReplicaSet) {
+ private List<Peer> genSchemaRegionPeerList(TRegionReplicaSet regionReplicaSet) {
List<Peer> peerList = new ArrayList<>();
for (TDataNodeLocation node : regionReplicaSet.getDataNodeLocations()) {
peerList.add(
new Peer(
new SchemaRegionId(regionReplicaSet.getRegionId().getId()),
- node.getConsensusEndPoint()));
+ node.getSchemaRegionConsensusEndPoint()));
}
return peerList;
}
diff --git a/server/src/test/java/org/apache/iotdb/db/wal/node/ConsensusReqReaderTest.java b/server/src/test/java/org/apache/iotdb/db/wal/node/ConsensusReqReaderTest.java
index 7eb5f06b90..579b413961 100644
--- a/server/src/test/java/org/apache/iotdb/db/wal/node/ConsensusReqReaderTest.java
+++ b/server/src/test/java/org/apache/iotdb/db/wal/node/ConsensusReqReaderTest.java
@@ -21,7 +21,7 @@ package org.apache.iotdb.db.wal.node;
import org.apache.iotdb.commons.exception.IllegalPathException;
import org.apache.iotdb.commons.path.PartialPath;
import org.apache.iotdb.consensus.common.request.IConsensusRequest;
-import org.apache.iotdb.consensus.wal.ConsensusReqReader;
+import org.apache.iotdb.consensus.multileader.wal.ConsensusReqReader;
import org.apache.iotdb.db.conf.IoTDBConfig;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
import org.apache.iotdb.db.constant.TestConstant;
diff --git a/server/src/test/resources/datanode1conf/iotdb-engine.properties b/server/src/test/resources/datanode1conf/iotdb-engine.properties
index 0f02933bbc..cced42b412 100644
--- a/server/src/test/resources/datanode1conf/iotdb-engine.properties
+++ b/server/src/test/resources/datanode1conf/iotdb-engine.properties
@@ -23,7 +23,8 @@ internal_ip=127.0.0.1
rpc_port=6667
data_block_manager_port=8777
internal_port=9003
-consensus_port=40010
+data_region_consensus_port=40010
+schema_region_consensus_port=50010
config_nodes=0.0.0.0:22277,0.0.0.0:22279,0.0.0.0:22281
diff --git a/server/src/test/resources/datanode2conf/iotdb-engine.properties b/server/src/test/resources/datanode2conf/iotdb-engine.properties
index 429c025a6b..c570d996b7 100644
--- a/server/src/test/resources/datanode2conf/iotdb-engine.properties
+++ b/server/src/test/resources/datanode2conf/iotdb-engine.properties
@@ -23,7 +23,8 @@ internal_ip=127.0.0.1
rpc_port=6669
data_block_manager_port=8779
internal_port=9005
-consensus_port=40012
+data_region_consensus_port=40012
+schema_region_consensus_port=50012
config_nodes=0.0.0.0:22277,0.0.0.0:22279,0.0.0.0:22281
diff --git a/server/src/test/resources/datanode3conf/iotdb-engine.properties b/server/src/test/resources/datanode3conf/iotdb-engine.properties
index 5a390729a6..956faee018 100644
--- a/server/src/test/resources/datanode3conf/iotdb-engine.properties
+++ b/server/src/test/resources/datanode3conf/iotdb-engine.properties
@@ -23,7 +23,8 @@ internal_ip=127.0.0.1
rpc_port=6671
data_block_manager_port=8781
internal_port=9007
-consensus_port=40014
+data_region_consensus_port=40014
+schema_region_consensus_port=50014
config_nodes=0.0.0.0:22277,0.0.0.0:22279,0.0.0.0:22281
diff --git a/thrift-commons/src/main/thrift/common.thrift b/thrift-commons/src/main/thrift/common.thrift
index aad4d3e13a..9f3de32db9 100644
--- a/thrift-commons/src/main/thrift/common.thrift
+++ b/thrift-commons/src/main/thrift/common.thrift
@@ -74,8 +74,10 @@ struct TDataNodeLocation {
3: required TEndPoint internalEndPoint
// TEndPoint for transfering data between DataNodes
4: required TEndPoint dataBlockManagerEndPoint
- // TEndPoint for DataNode's ConsensusLayer
- 5: required TEndPoint consensusEndPoint
+ // TEndPoint for DataNode's dataRegion consensus protocol
+ 5: required TEndPoint dataRegionConsensusEndPoint
+ // TEndPoint for DataNode's schemaRegion consensus protocol
+ 6: required TEndPoint schemaRegionConsensusEndPoint
}
struct THeartbeatResp {
diff --git a/thrift-confignode/src/main/thrift/confignode.thrift b/thrift-confignode/src/main/thrift/confignode.thrift
index 42378a0985..ac3f749041 100644
--- a/thrift-confignode/src/main/thrift/confignode.thrift
+++ b/thrift-confignode/src/main/thrift/confignode.thrift
@@ -30,10 +30,11 @@ struct TDataNodeRegisterReq {
}
struct TGlobalConfig {
- 1: required string dataNodeConsensusProtocolClass
- 2: required i32 seriesPartitionSlotNum
- 3: required string seriesPartitionExecutorClass
- 4: required i64 timePartitionInterval
+ 1: required string dataRegionConsensusProtocolClass
+ 2: required string schemaRegionConsensusProtocolClass
+ 3: required i32 seriesPartitionSlotNum
+ 4: required string seriesPartitionExecutorClass
+ 5: required i64 timePartitionInterval
}
struct TDataNodeRegisterResp {
@@ -191,13 +192,14 @@ struct TCheckUserPrivilegesReq{
// ConfigNode
struct TConfigNodeRegisterReq {
1: required common.TConfigNodeLocation configNodeLocation
- 2: required string dataNodeConsensusProtocolClass
- 3: required i32 seriesPartitionSlotNum
- 4: required string seriesPartitionExecutorClass
- 5: required i64 defaultTTL
- 6: required i64 timePartitionInterval
- 7: required i32 schemaReplicationFactor
- 8: required i32 dataReplicationFactor
+ 2: required string dataRegionConsensusProtocolClass
+ 3: required string schemaRegionConsensusProtocolClass
+ 4: required i32 seriesPartitionSlotNum
+ 5: required string seriesPartitionExecutorClass
+ 6: required i64 defaultTTL
+ 7: required i64 timePartitionInterval
+ 8: required i32 schemaReplicationFactor
+ 9: required i32 dataReplicationFactor
}
struct TConfigNodeRegisterResp {
diff --git a/consensus/pom.xml b/thrift-multi-leader-consensus/pom.xml
similarity index 56%
copy from consensus/pom.xml
copy to thrift-multi-leader-consensus/pom.xml
index e4d873bb19..a55147ded5 100644
--- a/consensus/pom.xml
+++ b/thrift-multi-leader-consensus/pom.xml
@@ -20,42 +20,48 @@
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
<parent>
- <artifactId>iotdb-parent</artifactId>
<groupId>org.apache.iotdb</groupId>
+ <artifactId>iotdb-parent</artifactId>
<version>0.14.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
- <modelVersion>4.0.0</modelVersion>
- <artifactId>iotdb-consensus</artifactId>
- <name>IoTDB Consensus</name>
+ <artifactId>thrift-multi-leader-consensus</artifactId>
+ <name>rpc-thrift-multi-leader-consensus</name>
+ <description>Rpc modules for multi leader consensus algorithm</description>
<dependencies>
- <!-- https://mvnrepository.com/artifact/org.apache.ratis/ratis-server -->
- <dependency>
- <groupId>org.apache.ratis</groupId>
- <artifactId>ratis-server</artifactId>
- <version>${ratis.version}</version>
- </dependency>
- <dependency>
- <groupId>org.apache.ratis</groupId>
- <artifactId>ratis-common</artifactId>
- <version>${ratis.version}</version>
- </dependency>
<dependency>
- <groupId>org.apache.ratis</groupId>
- <artifactId>ratis-grpc</artifactId>
- <version>${ratis.version}</version>
+ <groupId>org.apache.thrift</groupId>
+ <artifactId>libthrift</artifactId>
</dependency>
<dependency>
<groupId>org.apache.iotdb</groupId>
- <artifactId>node-commons</artifactId>
+ <artifactId>iotdb-thrift-commons</artifactId>
<version>${project.version}</version>
- <scope>compile</scope>
</dependency>
</dependencies>
- <properties>
- <maven.compiler.source>8</maven.compiler.source>
- <maven.compiler.target>8</maven.compiler.target>
- <ratis.version>2.3.0</ratis.version>
- </properties>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <version>3.2.0</version>
+ <executions>
+ <execution>
+ <id>add-source</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>add-source</goal>
+ </goals>
+ <configuration>
+ <sources>
+ <source>${project.build.directory}/generated-sources/thrift</source>
+ </sources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
</project>
diff --git a/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusResponse.java b/thrift-multi-leader-consensus/src/main/thrift/mutlileader.thrift
similarity index 63%
copy from consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusResponse.java
copy to thrift-multi-leader-consensus/src/main/thrift/mutlileader.thrift
index 355b0d035a..2fa382843a 100644
--- a/consensus/src/main/java/org/apache/iotdb/consensus/common/response/ConsensusResponse.java
+++ b/thrift-multi-leader-consensus/src/main/thrift/mutlileader.thrift
@@ -17,23 +17,28 @@
* under the License.
*/
-package org.apache.iotdb.consensus.common.response;
+include "common.thrift"
+namespace java org.apache.iotdb.consensus.multileader.thrift
-import org.apache.iotdb.consensus.exception.ConsensusException;
-
-public abstract class ConsensusResponse {
- private final ConsensusException exception;
+enum TLogType {
+ FragmentInstance,
+ InsertNode
+}
- public ConsensusResponse(ConsensusException exception) {
- this.exception = exception;
- }
+struct TLogBatch {
+ 1: required TLogType type
+ 2: required binary data
+}
- public ConsensusException getException() {
- return exception;
- }
+struct TSyncLogReq {
+ 1: required common.TConsensusGroupId consensusGroupId
+ 2: required list<TLogBatch> batches
+}
- @Override
- public String toString() {
- return "exception=" + exception;
- }
+struct TSyncLogRes {
+ 1: required list<common.TSStatus> status
}
+
+service MultiLeaderConsensusIService {
+ TSyncLogRes syncLog(TSyncLogReq req)
+}
\ No newline at end of file