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/10/29 03:03:30 UTC
[iotdb] branch master updated: [IOTDB-4341] Refactor LoadBalancing framework and maintain RegionRouteMap in RouteBalancer (#7766)
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 ad570418ad [IOTDB-4341] Refactor LoadBalancing framework and maintain RegionRouteMap in RouteBalancer (#7766)
ad570418ad is described below
commit ad570418ad4712bd9bbf27f657b444aa755506df
Author: YongzaoDan <33...@users.noreply.github.com>
AuthorDate: Sat Oct 29 11:03:24 2022 +0800
[IOTDB-4341] Refactor LoadBalancing framework and maintain RegionRouteMap in RouteBalancer (#7766)
---
.../heartbeat/DataNodeHeartbeatHandler.java | 24 +-
.../write/statistics/UpdateLoadStatisticsPlan.java | 81 +++--
.../statemachine/PartitionRegionStateMachine.java | 12 +-
.../iotdb/confignode/manager/load/LoadManager.java | 55 ++--
.../manager/load/LoadManagerMetrics.java | 8 +-
.../manager/load/balancer/RouteBalancer.java | 260 ++++++++++++----
.../manager/load/balancer/router/IRouter.java | 4 +-
.../load/balancer/router/LazyGreedyRouter.java | 159 ----------
.../manager/load/balancer/router/LeaderRouter.java | 25 +-
.../balancer/router/LoadScoreGreedyRouter.java | 21 +-
.../load/balancer/router/RegionRouteMap.java | 172 +++++++++++
.../confignode/manager/node/BaseNodeCache.java | 20 +-
.../manager/node/ConfigNodeHeartbeatCache.java | 18 +-
.../manager/node/DataNodeHeartbeatCache.java | 16 +-
.../iotdb/confignode/manager/node/NodeManager.java | 147 +++++----
.../manager/partition/PartitionManager.java | 117 +++----
.../confignode/manager/partition/RegionCache.java | 2 +-
.../manager/partition/RegionGroupCache.java | 67 ++--
.../manager/partition/RegionHeartbeatSample.java | 11 +-
.../persistence/executor/ConfigPlanExecutor.java | 3 +-
.../confignode/persistence/node/NodeInfo.java | 22 +-
.../persistence/node/NodeStatistics.java | 24 +-
.../persistence/partition/PartitionInfo.java | 109 ++++++-
.../partition/StorageGroupPartitionTable.java | 17 +
.../statistics/RegionGroupStatistics.java | 36 +--
.../partition/statistics/RegionStatistics.java | 48 +--
.../procedure/env/ConfigNodeProcedureEnv.java | 67 +++-
.../impl/node/RemoveDataNodeProcedure.java | 2 +-
.../procedure/impl/schema/DataNodeRegionTask.java | 4 +-
.../impl/schema/DeleteTimeSeriesProcedure.java | 2 +-
.../statemachine/CreateRegionGroupsProcedure.java | 11 +-
.../procedure/state/CreateRegionGroupsState.java | 13 +-
.../request/ConfigPhysicalPlanSerDeTest.java | 32 +-
.../load/balancer/router/LazyGreedyRouterTest.java | 166 ----------
.../load/balancer/router/LeaderRouterTest.java | 147 +--------
.../balancer/router/LoadScoreGreedyRouterTest.java | 32 +-
.../load/balancer/router/RegionRouteMapTest.java | 82 +++++
.../confignode/manager/node/NodeCacheTest.java | 54 ++++
.../manager/partition/RegionGroupCacheTest.java | 53 ++--
.../confignode/persistence/PartitionInfoTest.java | 29 +-
.../statistics/RegionGroupStatisticsTest.java | 4 +-
.../partition/statistics/RegionStatisticsTest.java | 2 +-
.../java/org/apache/iotdb/it/env/AbstractEnv.java | 5 +-
...figNodeIT.java => IoTDBClusterAuthorizeIT.java} | 344 +--------------------
.../iotdb/confignode/it/IoTDBClusterNodeIT.java | 308 ++++++++++++++++++
.../confignode/it/IoTDBClusterPartitionIT.java | 1 +
.../it/IoTDBClusterRegionLeaderBalancingIT.java | 152 +++++++++
.../confignode/it/IoTDBConfigNodeSnapshotIT.java | 4 +-
.../it/IoTDBConfigNodeSwitchLeaderIT.java | 76 +++--
.../iotdb/confignode/it/IoTDBStorageGroupIT.java | 3 +-
.../iotdb/commons/cluster/RegionRoleType.java | 10 +-
.../apache/iotdb/commons/cluster/RegionStatus.java | 5 +
52 files changed, 1719 insertions(+), 1367 deletions(-)
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/client/async/handlers/heartbeat/DataNodeHeartbeatHandler.java b/confignode/src/main/java/org/apache/iotdb/confignode/client/async/handlers/heartbeat/DataNodeHeartbeatHandler.java
index 65729102b5..3b24e17189 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/client/async/handlers/heartbeat/DataNodeHeartbeatHandler.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/client/async/handlers/heartbeat/DataNodeHeartbeatHandler.java
@@ -21,11 +21,13 @@ package org.apache.iotdb.confignode.client.async.handlers.heartbeat;
import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
import org.apache.iotdb.commons.cluster.RegionStatus;
+import org.apache.iotdb.confignode.manager.load.balancer.RouteBalancer;
import org.apache.iotdb.confignode.manager.node.DataNodeHeartbeatCache;
import org.apache.iotdb.confignode.manager.node.NodeHeartbeatSample;
import org.apache.iotdb.confignode.manager.partition.RegionGroupCache;
import org.apache.iotdb.confignode.manager.partition.RegionHeartbeatSample;
import org.apache.iotdb.mpp.rpc.thrift.THeartbeatResp;
+import org.apache.iotdb.tsfile.utils.Pair;
import org.apache.thrift.async.AsyncMethodCallback;
@@ -37,14 +39,17 @@ public class DataNodeHeartbeatHandler implements AsyncMethodCallback<THeartbeatR
private final TDataNodeLocation dataNodeLocation;
private final DataNodeHeartbeatCache dataNodeHeartbeatCache;
private final Map<TConsensusGroupId, RegionGroupCache> regionGroupCacheMap;
+ private final RouteBalancer routeBalancer;
public DataNodeHeartbeatHandler(
TDataNodeLocation dataNodeLocation,
DataNodeHeartbeatCache dataNodeHeartbeatCache,
- Map<TConsensusGroupId, RegionGroupCache> regionGroupCacheMap) {
+ Map<TConsensusGroupId, RegionGroupCache> regionGroupCacheMap,
+ RouteBalancer routeBalancer) {
this.dataNodeLocation = dataNodeLocation;
this.dataNodeHeartbeatCache = dataNodeHeartbeatCache;
this.regionGroupCacheMap = regionGroupCacheMap;
+ this.routeBalancer = routeBalancer;
}
@Override
@@ -58,8 +63,9 @@ public class DataNodeHeartbeatHandler implements AsyncMethodCallback<THeartbeatR
// Update RegionGroupCache
heartbeatResp
.getJudgedLeaders()
+ .keySet()
.forEach(
- (consensusGroupId, isLeader) ->
+ consensusGroupId ->
regionGroupCacheMap
.computeIfAbsent(
consensusGroupId, empty -> new RegionGroupCache(consensusGroupId))
@@ -68,9 +74,21 @@ public class DataNodeHeartbeatHandler implements AsyncMethodCallback<THeartbeatR
new RegionHeartbeatSample(
heartbeatResp.getHeartbeatTimestamp(),
receiveTime,
- isLeader,
// Region will inherit DataNode's status
RegionStatus.parse(heartbeatResp.getStatus()))));
+
+ // Update leaderCache
+ heartbeatResp
+ .getJudgedLeaders()
+ .forEach(
+ (consensusGroupId, isLeader) -> {
+ if (isLeader) {
+ routeBalancer.cacheLeaderSample(
+ consensusGroupId,
+ new Pair<>(
+ heartbeatResp.getHeartbeatTimestamp(), dataNodeLocation.getDataNodeId()));
+ }
+ });
}
@Override
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/consensus/request/write/statistics/UpdateLoadStatisticsPlan.java b/confignode/src/main/java/org/apache/iotdb/confignode/consensus/request/write/statistics/UpdateLoadStatisticsPlan.java
index b3b9ba08b3..9ad3c27a3c 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/consensus/request/write/statistics/UpdateLoadStatisticsPlan.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/consensus/request/write/statistics/UpdateLoadStatisticsPlan.java
@@ -22,16 +22,22 @@ import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
import org.apache.iotdb.commons.utils.ThriftCommonsSerDeUtils;
import org.apache.iotdb.confignode.consensus.request.ConfigPhysicalPlan;
import org.apache.iotdb.confignode.consensus.request.ConfigPhysicalPlanType;
+import org.apache.iotdb.confignode.manager.load.balancer.router.RegionRouteMap;
import org.apache.iotdb.confignode.persistence.node.NodeStatistics;
import org.apache.iotdb.confignode.persistence.partition.statistics.RegionGroupStatistics;
import org.apache.iotdb.tsfile.utils.ReadWriteIOUtils;
+import org.apache.thrift.TException;
+import org.apache.thrift.protocol.TBinaryProtocol;
+import org.apache.thrift.transport.TIOStreamTransport;
+import org.apache.thrift.transport.TTransport;
+
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
-import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
public class UpdateLoadStatisticsPlan extends ConfigPhysicalPlan {
@@ -41,15 +47,24 @@ public class UpdateLoadStatisticsPlan extends ConfigPhysicalPlan {
// Map<TConsensusGroupId, newRegionGroupStatistics>
private final Map<TConsensusGroupId, RegionGroupStatistics> regionGroupStatisticsMap;
+ private final RegionRouteMap regionRouteMap;
+
public UpdateLoadStatisticsPlan() {
super(ConfigPhysicalPlanType.UpdateLoadStatistics);
- this.nodeStatisticsMap = new HashMap<>();
- this.regionGroupStatisticsMap = new HashMap<>();
+ this.nodeStatisticsMap = new ConcurrentHashMap<>();
+ this.regionGroupStatisticsMap = new ConcurrentHashMap<>();
+ this.regionRouteMap = new RegionRouteMap();
}
- /** We should update and consensus the newer statistics information if exists */
- public boolean isNeedUpdate() {
- return !nodeStatisticsMap.isEmpty() || !regionGroupStatisticsMap.isEmpty();
+ /**
+ * Check if the current UpdateLoadStatisticsPlan is empty
+ *
+ * @return True if nodeStatisticsMap, regionGroupStatisticsMap or RegionRouteMap is empty
+ */
+ public boolean isEmpty() {
+ return nodeStatisticsMap.isEmpty()
+ && regionGroupStatisticsMap.isEmpty()
+ && regionRouteMap.isEmpty();
}
public void putNodeStatistics(int nodeId, NodeStatistics nodeStatistics) {
@@ -69,22 +84,40 @@ public class UpdateLoadStatisticsPlan extends ConfigPhysicalPlan {
return regionGroupStatisticsMap;
}
- @Override
- protected void serializeImpl(DataOutputStream stream) throws IOException {
- ReadWriteIOUtils.write(ConfigPhysicalPlanType.UpdateLoadStatistics.ordinal(), stream);
+ public RegionRouteMap getRegionRouteMap() {
+ return regionRouteMap;
+ }
- ReadWriteIOUtils.write(nodeStatisticsMap.size(), stream);
- for (Map.Entry<Integer, NodeStatistics> nodeStatisticsEntry : nodeStatisticsMap.entrySet()) {
- ReadWriteIOUtils.write(nodeStatisticsEntry.getKey(), stream);
- nodeStatisticsEntry.getValue().serialize(stream);
- }
+ public void setRegionRouteMap(RegionRouteMap regionRouteMap) {
+ this.regionRouteMap.setRegionLeaderMap(regionRouteMap.getRegionLeaderMap());
+ this.regionRouteMap.setRegionPriorityMap(regionRouteMap.getRegionPriorityMap());
+ }
- ReadWriteIOUtils.write(regionGroupStatisticsMap.size(), stream);
- for (Map.Entry<TConsensusGroupId, RegionGroupStatistics> regionGroupStatisticsEntry :
- regionGroupStatisticsMap.entrySet()) {
- ThriftCommonsSerDeUtils.serializeTConsensusGroupId(
- regionGroupStatisticsEntry.getKey(), stream);
- regionGroupStatisticsEntry.getValue().serialize(stream);
+ @Override
+ protected void serializeImpl(DataOutputStream stream) throws IOException {
+ try {
+ TTransport transport = new TIOStreamTransport(stream);
+ TBinaryProtocol protocol = new TBinaryProtocol(transport);
+
+ ReadWriteIOUtils.write(ConfigPhysicalPlanType.UpdateLoadStatistics.ordinal(), stream);
+
+ ReadWriteIOUtils.write(nodeStatisticsMap.size(), stream);
+ for (Map.Entry<Integer, NodeStatistics> nodeStatisticsEntry : nodeStatisticsMap.entrySet()) {
+ ReadWriteIOUtils.write(nodeStatisticsEntry.getKey(), stream);
+ nodeStatisticsEntry.getValue().serialize(stream);
+ }
+
+ ReadWriteIOUtils.write(regionGroupStatisticsMap.size(), stream);
+ for (Map.Entry<TConsensusGroupId, RegionGroupStatistics> regionGroupStatisticsEntry :
+ regionGroupStatisticsMap.entrySet()) {
+ ThriftCommonsSerDeUtils.serializeTConsensusGroupId(
+ regionGroupStatisticsEntry.getKey(), stream);
+ regionGroupStatisticsEntry.getValue().serialize(stream);
+ }
+
+ regionRouteMap.serialize(stream, protocol);
+ } catch (TException e) {
+ throw new IOException(e);
}
}
@@ -106,6 +139,8 @@ public class UpdateLoadStatisticsPlan extends ConfigPhysicalPlan {
regionGroupStatistics.deserialize(buffer);
regionGroupStatisticsMap.put(consensusGroupId, regionGroupStatistics);
}
+
+ regionRouteMap.deserialize(buffer);
}
@Override
@@ -115,11 +150,13 @@ public class UpdateLoadStatisticsPlan extends ConfigPhysicalPlan {
if (!super.equals(o)) return false;
UpdateLoadStatisticsPlan that = (UpdateLoadStatisticsPlan) o;
return nodeStatisticsMap.equals(that.nodeStatisticsMap)
- && regionGroupStatisticsMap.equals(that.regionGroupStatisticsMap);
+ && regionGroupStatisticsMap.equals(that.regionGroupStatisticsMap)
+ && regionRouteMap.equals(that.regionRouteMap);
}
@Override
public int hashCode() {
- return Objects.hash(super.hashCode(), nodeStatisticsMap, regionGroupStatisticsMap);
+ return Objects.hash(
+ super.hashCode(), nodeStatisticsMap, regionGroupStatisticsMap, regionRouteMap);
}
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/consensus/statemachine/PartitionRegionStateMachine.java b/confignode/src/main/java/org/apache/iotdb/confignode/consensus/statemachine/PartitionRegionStateMachine.java
index 57c3850bd6..24ece875f2 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/consensus/statemachine/PartitionRegionStateMachine.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/consensus/statemachine/PartitionRegionStateMachine.java
@@ -175,9 +175,14 @@ public class PartitionRegionStateMachine
"Current node [nodeId: {}, ip:port: {}] becomes Leader",
newLeaderId,
currentNodeTEndPoint);
+
+ // Recover HeartbeatCache by inheriting old-leader's statistics result
configManager.getLoadManager().recoverHeartbeatCache();
+
+ // Start leader scheduling services
configManager.getProcedureManager().shiftExecutor(true);
- configManager.getLoadManager().startLoadBalancingService();
+ configManager.getLoadManager().startLoadStatisticsService();
+ configManager.getLoadManager().getRouteBalancer().startRouteBalancingService();
configManager.getNodeManager().startHeartbeatService();
configManager.getNodeManager().startUnknownDataNodeDetector();
configManager.getPartitionManager().startRegionCleaner();
@@ -194,8 +199,11 @@ public class PartitionRegionStateMachine
currentNodeId,
currentNodeTEndPoint,
newLeaderId);
+
+ // Stop leader scheduling services
configManager.getProcedureManager().shiftExecutor(false);
- configManager.getLoadManager().stopLoadBalancingService();
+ configManager.getLoadManager().stopLoadStatisticsService();
+ configManager.getLoadManager().getRouteBalancer().stopRouteBalancingService();
configManager.getNodeManager().stopHeartbeatService();
configManager.getNodeManager().stopUnknownDataNodeDetector();
configManager.getPartitionManager().stopRegionCleaner();
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/LoadManager.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/LoadManager.java
index 4051dcc433..c853d63dbd 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/LoadManager.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/LoadManager.java
@@ -49,8 +49,6 @@ import org.apache.iotdb.confignode.manager.load.balancer.RegionBalancer;
import org.apache.iotdb.confignode.manager.load.balancer.RouteBalancer;
import org.apache.iotdb.confignode.manager.node.NodeManager;
import org.apache.iotdb.confignode.manager.partition.PartitionManager;
-import org.apache.iotdb.confignode.persistence.node.NodeStatistics;
-import org.apache.iotdb.confignode.persistence.partition.statistics.RegionGroupStatistics;
import org.apache.iotdb.mpp.rpc.thrift.TRegionRouteReq;
import org.slf4j.Logger;
@@ -139,6 +137,10 @@ public class LoadManager {
return partitionBalancer.allocateDataPartition(unassignedDataPartitionSlotsMap);
}
+ public Map<TConsensusGroupId, Integer> getLatestRegionLeaderMap() {
+ return routeBalancer.getLatestRegionLeaderMap();
+ }
+
/**
* Generate an optimal real-time read/write requests routing policy.
*
@@ -147,12 +149,11 @@ public class LoadManager {
* sorting result have higher priority.
*/
public Map<TConsensusGroupId, TRegionReplicaSet> getLatestRegionRouteMap() {
- // Always take the latest locations of RegionGroups as the input parameter
- return routeBalancer.getLatestRegionRouteMap(getPartitionManager().getAllReplicaSets());
+ return routeBalancer.getLatestRegionPriorityMap();
}
- /** Start the load balancing service */
- public void startLoadBalancingService() {
+ /** Start the load statistics service */
+ public void startLoadStatisticsService() {
synchronized (scheduleMonitor) {
if (currentLoadStatisticsFuture == null) {
currentLoadStatisticsFuture =
@@ -167,8 +168,8 @@ public class LoadManager {
}
}
- /** Stop the load balancing service */
- public void stopLoadBalancingService() {
+ /** Stop the load statistics service */
+ public void stopLoadStatisticsService() {
synchronized (scheduleMonitor) {
if (currentLoadStatisticsFuture != null) {
currentLoadStatisticsFuture.cancel(false);
@@ -186,10 +187,12 @@ public class LoadManager {
.getNodeCacheMap()
.forEach(
(nodeId, nodeCache) -> {
- // Check if NodeStatistics needs to be updated
- NodeStatistics nodeStatistics = nodeCache.updateNodeStatistics();
- if (nodeStatistics != null) {
- updateLoadStatisticsPlan.putNodeStatistics(nodeId, nodeStatistics);
+ // Update and check if NodeStatistics needs consensus
+ nodeCache.updateNodeStatistics();
+ if (!nodeCache
+ .getStatistics()
+ .equals(getNodeManager().getNodeStatistics(nodeId, false))) {
+ updateLoadStatisticsPlan.putNodeStatistics(nodeId, nodeCache.getStatistics());
}
});
@@ -197,21 +200,28 @@ public class LoadManager {
getPartitionManager()
.getRegionGroupCacheMap()
.forEach(
- (consensusGroupId, regionGroupCache) -> {
- // Check if RegionGroupStatistics needs to be updated
- RegionGroupStatistics regionGroupStatistics =
- regionGroupCache.updateRegionGroupStatistics();
- if (regionGroupStatistics != null) {
+ (regionGroupId, regionGroupCache) -> {
+ // Update and check if RegionGroupStatistics needs consensus
+ regionGroupCache.updateRegionGroupStatistics();
+ if (!regionGroupCache
+ .getStatistics()
+ .equals(getPartitionManager().getRegionGroupStatistics(regionGroupId, false))) {
updateLoadStatisticsPlan.putRegionGroupStatistics(
- consensusGroupId, regionGroupStatistics);
+ regionGroupId, regionGroupCache.getStatistics());
}
});
- // Update LoadStatistics if necessary
- if (updateLoadStatisticsPlan.isNeedUpdate()) {
- getConsensusManager().write(updateLoadStatisticsPlan);
+ // Update RegionRouteMap
+ routeBalancer.updateRegionRouteMap();
+ if (!routeBalancer
+ .getLatestRegionRouteMap()
+ .equals(getPartitionManager().getRegionRouteMap())) {
+ updateLoadStatisticsPlan.setRegionRouteMap(routeBalancer.getLatestRegionRouteMap());
+ }
- // TODO: Broadcast the latest RegionRouteMap in RegionBalancer
+ // Consensus-write LoadStatistics if not empty
+ if (!updateLoadStatisticsPlan.isEmpty()) {
+ getConsensusManager().write(updateLoadStatisticsPlan);
broadcastLatestRegionRouteMap();
}
}
@@ -260,6 +270,7 @@ public class LoadManager {
public void recoverHeartbeatCache() {
getNodeManager().recoverNodeCacheMap();
getPartitionManager().recoverRegionGroupCacheMap();
+ routeBalancer.recoverRegionRouteMap();
}
public RouteBalancer getRouteBalancer() {
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/LoadManagerMetrics.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/LoadManagerMetrics.java
index 989dcaae1b..e594406216 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/LoadManagerMetrics.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/LoadManagerMetrics.java
@@ -103,8 +103,8 @@ public class LoadManagerMetrics implements IMetricSet {
private Integer getLeadershipCountByDatanode(int dataNodeId) {
Map<Integer, Integer> idToCountMap = new ConcurrentHashMap<>();
- getPartitionManager()
- .getAllLeadership()
+ getLoadManager()
+ .getLatestRegionLeaderMap()
.forEach((consensusGroupId, nodeId) -> idToCountMap.merge(nodeId, 1, Integer::sum));
return idToCountMap.get(dataNodeId);
}
@@ -187,6 +187,10 @@ public class LoadManagerMetrics implements IMetricSet {
return configManager.getPartitionManager();
}
+ private LoadManager getLoadManager() {
+ return configManager.getLoadManager();
+ }
+
private int getRunningConfigNodesNum(AbstractMetricService metricService) {
List<TConfigNodeLocation> runningConfigNodes =
getNodeManager().filterConfigNodeThroughStatus(NodeStatus.Running);
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/RouteBalancer.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/RouteBalancer.java
index c14b9e4b2c..1f85d755c2 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/RouteBalancer.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/RouteBalancer.java
@@ -21,96 +21,242 @@ package org.apache.iotdb.confignode.manager.load.balancer;
import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet;
-import org.apache.iotdb.commons.cluster.NodeStatus;
+import org.apache.iotdb.commons.concurrent.IoTDBThreadPoolFactory;
+import org.apache.iotdb.commons.concurrent.threadpool.ScheduledExecutorUtil;
import org.apache.iotdb.confignode.conf.ConfigNodeDescriptor;
import org.apache.iotdb.confignode.manager.IManager;
import org.apache.iotdb.confignode.manager.load.balancer.router.IRouter;
-import org.apache.iotdb.confignode.manager.load.balancer.router.LazyGreedyRouter;
import org.apache.iotdb.confignode.manager.load.balancer.router.LeaderRouter;
import org.apache.iotdb.confignode.manager.load.balancer.router.LoadScoreGreedyRouter;
+import org.apache.iotdb.confignode.manager.load.balancer.router.RegionRouteMap;
import org.apache.iotdb.confignode.manager.node.NodeManager;
import org.apache.iotdb.confignode.manager.partition.PartitionManager;
import org.apache.iotdb.consensus.ConsensusFactory;
+import org.apache.iotdb.tsfile.utils.Pair;
-import java.util.ArrayList;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
/**
- * The RouteBalancer plays the role of load information collector since different routing policy
- * need different load information.
+ * The RouteBalancer will maintain cluster RegionRouteMap, which contains:
+ *
+ * <p>1. regionLeaderMap, record the leader for each RegionGroup
+ *
+ * <p>2. regionPriorityMap, record the priority for read/write requests in each RegionGroup
*/
public class RouteBalancer {
+ private static final Logger LOGGER = LoggerFactory.getLogger(RouteBalancer.class);
+
+ private static final boolean isMultiLeader =
+ ConsensusFactory.MultiLeaderConsensus.equals(
+ ConfigNodeDescriptor.getInstance().getConf().getDataRegionConsensusProtocolClass());
public static final String LEADER_POLICY = "leader";
public static final String GREEDY_POLICY = "greedy";
private final IManager configManager;
- private final LazyGreedyRouter lazyGreedyRouter;
+ // Key: RegionGroupId
+ // Value: Pair<Timestamp, LeaderDataNodeId>, where
+ // the left value stands for sampling timestamp
+ // and the right value stands for the index of DataNode that leader resides.
+ private final Map<TConsensusGroupId, Pair<Long, Integer>> leaderCache;
+
+ /** RegionRouteMap */
+ private final RegionRouteMap regionRouteMap;
+ // For generating optimal RegionRouteMap
+ private final IRouter router;
+
+ /** Leader Balancing service */
+ private Future<?> currentLeaderBalancingFuture;
+
+ private final ScheduledExecutorService leaderBalancingExecutor =
+ IoTDBThreadPoolFactory.newSingleThreadScheduledExecutor("Cluster-LeaderBalancing-Service");
+ private final Object scheduleMonitor = new Object();
public RouteBalancer(IManager configManager) {
this.configManager = configManager;
- this.lazyGreedyRouter = new LazyGreedyRouter();
+
+ this.leaderCache = new ConcurrentHashMap<>();
+
+ this.regionRouteMap = new RegionRouteMap();
+ switch (ConfigNodeDescriptor.getInstance().getConf().getRoutingPolicy()) {
+ case GREEDY_POLICY:
+ this.router = new LoadScoreGreedyRouter();
+ break;
+ case LEADER_POLICY:
+ default:
+ this.router = new LeaderRouter();
+ break;
+ }
+ }
+
+ /**
+ * Cache the newest leaderHeartbeatSample
+ *
+ * @param regionGroupId Corresponding RegionGroup's index
+ * @param leaderSample <Sample timestamp, leaderDataNodeId>, The newest HeartbeatSample
+ */
+ public void cacheLeaderSample(TConsensusGroupId regionGroupId, Pair<Long, Integer> leaderSample) {
+ if (TConsensusGroupType.DataRegion.equals(regionGroupId.getType()) && isMultiLeader) {
+ // The leadership of multi-leader consensus protocol is decided by ConfigNode-leader
+ return;
+ }
+
+ leaderCache.putIfAbsent(regionGroupId, leaderSample);
+ synchronized (leaderCache.get(regionGroupId)) {
+ if (leaderCache.get(regionGroupId).getLeft() < leaderSample.getLeft()) {
+ leaderCache.replace(regionGroupId, leaderSample);
+ }
+ }
+ }
+
+ /** Invoking periodically to update the latest RegionRouteMap */
+ public void updateRegionRouteMap() {
+ synchronized (regionRouteMap) {
+ updateRegionLeaderMap();
+ updateRegionPriorityMap();
+ }
}
- public Map<TConsensusGroupId, TRegionReplicaSet> getLatestRegionRouteMap(
- List<TRegionReplicaSet> regionReplicaSets) {
- List<TRegionReplicaSet> schemaRegionGroups = new ArrayList<>();
- List<TRegionReplicaSet> dataRegionGroups = new ArrayList<>();
-
- regionReplicaSets.forEach(
- regionReplicaSet -> {
- switch (regionReplicaSet.getRegionId().getType()) {
- case SchemaRegion:
- schemaRegionGroups.add(regionReplicaSet);
- break;
- case DataRegion:
- dataRegionGroups.add(regionReplicaSet);
- break;
+ private void updateRegionLeaderMap() {
+ leaderCache.forEach(
+ (regionGroupId, leadershipSample) -> {
+ if (TConsensusGroupType.DataRegion.equals(regionGroupId.getType()) && isMultiLeader) {
+ // Ignore update leader when using multi-leader consensus protocol
+ return;
+ }
+
+ if (leadershipSample.getRight() != regionRouteMap.getLeader(regionGroupId)) {
+ // Update leader
+ regionRouteMap.setLeader(regionGroupId, leadershipSample.getRight());
}
});
+ }
+
+ private void updateRegionPriorityMap() {
+ Map<TConsensusGroupId, Integer> regionLeaderMap = regionRouteMap.getRegionLeaderMap();
+ Map<Integer, Long> dataNodeLoadScoreMap = getNodeManager().getAllLoadScores();
+
+ // Balancing region priority in each SchemaRegionGroup
+ Map<TConsensusGroupId, TRegionReplicaSet> latestRegionPriorityMap =
+ router.getLatestRegionRouteMap(
+ getPartitionManager().getAllReplicaSets(TConsensusGroupType.SchemaRegion),
+ regionLeaderMap,
+ dataNodeLoadScoreMap);
+ // Balancing region priority in each DataRegionGroup
+ latestRegionPriorityMap.putAll(
+ router.getLatestRegionRouteMap(
+ getPartitionManager().getAllReplicaSets(TConsensusGroupType.DataRegion),
+ regionLeaderMap,
+ dataNodeLoadScoreMap));
- // Generate SchemaRegionRouteMap
- Map<TConsensusGroupId, TRegionReplicaSet> result =
- genRouter(TConsensusGroupType.SchemaRegion).getLatestRegionRouteMap(schemaRegionGroups);
- // Generate DataRegionRouteMap
- result.putAll(
- genRouter(TConsensusGroupType.DataRegion).getLatestRegionRouteMap(dataRegionGroups));
- return result;
+ if (!latestRegionPriorityMap.equals(regionRouteMap.getRegionPriorityMap())) {
+ regionRouteMap.setRegionPriorityMap(latestRegionPriorityMap);
+ }
}
- private IRouter genRouter(TConsensusGroupType groupType) {
- String policy = ConfigNodeDescriptor.getInstance().getConf().getRoutingPolicy();
- switch (groupType) {
- case SchemaRegion:
- if (LEADER_POLICY.equals(policy)) {
- return new LeaderRouter(
- getPartitionManager().getAllLeadership(), getNodeManager().getAllLoadScores());
- } else {
- return new LoadScoreGreedyRouter(getNodeManager().getAllLoadScores());
- }
- case DataRegion:
- default:
- if (ConfigNodeDescriptor.getInstance()
- .getConf()
- .getDataRegionConsensusProtocolClass()
- .equals(ConsensusFactory.MultiLeaderConsensus)) {
- // Latent router for MultiLeader consensus protocol
- lazyGreedyRouter.updateDisabledDataNodes(
- getNodeManager()
- .filterDataNodeThroughStatus(
- NodeStatus.Unknown, NodeStatus.Removing, NodeStatus.ReadOnly));
- return lazyGreedyRouter;
- } else if (LEADER_POLICY.equals(policy)) {
- return new LeaderRouter(
- getPartitionManager().getAllLeadership(), getNodeManager().getAllLoadScores());
- } else {
- return new LoadScoreGreedyRouter(getNodeManager().getAllLoadScores());
+ /**
+ * Select leader for the specified RegionGroup greedily. The selected leader will be the DataNode
+ * that currently has the fewest leaders
+ *
+ * @param regionGroupId The specified RegionGroup
+ * @param dataNodeIds The indices of DataNodes where the RegionReplicas reside
+ */
+ public void greedySelectLeader(TConsensusGroupId regionGroupId, List<Integer> dataNodeIds) {
+ synchronized (regionRouteMap) {
+ // Map<DataNodeId, The number of leaders>
+ Map<Integer, AtomicInteger> leaderCounter = new HashMap<>();
+ regionRouteMap
+ .getRegionLeaderMap()
+ .values()
+ .forEach(
+ leaderId ->
+ leaderCounter
+ .computeIfAbsent(leaderId, empty -> new AtomicInteger(0))
+ .getAndIncrement());
+
+ int newLeaderId = -1;
+ int minCount = Integer.MAX_VALUE;
+ AtomicInteger zero = new AtomicInteger(0);
+ for (int dataNodeId : dataNodeIds) {
+ int leaderCount = leaderCounter.getOrDefault(dataNodeId, zero).get();
+ if (leaderCount < minCount) {
+ newLeaderId = dataNodeId;
+ minCount = leaderCount;
}
+ }
+ regionRouteMap.setLeader(regionGroupId, newLeaderId);
+ }
+ }
+
+ /** Start the route balancing service */
+ public void startRouteBalancingService() {
+ synchronized (scheduleMonitor) {
+ if (currentLeaderBalancingFuture == null) {
+ currentLeaderBalancingFuture =
+ ScheduledExecutorUtil.safelyScheduleWithFixedDelay(
+ leaderBalancingExecutor,
+ this::balancingRegionLeader,
+ 0,
+ // Execute route balancing service in every 10 loops of heartbeat service
+ NodeManager.HEARTBEAT_INTERVAL * 10,
+ TimeUnit.MILLISECONDS);
+ LOGGER.info("Route-Balancing service is started successfully.");
+ }
+ }
+ }
+
+ /** Stop the route balancing service */
+ public void stopRouteBalancingService() {
+ synchronized (scheduleMonitor) {
+ if (currentLeaderBalancingFuture != null) {
+ currentLeaderBalancingFuture.cancel(false);
+ currentLeaderBalancingFuture = null;
+ leaderCache.clear();
+ LOGGER.info("Route-Balancing service is stopped successfully.");
+ }
+ }
+ }
+
+ private void balancingRegionLeader() {
+ // TODO: IOTDB-4768
+ }
+
+ /** Recover the regionRouteMap when the ConfigNode-Leader is switched */
+ public void recoverRegionRouteMap() {
+ synchronized (regionRouteMap) {
+ RegionRouteMap inheritRegionRouteMap = getPartitionManager().getRegionRouteMap();
+ regionRouteMap.setRegionLeaderMap(
+ new ConcurrentHashMap<>(inheritRegionRouteMap.getRegionLeaderMap()));
+ regionRouteMap.setRegionPriorityMap(
+ new ConcurrentHashMap<>(inheritRegionRouteMap.getRegionPriorityMap()));
+
+ LOGGER.info("[InheritLoadStatistics] RegionRouteMap: {}", regionRouteMap);
}
}
+ public Map<TConsensusGroupId, Integer> getLatestRegionLeaderMap() {
+ return regionRouteMap.getRegionLeaderMap();
+ }
+
+ public Map<TConsensusGroupId, TRegionReplicaSet> getLatestRegionPriorityMap() {
+ return regionRouteMap.getRegionPriorityMap();
+ }
+
+ public RegionRouteMap getLatestRegionRouteMap() {
+ return regionRouteMap;
+ }
+
private NodeManager getNodeManager() {
return configManager.getNodeManager();
}
@@ -118,8 +264,4 @@ public class RouteBalancer {
private PartitionManager getPartitionManager() {
return configManager.getPartitionManager();
}
-
- public Map<TConsensusGroupId, TRegionReplicaSet> getRouteMap() {
- return lazyGreedyRouter.getRouteMap();
- }
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/IRouter.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/IRouter.java
index 2ff8500aaa..b6e875f77c 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/IRouter.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/IRouter.java
@@ -39,5 +39,7 @@ public interface IRouter {
* sorting result have higher priority.
*/
Map<TConsensusGroupId, TRegionReplicaSet> getLatestRegionRouteMap(
- List<TRegionReplicaSet> replicaSets);
+ List<TRegionReplicaSet> replicaSets,
+ Map<TConsensusGroupId, Integer> regionLeaderMap,
+ Map<Integer, Long> dataNodeLoadScoreMap);
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LazyGreedyRouter.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LazyGreedyRouter.java
deleted file mode 100644
index 4c4e12fcc5..0000000000
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LazyGreedyRouter.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * 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.confignode.manager.load.balancer.router;
-
-import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
-import org.apache.iotdb.common.rpc.thrift.TDataNodeConfiguration;
-import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
-import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.stream.Collectors;
-
-/**
- * The LazyGreedyRouter mainly applies to the MultiLeader consensus protocol, it will make the
- * number of leaders in each online DataNode as equal as possible
- */
-public class LazyGreedyRouter implements IRouter {
-
- /** Set<DataNodeId> which stores the DataNodes that unable to provide service */
- private final Set<Integer> disabledDataNodes;
-
- private final Map<TConsensusGroupId, TRegionReplicaSet> routeMap;
-
- public LazyGreedyRouter() {
- this.disabledDataNodes = Collections.synchronizedSet(new HashSet<>());
- this.routeMap = new ConcurrentHashMap<>();
- }
-
- /**
- * Update the disabledDataNodes cache in LazyRandomRouter
- *
- * @param disabledDataNodes DataNodes whose status aren't Running
- */
- public void updateDisabledDataNodes(List<TDataNodeConfiguration> disabledDataNodes) {
- synchronized (this.disabledDataNodes) {
- this.disabledDataNodes.clear();
- this.disabledDataNodes.addAll(
- disabledDataNodes.stream()
- .map(dataNodeConfiguration -> dataNodeConfiguration.getLocation().getDataNodeId())
- .collect(Collectors.toList()));
- }
- }
-
- @Override
- public Map<TConsensusGroupId, TRegionReplicaSet> getLatestRegionRouteMap(
- List<TRegionReplicaSet> replicaSets) {
- synchronized (disabledDataNodes) {
- // Map<DataNodeId, leaderCount> Count the number of leaders in each DataNodes
- Map<Integer, Integer> leaderCounter = new HashMap<>();
- Map<TConsensusGroupId, TRegionReplicaSet> result = new ConcurrentHashMap<>();
- List<TRegionReplicaSet> updateReplicas = new ArrayList<>();
-
- for (TRegionReplicaSet replicaSet : replicaSets) {
- if (routeEntryNeedsUpdate(replicaSet)) {
- // The greedy algorithm should be performed lastly
- updateReplicas.add(replicaSet);
- } else {
- // Update counter
- leaderCounter.compute(
- routeMap.get(replicaSet.getRegionId()).getDataNodeLocations().get(0).getDataNodeId(),
- (dataNodeId, counter) -> (counter == null ? 1 : counter + 1));
- // Record the unaltered results
- result.put(replicaSet.getRegionId(), routeMap.get(replicaSet.getRegionId()));
- }
- }
-
- for (TRegionReplicaSet replicaSet : updateReplicas) {
- updateRouteEntry(replicaSet, leaderCounter);
- result.put(replicaSet.getRegionId(), routeMap.get(replicaSet.getRegionId()));
- }
-
- return result;
- }
- }
-
- /** Check whether the specific RegionReplicaSet's routing policy needs update */
- private boolean routeEntryNeedsUpdate(TRegionReplicaSet replicaSet) {
- TConsensusGroupId groupId = replicaSet.getRegionId();
- if (!routeMap.containsKey(groupId)) {
- // The RouteEntry needs update when it is not recorded yet
- return true;
- }
-
- Set<Integer> cacheReplicaSet =
- routeMap.get(groupId).getDataNodeLocations().stream()
- .map(TDataNodeLocation::getDataNodeId)
- .collect(Collectors.toSet());
- Set<Integer> inputReplicaSet =
- replicaSet.getDataNodeLocations().stream()
- .map(TDataNodeLocation::getDataNodeId)
- .collect(Collectors.toSet());
- if (!cacheReplicaSet.equals(inputReplicaSet)) {
- // The RouteEntry needs update when the cached record is outdated
- return true;
- }
-
- // The RouteEntry needs update when the status of DataNode corresponding to the first priority
- // is unknown
- return disabledDataNodes.contains(
- routeMap.get(groupId).getDataNodeLocations().get(0).getDataNodeId());
- }
-
- private void updateRouteEntry(TRegionReplicaSet replicaSet, Map<Integer, Integer> leaderCounter) {
- TRegionReplicaSet newRouteEntry = new TRegionReplicaSet(replicaSet);
- Collections.shuffle(newRouteEntry.getDataNodeLocations(), new Random());
-
- // Greedily select the leader replica
- int leaderIndex = -1;
- int locateLeaderCount = Integer.MAX_VALUE;
- for (int i = 0; i < newRouteEntry.getDataNodeLocationsSize(); i++) {
- int currentDataNodeId = newRouteEntry.getDataNodeLocations().get(i).getDataNodeId();
- if (!disabledDataNodes.contains(currentDataNodeId)
- && leaderCounter.getOrDefault(currentDataNodeId, 0) < locateLeaderCount) {
- leaderIndex = i;
- locateLeaderCount = leaderCounter.getOrDefault(currentDataNodeId, 0);
- }
- }
-
- if (leaderIndex == -1) {
- // Prevent corner case that all DataNodes fail down
- leaderIndex = 0;
- }
-
- // Swap leader replica and update statistic
- Collections.swap(newRouteEntry.getDataNodeLocations(), 0, leaderIndex);
- leaderCounter.compute(
- newRouteEntry.getDataNodeLocations().get(0).getDataNodeId(),
- (dataNodeId, counter) -> (counter == null ? 1 : counter + 1));
- routeMap.put(newRouteEntry.getRegionId(), newRouteEntry);
- }
-
- public Map<TConsensusGroupId, TRegionReplicaSet> getRouteMap() {
- return routeMap;
- }
-}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LeaderRouter.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LeaderRouter.java
index 2d0996ddcb..4ab5505f48 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LeaderRouter.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LeaderRouter.java
@@ -32,24 +32,21 @@ import java.util.concurrent.ConcurrentHashMap;
/** The LeaderRouter always pick the leader Replica */
public class LeaderRouter implements IRouter {
- // Map<RegionGroupId, leader location>
- private final Map<TConsensusGroupId, Integer> leaderMap;
- // Map<DataNodeId, loadScore>
- private final Map<Integer, Long> loadScoreMap;
-
- public LeaderRouter(Map<TConsensusGroupId, Integer> leaderMap, Map<Integer, Long> loadScoreMap) {
- this.leaderMap = leaderMap;
- this.loadScoreMap = loadScoreMap;
+ public LeaderRouter() {
+ // Empty constructor
}
@Override
public Map<TConsensusGroupId, TRegionReplicaSet> getLatestRegionRouteMap(
- List<TRegionReplicaSet> replicaSets) {
- Map<TConsensusGroupId, TRegionReplicaSet> result = new ConcurrentHashMap<>();
+ List<TRegionReplicaSet> replicaSets,
+ Map<TConsensusGroupId, Integer> regionLeaderMap,
+ Map<Integer, Long> dataNodeLoadScoreMap) {
+
+ Map<TConsensusGroupId, TRegionReplicaSet> regionPriorityMap = new ConcurrentHashMap<>();
replicaSets.forEach(
replicaSet -> {
- int leaderId = leaderMap.getOrDefault(replicaSet.getRegionId(), -1);
+ int leaderId = regionLeaderMap.getOrDefault(replicaSet.getRegionId(), -1);
TRegionReplicaSet sortedReplicaSet = new TRegionReplicaSet();
sortedReplicaSet.setRegionId(replicaSet.getRegionId());
@@ -74,7 +71,7 @@ public class LeaderRouter implements IRouter {
// In this case we put a maximum loadScore into the sortList.
sortList.add(
new Pair<>(
- loadScoreMap.computeIfAbsent(
+ dataNodeLoadScoreMap.computeIfAbsent(
dataNodeLocation.getDataNodeId(), empty -> Long.MAX_VALUE),
dataNodeLocation));
});
@@ -85,9 +82,9 @@ public class LeaderRouter implements IRouter {
}
}
- result.put(sortedReplicaSet.getRegionId(), sortedReplicaSet);
+ regionPriorityMap.put(sortedReplicaSet.getRegionId(), sortedReplicaSet);
});
- return result;
+ return regionPriorityMap;
}
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LoadScoreGreedyRouter.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LoadScoreGreedyRouter.java
index 2a9daf3e75..5d5fda43b5 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LoadScoreGreedyRouter.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/LoadScoreGreedyRouter.java
@@ -32,18 +32,17 @@ import java.util.concurrent.ConcurrentHashMap;
/** The LoadScoreGreedyRouter always pick the Replica with the lowest loadScore */
public class LoadScoreGreedyRouter implements IRouter {
- // Map<DataNodeId, loadScore>
- private final Map<Integer, Long> loadScoreMap;
-
- /** The constructor is used to pass in the load information needed by the algorithm */
- public LoadScoreGreedyRouter(Map<Integer, Long> loadScoreMap) {
- this.loadScoreMap = loadScoreMap;
+ public LoadScoreGreedyRouter() {
+ // Empty constructor
}
@Override
public Map<TConsensusGroupId, TRegionReplicaSet> getLatestRegionRouteMap(
- List<TRegionReplicaSet> replicaSets) {
- Map<TConsensusGroupId, TRegionReplicaSet> result = new ConcurrentHashMap<>();
+ List<TRegionReplicaSet> replicaSets,
+ Map<TConsensusGroupId, Integer> regionLeaderMap,
+ Map<Integer, Long> dataNodeLoadScoreMap) {
+
+ Map<TConsensusGroupId, TRegionReplicaSet> regionPriorityMap = new ConcurrentHashMap<>();
replicaSets.forEach(
replicaSet -> {
@@ -61,7 +60,7 @@ public class LoadScoreGreedyRouter implements IRouter {
// In this case we put a maximum loadScore into the sortList.
sortList.add(
new Pair<>(
- loadScoreMap.computeIfAbsent(
+ dataNodeLoadScoreMap.computeIfAbsent(
dataNodeLocation.getDataNodeId(), empty -> Long.MAX_VALUE),
dataNodeLocation));
});
@@ -71,9 +70,9 @@ public class LoadScoreGreedyRouter implements IRouter {
sortedReplicaSet.addToDataNodeLocations(entry.getRight());
}
- result.put(sortedReplicaSet.getRegionId(), sortedReplicaSet);
+ regionPriorityMap.put(sortedReplicaSet.getRegionId(), sortedReplicaSet);
});
- return result;
+ return regionPriorityMap;
}
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/RegionRouteMap.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/RegionRouteMap.java
new file mode 100644
index 0000000000..906fd610ca
--- /dev/null
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/router/RegionRouteMap.java
@@ -0,0 +1,172 @@
+/*
+ * 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.confignode.manager.load.balancer.router;
+
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
+import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet;
+import org.apache.iotdb.commons.utils.ThriftCommonsSerDeUtils;
+import org.apache.iotdb.tsfile.utils.ReadWriteIOUtils;
+
+import org.apache.thrift.TException;
+import org.apache.thrift.protocol.TProtocol;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class RegionRouteMap {
+
+ // Map<RegionGroupId, LeaderDataNodeId>
+ private Map<TConsensusGroupId, Integer> regionLeaderMap;
+
+ // Map<RegionGroupId, TRegionReplicaSet>
+ // Indicate the routing priority of read/write requests for each RegionGroup.
+ // The replica with higher sorting result have higher priority.
+ // TODO: Might be split into readRouteMap and writeRouteMap in the future
+ private Map<TConsensusGroupId, TRegionReplicaSet> regionPriorityMap;
+
+ public RegionRouteMap() {
+ this.regionLeaderMap = new ConcurrentHashMap<>();
+ this.regionPriorityMap = new ConcurrentHashMap<>();
+ }
+
+ public int getLeader(TConsensusGroupId regionGroupId) {
+ return regionLeaderMap.getOrDefault(regionGroupId, -1);
+ }
+
+ public void setLeader(TConsensusGroupId regionGroupId, int leaderId) {
+ regionLeaderMap.put(regionGroupId, leaderId);
+ }
+
+ public Map<TConsensusGroupId, Integer> getRegionLeaderMap() {
+ return regionLeaderMap;
+ }
+
+ public void setRegionLeaderMap(Map<TConsensusGroupId, Integer> regionLeaderMap) {
+ this.regionLeaderMap = regionLeaderMap;
+ }
+
+ public Map<TConsensusGroupId, TRegionReplicaSet> getRegionPriorityMap() {
+ return regionPriorityMap;
+ }
+
+ public boolean isEmpty() {
+ return regionLeaderMap.isEmpty() && regionPriorityMap.isEmpty();
+ }
+
+ public void setRegionPriorityMap(Map<TConsensusGroupId, TRegionReplicaSet> regionPriorityMap) {
+ this.regionPriorityMap = regionPriorityMap;
+ }
+
+ public void serialize(OutputStream stream, TProtocol protocol) throws IOException {
+ try {
+ ReadWriteIOUtils.write(regionLeaderMap.size(), stream);
+ for (Map.Entry<TConsensusGroupId, Integer> leaderEntry : regionLeaderMap.entrySet()) {
+ leaderEntry.getKey().write(protocol);
+ ReadWriteIOUtils.write(leaderEntry.getValue(), stream);
+ }
+
+ ReadWriteIOUtils.write(regionPriorityMap.size(), stream);
+ for (Map.Entry<TConsensusGroupId, TRegionReplicaSet> priorityEntry :
+ regionPriorityMap.entrySet()) {
+ priorityEntry.getKey().write(protocol);
+ priorityEntry.getValue().write(protocol);
+ }
+ } catch (TException e) {
+ throw new IOException(e);
+ }
+ }
+
+ // Deserializer for consensus-write
+ public void deserialize(ByteBuffer buffer) {
+ this.regionLeaderMap = new ConcurrentHashMap<>();
+ int leaderEntryNum = buffer.getInt();
+ for (int i = 0; i < leaderEntryNum; i++) {
+ TConsensusGroupId regionGroupId =
+ ThriftCommonsSerDeUtils.deserializeTConsensusGroupId(buffer);
+ int leaderId = buffer.getInt();
+ regionLeaderMap.put(regionGroupId, leaderId);
+ }
+
+ this.regionPriorityMap = new ConcurrentHashMap<>();
+ int priorityEntryNum = buffer.getInt();
+ for (int i = 0; i < priorityEntryNum; i++) {
+ TConsensusGroupId regionGroupId =
+ ThriftCommonsSerDeUtils.deserializeTConsensusGroupId(buffer);
+ TRegionReplicaSet regionReplicaSet =
+ ThriftCommonsSerDeUtils.deserializeTRegionReplicaSet(buffer);
+ regionPriorityMap.put(regionGroupId, regionReplicaSet);
+ }
+ }
+
+ // Deserializer for snapshot
+ public void deserialize(InputStream stream, TProtocol protocol) throws IOException, TException {
+ this.regionLeaderMap = new ConcurrentHashMap<>();
+ int leaderEntryNum = ReadWriteIOUtils.readInt(stream);
+ for (int i = 0; i < leaderEntryNum; i++) {
+ TConsensusGroupId regionGroupId = new TConsensusGroupId();
+ regionGroupId.read(protocol);
+ int leaderId = ReadWriteIOUtils.readInt(stream);
+ regionLeaderMap.put(regionGroupId, leaderId);
+ }
+
+ this.regionPriorityMap = new ConcurrentHashMap<>();
+ int priorityEntryNum = ReadWriteIOUtils.readInt(stream);
+ for (int i = 0; i < priorityEntryNum; i++) {
+ TConsensusGroupId regionGroupId = new TConsensusGroupId();
+ regionGroupId.read(protocol);
+ TRegionReplicaSet regionReplicaSet = new TRegionReplicaSet();
+ regionReplicaSet.read(protocol);
+ regionPriorityMap.put(regionGroupId, regionReplicaSet);
+ }
+ }
+
+ public void clear() {
+ regionLeaderMap.clear();
+ regionPriorityMap.clear();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ RegionRouteMap that = (RegionRouteMap) o;
+ return regionLeaderMap.equals(that.regionLeaderMap)
+ && regionPriorityMap.equals(that.regionPriorityMap);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(regionLeaderMap, regionPriorityMap);
+ }
+
+ @Override
+ public String toString() {
+ return "RegionRouteMap{"
+ + "regionLeaderMap="
+ + regionLeaderMap
+ + ", regionPriorityMap="
+ + regionPriorityMap
+ + '}';
+ }
+}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/BaseNodeCache.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/BaseNodeCache.java
index f93f0c0e1f..8675dd1aab 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/BaseNodeCache.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/BaseNodeCache.java
@@ -62,12 +62,21 @@ public abstract class BaseNodeCache {
}
}
+ /** Invoking periodically to update Node's latest NodeStatistics */
+ public abstract void updateNodeStatistics();
+
/**
- * Invoking periodically to update Nodes' current load statistics
+ * Actively append a custom NodeHeartbeatSample to force a change in the NodeStatistics.
+ *
+ * <p>For example, this interface can be invoked in Node removing process to forcibly change the
+ * corresponding Node's status to Removing without waiting for heartbeat sampling
*
- * @return NodeStatistics if some fields of statistics changed, null otherwise
+ * @param newHeartbeatSample A custom NodeHeartbeatSample that will lead to needed NodeStatistics
*/
- public abstract NodeStatistics updateNodeStatistics();
+ public void forceUpdate(NodeHeartbeatSample newHeartbeatSample) {
+ cacheHeartbeatSample(newHeartbeatSample);
+ updateNodeStatistics();
+ }
/**
* TODO: The loadScore of each Node will be changed to Double
@@ -84,6 +93,7 @@ public abstract class BaseNodeCache {
return NodeStatus.parse(statistics.getStatus().getStatus());
}
+ /** @return The reason why lead to current NodeStatus */
public String getNodeStatusWithReason() {
if (statistics.getStatusReason() == null) {
return statistics.getStatus().getStatus();
@@ -92,7 +102,7 @@ public abstract class BaseNodeCache {
}
}
- public void setRemoving() {
- this.statistics.setRemoving();
+ public NodeStatistics getStatistics() {
+ return statistics;
}
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/ConfigNodeHeartbeatCache.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/ConfigNodeHeartbeatCache.java
index c06ee43a99..772adcc48b 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/ConfigNodeHeartbeatCache.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/ConfigNodeHeartbeatCache.java
@@ -24,7 +24,7 @@ import org.apache.iotdb.confignode.persistence.node.NodeStatistics;
public class ConfigNodeHeartbeatCache extends BaseNodeCache {
- private static final NodeStatistics CURRENT_NODE_STATISTICS =
+ public static final NodeStatistics CURRENT_NODE_STATISTICS =
new NodeStatistics(0, NodeStatus.Running, null);
private final TConfigNodeLocation configNodeLocation;
@@ -43,13 +43,10 @@ public class ConfigNodeHeartbeatCache extends BaseNodeCache {
}
@Override
- public NodeStatistics updateNodeStatistics() {
+ public void updateNodeStatistics() {
// Skip itself
if (configNodeLocation.getInternalEndPoint().equals(NodeManager.CURRENT_NODE)) {
- // For first time update
- return CURRENT_NODE_STATISTICS.equals(statistics)
- ? null
- : (statistics = CURRENT_NODE_STATISTICS);
+ return;
}
long lastSendTime = 0;
@@ -68,10 +65,15 @@ public class ConfigNodeHeartbeatCache extends BaseNodeCache {
status = NodeStatus.Running;
}
- // Update loadScore
+ /* Update loadScore */
+ // Only consider Running ConfigNode as available currently
+ // TODO: Construct load score module
long loadScore = NodeStatus.isNormalStatus(status) ? 0 : Long.MAX_VALUE;
NodeStatistics newStatistics = new NodeStatistics(loadScore, status, null);
- return newStatistics.equals(statistics) ? null : (statistics = newStatistics);
+ if (!statistics.equals(newStatistics)) {
+ // Update NodeStatistics if necessary
+ statistics = newStatistics;
+ }
}
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/DataNodeHeartbeatCache.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/DataNodeHeartbeatCache.java
index 788181e3ec..0a357f0b81 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/DataNodeHeartbeatCache.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/DataNodeHeartbeatCache.java
@@ -29,13 +29,8 @@ public class DataNodeHeartbeatCache extends BaseNodeCache {
super();
}
- /** Constructor that only used when ConfigNode-leader switched */
- public DataNodeHeartbeatCache(NodeStatistics nodeStatistics) {
- this.statistics = nodeStatistics;
- }
-
@Override
- public NodeStatistics updateNodeStatistics() {
+ public void updateNodeStatistics() {
NodeHeartbeatSample lastSample = null;
synchronized (slidingWindow) {
if (slidingWindow.size() > 0) {
@@ -56,9 +51,14 @@ public class DataNodeHeartbeatCache extends BaseNodeCache {
}
/* Update loadScore */
- long loadScore = NodeStatus.isNormalStatus(status) ? -lastSendTime : Long.MAX_VALUE;
+ // Only consider Running DataNode as available currently
+ // TODO: Construct load score module
+ long loadScore = NodeStatus.isNormalStatus(status) ? 0 : Long.MAX_VALUE;
NodeStatistics newStatistics = new NodeStatistics(loadScore, status, statusReason);
- return newStatistics.equals(statistics) ? null : (statistics = newStatistics);
+ if (!statistics.equals(newStatistics)) {
+ // Update NodeStatistics if necessary
+ statistics = newStatistics;
+ }
}
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/NodeManager.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/NodeManager.java
index 31fec948fd..cc31b66cc1 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/NodeManager.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/node/NodeManager.java
@@ -41,7 +41,6 @@ import org.apache.iotdb.confignode.client.async.AsyncDataNodeHeartbeatClientPool
import org.apache.iotdb.confignode.client.async.handlers.AsyncClientHandler;
import org.apache.iotdb.confignode.client.async.handlers.heartbeat.ConfigNodeHeartbeatHandler;
import org.apache.iotdb.confignode.client.async.handlers.heartbeat.DataNodeHeartbeatHandler;
-import org.apache.iotdb.confignode.client.sync.SyncDataNodeClientPool;
import org.apache.iotdb.confignode.conf.ConfigNodeConfig;
import org.apache.iotdb.confignode.conf.ConfigNodeDescriptor;
import org.apache.iotdb.confignode.consensus.request.read.GetDataNodeConfigurationPlan;
@@ -57,6 +56,7 @@ import org.apache.iotdb.confignode.manager.ClusterSchemaManager;
import org.apache.iotdb.confignode.manager.ConfigManager;
import org.apache.iotdb.confignode.manager.ConsensusManager;
import org.apache.iotdb.confignode.manager.IManager;
+import org.apache.iotdb.confignode.manager.load.LoadManager;
import org.apache.iotdb.confignode.manager.partition.PartitionManager;
import org.apache.iotdb.confignode.persistence.metric.NodeInfoMetrics;
import org.apache.iotdb.confignode.persistence.node.NodeInfo;
@@ -481,6 +481,10 @@ public class NodeManager {
return dataNodeInfoList;
}
+ public List<TConfigNodeLocation> getRegisteredConfigNodes() {
+ return nodeInfo.getRegisteredConfigNodes();
+ }
+
public List<TConfigNodeInfo> getRegisteredConfigNodeInfoList() {
List<TConfigNodeInfo> configNodeInfoList = new ArrayList<>();
List<TConfigNodeLocation> registeredConfigNodes = this.getRegisteredConfigNodes();
@@ -696,7 +700,8 @@ public class NodeManager {
nodeCacheMap.computeIfAbsent(
dataNodeInfo.getLocation().getDataNodeId(),
empty -> new DataNodeHeartbeatCache()),
- getPartitionManager().getRegionGroupCacheMap());
+ getPartitionManager().getRegionGroupCacheMap(),
+ getLoadManager().getRouteBalancer());
AsyncDataNodeHeartbeatClientPool.getInstance()
.getDataNodeHeartBeat(
dataNodeInfo.getLocation().getInternalEndPoint(), heartbeatReq, handler);
@@ -714,8 +719,6 @@ public class NodeManager {
for (TConfigNodeLocation configNodeLocation : registeredConfigNodes) {
if (configNodeLocation.getInternalEndPoint().equals(CURRENT_NODE)) {
// Skip itself
- nodeCacheMap.putIfAbsent(
- configNodeLocation.getConfigNodeId(), new ConfigNodeHeartbeatCache(configNodeLocation));
continue;
}
@@ -878,9 +881,9 @@ public class NodeManager {
}
/**
- * Get the DataNodeLocation of the DataNode which has the lowest load
+ * Get the DataNodeLocation of the DataNode which has the lowest loadScore
*
- * @return TDataNodeLocation
+ * @return TDataNodeLocation with the lowest loadScore
*/
public Optional<TDataNodeLocation> getLowestLoadDataNode() {
// TODO get real lowest load data node after scoring algorithm being implemented
@@ -895,40 +898,10 @@ public class NodeManager {
}
}
- /** Recover the nodeCacheMap when the ConfigNode-Leader is switched */
- public void recoverNodeCacheMap() {
- Map<Integer, NodeStatistics> nodeStatisticsMap = nodeInfo.getNodeStatisticsMap();
- nodeCacheMap.clear();
-
- getRegisteredConfigNodes()
- .forEach(
- configNodeLocation -> {
- int configNodeId = configNodeLocation.getConfigNodeId();
- nodeCacheMap.put(
- configNodeId,
- new ConfigNodeHeartbeatCache(
- configNodeLocation,
- nodeStatisticsMap.getOrDefault(
- configNodeId, NodeStatistics.generateDefaultNodeStatistics())));
- });
- getRegisteredDataNodes()
- .forEach(
- dataNodeConfiguration -> {
- int dataNodeId = dataNodeConfiguration.getLocation().getDataNodeId();
- nodeCacheMap.put(
- dataNodeId,
- new DataNodeHeartbeatCache(
- nodeStatisticsMap.getOrDefault(
- dataNodeId, NodeStatistics.generateDefaultNodeStatistics())));
- });
-
- LOGGER.info("Inherit NodeStatistics: {}", nodeStatisticsMap);
- }
-
/**
- * Get the DataNodeLocation of the lowest load DataNode in input
+ * Get the DataNodeLocation which has the lowest loadScore within input
*
- * @return TDataNodeLocation
+ * @return TDataNodeLocation with the lowest loadScore
*/
public TDataNodeLocation getLowestLoadDataNode(Set<Integer> nodes) {
AtomicInteger result = new AtomicInteger();
@@ -949,31 +922,79 @@ public class NodeManager {
return configManager.getNodeManager().getRegisteredDataNodeLocations().get(result.get());
}
- public boolean isNodeRemoving(int dataNodeId) {
- DataNodeHeartbeatCache cache =
- (DataNodeHeartbeatCache) configManager.getNodeManager().getNodeCacheMap().get(dataNodeId);
- if (cache != null) {
- return NodeStatus.Removing.equals(cache.getNodeStatus());
- }
- return false;
- }
-
- public void setNodeRemovingStatus(TDataNodeLocation dataNodeLocation) {
- SyncDataNodeClientPool.getInstance()
- .sendSyncRequestToDataNodeWithRetry(
- dataNodeLocation.getInternalEndPoint(),
- NodeStatus.Removing.getStatus(),
- DataNodeRequestType.SET_SYSTEM_STATUS);
- DataNodeHeartbeatCache cache =
- (DataNodeHeartbeatCache)
- configManager.getNodeManager().getNodeCacheMap().get(dataNodeLocation.getDataNodeId());
- if (cache != null) {
- cache.setRemoving();
- }
+ /** Recover the nodeCacheMap when the ConfigNode-Leader is switched */
+ public void recoverNodeCacheMap() {
+ Map<Integer, NodeStatistics> nodeStatisticsMap = nodeInfo.getNodeStatisticsMap();
+ nodeCacheMap.clear();
+ LOGGER.info("[InheritLoadStatistics] Start to inherit NodeStatistics...");
+
+ // Force update ConfigNode-leader
+ nodeCacheMap.put(
+ ConfigNodeDescriptor.getInstance().getConf().getConfigNodeId(),
+ new ConfigNodeHeartbeatCache(
+ new TConfigNodeLocation(
+ ConfigNodeDescriptor.getInstance().getConf().getConfigNodeId(),
+ CURRENT_NODE,
+ new TEndPoint(
+ ConfigNodeDescriptor.getInstance().getConf().getInternalAddress(),
+ ConfigNodeDescriptor.getInstance().getConf().getConsensusPort())),
+ ConfigNodeHeartbeatCache.CURRENT_NODE_STATISTICS));
+
+ // Inherit ConfigNodeStatistics
+ getRegisteredConfigNodes()
+ .forEach(
+ configNodeLocation -> {
+ int configNodeId = configNodeLocation.getConfigNodeId();
+ if (!configNodeLocation.getInternalEndPoint().equals(CURRENT_NODE)
+ && nodeStatisticsMap.containsKey(configNodeId)) {
+ nodeCacheMap.put(configNodeId, new ConfigNodeHeartbeatCache(configNodeLocation));
+ nodeCacheMap
+ .get(configNodeId)
+ .forceUpdate(
+ nodeStatisticsMap.get(configNodeId).convertToNodeHeartbeatSample());
+ LOGGER.info(
+ "[InheritLoadStatistics]\t {}={}",
+ "nodeId{" + configNodeId + "}",
+ nodeCacheMap.get(configNodeId).getStatistics());
+ }
+ });
+
+ // Inherit DataNodeStatistics
+ getRegisteredDataNodes()
+ .forEach(
+ dataNodeConfiguration -> {
+ int dataNodeId = dataNodeConfiguration.getLocation().getDataNodeId();
+ if (nodeStatisticsMap.containsKey(dataNodeId)) {
+ nodeCacheMap.put(dataNodeId, new DataNodeHeartbeatCache());
+ nodeCacheMap
+ .get(dataNodeId)
+ .forceUpdate(nodeStatisticsMap.get(dataNodeId).convertToNodeHeartbeatSample());
+ LOGGER.info(
+ "[InheritLoadStatistics]\t {}={}",
+ "nodeId{" + dataNodeId + "}",
+ nodeCacheMap.get(dataNodeId).getStatistics());
+ }
+ });
+
+ LOGGER.info("[InheritLoadStatistics] Inherit NodeStatistics finish");
}
- public List<TConfigNodeLocation> getRegisteredConfigNodes() {
- return nodeInfo.getRegisteredConfigNodes();
+ /**
+ * @param nodeId The specified Node's index
+ * @param isLatest Is the NodeStatistics latest
+ * @return NodeStatistics in NodeCache if the isLatest is set to True, NodeStatistics in NodeInfo
+ * otherwise
+ */
+ public NodeStatistics getNodeStatistics(int nodeId, boolean isLatest) {
+ if (isLatest) {
+ return nodeCacheMap.containsKey(nodeId)
+ ? nodeCacheMap.get(nodeId).getStatistics()
+ : NodeStatistics.generateDefaultNodeStatistics();
+ } else {
+ return nodeInfo.getNodeStatisticsMap().containsKey(nodeId)
+ ? nodeInfo.getNodeStatisticsMap().get(nodeId)
+ : NodeStatistics.generateDefaultNodeStatistics();
+ }
}
private ConsensusManager getConsensusManager() {
@@ -987,4 +1008,8 @@ public class NodeManager {
private PartitionManager getPartitionManager() {
return configManager.getPartitionManager();
}
+
+ private LoadManager getLoadManager() {
+ return configManager.getLoadManager();
+ }
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/PartitionManager.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/PartitionManager.java
index 1aaf517313..07b0b9db83 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/PartitionManager.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/PartitionManager.java
@@ -67,13 +67,13 @@ import org.apache.iotdb.confignode.manager.ConsensusManager;
import org.apache.iotdb.confignode.manager.IManager;
import org.apache.iotdb.confignode.manager.ProcedureManager;
import org.apache.iotdb.confignode.manager.load.LoadManager;
+import org.apache.iotdb.confignode.manager.load.balancer.router.RegionRouteMap;
import org.apache.iotdb.confignode.persistence.metric.PartitionInfoMetrics;
import org.apache.iotdb.confignode.persistence.partition.PartitionInfo;
import org.apache.iotdb.confignode.persistence.partition.maintainer.RegionCreateTask;
import org.apache.iotdb.confignode.persistence.partition.maintainer.RegionDeleteTask;
import org.apache.iotdb.confignode.persistence.partition.maintainer.RegionMaintainTask;
import org.apache.iotdb.confignode.persistence.partition.statistics.RegionGroupStatistics;
-import org.apache.iotdb.consensus.ConsensusFactory;
import org.apache.iotdb.consensus.common.DataSet;
import org.apache.iotdb.consensus.common.response.ConsensusReadResponse;
import org.apache.iotdb.mpp.rpc.thrift.TCreateDataRegionReq;
@@ -450,6 +450,16 @@ public class PartitionManager {
return partitionInfo.getAllReplicaSets();
}
+ /**
+ * Only leader use this interface.
+ *
+ * @param type The specified TConsensusGroupType
+ * @return Deep copy of all Regions' RegionReplicaSet with the specified TConsensusGroupType
+ */
+ public List<TRegionReplicaSet> getAllReplicaSets(TConsensusGroupType type) {
+ return partitionInfo.getAllReplicaSets(type);
+ }
+
/**
* Only leader use this interface.
*
@@ -555,7 +565,7 @@ public class PartitionManager {
// Get static result
RegionInfoListResp regionInfoListResp =
(RegionInfoListResp) getConsensusManager().read(req).getDataset();
- Map<TConsensusGroupId, Integer> allLeadership = getAllLeadership();
+ Map<TConsensusGroupId, Integer> allLeadership = getLoadManager().getLatestRegionLeaderMap();
// Get cached result
regionInfoListResp
@@ -734,55 +744,6 @@ public class PartitionManager {
regionGroupCacheMap.remove(consensusGroupId);
}
- /**
- * Get the leadership of each RegionGroup.
- *
- * @return Map<RegionGroupId, DataNodeId where the leader located>
- * <p>Some RegionGroups that supposed to be occurred in the result map might be nonexistent
- * and some leaderId might be -1(leader unknown yet) due to heartbeat latency
- */
- public Map<TConsensusGroupId, Integer> getAllLeadership() {
-
- // TODO: Will be optimized by IOTDB-4341
-
- Map<TConsensusGroupId, Integer> result = new ConcurrentHashMap<>();
- if (ConfigNodeDescriptor.getInstance()
- .getConf()
- .getDataRegionConsensusProtocolClass()
- .equals(ConsensusFactory.MultiLeaderConsensus)) {
- regionGroupCacheMap.forEach(
- (consensusGroupId, regionGroupCache) -> {
- if (consensusGroupId.getType().equals(TConsensusGroupType.SchemaRegion)) {
- int leaderDataNodeId = regionGroupCache.getStatistics().getLeaderDataNodeId();
- if (configManager.getNodeManager().isNodeRemoving(leaderDataNodeId)) {
- result.put(consensusGroupId, -1);
- } else {
- result.put(consensusGroupId, leaderDataNodeId);
- }
- }
- });
- getLoadManager()
- .getRouteBalancer()
- .getRouteMap()
- .forEach(
- (consensusGroupId, regionReplicaSet) ->
- result.put(
- consensusGroupId,
- regionReplicaSet.getDataNodeLocations().get(0).getDataNodeId()));
- } else {
- regionGroupCacheMap.forEach(
- (consensusGroupId, regionGroupCache) -> {
- int leaderDataNodeId = regionGroupCache.getStatistics().getLeaderDataNodeId();
- if (configManager.getNodeManager().isNodeRemoving(leaderDataNodeId)) {
- result.put(consensusGroupId, -1);
- } else {
- result.put(consensusGroupId, leaderDataNodeId);
- }
- });
- }
- return result;
- }
-
/**
* Filter the RegionGroups in the specified StorageGroup through the RegionGroupStatus
*
@@ -834,35 +795,55 @@ public class PartitionManager {
: RegionGroupStatus.Disabled;
}
- public void cacheHeartbeatSample(
- int belongedDataNodeId,
- TConsensusGroupId regionGroupId,
- RegionHeartbeatSample regionHeartbeatSample) {
- regionGroupCacheMap
- .computeIfAbsent(regionGroupId, empty -> new RegionGroupCache(regionGroupId))
- .cacheHeartbeatSample(belongedDataNodeId, regionHeartbeatSample);
- regionGroupCacheMap.get(regionGroupId).updateRegionGroupStatistics();
- }
-
/** Recover the regionGroupCacheMap when the ConfigNode-Leader is switched */
public void recoverRegionGroupCacheMap() {
Map<TConsensusGroupId, RegionGroupStatistics> regionGroupStatisticsMap =
partitionInfo.getRegionGroupStatisticsMap();
regionGroupCacheMap.clear();
+ LOGGER.info("[InheritLoadStatistics] Start to inherit RegionGroupStatistics...");
+
getAllReplicaSets()
.forEach(
regionReplicaSet -> {
TConsensusGroupId groupId = regionReplicaSet.getRegionId();
- regionGroupCacheMap.put(
- groupId,
- new RegionGroupCache(
- groupId,
- regionGroupStatisticsMap.getOrDefault(
- groupId, RegionGroupStatistics.generateDefaultRegionGroupStatistics())));
+ if (regionGroupStatisticsMap.containsKey(groupId)) {
+ regionGroupCacheMap.put(groupId, new RegionGroupCache(groupId));
+ regionGroupCacheMap
+ .get(groupId)
+ .forceUpdate(
+ regionGroupStatisticsMap.get(groupId).convertToRegionHeartbeatSampleMap());
+ LOGGER.info(
+ "[InheritLoadStatistics]\t {}={}",
+ groupId,
+ regionGroupCacheMap.get(groupId).getStatistics());
+ }
});
- LOGGER.info("Inherit RegionGroupStatistics: {}", regionGroupStatisticsMap);
+ LOGGER.info("[InheritLoadStatistics] Inherit RegionGroupStatistics finish");
+ }
+
+ /**
+ * @param regionGroupId The specified RegionGroup's index
+ * @param isLatest Is the RegionGroupStatistics latest
+ * @return RegionGroupStatistics in RegionGroupCache if the isLatest is set to True,
+ * RegionGroupStatistics in PartitionInfo otherwise
+ */
+ public RegionGroupStatistics getRegionGroupStatistics(
+ TConsensusGroupId regionGroupId, boolean isLatest) {
+ if (isLatest) {
+ return regionGroupCacheMap.containsKey(regionGroupId)
+ ? regionGroupCacheMap.get(regionGroupId).getStatistics()
+ : RegionGroupStatistics.generateDefaultRegionGroupStatistics();
+ } else {
+ return partitionInfo.getRegionGroupStatisticsMap().containsKey(regionGroupId)
+ ? partitionInfo.getRegionGroupStatisticsMap().get(regionGroupId)
+ : RegionGroupStatistics.generateDefaultRegionGroupStatistics();
+ }
+ }
+
+ public RegionRouteMap getRegionRouteMap() {
+ return partitionInfo.getRegionRouteMap();
}
public ScheduledExecutorService getRegionMaintainer() {
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionCache.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionCache.java
index 5ea6826b76..e4e3a2a3b2 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionCache.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionCache.java
@@ -65,7 +65,7 @@ public class RegionCache {
status = lastSample.getStatus();
}
- return new RegionStatistics(lastSample.getSendTimestamp(), lastSample.isLeader(), status);
+ return new RegionStatistics(status);
}
private RegionHeartbeatSample getLastSample() {
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionGroupCache.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionGroupCache.java
index 0e13cd78bc..56648d4979 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionGroupCache.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionGroupCache.java
@@ -19,16 +19,9 @@
package org.apache.iotdb.confignode.manager.partition;
import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
-import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
import org.apache.iotdb.commons.cluster.RegionStatus;
-import org.apache.iotdb.confignode.conf.ConfigNodeConfig;
-import org.apache.iotdb.confignode.conf.ConfigNodeDescriptor;
import org.apache.iotdb.confignode.persistence.partition.statistics.RegionGroupStatistics;
import org.apache.iotdb.confignode.persistence.partition.statistics.RegionStatistics;
-import org.apache.iotdb.consensus.ConsensusFactory;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
@@ -36,12 +29,6 @@ import java.util.concurrent.ConcurrentHashMap;
public class RegionGroupCache {
- private static final Logger LOGGER = LoggerFactory.getLogger(RegionGroupCache.class);
-
- private static final ConfigNodeConfig CONF = ConfigNodeDescriptor.getInstance().getConf();
- private static final String DATA_REGION_CONSENSUS_PROTOCOL_CLASS =
- CONF.getDataRegionConsensusProtocolClass();
-
private final TConsensusGroupId consensusGroupId;
// Map<DataNodeId(where a RegionReplica resides), RegionCache>
@@ -57,14 +44,6 @@ public class RegionGroupCache {
this.statistics = RegionGroupStatistics.generateDefaultRegionGroupStatistics();
}
- public RegionGroupCache(
- TConsensusGroupId consensusGroupId, RegionGroupStatistics regionGroupStatistics) {
- this.consensusGroupId = consensusGroupId;
- this.regionCacheMap = new ConcurrentHashMap<>();
-
- this.statistics = regionGroupStatistics;
- }
-
public void cacheHeartbeatSample(int dataNodeId, RegionHeartbeatSample newHeartbeatSample) {
regionCacheMap
.computeIfAbsent(dataNodeId, empty -> new RegionCache())
@@ -77,42 +56,24 @@ public class RegionGroupCache {
* <p>1. RegionGroupStatus
*
* <p>2. RegionStatus
- *
- * <p>2. LeaderDataNodeId
- *
- * @return RegionGroupStatistics if some fields of statistics changed, null otherwise
*/
- public RegionGroupStatistics updateRegionGroupStatistics() {
- long updateVersion = Long.MIN_VALUE;
- int leaderDataNodeId = -1;
+ public void updateRegionGroupStatistics() {
Map<Integer, RegionStatistics> regionStatisticsMap = new HashMap<>();
for (Map.Entry<Integer, RegionCache> cacheEntry : regionCacheMap.entrySet()) {
// Update RegionStatistics
RegionStatistics regionStatistics = cacheEntry.getValue().getRegionStatistics();
regionStatisticsMap.put(cacheEntry.getKey(), regionStatistics);
-
- // Update leaderDataNodeId
- if (regionStatistics.getVersionTimestamp() > updateVersion && regionStatistics.isLeader()) {
- updateVersion = regionStatistics.getVersionTimestamp();
- leaderDataNodeId = cacheEntry.getKey();
- }
- }
-
- // Keep leaderDataNodeId as the default value when
- // using the MultiLeader consensus protocol
- if (ConsensusFactory.MultiLeaderConsensus.equals(DATA_REGION_CONSENSUS_PROTOCOL_CLASS)
- && TConsensusGroupType.DataRegion.equals(consensusGroupId.getType())) {
- leaderDataNodeId = -1;
}
// Update RegionGroupStatus
RegionGroupStatus status = updateRegionGroupStatus(regionStatisticsMap);
RegionGroupStatistics newRegionGroupStatistics =
- new RegionGroupStatistics(leaderDataNodeId, status, regionStatisticsMap);
- return newRegionGroupStatistics.equals(statistics)
- ? null
- : (statistics = newRegionGroupStatistics);
+ new RegionGroupStatistics(status, regionStatisticsMap);
+ if (!statistics.equals(newRegionGroupStatistics)) {
+ // Update RegionGroupStatistics if necessary
+ statistics = newRegionGroupStatistics;
+ }
}
private RegionGroupStatus updateRegionGroupStatus(
@@ -142,10 +103,26 @@ public class RegionGroupCache {
}
}
+ /**
+ * Actively append custom NodeHeartbeatSamples to force a change in the RegionGroupStatistics.
+ *
+ * <p>For example, this interface can be invoked in RegionGroup creating process to forcibly
+ * activate the corresponding RegionGroup's status to Available without waiting for heartbeat
+ * sampling
+ *
+ * @param newHeartbeatSamples Custom RegionHeartbeatSamples that will lead to needed
+ * RegionGroupStatistics
+ */
+ public void forceUpdate(Map<Integer, RegionHeartbeatSample> newHeartbeatSamples) {
+ newHeartbeatSamples.forEach(this::cacheHeartbeatSample);
+ updateRegionGroupStatistics();
+ }
+
public void removeCacheIfExists(int dataNodeId) {
regionCacheMap.remove(dataNodeId);
}
+ /** @return The latest RegionGroupStatistics of the current RegionGroup */
public RegionGroupStatistics getStatistics() {
return statistics;
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionHeartbeatSample.java b/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionHeartbeatSample.java
index fa4e565a35..2ce3b21d3e 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionHeartbeatSample.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/manager/partition/RegionHeartbeatSample.java
@@ -25,18 +25,13 @@ public class RegionHeartbeatSample {
// Unit: ms
private final long sendTimestamp;
private final long receiveTimestamp;
-
- private final boolean isLeader;
private final RegionStatus status;
// TODO: Add load sample
- public RegionHeartbeatSample(
- long sendTimestamp, long receiveTimestamp, boolean isLeader, RegionStatus status) {
+ public RegionHeartbeatSample(long sendTimestamp, long receiveTimestamp, RegionStatus status) {
this.sendTimestamp = sendTimestamp;
this.receiveTimestamp = receiveTimestamp;
-
- this.isLeader = isLeader;
this.status = status;
}
@@ -48,10 +43,6 @@ public class RegionHeartbeatSample {
return receiveTimestamp;
}
- public boolean isLeader() {
- return isLeader;
- }
-
public RegionStatus getStatus() {
return status;
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/executor/ConfigPlanExecutor.java b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/executor/ConfigPlanExecutor.java
index d9df207d50..8bf5a7bb3b 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/executor/ConfigPlanExecutor.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/executor/ConfigPlanExecutor.java
@@ -344,7 +344,8 @@ public class ConfigPlanExecutor {
"[UpdateLoadStatistics] Update cluster load statistics, timestamp: {}",
System.currentTimeMillis());
nodeInfo.updateNodeStatistics((UpdateLoadStatisticsPlan) physicalPlan);
- return partitionInfo.updateRegionGroupStatistics((UpdateLoadStatisticsPlan) physicalPlan);
+ return partitionInfo.updateRegionGroupStatisticsAndRegionRouteMap(
+ (UpdateLoadStatisticsPlan) physicalPlan);
default:
throw new UnknownPhysicalPlanTypeException(physicalPlan.getType());
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/node/NodeInfo.java b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/node/NodeInfo.java
index 8f51f4f213..e0df35a038 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/node/NodeInfo.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/node/NodeInfo.java
@@ -379,15 +379,19 @@ public class NodeInfo implements SnapshotProcessor {
* @param updateLoadStatisticsPlan UpdateLoadStatisticsPlan
*/
public void updateNodeStatistics(UpdateLoadStatisticsPlan updateLoadStatisticsPlan) {
- nodeStatisticsMap.putAll(updateLoadStatisticsPlan.getNodeStatisticsMap());
-
- // Log current NodeStatistics
- LOGGER.info("[UpdateLoadStatistics] NodeStatisticsMap: ");
- for (Map.Entry<Integer, NodeStatistics> nodeCacheEntry : nodeStatisticsMap.entrySet()) {
- LOGGER.info(
- "[UpdateLoadStatistics]\t {}={}",
- "nodeId{" + nodeCacheEntry.getKey() + "}",
- nodeCacheEntry.getValue());
+ if (!updateLoadStatisticsPlan.getNodeStatisticsMap().isEmpty()) {
+ synchronized (nodeStatisticsMap) {
+ // Update nodeStatisticsMap
+ nodeStatisticsMap.putAll(updateLoadStatisticsPlan.getNodeStatisticsMap());
+ // Log current NodeStatistics
+ LOGGER.info("[UpdateLoadStatistics] NodeStatisticsMap: ");
+ for (Map.Entry<Integer, NodeStatistics> nodeCacheEntry : nodeStatisticsMap.entrySet()) {
+ LOGGER.info(
+ "[UpdateLoadStatistics]\t {}={}",
+ "nodeId{" + nodeCacheEntry.getKey() + "}",
+ nodeCacheEntry.getValue());
+ }
+ }
}
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/node/NodeStatistics.java b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/node/NodeStatistics.java
index 79b5fa14d3..eda6610a4f 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/node/NodeStatistics.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/node/NodeStatistics.java
@@ -19,6 +19,8 @@
package org.apache.iotdb.confignode.persistence.node;
import org.apache.iotdb.commons.cluster.NodeStatus;
+import org.apache.iotdb.confignode.manager.node.NodeHeartbeatSample;
+import org.apache.iotdb.mpp.rpc.thrift.THeartbeatResp;
import org.apache.iotdb.tsfile.utils.ReadWriteIOUtils;
import java.io.IOException;
@@ -60,11 +62,6 @@ public class NodeStatistics {
return statusReason;
}
- public void setRemoving() {
- this.statusReason = null;
- this.status = NodeStatus.Removing;
- }
-
public void serialize(OutputStream stream) throws IOException {
ReadWriteIOUtils.write(loadScore, stream);
ReadWriteIOUtils.write(status.getStatus(), stream);
@@ -87,6 +84,7 @@ public class NodeStatistics {
}
}
+ // Deserializer for snapshot
public void deserialize(InputStream inputStream) throws IOException {
loadScore = ReadWriteIOUtils.readLong(inputStream);
status = NodeStatus.parse(ReadWriteIOUtils.readString(inputStream));
@@ -101,17 +99,21 @@ public class NodeStatistics {
return new NodeStatistics(Long.MAX_VALUE, NodeStatus.Unknown, null);
}
+ public NodeHeartbeatSample convertToNodeHeartbeatSample() {
+ long currentTime = System.currentTimeMillis();
+ return new NodeHeartbeatSample(
+ new THeartbeatResp(currentTime, status.getStatus()).setStatusReason(statusReason),
+ currentTime);
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
NodeStatistics that = (NodeStatistics) o;
- return status == that.status
- && Objects.equals(statusReason, that.statusReason)
- // In order to prevent the NodeStatistics from updating too fast.
- // Here we consider the loadScore equal when the difference is small.
- // TODO: optimize
- && Math.abs(loadScore - that.loadScore) < 60 * 1000;
+ return loadScore == that.loadScore
+ && status == that.status
+ && Objects.equals(statusReason, that.statusReason);
}
@Override
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/PartitionInfo.java b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/PartitionInfo.java
index e33d850670..8cab5f012a 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/PartitionInfo.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/PartitionInfo.java
@@ -55,6 +55,7 @@ import org.apache.iotdb.confignode.consensus.response.RegionInfoListResp;
import org.apache.iotdb.confignode.consensus.response.SchemaNodeManagementResp;
import org.apache.iotdb.confignode.consensus.response.SchemaPartitionResp;
import org.apache.iotdb.confignode.exception.StorageGroupNotExistsException;
+import org.apache.iotdb.confignode.manager.load.balancer.router.RegionRouteMap;
import org.apache.iotdb.confignode.persistence.metric.PartitionInfoMetrics;
import org.apache.iotdb.confignode.persistence.partition.maintainer.RegionMaintainTask;
import org.apache.iotdb.confignode.persistence.partition.statistics.RegionGroupStatistics;
@@ -102,24 +103,32 @@ public class PartitionInfo implements SnapshotProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(PartitionInfo.class);
+ /** For Cluster Partition */
// For allocating Regions
private final AtomicInteger nextRegionGroupId;
-
// Map<StorageGroupName, StorageGroupPartitionInfo>
private final Map<String, StorageGroupPartitionTable> storageGroupPartitionTables;
- private final Map<TConsensusGroupId, RegionGroupStatistics> regionGroupStatisticsMap;
-
+ /** For Region-Maintainer */
// For RegionReplicas' asynchronous management
private final List<RegionMaintainTask> regionMaintainTaskList;
+ /** For Load-Balancing */
+ // Map<RegionGroupId, RegionGroupStatistics>
+ private final Map<TConsensusGroupId, RegionGroupStatistics> regionGroupStatisticsMap;
+
+ private final RegionRouteMap regionRouteMap;
+
private final String snapshotFileName = "partition_info.bin";
public PartitionInfo() {
this.nextRegionGroupId = new AtomicInteger(-1);
this.storageGroupPartitionTables = new ConcurrentHashMap<>();
- this.regionGroupStatisticsMap = new ConcurrentHashMap<>();
+
this.regionMaintainTaskList = Collections.synchronizedList(new ArrayList<>());
+
+ this.regionGroupStatisticsMap = new ConcurrentHashMap<>();
+ this.regionRouteMap = new RegionRouteMap();
}
public int generateNextRegionGroupId() {
@@ -578,6 +587,22 @@ public class PartitionInfo implements SnapshotProcessor {
return result;
}
+ /**
+ * Only leader use this interface.
+ *
+ * @param type The specified TConsensusGroupType
+ * @return Deep copy of all Regions' RegionReplicaSet with the specified TConsensusGroupType
+ */
+ public List<TRegionReplicaSet> getAllReplicaSets(TConsensusGroupType type) {
+ List<TRegionReplicaSet> result = new ArrayList<>();
+ storageGroupPartitionTables
+ .values()
+ .forEach(
+ storageGroupPartitionTable ->
+ result.addAll(storageGroupPartitionTable.getAllReplicaSets(type)));
+ return result;
+ }
+
/**
* Only leader use this interface.
*
@@ -692,17 +717,54 @@ public class PartitionInfo implements SnapshotProcessor {
*
* @param updateLoadStatisticsPlan UpdateLoadStatisticsPlan
*/
- public TSStatus updateRegionGroupStatistics(UpdateLoadStatisticsPlan updateLoadStatisticsPlan) {
- regionGroupStatisticsMap.putAll(updateLoadStatisticsPlan.getRegionGroupStatisticsMap());
-
- // Log current RegionGroupStatistics
- LOGGER.info("[UpdateLoadStatistics] RegionGroupStatisticsMap: ");
- for (Map.Entry<TConsensusGroupId, RegionGroupStatistics> regionGroupStatisticsEntry :
- regionGroupStatisticsMap.entrySet()) {
- LOGGER.info(
- "[UpdateLoadStatistics]\t {}={}",
- regionGroupStatisticsEntry.getKey(),
- regionGroupStatisticsEntry.getValue());
+ public TSStatus updateRegionGroupStatisticsAndRegionRouteMap(
+ UpdateLoadStatisticsPlan updateLoadStatisticsPlan) {
+ if (!updateLoadStatisticsPlan.getRegionGroupStatisticsMap().isEmpty()) {
+ synchronized (regionGroupStatisticsMap) {
+ // Update regionGroupStatisticsMap
+ regionGroupStatisticsMap.putAll(updateLoadStatisticsPlan.getRegionGroupStatisticsMap());
+ // Log current RegionGroupStatistics
+ LOGGER.info("[UpdateLoadStatistics] RegionGroupStatisticsMap: ");
+ for (Map.Entry<TConsensusGroupId, RegionGroupStatistics> regionGroupStatisticsEntry :
+ regionGroupStatisticsMap.entrySet()) {
+ LOGGER.info(
+ "[UpdateLoadStatistics]\t {}={}",
+ regionGroupStatisticsEntry.getKey(),
+ regionGroupStatisticsEntry.getValue());
+ }
+ }
+ }
+
+ if (!updateLoadStatisticsPlan.getRegionRouteMap().isEmpty()) {
+ synchronized (regionRouteMap) {
+ // Update regionLeaderMap
+ regionRouteMap
+ .getRegionLeaderMap()
+ .putAll(updateLoadStatisticsPlan.getRegionRouteMap().getRegionLeaderMap());
+ // Log current regionLeaderMap
+ LOGGER.info("[UpdateLoadStatistics] RegionLeaderMap: ");
+ for (Map.Entry<TConsensusGroupId, Integer> regionLeaderEntry :
+ regionRouteMap.getRegionLeaderMap().entrySet()) {
+ LOGGER.info(
+ "[UpdateLoadStatistics]\t {}={}",
+ regionLeaderEntry.getKey(),
+ regionLeaderEntry.getValue());
+ }
+
+ // Update regionPriorityMap
+ regionRouteMap
+ .getRegionPriorityMap()
+ .putAll(updateLoadStatisticsPlan.getRegionRouteMap().getRegionPriorityMap());
+ // Log current regionPriorityMap
+ LOGGER.info("[UpdateLoadStatistics] RegionPriorityMap: ");
+ for (Map.Entry<TConsensusGroupId, TRegionReplicaSet> regionPriorityEntry :
+ regionRouteMap.getRegionPriorityMap().entrySet()) {
+ LOGGER.info(
+ "[UpdateLoadStatistics]\t {}={}",
+ regionPriorityEntry.getKey(),
+ regionPriorityEntry.getValue());
+ }
+ }
}
return RpcUtils.SUCCESS_STATUS;
@@ -713,6 +775,10 @@ public class PartitionInfo implements SnapshotProcessor {
return regionGroupStatisticsMap;
}
+ public RegionRouteMap getRegionRouteMap() {
+ return regionRouteMap;
+ }
+
@Override
public boolean processTakeSnapshot(File snapshotDir) throws TException, IOException {
@@ -757,6 +823,9 @@ public class PartitionInfo implements SnapshotProcessor {
regionGroupStatisticsEntry.getValue().serialize(fileOutputStream);
}
+ // serialize RegionRouteMap
+ regionRouteMap.serialize(fileOutputStream, protocol);
+
// write to file
fileOutputStream.flush();
fileOutputStream.close();
@@ -823,6 +892,9 @@ public class PartitionInfo implements SnapshotProcessor {
regionGroupStatistics.deserialize(fileInputStream);
regionGroupStatisticsMap.put(groupId, regionGroupStatistics);
}
+
+ // restore RegionRouteMap
+ regionRouteMap.deserialize(fileInputStream, protocol);
}
}
@@ -873,6 +945,7 @@ public class PartitionInfo implements SnapshotProcessor {
storageGroupPartitionTables.clear();
regionMaintainTaskList.clear();
regionGroupStatisticsMap.clear();
+ regionRouteMap.clear();
}
@Override
@@ -882,8 +955,9 @@ public class PartitionInfo implements SnapshotProcessor {
PartitionInfo that = (PartitionInfo) o;
return nextRegionGroupId.get() == that.nextRegionGroupId.get()
&& storageGroupPartitionTables.equals(that.storageGroupPartitionTables)
+ && regionMaintainTaskList.equals(that.regionMaintainTaskList)
&& regionGroupStatisticsMap.equals(that.regionGroupStatisticsMap)
- && regionMaintainTaskList.equals(that.regionMaintainTaskList);
+ && regionRouteMap.equals(that.regionRouteMap);
}
@Override
@@ -891,7 +965,8 @@ public class PartitionInfo implements SnapshotProcessor {
return Objects.hash(
nextRegionGroupId,
storageGroupPartitionTables,
+ regionMaintainTaskList,
regionGroupStatisticsMap,
- regionMaintainTaskList);
+ regionRouteMap);
}
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/StorageGroupPartitionTable.java b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/StorageGroupPartitionTable.java
index 70fc776447..5a1a1dfca2 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/StorageGroupPartitionTable.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/StorageGroupPartitionTable.java
@@ -113,6 +113,23 @@ public class StorageGroupPartitionTable {
return result;
}
+ /**
+ * Get all RegionGroups currently owned by this StorageGroup
+ *
+ * @param type The specified TConsensusGroupType
+ * @return Deep copy of all Regions' RegionReplicaSet with the specified TConsensusGroupType
+ */
+ public List<TRegionReplicaSet> getAllReplicaSets(TConsensusGroupType type) {
+ List<TRegionReplicaSet> result = new ArrayList<>();
+
+ for (RegionGroup regionGroup : regionGroupMap.values()) {
+ if (type.equals(regionGroup.getId().getType())) {
+ result.add(regionGroup.getReplicaSet());
+ }
+ }
+
+ return result;
+ }
/**
* Get all RegionGroups currently owned by this StorageGroup
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionGroupStatistics.java b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionGroupStatistics.java
index 3347f0e374..ef018f5d3e 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionGroupStatistics.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionGroupStatistics.java
@@ -20,6 +20,7 @@ package org.apache.iotdb.confignode.persistence.partition.statistics;
import org.apache.iotdb.commons.cluster.RegionStatus;
import org.apache.iotdb.confignode.manager.partition.RegionGroupStatus;
+import org.apache.iotdb.confignode.manager.partition.RegionHeartbeatSample;
import org.apache.iotdb.tsfile.utils.ReadWriteIOUtils;
import java.io.IOException;
@@ -29,12 +30,10 @@ import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
public class RegionGroupStatistics {
- // The DataNode where the leader resides
- private int leaderDataNodeId;
-
private RegionGroupStatus regionGroupStatus;
private final Map<Integer, RegionStatistics> regionStatisticsMap;
@@ -44,18 +43,11 @@ public class RegionGroupStatistics {
}
public RegionGroupStatistics(
- int leaderDataNodeId,
- RegionGroupStatus regionGroupStatus,
- Map<Integer, RegionStatistics> regionStatisticsMap) {
- this.leaderDataNodeId = leaderDataNodeId;
+ RegionGroupStatus regionGroupStatus, Map<Integer, RegionStatistics> regionStatisticsMap) {
this.regionGroupStatus = regionGroupStatus;
this.regionStatisticsMap = regionStatisticsMap;
}
- public int getLeaderDataNodeId() {
- return leaderDataNodeId;
- }
-
public RegionGroupStatus getRegionGroupStatus() {
return regionGroupStatus;
}
@@ -73,11 +65,18 @@ public class RegionGroupStatistics {
}
public static RegionGroupStatistics generateDefaultRegionGroupStatistics() {
- return new RegionGroupStatistics(-1, RegionGroupStatus.Disabled, new HashMap<>());
+ return new RegionGroupStatistics(RegionGroupStatus.Disabled, new HashMap<>());
+ }
+
+ public Map<Integer, RegionHeartbeatSample> convertToRegionHeartbeatSampleMap() {
+ Map<Integer, RegionHeartbeatSample> result = new ConcurrentHashMap<>();
+ regionStatisticsMap.forEach(
+ (dataNodeId, regionStatistics) ->
+ result.put(dataNodeId, regionStatistics.convertToRegionHeartbeatSample()));
+ return result;
}
public void serialize(OutputStream stream) throws IOException {
- ReadWriteIOUtils.write(leaderDataNodeId, stream);
ReadWriteIOUtils.write(regionGroupStatus.getStatus(), stream);
ReadWriteIOUtils.write(regionStatisticsMap.size(), stream);
@@ -90,7 +89,6 @@ public class RegionGroupStatistics {
// Deserializer for snapshot
public void deserialize(InputStream inputStream) throws IOException {
- this.leaderDataNodeId = ReadWriteIOUtils.readInt(inputStream);
this.regionGroupStatus = RegionGroupStatus.parse(ReadWriteIOUtils.readString(inputStream));
int regionNum = ReadWriteIOUtils.readInt(inputStream);
@@ -104,7 +102,6 @@ public class RegionGroupStatistics {
// Deserializer for consensus-write
public void deserialize(ByteBuffer buffer) {
- this.leaderDataNodeId = buffer.getInt();
this.regionGroupStatus = RegionGroupStatus.parse(ReadWriteIOUtils.readString(buffer));
int regionNum = buffer.getInt();
@@ -121,22 +118,19 @@ public class RegionGroupStatistics {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RegionGroupStatistics that = (RegionGroupStatistics) o;
- return leaderDataNodeId == that.leaderDataNodeId
- && regionGroupStatus == that.regionGroupStatus
+ return regionGroupStatus == that.regionGroupStatus
&& regionStatisticsMap.equals(that.regionStatisticsMap);
}
@Override
public int hashCode() {
- return Objects.hash(leaderDataNodeId, regionGroupStatus, regionStatisticsMap);
+ return Objects.hash(regionGroupStatus, regionStatisticsMap);
}
@Override
public String toString() {
return "RegionGroupStatistics{"
- + "leaderDataNodeId="
- + leaderDataNodeId
- + ", regionGroupStatus="
+ + "regionGroupStatus="
+ regionGroupStatus
+ ", regionStatisticsMap="
+ regionStatisticsMap
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionStatistics.java b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionStatistics.java
index e4ee0e51d0..2d77498df1 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionStatistics.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionStatistics.java
@@ -19,6 +19,7 @@
package org.apache.iotdb.confignode.persistence.partition.statistics;
import org.apache.iotdb.commons.cluster.RegionStatus;
+import org.apache.iotdb.confignode.manager.partition.RegionHeartbeatSample;
import org.apache.iotdb.tsfile.utils.ReadWriteIOUtils;
import java.io.IOException;
@@ -29,53 +30,36 @@ import java.util.Objects;
public class RegionStatistics {
- // For confirm the leadership.
- // The Region who claim itself as the leader and
- // has the maximum versionTimestamp is considered as the true leader
- private long versionTimestamp;
- private boolean isLeader;
-
private RegionStatus regionStatus;
public RegionStatistics() {
// Empty constructor
}
- public RegionStatistics(long versionTimestamp, boolean isLeader, RegionStatus regionStatus) {
- this.versionTimestamp = versionTimestamp;
- this.isLeader = isLeader;
+ public RegionStatistics(RegionStatus regionStatus) {
this.regionStatus = regionStatus;
}
- public long getVersionTimestamp() {
- return versionTimestamp;
- }
-
- public boolean isLeader() {
- return isLeader;
- }
-
public RegionStatus getRegionStatus() {
return regionStatus;
}
+ public RegionHeartbeatSample convertToRegionHeartbeatSample() {
+ long currentTime = System.currentTimeMillis();
+ return new RegionHeartbeatSample(currentTime, currentTime, regionStatus);
+ }
+
public void serialize(OutputStream stream) throws IOException {
- ReadWriteIOUtils.write(versionTimestamp, stream);
- ReadWriteIOUtils.write(isLeader, stream);
ReadWriteIOUtils.write(regionStatus.getStatus(), stream);
}
// Deserializer for snapshot
public void deserialize(InputStream inputStream) throws IOException {
- this.versionTimestamp = ReadWriteIOUtils.readLong(inputStream);
- this.isLeader = ReadWriteIOUtils.readBool(inputStream);
this.regionStatus = RegionStatus.parse(ReadWriteIOUtils.readString(inputStream));
}
// Deserializer for consensus-write
public void deserialize(ByteBuffer buffer) {
- this.versionTimestamp = buffer.getLong();
- this.isLeader = ReadWriteIOUtils.readBool(buffer);
this.regionStatus = RegionStatus.parse(ReadWriteIOUtils.readString(buffer));
}
@@ -84,28 +68,16 @@ public class RegionStatistics {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RegionStatistics that = (RegionStatistics) o;
- return isLeader == that.isLeader
- && regionStatus == that.regionStatus
- // In order to prevent the RegionStatistics from updating too fast.
- // Here we consider the versionTimestamp equal when the difference is small.
- // TODO: optimize
- && Math.abs(versionTimestamp - that.versionTimestamp) < 60 * 1000;
+ return regionStatus == that.regionStatus;
}
@Override
public int hashCode() {
- return Objects.hash(versionTimestamp, isLeader, regionStatus);
+ return Objects.hash(regionStatus);
}
@Override
public String toString() {
- return "RegionStatistics{"
- + "versionTimestamp="
- + versionTimestamp
- + ", isLeader="
- + isLeader
- + ", regionStatus="
- + regionStatus
- + '}';
+ return "RegionStatistics{" + "regionStatus=" + regionStatus + '}';
}
}
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/ConfigNodeProcedureEnv.java b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/ConfigNodeProcedureEnv.java
index c74fa4b680..363f227166 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/ConfigNodeProcedureEnv.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/ConfigNodeProcedureEnv.java
@@ -35,6 +35,7 @@ import org.apache.iotdb.confignode.client.async.AsyncDataNodeClientPool;
import org.apache.iotdb.confignode.client.async.handlers.AsyncClientHandler;
import org.apache.iotdb.confignode.client.sync.SyncConfigNodeClientPool;
import org.apache.iotdb.confignode.client.sync.SyncDataNodeClientPool;
+import org.apache.iotdb.confignode.conf.ConfigNodeDescriptor;
import org.apache.iotdb.confignode.consensus.request.write.confignode.RemoveConfigNodePlan;
import org.apache.iotdb.confignode.consensus.request.write.region.CreateRegionGroupsPlan;
import org.apache.iotdb.confignode.consensus.request.write.storagegroup.DeleteStorageGroupPlan;
@@ -46,19 +47,23 @@ import org.apache.iotdb.confignode.manager.ClusterSchemaManager;
import org.apache.iotdb.confignode.manager.ConfigManager;
import org.apache.iotdb.confignode.manager.ConsensusManager;
import org.apache.iotdb.confignode.manager.load.LoadManager;
+import org.apache.iotdb.confignode.manager.node.NodeHeartbeatSample;
import org.apache.iotdb.confignode.manager.node.NodeManager;
import org.apache.iotdb.confignode.manager.partition.PartitionManager;
+import org.apache.iotdb.confignode.manager.partition.RegionGroupCache;
import org.apache.iotdb.confignode.manager.partition.RegionHeartbeatSample;
import org.apache.iotdb.confignode.persistence.node.NodeInfo;
import org.apache.iotdb.confignode.procedure.exception.ProcedureException;
import org.apache.iotdb.confignode.procedure.scheduler.LockQueue;
import org.apache.iotdb.confignode.procedure.scheduler.ProcedureScheduler;
import org.apache.iotdb.confignode.rpc.thrift.TAddConsensusGroupReq;
+import org.apache.iotdb.consensus.ConsensusFactory;
import org.apache.iotdb.mpp.rpc.thrift.TActiveTriggerInstanceReq;
import org.apache.iotdb.mpp.rpc.thrift.TCreateDataRegionReq;
import org.apache.iotdb.mpp.rpc.thrift.TCreateSchemaRegionReq;
import org.apache.iotdb.mpp.rpc.thrift.TCreateTriggerInstanceReq;
import org.apache.iotdb.mpp.rpc.thrift.TDropTriggerInstanceReq;
+import org.apache.iotdb.mpp.rpc.thrift.THeartbeatResp;
import org.apache.iotdb.mpp.rpc.thrift.TInactiveTriggerInstanceReq;
import org.apache.iotdb.mpp.rpc.thrift.TInvalidateCacheReq;
import org.apache.iotdb.mpp.rpc.thrift.TUpdateConfigNodeGroupReq;
@@ -262,12 +267,14 @@ public class ConfigNodeProcedureEnv {
}
/**
- * Stop Config Node
+ * Stop ConfigNode and remove heartbeatCache
*
* @param tConfigNodeLocation config node location
* @throws ProcedureException if failed status
*/
public void stopConfigNode(TConfigNodeLocation tConfigNodeLocation) throws ProcedureException {
+ getNodeManager().removeNodeCache(tConfigNodeLocation.getConfigNodeId());
+
TSStatus tsStatus =
(TSStatus)
SyncConfigNodeClientPool.getInstance()
@@ -275,7 +282,7 @@ public class ConfigNodeProcedureEnv {
tConfigNodeLocation.getInternalEndPoint(),
tConfigNodeLocation,
ConfigNodeRequestType.STOP_CONFIG_NODE);
- getNodeManager().removeNodeCache(tConfigNodeLocation.getConfigNodeId());
+
if (tsStatus.getCode() != TSStatusCode.SUCCESS_STATUS.getStatusCode()) {
throw new ProcedureException(tsStatus.getMessage());
}
@@ -319,14 +326,28 @@ public class ConfigNodeProcedureEnv {
}
/**
- * Mark the given datanode as removing status, and broadcast the region map, to avoid read or
- * write request routing to this node.
+ * Mark the given datanode as removing status to avoid read or write request routing to this node.
*
* @param dataNodeLocation the datanode to be marked as removing status
*/
- public void markDataNodeAsRemovingAndBroadCast(TDataNodeLocation dataNodeLocation) {
- configManager.getNodeManager().setNodeRemovingStatus(dataNodeLocation);
- configManager.getLoadManager().broadcastLatestRegionRouteMap();
+ public void markDataNodeAsRemovingAndBroadcast(TDataNodeLocation dataNodeLocation) {
+ // Send request to update NodeStatus on the DataNode to be removed
+ SyncDataNodeClientPool.getInstance()
+ .sendSyncRequestToDataNodeWithRetry(
+ dataNodeLocation.getInternalEndPoint(),
+ NodeStatus.Removing.getStatus(),
+ DataNodeRequestType.SET_SYSTEM_STATUS);
+
+ // Force updating NodeStatus
+ long currentTime = System.currentTimeMillis();
+ NodeHeartbeatSample removingSample =
+ new NodeHeartbeatSample(
+ new THeartbeatResp(currentTime, NodeStatus.Removing.getStatus()).setStatusReason(null),
+ currentTime);
+ getNodeManager()
+ .getNodeCacheMap()
+ .get(dataNodeLocation.getDataNodeId())
+ .forceUpdate(removingSample);
}
/**
@@ -468,17 +489,35 @@ public class ConfigNodeProcedureEnv {
getLoadManager().broadcastLatestRegionRouteMap();
}
- public void buildRegionGroupCache(
+ public void activateRegionGroup(
TConsensusGroupId regionGroupId, Map<Integer, RegionStatus> regionStatusMap) {
+ // Force activating RegionGroup
long currentTime = System.currentTimeMillis();
+ Map<Integer, RegionHeartbeatSample> heartbeatSampleMap = new HashMap<>();
regionStatusMap.forEach(
(dataNodeId, regionStatus) ->
- getPartitionManager()
- .cacheHeartbeatSample(
- dataNodeId,
- regionGroupId,
- new RegionHeartbeatSample(currentTime, currentTime, false, regionStatus)));
- getPartitionManager().getRegionGroupCacheMap().get(regionGroupId).updateRegionGroupStatistics();
+ heartbeatSampleMap.put(
+ dataNodeId, new RegionHeartbeatSample(currentTime, currentTime, regionStatus)));
+ getPartitionManager()
+ .getRegionGroupCacheMap()
+ .computeIfAbsent(regionGroupId, empty -> new RegionGroupCache(regionGroupId))
+ .forceUpdate(heartbeatSampleMap);
+
+ // Select leader greedily for multi-leader consensus protocol
+ if (TConsensusGroupType.DataRegion.equals(regionGroupId.getType())
+ && ConsensusFactory.MultiLeaderConsensus.equals(
+ ConfigNodeDescriptor.getInstance().getConf().getDataRegionConsensusProtocolClass())) {
+ List<Integer> availableDataNodes = new ArrayList<>();
+ for (Map.Entry<Integer, RegionStatus> statusEntry : regionStatusMap.entrySet()) {
+ if (RegionStatus.isNormalStatus(statusEntry.getValue())) {
+ availableDataNodes.add(statusEntry.getKey());
+ }
+ }
+ getLoadManager().getRouteBalancer().greedySelectLeader(regionGroupId, availableDataNodes);
+ }
+
+ // Force update RegionRouteMap
+ getLoadManager().getRouteBalancer().updateRegionRouteMap();
}
public List<TRegionReplicaSet> getAllReplicaSets(String storageGroup) {
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/node/RemoveDataNodeProcedure.java b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/node/RemoveDataNodeProcedure.java
index d13b4abb60..9a99e825e4 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/node/RemoveDataNodeProcedure.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/node/RemoveDataNodeProcedure.java
@@ -77,7 +77,7 @@ public class RemoveDataNodeProcedure extends AbstractNodeProcedure<RemoveDataNod
}
case REMOVE_DATA_NODE_PREPARE:
// mark the datanode as removing status and broadcast region route map
- env.markDataNodeAsRemovingAndBroadCast(disableDataNodeLocation);
+ env.markDataNodeAsRemovingAndBroadcast(disableDataNodeLocation);
execDataNodeRegionIds =
env.getDataNodeRemoveHandler().getDataNodeRegionIds(disableDataNodeLocation);
LOG.info(
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DataNodeRegionTask.java b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DataNodeRegionTask.java
index c18beba40c..0c5bfccb2d 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DataNodeRegionTask.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DataNodeRegionTask.java
@@ -68,7 +68,7 @@ abstract class DataNodeRegionTask<T> {
executeOnAllReplicaset
? getAllReplicaDataNodeRegionGroupMap(targetSchemaRegionGroup)
: getLeaderDataNodeRegionGroupMap(
- env.getConfigManager().getPartitionManager().getAllLeadership(),
+ env.getConfigManager().getLoadManager().getLatestRegionLeaderMap(),
targetSchemaRegionGroup);
while (!dataNodeConsensusGroupIdMap.isEmpty()) {
Map<TDataNodeLocation, List<TConsensusGroupId>> currentFailedDataNodeMap =
@@ -124,7 +124,7 @@ abstract class DataNodeRegionTask<T> {
Map<TDataNodeLocation, List<TConsensusGroupId>> failedDataNodeConsensusGroupIdMap,
Set<TDataNodeLocation> allFailedDataNodeSet) {
Map<TConsensusGroupId, Integer> leaderMap =
- env.getConfigManager().getPartitionManager().getAllLeadership();
+ env.getConfigManager().getLoadManager().getLatestRegionLeaderMap();
Map<TDataNodeLocation, List<TConsensusGroupId>> availableDataNodeLocation = new HashMap<>();
for (List<TConsensusGroupId> consensusGroupIdList :
failedDataNodeConsensusGroupIdMap.values()) {
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeleteTimeSeriesProcedure.java b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeleteTimeSeriesProcedure.java
index 2300839e67..936595ddb8 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeleteTimeSeriesProcedure.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/schema/DeleteTimeSeriesProcedure.java
@@ -220,7 +220,7 @@ public class DeleteTimeSeriesProcedure
env.getConfigManager().getRelatedSchemaRegionGroup(patternTree);
Map<TDataNodeLocation, List<TConsensusGroupId>> dataNodeSchemaRegionGroupGroupIdMap =
getLeaderDataNodeRegionGroupMap(
- env.getConfigManager().getPartitionManager().getAllLeadership(),
+ env.getConfigManager().getLoadManager().getLatestRegionLeaderMap(),
relatedSchemaRegionGroup);
// fetch schema black list by dataNode
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/statemachine/CreateRegionGroupsProcedure.java b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/statemachine/CreateRegionGroupsProcedure.java
index 3f134665db..659ddc6b8b 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/statemachine/CreateRegionGroupsProcedure.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/statemachine/CreateRegionGroupsProcedure.java
@@ -148,9 +148,9 @@ public class CreateRegionGroupsProcedure
env.persistAndBroadcastRegionGroup(persistPlan);
env.getConfigManager().getConsensusManager().write(offerPlan);
- setNextState(CreateRegionGroupsState.BUILD_REGION_GROUP_CACHE);
+ setNextState(CreateRegionGroupsState.ACTIVATE_REGION_GROUPS);
break;
- case BUILD_REGION_GROUP_CACHE:
+ case ACTIVATE_REGION_GROUPS:
// Build RegionGroupCache immediately to make these successfully built RegionGroup available
createRegionGroupsPlan
.getRegionGroupMap()
@@ -168,12 +168,15 @@ public class CreateRegionGroupsProcedure
if (!failedRegionReplicaSets.containsKey(
regionReplicaSet.getRegionId())) {
- env.buildRegionGroupCache(regionReplicaSet.getRegionId(), statusMap);
+ // All RegionReplicas created successfully
+ // All RegionStatus are Running
+ env.activateRegionGroup(regionReplicaSet.getRegionId(), statusMap);
} else {
TRegionReplicaSet failedRegionReplicas =
failedRegionReplicaSets.get(regionReplicaSet.getRegionId());
if (failedRegionReplicas.getDataNodeLocationsSize()
<= (regionReplicaSet.getDataNodeLocationsSize() - 1) / 2) {
+ // Replace the RegionStatus of those RegionReplicas to Unknown
failedRegionReplicas
.getDataNodeLocations()
.forEach(
@@ -181,7 +184,7 @@ public class CreateRegionGroupsProcedure
statusMap.replace(
dataNodeLocation.getDataNodeId(),
RegionStatus.Unknown));
- env.buildRegionGroupCache(regionReplicaSet.getRegionId(), statusMap);
+ env.activateRegionGroup(regionReplicaSet.getRegionId(), statusMap);
}
}
}));
diff --git a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/CreateRegionGroupsState.java b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/CreateRegionGroupsState.java
index a332f0c2c4..6ade1d1c8a 100644
--- a/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/CreateRegionGroupsState.java
+++ b/confignode/src/main/java/org/apache/iotdb/confignode/procedure/state/CreateRegionGroupsState.java
@@ -19,14 +19,21 @@
package org.apache.iotdb.confignode.procedure.state;
public enum CreateRegionGroupsState {
+
// Create RegionGroups on remote DataNodes
CREATE_REGION_GROUPS,
+
// Shunt the RegionReplicas, including:
// 1. Persist successfully created RegionGroups' record
- // 2. Recreate RegionReplicas that failed to create, when there are more than half of
- // RegionReplicas created successfully on the same RegionGroup
+ // 2. Add recreate RegionReplicas task in RegionMaintainer
+ // for those RegionReplicas that failed to create, when
+ // there are more than half of RegionReplicas created successfully on the same RegionGroup
// 3. Delete redundant RegionReplicas in contrast to case 2.
SHUNT_REGION_REPLICAS,
- BUILD_REGION_GROUP_CACHE,
+
+ // Mark RegionGroupCache as available for those RegionGroups that created successfully.
+ // For DataRegionGroups that use multi-leader consensus protocol, select leader by the way
+ ACTIVATE_REGION_GROUPS,
+
CREATE_REGION_GROUPS_FINISH
}
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/consensus/request/ConfigPhysicalPlanSerDeTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/consensus/request/ConfigPhysicalPlanSerDeTest.java
index bbfa2541c4..fe7efb6fdf 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/consensus/request/ConfigPhysicalPlanSerDeTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/consensus/request/ConfigPhysicalPlanSerDeTest.java
@@ -105,6 +105,7 @@ import org.apache.iotdb.confignode.consensus.request.write.trigger.DeleteTrigger
import org.apache.iotdb.confignode.consensus.request.write.trigger.UpdateTriggerLocationPlan;
import org.apache.iotdb.confignode.consensus.request.write.trigger.UpdateTriggerStateInTablePlan;
import org.apache.iotdb.confignode.consensus.request.write.trigger.UpdateTriggersOnTransferNodesPlan;
+import org.apache.iotdb.confignode.manager.load.balancer.router.RegionRouteMap;
import org.apache.iotdb.confignode.manager.partition.RegionGroupStatus;
import org.apache.iotdb.confignode.persistence.node.NodeStatistics;
import org.apache.iotdb.confignode.persistence.partition.maintainer.RegionCreateTask;
@@ -1169,21 +1170,48 @@ public class ConfigPhysicalPlanSerDeTest {
public void UpdateLoadStatisticsPlanTest() throws IOException {
UpdateLoadStatisticsPlan updateLoadStatisticsPlan0 = new UpdateLoadStatisticsPlan();
+ // Set NodeStatistics
for (int i = 0; i < 3; i++) {
updateLoadStatisticsPlan0.putNodeStatistics(
i, new NodeStatistics(i, NodeStatus.Running, null));
}
+ // Set RegionGroupStatistics
for (int i = 0; i < 10; i++) {
Map<Integer, RegionStatistics> regionStatisticsMap = new HashMap<>();
for (int j = 0; j < 3; j++) {
- regionStatisticsMap.put(j, new RegionStatistics(j, false, RegionStatus.Unknown));
+ regionStatisticsMap.put(j, new RegionStatistics(RegionStatus.Unknown));
}
updateLoadStatisticsPlan0.putRegionGroupStatistics(
new TConsensusGroupId(DataRegion, i),
- new RegionGroupStatistics(-1, RegionGroupStatus.Available, regionStatisticsMap));
+ new RegionGroupStatistics(RegionGroupStatus.Available, regionStatisticsMap));
}
+ // Set RegionRouteMap
+ RegionRouteMap regionRouteMap = new RegionRouteMap();
+ Map<TConsensusGroupId, Integer> regionLeaderMap = new HashMap<>();
+ Map<TConsensusGroupId, TRegionReplicaSet> regionPriorityMap = new HashMap<>();
+ for (int i = 0; i < 10; i++) {
+ TConsensusGroupId regionGroupId = new TConsensusGroupId(SchemaRegion, i);
+ TRegionReplicaSet regionReplicaSet = new TRegionReplicaSet();
+ regionReplicaSet.setRegionId(regionGroupId);
+ for (int j = 0; j < 3; j++) {
+ regionReplicaSet.addToDataNodeLocations(
+ new TDataNodeLocation(
+ j,
+ new TEndPoint("0.0.0.0", 6667 + j),
+ new TEndPoint("0.0.0.0", 9003 + j),
+ new TEndPoint("0.0.0.0", 8777 + j),
+ new TEndPoint("0.0.0.0", 40010 + j),
+ new TEndPoint("0.0.0.0", 50010 + j)));
+ }
+ regionLeaderMap.put(regionGroupId, i % 3);
+ regionPriorityMap.put(regionGroupId, regionReplicaSet);
+ }
+ regionRouteMap.setRegionLeaderMap(regionLeaderMap);
+ regionRouteMap.setRegionPriorityMap(regionPriorityMap);
+ updateLoadStatisticsPlan0.setRegionRouteMap(regionRouteMap);
+
UpdateLoadStatisticsPlan updateLoadStatisticsPlan1 =
(UpdateLoadStatisticsPlan)
ConfigPhysicalPlan.Factory.create(updateLoadStatisticsPlan0.serializeToByteBuffer());
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LazyGreedyRouterTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LazyGreedyRouterTest.java
deleted file mode 100644
index 9cdc6dffb2..0000000000
--- a/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LazyGreedyRouterTest.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * 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.confignode.manager.load.balancer.router;
-
-import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
-import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
-import org.apache.iotdb.common.rpc.thrift.TDataNodeConfiguration;
-import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
-import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class LazyGreedyRouterTest {
-
- @Test
- public void testGenLatestRegionRouteMap() {
- LazyGreedyRouter lazyGreedyRouter = new LazyGreedyRouter();
-
- /* Prepare TRegionReplicaSets */
- List<TRegionReplicaSet> regionReplicaSetList = new ArrayList<>();
- for (int i = 0; i < 12; i++) {
- TRegionReplicaSet regionReplicaSet = new TRegionReplicaSet();
- regionReplicaSet.setRegionId(new TConsensusGroupId(TConsensusGroupType.DataRegion, i));
- for (int j = 1; j <= 3; j++) {
- regionReplicaSet.addToDataNodeLocations(new TDataNodeLocation().setDataNodeId(j));
- }
- regionReplicaSetList.add(regionReplicaSet);
- }
-
- /* Test1: The number of leaders in each DataNode should be approximately 4 */
- Map<TConsensusGroupId, TRegionReplicaSet> routeMap =
- lazyGreedyRouter.getLatestRegionRouteMap(regionReplicaSetList);
- Map<Integer, AtomicInteger> leaderCounter = new HashMap<>();
- routeMap
- .values()
- .forEach(
- regionReplicaSet ->
- leaderCounter
- .computeIfAbsent(
- regionReplicaSet.getDataNodeLocations().get(0).getDataNodeId(),
- empty -> new AtomicInteger(0))
- .getAndIncrement());
- Assert.assertEquals(3, leaderCounter.size());
- for (int i = 1; i <= 3; i++) {
- Assert.assertTrue(3 <= leaderCounter.get(i).get());
- Assert.assertTrue(leaderCounter.get(i).get() <= 5);
- }
-
- /* Unknown DataNodes */
- List<TDataNodeConfiguration> dataNodeConfigurations = new ArrayList<>();
- dataNodeConfigurations.add(
- new TDataNodeConfiguration().setLocation(new TDataNodeLocation().setDataNodeId(2)));
-
- /* Test2: The number of leaders in DataNode-1 and DataNode-3 should be approximately 6 */
- lazyGreedyRouter.updateDisabledDataNodes(dataNodeConfigurations);
- leaderCounter.clear();
- routeMap = lazyGreedyRouter.getLatestRegionRouteMap(regionReplicaSetList);
- routeMap
- .values()
- .forEach(
- regionReplicaSet ->
- leaderCounter
- .computeIfAbsent(
- regionReplicaSet.getDataNodeLocations().get(0).getDataNodeId(),
- empty -> new AtomicInteger(0))
- .getAndIncrement());
- Assert.assertEquals(2, leaderCounter.size());
- Assert.assertTrue(4 <= leaderCounter.get(1).get());
- Assert.assertTrue(leaderCounter.get(1).get() <= 8);
- Assert.assertTrue(4 <= leaderCounter.get(3).get());
- Assert.assertTrue(leaderCounter.get(3).get() <= 8);
- }
-
- @Test
- public void testGenLatestRegionRouteMapWithDifferentReplicaSize() {
- LazyGreedyRouter lazyGreedyRouter = new LazyGreedyRouter();
-
- /* Prepare TRegionReplicaSets */
- List<TRegionReplicaSet> regionReplicaSetList = new ArrayList<>();
- for (int i = 0; i < 12; i++) {
- TRegionReplicaSet regionReplicaSet = new TRegionReplicaSet();
- regionReplicaSet.setRegionId(new TConsensusGroupId(TConsensusGroupType.DataRegion, i));
- for (int j = 1; j <= 3; j++) {
- regionReplicaSet.addToDataNodeLocations(new TDataNodeLocation().setDataNodeId(j));
- }
- regionReplicaSetList.add(regionReplicaSet);
- }
- int dataNodeId = 0;
- for (int i = 12; i < 18; i++) {
- TRegionReplicaSet regionReplicaSet = new TRegionReplicaSet();
- regionReplicaSet.setRegionId(new TConsensusGroupId(TConsensusGroupType.DataRegion, i));
- for (int j = 0; j < 2; j++) {
- regionReplicaSet.addToDataNodeLocations(
- new TDataNodeLocation().setDataNodeId(dataNodeId + 1));
- dataNodeId = (dataNodeId + 1) % 3;
- }
- regionReplicaSetList.add(regionReplicaSet);
- }
-
- /* Test1: The number of leaders in each DataNode should be approximately 6 */
- Map<TConsensusGroupId, TRegionReplicaSet> routeMap =
- lazyGreedyRouter.getLatestRegionRouteMap(regionReplicaSetList);
- Map<Integer, AtomicInteger> leaderCounter = new HashMap<>();
- routeMap
- .values()
- .forEach(
- regionReplicaSet ->
- leaderCounter
- .computeIfAbsent(
- regionReplicaSet.getDataNodeLocations().get(0).getDataNodeId(),
- empty -> new AtomicInteger(0))
- .getAndIncrement());
- Assert.assertEquals(3, leaderCounter.size());
- for (int i = 1; i <= 3; i++) {
- Assert.assertTrue(4 <= leaderCounter.get(i).get());
- Assert.assertTrue(leaderCounter.get(i).get() <= 8);
- }
-
- /* Unknown DataNodes */
- List<TDataNodeConfiguration> dataNodeConfigurations = new ArrayList<>();
- dataNodeConfigurations.add(
- new TDataNodeConfiguration().setLocation(new TDataNodeLocation().setDataNodeId(2)));
-
- /* Test2: The number of leaders in DataNode-1 and DataNode-3 should be exactly 9 */
- lazyGreedyRouter.updateDisabledDataNodes(dataNodeConfigurations);
- leaderCounter.clear();
- routeMap = lazyGreedyRouter.getLatestRegionRouteMap(regionReplicaSetList);
- routeMap
- .values()
- .forEach(
- regionReplicaSet ->
- leaderCounter
- .computeIfAbsent(
- regionReplicaSet.getDataNodeLocations().get(0).getDataNodeId(),
- empty -> new AtomicInteger(0))
- .getAndIncrement());
- Assert.assertEquals(2, leaderCounter.size());
- Assert.assertTrue(7 <= leaderCounter.get(1).get());
- Assert.assertTrue(leaderCounter.get(1).get() <= 11);
- Assert.assertTrue(7 <= leaderCounter.get(3).get());
- Assert.assertTrue(leaderCounter.get(3).get() <= 11);
- }
-}
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LeaderRouterTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LeaderRouterTest.java
index 8148a43cac..63b13c8497 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LeaderRouterTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LeaderRouterTest.java
@@ -24,13 +24,9 @@ import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet;
import org.apache.iotdb.commons.cluster.NodeStatus;
-import org.apache.iotdb.commons.cluster.RegionStatus;
import org.apache.iotdb.confignode.manager.node.BaseNodeCache;
import org.apache.iotdb.confignode.manager.node.DataNodeHeartbeatCache;
import org.apache.iotdb.confignode.manager.node.NodeHeartbeatSample;
-import org.apache.iotdb.confignode.manager.partition.RegionGroupCache;
-import org.apache.iotdb.confignode.manager.partition.RegionHeartbeatSample;
-import org.apache.iotdb.confignode.persistence.partition.statistics.RegionGroupStatistics;
import org.apache.iotdb.mpp.rpc.thrift.THeartbeatResp;
import org.junit.Assert;
@@ -65,13 +61,14 @@ public class LeaderRouterTest {
Map<Integer, BaseNodeCache> nodeCacheMap = new HashMap<>();
for (int i = 0; i < 6; i++) {
nodeCacheMap.put(i, new DataNodeHeartbeatCache());
- // Simulate that the DataNode-i returned a heartbeat at (currentTime - i * 1000) ms
- nodeCacheMap
- .get(i)
- .cacheHeartbeatSample(
- new NodeHeartbeatSample(
- new THeartbeatResp(currentTimeMillis - i * 1000, NodeStatus.Running.getStatus()),
- currentTimeMillis - i * 1000));
+ if (i != 2 && i != 5) {
+ nodeCacheMap
+ .get(i)
+ .cacheHeartbeatSample(
+ new NodeHeartbeatSample(
+ new THeartbeatResp(currentTimeMillis, NodeStatus.Running.getStatus()),
+ currentTimeMillis));
+ }
}
nodeCacheMap.values().forEach(BaseNodeCache::updateNodeStatistics);
@@ -96,44 +93,14 @@ public class LeaderRouterTest {
dataNodeLocations.get(5), dataNodeLocations.get(4), dataNodeLocations.get(3)));
List<TRegionReplicaSet> regionReplicaSets = Arrays.asList(regionReplicaSet1, regionReplicaSet2);
- // Build regionGroupCacheMap
- Map<TConsensusGroupId, RegionGroupCache> regionGroupCacheMap = new HashMap<>();
- regionGroupCacheMap.put(groupId1, new RegionGroupCache(groupId1));
- regionGroupCacheMap.put(groupId2, new RegionGroupCache(groupId2));
-
- /* Simulate ratis consensus protocol(only one leader) */
- regionGroupCacheMap
- .get(groupId1)
- .cacheHeartbeatSample(0, new RegionHeartbeatSample(10, 10, false, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId1)
- .cacheHeartbeatSample(1, new RegionHeartbeatSample(11, 11, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId1)
- .cacheHeartbeatSample(2, new RegionHeartbeatSample(12, 12, false, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId2)
- .cacheHeartbeatSample(3, new RegionHeartbeatSample(13, 13, false, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId2)
- .cacheHeartbeatSample(4, new RegionHeartbeatSample(14, 14, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId2)
- .cacheHeartbeatSample(5, new RegionHeartbeatSample(15, 15, false, RegionStatus.Running));
-
- // Update RegionGroupStatistics and get leaderMap
+ // Build leaderMap
Map<TConsensusGroupId, Integer> leaderMap = new HashMap<>();
- regionGroupCacheMap.forEach(
- (groupId, regionGroupCache) -> {
- RegionGroupStatistics regionGroupStatistics =
- regionGroupCache.updateRegionGroupStatistics();
- Assert.assertNotNull(regionGroupStatistics);
- leaderMap.put(groupId, regionGroupStatistics.getLeaderDataNodeId());
- });
+ leaderMap.put(groupId1, 1);
+ leaderMap.put(groupId2, 4);
// Check result
Map<TConsensusGroupId, TRegionReplicaSet> result =
- new LeaderRouter(leaderMap, loadScoreMap).getLatestRegionRouteMap(regionReplicaSets);
+ new LeaderRouter().getLatestRegionRouteMap(regionReplicaSets, leaderMap, loadScoreMap);
TRegionReplicaSet result1 = result.get(groupId1);
// Leader first
Assert.assertEquals(dataNodeLocations.get(1), result1.getDataNodeLocations().get(0));
@@ -146,95 +113,5 @@ public class LeaderRouterTest {
// The others will be sorted by loadScore
Assert.assertEquals(dataNodeLocations.get(3), result2.getDataNodeLocations().get(1));
Assert.assertEquals(dataNodeLocations.get(5), result2.getDataNodeLocations().get(2));
-
- /* Simulate multiLeader consensus protocol(Each Region believes it is the leader) */
- regionGroupCacheMap
- .get(groupId1)
- .cacheHeartbeatSample(
- 0, new RegionHeartbeatSample(100000, 100000, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId1)
- .cacheHeartbeatSample(
- 1, new RegionHeartbeatSample(100010, 100010, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId1)
- .cacheHeartbeatSample(
- 2, new RegionHeartbeatSample(100020, 100020, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId2)
- .cacheHeartbeatSample(
- 3, new RegionHeartbeatSample(100030, 100030, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId2)
- .cacheHeartbeatSample(
- 4, new RegionHeartbeatSample(100040, 100040, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId2)
- .cacheHeartbeatSample(
- 5, new RegionHeartbeatSample(100050, 100050, true, RegionStatus.Running));
-
- // Get leaderMap
- leaderMap.clear();
- regionGroupCacheMap.forEach(
- (groupId, regionGroupCache) -> {
- RegionGroupStatistics regionGroupStatistics =
- regionGroupCache.updateRegionGroupStatistics();
- Assert.assertNotNull(regionGroupStatistics);
- leaderMap.put(groupId, regionGroupStatistics.getLeaderDataNodeId());
- });
-
- // Check result
- result = new LeaderRouter(leaderMap, loadScoreMap).getLatestRegionRouteMap(regionReplicaSets);
- result1 = result.get(groupId1);
- // The others will only be sorted by loadScore
- Assert.assertEquals(dataNodeLocations.get(2), result1.getDataNodeLocations().get(0));
- Assert.assertEquals(dataNodeLocations.get(0), result1.getDataNodeLocations().get(1));
- Assert.assertEquals(dataNodeLocations.get(1), result1.getDataNodeLocations().get(2));
- result2 = result.get(groupId2);
- // The others will only be sorted by loadScore
- Assert.assertEquals(dataNodeLocations.get(5), result2.getDataNodeLocations().get(0));
- Assert.assertEquals(dataNodeLocations.get(3), result2.getDataNodeLocations().get(1));
- Assert.assertEquals(dataNodeLocations.get(4), result2.getDataNodeLocations().get(2));
-
- /* Simulate multiLeader consensus protocol with a DataNode fails down */
- regionGroupCacheMap
- .get(groupId1)
- .cacheHeartbeatSample(
- 0, new RegionHeartbeatSample(200030, 200030, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId1)
- .cacheHeartbeatSample(
- 1, new RegionHeartbeatSample(200031, 200031, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId2)
- .cacheHeartbeatSample(
- 3, new RegionHeartbeatSample(200033, 200033, true, RegionStatus.Running));
- regionGroupCacheMap
- .get(groupId2)
- .cacheHeartbeatSample(
- 4, new RegionHeartbeatSample(200034, 200034, true, RegionStatus.Running));
-
- // Get leaderMap
- leaderMap.clear();
- regionGroupCacheMap.forEach(
- (groupId, regionGroupCache) -> {
- RegionGroupStatistics regionGroupStatistics =
- regionGroupCache.updateRegionGroupStatistics();
- Assert.assertNotNull(regionGroupStatistics);
- leaderMap.put(groupId, regionGroupStatistics.getLeaderDataNodeId());
- });
-
- // Check result
- result = new LeaderRouter(leaderMap, loadScoreMap).getLatestRegionRouteMap(regionReplicaSets);
- result1 = result.get(groupId1);
- // The others will only be sorted by loadScore
- Assert.assertEquals(dataNodeLocations.get(1), result1.getDataNodeLocations().get(0));
- Assert.assertEquals(dataNodeLocations.get(0), result1.getDataNodeLocations().get(1));
- Assert.assertEquals(dataNodeLocations.get(2), result1.getDataNodeLocations().get(2));
- result2 = result.get(groupId2);
- // The others will only be sorted by loadScore
- Assert.assertEquals(dataNodeLocations.get(4), result2.getDataNodeLocations().get(0));
- Assert.assertEquals(dataNodeLocations.get(3), result2.getDataNodeLocations().get(1));
- Assert.assertEquals(dataNodeLocations.get(5), result2.getDataNodeLocations().get(2));
}
}
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LoadScoreGreedyRouterTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LoadScoreGreedyRouterTest.java
index b4fa71fe37..aca4a83f95 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LoadScoreGreedyRouterTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/LoadScoreGreedyRouterTest.java
@@ -45,7 +45,7 @@ public class LoadScoreGreedyRouterTest {
public void testGenLoadScoreGreedyRoutingPolicy() {
/* Build TDataNodeLocations */
List<TDataNodeLocation> dataNodeLocations = new ArrayList<>();
- for (int i = 0; i < 6; i++) {
+ for (int i = 0; i < 4; i++) {
dataNodeLocations.add(
new TDataNodeLocation(
i,
@@ -59,15 +59,18 @@ public class LoadScoreGreedyRouterTest {
/* Build nodeCacheMap */
long currentTimeMillis = System.currentTimeMillis();
Map<Integer, BaseNodeCache> nodeCacheMap = new HashMap<>();
- for (int i = 0; i < 6; i++) {
+ NodeStatus[] statuses =
+ new NodeStatus[] {
+ NodeStatus.Running, NodeStatus.Unknown, NodeStatus.Running, NodeStatus.ReadOnly
+ };
+ for (int i = 0; i < 4; i++) {
nodeCacheMap.put(i, new DataNodeHeartbeatCache());
- // Simulate that the DataNode-i returned a heartbeat at (currentTime - i * 1000) ms
nodeCacheMap
.get(i)
.cacheHeartbeatSample(
new NodeHeartbeatSample(
- new THeartbeatResp(currentTimeMillis - i * 1000, NodeStatus.Running.getStatus()),
- currentTimeMillis - i * 1000));
+ new THeartbeatResp(currentTimeMillis, statuses[i].getStatus()),
+ currentTimeMillis));
}
nodeCacheMap.values().forEach(BaseNodeCache::updateNodeStatistics);
@@ -81,30 +84,27 @@ public class LoadScoreGreedyRouterTest {
TConsensusGroupId groupId1 = new TConsensusGroupId(TConsensusGroupType.SchemaRegion, 1);
TRegionReplicaSet regionReplicaSet1 =
new TRegionReplicaSet(
- groupId1,
- Arrays.asList(
- dataNodeLocations.get(2), dataNodeLocations.get(1), dataNodeLocations.get(0)));
+ groupId1, Arrays.asList(dataNodeLocations.get(1), dataNodeLocations.get(0)));
TConsensusGroupId groupId2 = new TConsensusGroupId(TConsensusGroupType.DataRegion, 2);
TRegionReplicaSet regionReplicaSet2 =
new TRegionReplicaSet(
- groupId2,
- Arrays.asList(
- dataNodeLocations.get(5), dataNodeLocations.get(4), dataNodeLocations.get(3)));
+ groupId2, Arrays.asList(dataNodeLocations.get(2), dataNodeLocations.get(3)));
/* Check result */
Map<TConsensusGroupId, TRegionReplicaSet> result =
- new LoadScoreGreedyRouter(loadScoreMap)
- .getLatestRegionRouteMap(Arrays.asList(regionReplicaSet1, regionReplicaSet2));
+ new LoadScoreGreedyRouter()
+ .getLatestRegionRouteMap(
+ Arrays.asList(regionReplicaSet1, regionReplicaSet2), new HashMap<>(), loadScoreMap);
Assert.assertEquals(2, result.size());
TRegionReplicaSet result1 = result.get(groupId1);
- for (int i = 0; i < 3; i++) {
+ for (int i = 0; i < 2; i++) {
Assert.assertEquals(dataNodeLocations.get(i), result1.getDataNodeLocations().get(i));
}
TRegionReplicaSet result2 = result.get(groupId2);
- for (int i = 3; i < 6; i++) {
- Assert.assertEquals(dataNodeLocations.get(i), result2.getDataNodeLocations().get(i - 3));
+ for (int i = 3; i < 4; i++) {
+ Assert.assertEquals(dataNodeLocations.get(i), result2.getDataNodeLocations().get(i - 2));
}
}
}
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/RegionRouteMapTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/RegionRouteMapTest.java
new file mode 100644
index 0000000000..9481802d48
--- /dev/null
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/router/RegionRouteMapTest.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.confignode.manager.load.balancer.router;
+
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
+import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.common.rpc.thrift.TRegionReplicaSet;
+import org.apache.iotdb.tsfile.utils.PublicBAOS;
+
+import org.apache.thrift.protocol.TBinaryProtocol;
+import org.apache.thrift.transport.TIOStreamTransport;
+import org.apache.thrift.transport.TTransport;
+import org.apache.thrift.transport.TTransportException;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.apache.iotdb.common.rpc.thrift.TConsensusGroupType.SchemaRegion;
+
+public class RegionRouteMapTest {
+
+ @Test
+ public void RegionRouteMapSerDeTest() throws IOException, TTransportException {
+ RegionRouteMap regionRouteMap0 = new RegionRouteMap();
+ Map<TConsensusGroupId, Integer> regionLeaderMap = new HashMap<>();
+ Map<TConsensusGroupId, TRegionReplicaSet> regionPriorityMap = new HashMap<>();
+ for (int i = 0; i < 10; i++) {
+ TConsensusGroupId regionGroupId = new TConsensusGroupId(SchemaRegion, i);
+ TRegionReplicaSet regionReplicaSet = new TRegionReplicaSet();
+ regionReplicaSet.setRegionId(regionGroupId);
+ for (int j = 0; j < 3; j++) {
+ regionReplicaSet.addToDataNodeLocations(
+ new TDataNodeLocation(
+ j,
+ new TEndPoint("0.0.0.0", 6667 + j),
+ new TEndPoint("0.0.0.0", 9003 + j),
+ new TEndPoint("0.0.0.0", 8777 + j),
+ new TEndPoint("0.0.0.0", 40010 + j),
+ new TEndPoint("0.0.0.0", 50010 + j)));
+ }
+ regionLeaderMap.put(regionGroupId, i % 3);
+ regionPriorityMap.put(regionGroupId, regionReplicaSet);
+ }
+ regionRouteMap0.setRegionLeaderMap(regionLeaderMap);
+ regionRouteMap0.setRegionPriorityMap(regionPriorityMap);
+
+ try (PublicBAOS byteArrayOutputStream = new PublicBAOS();
+ DataOutputStream outputStream = new DataOutputStream(byteArrayOutputStream)) {
+ TTransport transport = new TIOStreamTransport(outputStream);
+ TBinaryProtocol protocol = new TBinaryProtocol(transport);
+ regionRouteMap0.serialize(outputStream, protocol);
+
+ ByteBuffer buffer =
+ ByteBuffer.wrap(byteArrayOutputStream.getBuf(), 0, byteArrayOutputStream.size());
+ RegionRouteMap regionRouteMap1 = new RegionRouteMap();
+ regionRouteMap1.deserialize(buffer);
+ Assert.assertEquals(regionRouteMap0, regionRouteMap1);
+ }
+ }
+}
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/manager/node/NodeCacheTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/manager/node/NodeCacheTest.java
new file mode 100644
index 0000000000..fd2e255b74
--- /dev/null
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/manager/node/NodeCacheTest.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.confignode.manager.node;
+
+import org.apache.iotdb.commons.cluster.NodeStatus;
+import org.apache.iotdb.mpp.rpc.thrift.THeartbeatResp;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class NodeCacheTest {
+
+ @Test
+ public void forceUpdateTest() {
+ DataNodeHeartbeatCache dataNodeHeartbeatCache = new DataNodeHeartbeatCache();
+
+ // Test update to UnknownStatus
+ dataNodeHeartbeatCache.updateNodeStatistics();
+ Assert.assertEquals(NodeStatus.Unknown, dataNodeHeartbeatCache.getNodeStatus());
+ Assert.assertEquals(Long.MAX_VALUE, dataNodeHeartbeatCache.getLoadScore());
+
+ // Test force update to RunningStatus
+ long currentTime = System.currentTimeMillis() - 2000;
+ dataNodeHeartbeatCache.forceUpdate(
+ new NodeHeartbeatSample(
+ new THeartbeatResp(currentTime, NodeStatus.Running.getStatus()), currentTime));
+ Assert.assertEquals(NodeStatus.Running, dataNodeHeartbeatCache.getNodeStatus());
+ Assert.assertEquals(0, dataNodeHeartbeatCache.getLoadScore());
+
+ // Test force update to ReadOnlyStatus
+ currentTime += 2000;
+ dataNodeHeartbeatCache.forceUpdate(
+ new NodeHeartbeatSample(
+ new THeartbeatResp(currentTime, NodeStatus.ReadOnly.getStatus()), currentTime));
+ Assert.assertEquals(NodeStatus.ReadOnly, dataNodeHeartbeatCache.getNodeStatus());
+ Assert.assertEquals(Long.MAX_VALUE, dataNodeHeartbeatCache.getLoadScore());
+ }
+}
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/manager/partition/RegionGroupCacheTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/manager/partition/RegionGroupCacheTest.java
index 03dff073c9..a204ca84c3 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/manager/partition/RegionGroupCacheTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/manager/partition/RegionGroupCacheTest.java
@@ -27,34 +27,19 @@ import org.junit.Test;
public class RegionGroupCacheTest {
- @Test
- public void getLeaderDataNodeIdTest() {
- final int leaderId = 1;
- long currentTime = System.currentTimeMillis();
- RegionGroupCache regionGroupCache =
- new RegionGroupCache(new TConsensusGroupId(TConsensusGroupType.DataRegion, 0));
- for (int i = 0; i < 3; i++) {
- regionGroupCache.cacheHeartbeatSample(
- i,
- new RegionHeartbeatSample(currentTime, currentTime, i == leaderId, RegionStatus.Running));
- }
- Assert.assertNotNull(regionGroupCache.updateRegionGroupStatistics());
- Assert.assertEquals(leaderId, regionGroupCache.getStatistics().getLeaderDataNodeId());
- }
-
@Test
public void getRegionStatusTest() {
long currentTime = System.currentTimeMillis();
RegionGroupCache regionGroupCache =
new RegionGroupCache(new TConsensusGroupId(TConsensusGroupType.SchemaRegion, 1));
regionGroupCache.cacheHeartbeatSample(
- 0, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 0, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
regionGroupCache.cacheHeartbeatSample(
- 1, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Unknown));
+ 1, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Unknown));
regionGroupCache.cacheHeartbeatSample(
- 2, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Removing));
+ 2, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Removing));
regionGroupCache.cacheHeartbeatSample(
- 3, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.ReadOnly));
+ 3, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.ReadOnly));
regionGroupCache.updateRegionGroupStatistics();
Assert.assertEquals(RegionStatus.Running, regionGroupCache.getStatistics().getRegionStatus(0));
@@ -69,11 +54,11 @@ public class RegionGroupCacheTest {
RegionGroupCache runningRegionGroup =
new RegionGroupCache(new TConsensusGroupId(TConsensusGroupType.DataRegion, 0));
runningRegionGroup.cacheHeartbeatSample(
- 0, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 0, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
runningRegionGroup.cacheHeartbeatSample(
- 1, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 1, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
runningRegionGroup.cacheHeartbeatSample(
- 2, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 2, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
runningRegionGroup.updateRegionGroupStatistics();
Assert.assertEquals(
RegionGroupStatus.Running, runningRegionGroup.getStatistics().getRegionGroupStatus());
@@ -81,11 +66,11 @@ public class RegionGroupCacheTest {
RegionGroupCache availableRegionGroup =
new RegionGroupCache(new TConsensusGroupId(TConsensusGroupType.DataRegion, 1));
availableRegionGroup.cacheHeartbeatSample(
- 0, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 0, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
availableRegionGroup.cacheHeartbeatSample(
- 1, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Unknown));
+ 1, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Unknown));
availableRegionGroup.cacheHeartbeatSample(
- 2, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 2, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
availableRegionGroup.updateRegionGroupStatistics();
Assert.assertEquals(
RegionGroupStatus.Available, availableRegionGroup.getStatistics().getRegionGroupStatus());
@@ -93,11 +78,11 @@ public class RegionGroupCacheTest {
RegionGroupCache disabledRegionGroup0 =
new RegionGroupCache(new TConsensusGroupId(TConsensusGroupType.SchemaRegion, 2));
disabledRegionGroup0.cacheHeartbeatSample(
- 0, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 0, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
disabledRegionGroup0.cacheHeartbeatSample(
- 1, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.ReadOnly));
+ 1, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.ReadOnly));
disabledRegionGroup0.cacheHeartbeatSample(
- 2, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 2, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
disabledRegionGroup0.updateRegionGroupStatistics();
Assert.assertEquals(
RegionGroupStatus.Disabled, disabledRegionGroup0.getStatistics().getRegionGroupStatus());
@@ -105,11 +90,11 @@ public class RegionGroupCacheTest {
RegionGroupCache disabledRegionGroup1 =
new RegionGroupCache(new TConsensusGroupId(TConsensusGroupType.SchemaRegion, 3));
disabledRegionGroup1.cacheHeartbeatSample(
- 0, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 0, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
disabledRegionGroup1.cacheHeartbeatSample(
- 1, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Unknown));
+ 1, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Unknown));
disabledRegionGroup1.cacheHeartbeatSample(
- 2, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Unknown));
+ 2, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Unknown));
disabledRegionGroup1.updateRegionGroupStatistics();
Assert.assertEquals(
RegionGroupStatus.Disabled, disabledRegionGroup1.getStatistics().getRegionGroupStatus());
@@ -117,11 +102,11 @@ public class RegionGroupCacheTest {
RegionGroupCache disabledRegionGroup2 =
new RegionGroupCache(new TConsensusGroupId(TConsensusGroupType.DataRegion, 4));
disabledRegionGroup2.cacheHeartbeatSample(
- 0, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 0, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
disabledRegionGroup2.cacheHeartbeatSample(
- 1, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Running));
+ 1, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Running));
disabledRegionGroup2.cacheHeartbeatSample(
- 2, new RegionHeartbeatSample(currentTime, currentTime, false, RegionStatus.Removing));
+ 2, new RegionHeartbeatSample(currentTime, currentTime, RegionStatus.Removing));
disabledRegionGroup2.updateRegionGroupStatistics();
Assert.assertEquals(
RegionGroupStatus.Disabled, disabledRegionGroup2.getStatistics().getRegionGroupStatus());
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 d160872f23..3b52a9486d 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
@@ -38,6 +38,7 @@ import org.apache.iotdb.confignode.consensus.request.write.region.OfferRegionMai
import org.apache.iotdb.confignode.consensus.request.write.statistics.UpdateLoadStatisticsPlan;
import org.apache.iotdb.confignode.consensus.request.write.storagegroup.SetStorageGroupPlan;
import org.apache.iotdb.confignode.consensus.response.RegionInfoListResp;
+import org.apache.iotdb.confignode.manager.load.balancer.router.RegionRouteMap;
import org.apache.iotdb.confignode.manager.partition.RegionGroupStatus;
import org.apache.iotdb.confignode.persistence.partition.PartitionInfo;
import org.apache.iotdb.confignode.persistence.partition.maintainer.RegionCreateTask;
@@ -147,7 +148,8 @@ public class PartitionInfoTest {
partitionInfo.offerRegionMaintainTasks(generateOfferRegionMaintainTasksPlan());
- partitionInfo.updateRegionGroupStatistics(generateUpdateLoadStatisticsPlan());
+ partitionInfo.updateRegionGroupStatisticsAndRegionRouteMap(
+ generateUpdateLoadStatisticsPlan(schemaRegionReplicaSet, dataRegionReplicaSet));
partitionInfo.processTakeSnapshot(snapshotDir);
@@ -276,17 +278,36 @@ public class PartitionInfoTest {
return offerPlan;
}
- private UpdateLoadStatisticsPlan generateUpdateLoadStatisticsPlan() {
+ private UpdateLoadStatisticsPlan generateUpdateLoadStatisticsPlan(
+ TRegionReplicaSet schemaRegionReplicaSet, TRegionReplicaSet dataRegionReplicaSet) {
UpdateLoadStatisticsPlan updateLoadStatisticsPlan = new UpdateLoadStatisticsPlan();
+
+ // Build RegionGroupStatistics
for (int i = 0; i < 10; i++) {
Map<Integer, RegionStatistics> regionStatisticsMap = new HashMap<>();
for (int j = 0; j < 3; j++) {
- regionStatisticsMap.put(j, new RegionStatistics(j, false, RegionStatus.Unknown));
+ regionStatisticsMap.put(j, new RegionStatistics(RegionStatus.Unknown));
}
updateLoadStatisticsPlan.putRegionGroupStatistics(
new TConsensusGroupId(DataRegion, i),
- new RegionGroupStatistics(-1, RegionGroupStatus.Available, regionStatisticsMap));
+ new RegionGroupStatistics(RegionGroupStatus.Available, regionStatisticsMap));
}
+
+ // Build RegionRouteMap
+ RegionRouteMap regionRouteMap = new RegionRouteMap();
+
+ Map<TConsensusGroupId, Integer> regionLeaderMap = new HashMap<>();
+ regionLeaderMap.put(schemaRegionReplicaSet.getRegionId(), 0);
+ regionLeaderMap.put(dataRegionReplicaSet.getRegionId(), 1);
+ regionRouteMap.setRegionLeaderMap(regionLeaderMap);
+
+ Map<TConsensusGroupId, TRegionReplicaSet> regionPriorityMap = new HashMap<>();
+ regionPriorityMap.put(schemaRegionReplicaSet.getRegionId(), schemaRegionReplicaSet);
+ regionPriorityMap.put(dataRegionReplicaSet.getRegionId(), dataRegionReplicaSet);
+ regionRouteMap.setRegionPriorityMap(regionPriorityMap);
+
+ updateLoadStatisticsPlan.setRegionRouteMap(regionRouteMap);
+
return updateLoadStatisticsPlan;
}
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionGroupStatisticsTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionGroupStatisticsTest.java
index e3b830bb8d..3a53fbfcb4 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionGroupStatisticsTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionGroupStatisticsTest.java
@@ -37,11 +37,11 @@ public class RegionGroupStatisticsTest {
public void RegionGroupStatisticsSerDeTest() throws IOException {
Map<Integer, RegionStatistics> regionStatisticsMap = new HashMap<>();
for (int i = 0; i < 3; i++) {
- regionStatisticsMap.put(i, new RegionStatistics(i, false, RegionStatus.Unknown));
+ regionStatisticsMap.put(i, new RegionStatistics(RegionStatus.Unknown));
}
RegionGroupStatistics statistics0 =
- new RegionGroupStatistics(-1, RegionGroupStatus.Disabled, regionStatisticsMap);
+ new RegionGroupStatistics(RegionGroupStatus.Disabled, regionStatisticsMap);
try (PublicBAOS byteArrayOutputStream = new PublicBAOS();
DataOutputStream outputStream = new DataOutputStream(byteArrayOutputStream)) {
statistics0.serialize(outputStream);
diff --git a/confignode/src/test/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionStatisticsTest.java b/confignode/src/test/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionStatisticsTest.java
index 5fbd64ace8..67ca6959ec 100644
--- a/confignode/src/test/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionStatisticsTest.java
+++ b/confignode/src/test/java/org/apache/iotdb/confignode/persistence/partition/statistics/RegionStatisticsTest.java
@@ -32,7 +32,7 @@ public class RegionStatisticsTest {
@Test
public void RegionStatisticsSerDeTest1() throws IOException {
- RegionStatistics statistics0 = new RegionStatistics(20000522, true, RegionStatus.Running);
+ RegionStatistics statistics0 = new RegionStatistics(RegionStatus.Running);
try (PublicBAOS byteArrayOutputStream = new PublicBAOS();
DataOutputStream outputStream = new DataOutputStream(byteArrayOutputStream)) {
diff --git a/integration-test/src/main/java/org/apache/iotdb/it/env/AbstractEnv.java b/integration-test/src/main/java/org/apache/iotdb/it/env/AbstractEnv.java
index 550c2967e0..cb19819659 100644
--- a/integration-test/src/main/java/org/apache/iotdb/it/env/AbstractEnv.java
+++ b/integration-test/src/main/java/org/apache/iotdb/it/env/AbstractEnv.java
@@ -429,9 +429,8 @@ public abstract class AbstractEnv implements BaseEnv {
}
} catch (Exception e) {
logger.error(
- "Borrow ConfigNodeClient from ConfigNode: {} failed because: {}, retrying...",
- configNodeWrapper.getIpAndPortString(),
- e);
+ "Borrow ConfigNodeClient from ConfigNode: {} failed, retrying...",
+ configNodeWrapper.getIpAndPortString());
}
// Sleep 1s before next retry
diff --git a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeIT.java b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterAuthorizeIT.java
similarity index 50%
rename from integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeIT.java
rename to integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterAuthorizeIT.java
index d92b2a4a34..ecfef1f8c6 100644
--- a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeIT.java
+++ b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterAuthorizeIT.java
@@ -18,11 +18,6 @@
*/
package org.apache.iotdb.confignode.it;
-import org.apache.iotdb.common.rpc.thrift.TConfigNodeLocation;
-import org.apache.iotdb.common.rpc.thrift.TDataNodeConfiguration;
-import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
-import org.apache.iotdb.common.rpc.thrift.TEndPoint;
-import org.apache.iotdb.common.rpc.thrift.TNodeResource;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.auth.entity.PrivilegeType;
import org.apache.iotdb.commons.client.sync.SyncConfigNodeIServiceClient;
@@ -31,23 +26,8 @@ import org.apache.iotdb.confignode.rpc.thrift.IConfigNodeRPCService;
import org.apache.iotdb.confignode.rpc.thrift.TAuthorizerReq;
import org.apache.iotdb.confignode.rpc.thrift.TAuthorizerResp;
import org.apache.iotdb.confignode.rpc.thrift.TCheckUserPrivilegesReq;
-import org.apache.iotdb.confignode.rpc.thrift.TConfigNodeInfo;
-import org.apache.iotdb.confignode.rpc.thrift.TDataNodeConfigurationResp;
-import org.apache.iotdb.confignode.rpc.thrift.TDataNodeInfo;
-import org.apache.iotdb.confignode.rpc.thrift.TDataNodeRegisterReq;
-import org.apache.iotdb.confignode.rpc.thrift.TDataNodeRegisterResp;
-import org.apache.iotdb.confignode.rpc.thrift.TDataNodeRemoveReq;
-import org.apache.iotdb.confignode.rpc.thrift.TDataNodeRemoveResp;
-import org.apache.iotdb.confignode.rpc.thrift.TShowClusterResp;
-import org.apache.iotdb.confignode.rpc.thrift.TShowConfigNodesResp;
-import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodesResp;
-import org.apache.iotdb.consensus.ConsensusFactory;
import org.apache.iotdb.db.qp.logical.sys.AuthorOperator;
-import org.apache.iotdb.it.env.ConfigFactory;
-import org.apache.iotdb.it.env.ConfigNodeWrapper;
-import org.apache.iotdb.it.env.DataNodeWrapper;
import org.apache.iotdb.it.env.EnvFactory;
-import org.apache.iotdb.it.env.EnvUtils;
import org.apache.iotdb.it.framework.IoTDBTestRunner;
import org.apache.iotdb.itbase.category.ClusterIT;
import org.apache.iotdb.rpc.TSStatusCode;
@@ -62,344 +42,26 @@ import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
-import java.util.Map;
import java.util.Set;
-import static org.apache.iotdb.confignode.it.utils.ConfigNodeTestUtils.checkNodeConfig;
-import static org.apache.iotdb.confignode.it.utils.ConfigNodeTestUtils.getClusterNodeInfos;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(IoTDBTestRunner.class)
@Category({ClusterIT.class})
-public class IoTDBConfigNodeIT {
-
- protected static String originalConfigNodeConsensusProtocolClass;
- protected static String originalSchemaRegionConsensusProtocolClass;
- protected static String originalDataRegionConsensusProtocolClass;
- private final int retryNum = 30;
+public class IoTDBClusterAuthorizeIT {
@Before
public void setUp() throws Exception {
- originalConfigNodeConsensusProtocolClass =
- ConfigFactory.getConfig().getConfigNodeConsesusProtocolClass();
- originalSchemaRegionConsensusProtocolClass =
- ConfigFactory.getConfig().getSchemaRegionConsensusProtocolClass();
- originalDataRegionConsensusProtocolClass =
- ConfigFactory.getConfig().getDataRegionConsensusProtocolClass();
-
- ConfigFactory.getConfig().setConfigNodeConsesusProtocolClass(ConsensusFactory.RatisConsensus);
- ConfigFactory.getConfig()
- .setSchemaRegionConsensusProtocolClass(ConsensusFactory.RatisConsensus);
- ConfigFactory.getConfig().setDataRegionConsensusProtocolClass(ConsensusFactory.RatisConsensus);
-
- EnvFactory.getEnv().initBeforeClass();
+ // Init 1C0D environment
+ EnvFactory.getEnv().initClusterEnvironment(1, 0);
}
@After
public void tearDown() {
EnvFactory.getEnv().cleanAfterClass();
- ConfigFactory.getConfig()
- .setConfigNodeConsesusProtocolClass(originalConfigNodeConsensusProtocolClass);
- ConfigFactory.getConfig()
- .setSchemaRegionConsensusProtocolClass(originalSchemaRegionConsensusProtocolClass);
- ConfigFactory.getConfig()
- .setDataRegionConsensusProtocolClass(originalDataRegionConsensusProtocolClass);
- }
-
- @Test
- public void removeAndStopConfigNodeTest() {
- TShowClusterResp clusterNodes;
- TSStatus status;
-
- List<ConfigNodeWrapper> configNodeWrappers = EnvFactory.getEnv().getConfigNodeWrapperList();
- List<DataNodeWrapper> dataNodeWrappers = EnvFactory.getEnv().getDataNodeWrapperList();
-
- try (SyncConfigNodeIServiceClient client =
- (SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
- // add ConfigNode
- for (int i = 0; i < 2; i++) {
- ConfigNodeWrapper configNodeWrapper =
- new ConfigNodeWrapper(
- false,
- configNodeWrappers.get(0).getIpAndPortString(),
- "IoTDBConfigNodeIT",
- "removeAndStopConfigNodeTest",
- EnvUtils.searchAvailablePorts());
- configNodeWrapper.createDir();
- configNodeWrapper.changeConfig(ConfigFactory.getConfig().getConfignodeProperties());
- configNodeWrapper.start();
- configNodeWrappers.add(configNodeWrapper);
- }
- EnvFactory.getEnv().setConfigNodeWrapperList(configNodeWrappers);
- clusterNodes = getClusterNodeInfos(client, 3, 3);
- assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(), clusterNodes.getStatus().getCode());
- List<TConfigNodeLocation> configNodeLocationList = clusterNodes.getConfigNodeList();
- List<TDataNodeLocation> dataNodeLocationList = clusterNodes.getDataNodeList();
- checkNodeConfig(
- configNodeLocationList, dataNodeLocationList, configNodeWrappers, dataNodeWrappers);
-
- // test remove ConfigNode
- TConfigNodeLocation removedConfigNodeLocation = clusterNodes.getConfigNodeList().get(1);
- for (int i = 0; i < retryNum; i++) {
- Thread.sleep(1000);
- status = client.removeConfigNode(removedConfigNodeLocation);
- if (TSStatusCode.SUCCESS_STATUS.getStatusCode() == status.getCode()) {
- break;
- }
- }
-
- clusterNodes = getClusterNodeInfos(client, 2, 3);
- assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(), clusterNodes.getStatus().getCode());
- checkNodeConfig(
- clusterNodes.getConfigNodeList(),
- clusterNodes.getDataNodeList(),
- configNodeWrappers,
- dataNodeWrappers);
-
- List<TConfigNodeLocation> configNodeList = clusterNodes.getConfigNodeList();
- for (TConfigNodeLocation configNodeLocation : configNodeList) {
- assertNotEquals(removedConfigNodeLocation, configNodeLocation);
- }
-
- // test stop ConfigNode
- status = client.stopConfigNode(removedConfigNodeLocation);
- assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(), status.getCode());
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-
- @Test
- public void queryAndRemoveDataNodeTest() {
- TShowDataNodesResp showDataNodesResp = null;
- TDataNodeRegisterReq dataNodeRegisterReq;
- TDataNodeRegisterResp dataNodeRegisterResp;
- TDataNodeConfigurationResp dataNodeConfigurationResp;
- TDataNodeRemoveReq removeReq;
- TDataNodeRemoveResp removeResp;
-
- List<ConfigNodeWrapper> configNodeWrappers = EnvFactory.getEnv().getConfigNodeWrapperList();
- List<DataNodeWrapper> dataNodeWrappers = EnvFactory.getEnv().getDataNodeWrapperList();
- TDataNodeLocation dataNodeLocation = new TDataNodeLocation();
- TDataNodeConfiguration dataNodeConfiguration = new TDataNodeConfiguration();
- List<TDataNodeLocation> removeDataNodeLocationList = new ArrayList<>();
- List<TDataNodeInfo> dataNodeInfos;
-
- try (SyncConfigNodeIServiceClient client =
- (SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
- // add DataNode
- DataNodeWrapper dataNodeWrapper =
- new DataNodeWrapper(
- configNodeWrappers.get(0).getIpAndPortString(),
- "IoTDBConfigNodeIT",
- "dataNodeTest",
- EnvUtils.searchAvailablePorts());
- dataNodeWrapper.createDir();
- dataNodeWrapper.changeConfig(ConfigFactory.getConfig().getEngineProperties());
- dataNodeWrapper.start();
- dataNodeWrappers.add(dataNodeWrapper);
-
- EnvFactory.getEnv().setDataNodeWrapperList(dataNodeWrappers);
- for (int i = 0; i < retryNum; i++) {
- showDataNodesResp = client.showDataNodes();
- if (showDataNodesResp.getDataNodesInfoListSize() == 4) {
- break;
- }
- Thread.sleep(1000);
- }
- assertEquals(4, showDataNodesResp.getDataNodesInfoListSize());
-
- dataNodeInfos = showDataNodesResp.getDataNodesInfoList();
- dataNodeConfiguration.setLocation(dataNodeLocation);
- dataNodeConfiguration.setResource(new TNodeResource(8, 1024 * 1024));
- dataNodeRegisterReq = new TDataNodeRegisterReq(dataNodeConfiguration);
- TDataNodeInfo dataNodeInfo = dataNodeInfos.get(3);
-
- // test success re-register
- dataNodeLocation.setDataNodeId(dataNodeInfo.getDataNodeId());
- dataNodeLocation.setClientRpcEndPoint(
- new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort()));
- dataNodeLocation.setMPPDataExchangeEndPoint(
- new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort() + 1));
- dataNodeLocation.setInternalEndPoint(
- new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort() + 2));
- dataNodeLocation.setDataRegionConsensusEndPoint(
- new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort() + 3));
- dataNodeLocation.setSchemaRegionConsensusEndPoint(
- new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort() + 4));
-
- dataNodeRegisterResp = client.registerDataNode(dataNodeRegisterReq);
- assertEquals(
- TSStatusCode.DATANODE_ALREADY_REGISTERED.getStatusCode(),
- dataNodeRegisterResp.getStatus().getCode());
-
- // test query all DataNodeInfos
- dataNodeConfigurationResp = client.getDataNodeConfiguration(-1);
- Map<Integer, TDataNodeConfiguration> infoMap =
- dataNodeConfigurationResp.getDataNodeConfigurationMap();
- assertEquals(
- TSStatusCode.SUCCESS_STATUS.getStatusCode(),
- dataNodeConfigurationResp.getStatus().getCode());
- assertEquals(4, infoMap.size());
- List<Map.Entry<Integer, TDataNodeConfiguration>> infoList =
- new ArrayList<>(infoMap.entrySet());
- infoList.sort(Comparator.comparingInt(Map.Entry::getKey));
- int count = 0;
- for (DataNodeWrapper expectedDataNode : dataNodeWrappers) {
- for (int i = 0; i < 4; i++) {
- TDataNodeLocation dnLocation = infoList.get(i).getValue().getLocation();
- if (expectedDataNode.getInternalPort() == dnLocation.getInternalEndPoint().getPort()
- && expectedDataNode.getMppDataExchangePort()
- == dnLocation.getMPPDataExchangeEndPoint().getPort()
- && expectedDataNode.getSchemaRegionConsensusPort()
- == dnLocation.getSchemaRegionConsensusEndPoint().getPort()
- && expectedDataNode.getDataRegionConsensusPort()
- == dnLocation.getDataRegionConsensusEndPoint().getPort()) {
- count++;
- break;
- }
- }
- }
- assertEquals(4, count);
-
- // test query one DataNodeInfo
- dataNodeConfigurationResp = client.getDataNodeConfiguration(dataNodeLocation.getDataNodeId());
- infoMap = dataNodeConfigurationResp.getDataNodeConfigurationMap();
- TDataNodeLocation dnLocation =
- dataNodeConfigurationResp
- .getDataNodeConfigurationMap()
- .get(dataNodeLocation.getDataNodeId())
- .getLocation();
- assertEquals(
- TSStatusCode.SUCCESS_STATUS.getStatusCode(),
- dataNodeConfigurationResp.getStatus().getCode());
- assertEquals(1, infoMap.size());
- assertEquals(dataNodeLocation, dnLocation);
-
- // test remove DataNode
- dataNodeLocation = infoList.get(0).getValue().getLocation();
- removeDataNodeLocationList.add(dataNodeLocation);
- removeReq = new TDataNodeRemoveReq(removeDataNodeLocationList);
- removeResp = client.removeDataNode(removeReq);
- assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(), removeResp.getStatus().getCode());
-
- for (int i = 0; i < retryNum; i++) {
- showDataNodesResp = client.showDataNodes();
- if (showDataNodesResp.getDataNodesInfoListSize() == 3) {
- break;
- }
- Thread.sleep(1000);
- }
- assertEquals(3, showDataNodesResp.getDataNodesInfoListSize());
-
- dataNodeInfos = showDataNodesResp.getDataNodesInfoList();
- for (TDataNodeInfo dnInfo : dataNodeInfos) {
- assertNotEquals(dataNodeLocation.getDataNodeId(), dnInfo.getDataNodeId());
- }
- dataNodeConfigurationResp = client.getDataNodeConfiguration(dataNodeLocation.getDataNodeId());
- assertEquals(
- TSStatusCode.SUCCESS_STATUS.getStatusCode(),
- dataNodeConfigurationResp.getStatus().getCode());
- assertEquals(0, dataNodeConfigurationResp.getDataNodeConfigurationMap().size());
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
- }
-
- @Test
- public void showClusterAndNodesTest() {
- try (SyncConfigNodeIServiceClient client =
- (SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
-
- TShowClusterResp clusterNodes;
- TShowConfigNodesResp showConfigNodesResp;
- TShowDataNodesResp showDataNodesResp;
-
- List<ConfigNodeWrapper> configNodeWrappers = EnvFactory.getEnv().getConfigNodeWrapperList();
- List<DataNodeWrapper> dataNodeWrappers = EnvFactory.getEnv().getDataNodeWrapperList();
-
- // test showCluster
- clusterNodes = getClusterNodeInfos(client, 1, 3);
- List<TConfigNodeLocation> configNodeLocations = clusterNodes.getConfigNodeList();
- List<TDataNodeLocation> dataNodeLocations = clusterNodes.getDataNodeList();
-
- for (TConfigNodeLocation configNodeLocation : configNodeLocations) {
- boolean found = false;
- for (ConfigNodeWrapper configNodeWrapper : configNodeWrappers) {
- if (configNodeWrapper.getIp().equals(configNodeLocation.getInternalEndPoint().getIp())
- && configNodeWrapper.getPort() == configNodeLocation.getInternalEndPoint().getPort()
- && configNodeWrapper.getConsensusPort()
- == configNodeLocation.getConsensusEndPoint().getPort()) {
- found = true;
- break;
- }
- }
- assertTrue(found);
- }
-
- for (TDataNodeLocation dataNodeLocation : dataNodeLocations) {
- boolean found = false;
- for (DataNodeWrapper dataNodeWrapper : dataNodeWrappers) {
- if (dataNodeWrapper.getIp().equals(dataNodeLocation.getInternalEndPoint().getIp())
- && dataNodeWrapper.getPort() == dataNodeLocation.getClientRpcEndPoint().getPort()
- && dataNodeWrapper.getInternalPort()
- == dataNodeLocation.getInternalEndPoint().getPort()
- && dataNodeWrapper.getMppDataExchangePort()
- == dataNodeLocation.getMPPDataExchangeEndPoint().getPort()
- && dataNodeWrapper.getSchemaRegionConsensusPort()
- == dataNodeLocation.getSchemaRegionConsensusEndPoint().getPort()
- && dataNodeWrapper.getDataRegionConsensusPort()
- == dataNodeLocation.getDataRegionConsensusEndPoint().getPort()) {
- found = true;
- break;
- }
- }
- assertTrue(found);
- }
-
- // test showConfigNodes
- showConfigNodesResp = client.showConfigNodes();
- List<TConfigNodeInfo> configNodesInfo = showConfigNodesResp.getConfigNodesInfoList();
-
- for (TConfigNodeInfo configNodeInfo : configNodesInfo) {
- boolean found = false;
- for (ConfigNodeWrapper configNodeWrapper : configNodeWrappers) {
- if (configNodeWrapper.getIp().equals(configNodeInfo.getInternalAddress())
- && configNodeWrapper.getPort() == configNodeInfo.getInternalPort()) {
- found = true;
- break;
- }
- }
- assertTrue(found);
- }
-
- // test showDataNodes
- showDataNodesResp = client.showDataNodes();
- List<TDataNodeInfo> dataNodesInfo = showDataNodesResp.getDataNodesInfoList();
-
- for (TDataNodeInfo dataNodeInfo : dataNodesInfo) {
- boolean found = false;
- for (DataNodeWrapper dataNodeWrapper : dataNodeWrappers) {
- if (dataNodeWrapper.getIp().equals(dataNodeInfo.getRpcAddresss())
- && dataNodeWrapper.getPort() == dataNodeInfo.getRpcPort()) {
- found = true;
- break;
- }
- }
- assertTrue(found);
- }
- } catch (Exception e) {
- e.printStackTrace();
- fail(e.getMessage());
- }
}
private void cleanUserAndRole(IConfigNodeRPCService.Iface client) throws TException {
diff --git a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterNodeIT.java b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterNodeIT.java
new file mode 100644
index 0000000000..92479c93dc
--- /dev/null
+++ b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterNodeIT.java
@@ -0,0 +1,308 @@
+/*
+ * 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.confignode.it;
+
+import org.apache.iotdb.common.rpc.thrift.TConfigNodeLocation;
+import org.apache.iotdb.common.rpc.thrift.TDataNodeConfiguration;
+import org.apache.iotdb.common.rpc.thrift.TDataNodeLocation;
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.common.rpc.thrift.TNodeResource;
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.commons.client.sync.SyncConfigNodeIServiceClient;
+import org.apache.iotdb.confignode.rpc.thrift.TConfigNodeInfo;
+import org.apache.iotdb.confignode.rpc.thrift.TDataNodeConfigurationResp;
+import org.apache.iotdb.confignode.rpc.thrift.TDataNodeInfo;
+import org.apache.iotdb.confignode.rpc.thrift.TDataNodeRegisterReq;
+import org.apache.iotdb.confignode.rpc.thrift.TDataNodeRegisterResp;
+import org.apache.iotdb.confignode.rpc.thrift.TDataNodeRemoveReq;
+import org.apache.iotdb.confignode.rpc.thrift.TDataNodeRemoveResp;
+import org.apache.iotdb.confignode.rpc.thrift.TShowClusterResp;
+import org.apache.iotdb.confignode.rpc.thrift.TShowConfigNodesResp;
+import org.apache.iotdb.confignode.rpc.thrift.TShowDataNodesResp;
+import org.apache.iotdb.consensus.ConsensusFactory;
+import org.apache.iotdb.it.env.ConfigFactory;
+import org.apache.iotdb.it.env.ConfigNodeWrapper;
+import org.apache.iotdb.it.env.DataNodeWrapper;
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.ClusterIT;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.apache.thrift.TException;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+@RunWith(IoTDBTestRunner.class)
+@Category({ClusterIT.class})
+public class IoTDBClusterNodeIT {
+
+ private static final int testConfigNodeNum = 2;
+ private static final int testDataNodeNum = 2;
+
+ protected static String originalConfigNodeConsensusProtocolClass;
+ protected static String originalSchemaRegionConsensusProtocolClass;
+ protected static String originalDataRegionConsensusProtocolClass;
+ private static final String testConsensusProtocolClass = ConsensusFactory.RatisConsensus;
+
+ @Before
+ public void setUp() throws Exception {
+ originalConfigNodeConsensusProtocolClass =
+ ConfigFactory.getConfig().getConfigNodeConsesusProtocolClass();
+ ConfigFactory.getConfig().setConfigNodeConsesusProtocolClass(testConsensusProtocolClass);
+ originalSchemaRegionConsensusProtocolClass =
+ ConfigFactory.getConfig().getSchemaRegionConsensusProtocolClass();
+ ConfigFactory.getConfig().setSchemaRegionConsensusProtocolClass(testConsensusProtocolClass);
+ originalDataRegionConsensusProtocolClass =
+ ConfigFactory.getConfig().getDataRegionConsensusProtocolClass();
+ ConfigFactory.getConfig().setDataRegionConsensusProtocolClass(testConsensusProtocolClass);
+
+ // Init 2C2D environment
+ EnvFactory.getEnv().initClusterEnvironment(testConfigNodeNum, testDataNodeNum);
+ }
+
+ @After
+ public void tearDown() {
+ EnvFactory.getEnv().cleanAfterClass();
+ ConfigFactory.getConfig()
+ .setConfigNodeConsesusProtocolClass(originalConfigNodeConsensusProtocolClass);
+ ConfigFactory.getConfig()
+ .setSchemaRegionConsensusProtocolClass(originalSchemaRegionConsensusProtocolClass);
+ ConfigFactory.getConfig()
+ .setDataRegionConsensusProtocolClass(originalDataRegionConsensusProtocolClass);
+ }
+
+ @Test
+ public void showClusterAndNodesTest() throws IOException, InterruptedException, TException {
+ try (SyncConfigNodeIServiceClient client =
+ (SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
+
+ List<ConfigNodeWrapper> configNodeWrappers = EnvFactory.getEnv().getConfigNodeWrapperList();
+ List<DataNodeWrapper> dataNodeWrappers = EnvFactory.getEnv().getDataNodeWrapperList();
+
+ /* Test showCluster */
+ TShowClusterResp showClusterResp = client.showCluster();
+ // Check ConfigNodeLocation
+ List<TConfigNodeLocation> configNodeLocations = showClusterResp.getConfigNodeList();
+ for (TConfigNodeLocation configNodeLocation : configNodeLocations) {
+ boolean found = false;
+ for (ConfigNodeWrapper configNodeWrapper : configNodeWrappers) {
+ if (configNodeWrapper.getIp().equals(configNodeLocation.getInternalEndPoint().getIp())
+ && configNodeWrapper.getPort() == configNodeLocation.getInternalEndPoint().getPort()
+ && configNodeWrapper.getConsensusPort()
+ == configNodeLocation.getConsensusEndPoint().getPort()) {
+ found = true;
+ break;
+ }
+ }
+ assertTrue(found);
+ }
+ // Check DataNodeLocation
+ List<TDataNodeLocation> dataNodeLocations = showClusterResp.getDataNodeList();
+ for (TDataNodeLocation dataNodeLocation : dataNodeLocations) {
+ boolean found = false;
+ for (DataNodeWrapper dataNodeWrapper : dataNodeWrappers) {
+ if (dataNodeWrapper.getIp().equals(dataNodeLocation.getInternalEndPoint().getIp())
+ && dataNodeWrapper.getPort() == dataNodeLocation.getClientRpcEndPoint().getPort()
+ && dataNodeWrapper.getInternalPort()
+ == dataNodeLocation.getInternalEndPoint().getPort()
+ && dataNodeWrapper.getMppDataExchangePort()
+ == dataNodeLocation.getMPPDataExchangeEndPoint().getPort()
+ && dataNodeWrapper.getSchemaRegionConsensusPort()
+ == dataNodeLocation.getSchemaRegionConsensusEndPoint().getPort()
+ && dataNodeWrapper.getDataRegionConsensusPort()
+ == dataNodeLocation.getDataRegionConsensusEndPoint().getPort()) {
+ found = true;
+ break;
+ }
+ }
+ assertTrue(found);
+ }
+
+ /* Test showConfigNodes */
+ TShowConfigNodesResp showConfigNodesResp = client.showConfigNodes();
+ // Check ConfigNodeInfo
+ List<TConfigNodeInfo> configNodesInfo = showConfigNodesResp.getConfigNodesInfoList();
+ for (TConfigNodeInfo configNodeInfo : configNodesInfo) {
+ boolean found = false;
+ for (ConfigNodeWrapper configNodeWrapper : configNodeWrappers) {
+ if (configNodeWrapper.getIp().equals(configNodeInfo.getInternalAddress())
+ && configNodeWrapper.getPort() == configNodeInfo.getInternalPort()) {
+ found = true;
+ break;
+ }
+ }
+ assertTrue(found);
+ }
+
+ /* Test showDataNodes */
+ TShowDataNodesResp showDataNodesResp = client.showDataNodes();
+ // Check DataNodeInfo
+ List<TDataNodeInfo> dataNodesInfo = showDataNodesResp.getDataNodesInfoList();
+ for (TDataNodeInfo dataNodeInfo : dataNodesInfo) {
+ boolean found = false;
+ for (DataNodeWrapper dataNodeWrapper : dataNodeWrappers) {
+ if (dataNodeWrapper.getIp().equals(dataNodeInfo.getRpcAddresss())
+ && dataNodeWrapper.getPort() == dataNodeInfo.getRpcPort()) {
+ found = true;
+ break;
+ }
+ }
+ assertTrue(found);
+ }
+ }
+ }
+
+ @Test
+ public void removeAndStopConfigNodeTest() throws TException, IOException, InterruptedException {
+ TShowClusterResp showClusterResp;
+ TSStatus status;
+
+ try (SyncConfigNodeIServiceClient client =
+ (SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
+
+ // Test remove ConfigNode
+ showClusterResp = client.showCluster();
+ TConfigNodeLocation removedConfigNodeLocation = showClusterResp.getConfigNodeList().get(1);
+ status = client.removeConfigNode(removedConfigNodeLocation);
+ Assert.assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(), status.getCode());
+
+ // Waiting for RemoveConfigNodeProcedure
+ boolean isRemoved = false;
+ for (int retry = 0; retry < 10; retry++) {
+ showClusterResp = client.showCluster();
+ if (showClusterResp.getStatus().getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()
+ && showClusterResp.getConfigNodeListSize() == testConfigNodeNum - 1) {
+ isRemoved = true;
+ break;
+ }
+
+ TimeUnit.SECONDS.sleep(1);
+ }
+ if (!isRemoved) {
+ fail("Remove ConfigNode failed");
+ }
+
+ // Test stop ConfigNode
+ status = client.stopConfigNode(removedConfigNodeLocation);
+ assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(), status.getCode());
+ }
+ }
+
+ @Test
+ public void queryAndRemoveDataNodeTest() throws TException, IOException, InterruptedException {
+
+ try (SyncConfigNodeIServiceClient client =
+ (SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
+
+ /* Test success re-register */
+ TDataNodeRegisterReq dataNodeRegisterReq = new TDataNodeRegisterReq();
+ TDataNodeConfiguration dataNodeConfiguration = new TDataNodeConfiguration();
+ TDataNodeLocation dataNodeLocation = new TDataNodeLocation();
+
+ // Pick a registered DataNode
+ TShowDataNodesResp showDataNodesResp = client.showDataNodes();
+ TDataNodeInfo dataNodeInfo = showDataNodesResp.getDataNodesInfoList().get(0);
+
+ dataNodeLocation.setDataNodeId(dataNodeInfo.getDataNodeId());
+ dataNodeLocation.setClientRpcEndPoint(
+ new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort()));
+ dataNodeLocation.setMPPDataExchangeEndPoint(
+ new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort() + 1));
+ dataNodeLocation.setInternalEndPoint(
+ new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort() + 2));
+ dataNodeLocation.setDataRegionConsensusEndPoint(
+ new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort() + 3));
+ dataNodeLocation.setSchemaRegionConsensusEndPoint(
+ new TEndPoint(dataNodeInfo.getRpcAddresss(), dataNodeInfo.getRpcPort() + 4));
+
+ // Re-register DataNode
+ dataNodeConfiguration.setLocation(dataNodeLocation);
+ dataNodeConfiguration.setResource(new TNodeResource(8, 1024 * 1024));
+ dataNodeRegisterReq.setDataNodeConfiguration(dataNodeConfiguration);
+ TDataNodeRegisterResp dataNodeRegisterResp = client.registerDataNode(dataNodeRegisterReq);
+ assertEquals(
+ TSStatusCode.DATANODE_ALREADY_REGISTERED.getStatusCode(),
+ dataNodeRegisterResp.getStatus().getCode());
+
+ /* Test query one DataNodeInfo */
+ TDataNodeConfigurationResp dataNodeConfigurationResp =
+ client.getDataNodeConfiguration(dataNodeLocation.getDataNodeId());
+ Map<Integer, TDataNodeConfiguration> configurationMap =
+ dataNodeConfigurationResp.getDataNodeConfigurationMap();
+ TDataNodeLocation dnLocation =
+ dataNodeConfigurationResp
+ .getDataNodeConfigurationMap()
+ .get(dataNodeLocation.getDataNodeId())
+ .getLocation();
+ assertEquals(
+ TSStatusCode.SUCCESS_STATUS.getStatusCode(),
+ dataNodeConfigurationResp.getStatus().getCode());
+ assertEquals(1, configurationMap.size());
+ assertEquals(dataNodeLocation, dnLocation);
+
+ /* Test query all DataNodeConfiguration */
+ dataNodeConfigurationResp = client.getDataNodeConfiguration(-1);
+ configurationMap = dataNodeConfigurationResp.getDataNodeConfigurationMap();
+ assertEquals(
+ TSStatusCode.SUCCESS_STATUS.getStatusCode(),
+ dataNodeConfigurationResp.getStatus().getCode());
+ assertEquals(testDataNodeNum, configurationMap.size());
+
+ /* Test remove DataNode */
+ // Remove DataNode
+ dataNodeLocation =
+ dataNodeConfigurationResp
+ .getDataNodeConfigurationMap()
+ .get(
+ showDataNodesResp.getDataNodesInfoList().get(testDataNodeNum - 1).getDataNodeId())
+ .getLocation();
+ TDataNodeRemoveReq dataNodeRemoveReq =
+ new TDataNodeRemoveReq(Collections.singletonList(dataNodeLocation));
+ TDataNodeRemoveResp dataNodeRemoveResp = client.removeDataNode(dataNodeRemoveReq);
+ assertEquals(
+ TSStatusCode.SUCCESS_STATUS.getStatusCode(), dataNodeRemoveResp.getStatus().getCode());
+
+ // Waiting for RemoveDataNodeProcedure
+ for (int retry = 0; retry < 10; retry++) {
+ showDataNodesResp = client.showDataNodes();
+ if (showDataNodesResp.getStatus().getCode() == TSStatusCode.SUCCESS_STATUS.getStatusCode()
+ && showDataNodesResp.getDataNodesInfoListSize() == testDataNodeNum - 1) {
+ return;
+ }
+
+ TimeUnit.SECONDS.sleep(1);
+ }
+ fail("Remove DataNode failed");
+ }
+ }
+}
diff --git a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterPartitionIT.java b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterPartitionIT.java
index d13b506d69..61f322cec2 100644
--- a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterPartitionIT.java
+++ b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterPartitionIT.java
@@ -384,6 +384,7 @@ public class IoTDBClusterPartitionIT {
}
}
+ // TODO: Optimize in IOTDB-4334
@Test
public void testPartitionDurable() throws IOException, TException, InterruptedException {
final int testDataNodeId = 0;
diff --git a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterRegionLeaderBalancingIT.java b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterRegionLeaderBalancingIT.java
new file mode 100644
index 0000000000..dac2189cc8
--- /dev/null
+++ b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBClusterRegionLeaderBalancingIT.java
@@ -0,0 +1,152 @@
+/*
+ * 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.confignode.it;
+
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.common.rpc.thrift.TSeriesPartitionSlot;
+import org.apache.iotdb.common.rpc.thrift.TTimePartitionSlot;
+import org.apache.iotdb.commons.client.sync.SyncConfigNodeIServiceClient;
+import org.apache.iotdb.commons.cluster.RegionRoleType;
+import org.apache.iotdb.confignode.rpc.thrift.TDataPartitionReq;
+import org.apache.iotdb.confignode.rpc.thrift.TDataPartitionTableResp;
+import org.apache.iotdb.confignode.rpc.thrift.TSetStorageGroupReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowRegionReq;
+import org.apache.iotdb.confignode.rpc.thrift.TShowRegionResp;
+import org.apache.iotdb.confignode.rpc.thrift.TStorageGroupSchema;
+import org.apache.iotdb.consensus.ConsensusFactory;
+import org.apache.iotdb.it.env.ConfigFactory;
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.ClusterIT;
+import org.apache.iotdb.rpc.TSStatusCode;
+
+import org.apache.thrift.TException;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+@RunWith(IoTDBTestRunner.class)
+@Category({ClusterIT.class})
+public class IoTDBClusterRegionLeaderBalancingIT {
+
+ protected static String originalSchemaRegionConsensusProtocolClass;
+ private static final String testSchemaRegionConsensusProtocolClass =
+ ConsensusFactory.RatisConsensus;
+ protected static String originalDataRegionConsensusProtocolClass;
+ private static final String testDataRegionConsensusProtocolClass =
+ ConsensusFactory.MultiLeaderConsensus;
+
+ protected static int originalSchemaReplicationFactor;
+ protected static int originalDataReplicationFactor;
+ private static final int testReplicationFactor = 3;
+
+ private static final String sg = "root.sg";
+
+ @BeforeClass
+ public static void setUp() {
+ originalSchemaRegionConsensusProtocolClass =
+ ConfigFactory.getConfig().getSchemaRegionConsensusProtocolClass();
+ ConfigFactory.getConfig()
+ .setSchemaRegionConsensusProtocolClass(testSchemaRegionConsensusProtocolClass);
+
+ originalDataRegionConsensusProtocolClass =
+ ConfigFactory.getConfig().getDataRegionConsensusProtocolClass();
+ ConfigFactory.getConfig()
+ .setDataRegionConsensusProtocolClass(testDataRegionConsensusProtocolClass);
+
+ originalSchemaReplicationFactor = ConfigFactory.getConfig().getSchemaReplicationFactor();
+ originalDataReplicationFactor = ConfigFactory.getConfig().getDataReplicationFactor();
+ ConfigFactory.getConfig().setSchemaReplicationFactor(testReplicationFactor);
+ ConfigFactory.getConfig().setDataReplicationFactor(testReplicationFactor);
+ }
+
+ @AfterClass
+ public static void tearDown() {
+ ConfigFactory.getConfig()
+ .setSchemaRegionConsensusProtocolClass(originalSchemaRegionConsensusProtocolClass);
+ ConfigFactory.getConfig()
+ .setDataRegionConsensusProtocolClass(originalDataRegionConsensusProtocolClass);
+
+ ConfigFactory.getConfig().setSchemaReplicationFactor(originalSchemaReplicationFactor);
+ ConfigFactory.getConfig().setDataReplicationFactor(originalDataReplicationFactor);
+ }
+
+ @Test
+ public void testGreedyLeaderDistribution() throws IOException, InterruptedException, TException {
+ final int testConfigNodeNum = 1;
+ final int testDataNodeNum = 3;
+ EnvFactory.getEnv().initClusterEnvironment(testConfigNodeNum, testDataNodeNum);
+
+ TSStatus status;
+ final int storageGroupNum = 3;
+ try (SyncConfigNodeIServiceClient client =
+ (SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
+
+ // Set StorageGroups
+ for (int i = 0; i < storageGroupNum; i++) {
+ TSetStorageGroupReq setReq = new TSetStorageGroupReq(new TStorageGroupSchema(sg + i));
+ status = client.setStorageGroup(setReq);
+ Assert.assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(), status.getCode());
+ }
+
+ // Create a DataRegionGroup for each StorageGroup through getOrCreateDataPartition
+ for (int i = 0; i < storageGroupNum; i++) {
+ Map<TSeriesPartitionSlot, List<TTimePartitionSlot>> seriesSlotMap = new HashMap<>();
+ seriesSlotMap.put(
+ new TSeriesPartitionSlot(1), Collections.singletonList(new TTimePartitionSlot(100)));
+ Map<String, Map<TSeriesPartitionSlot, List<TTimePartitionSlot>>> sgSlotsMap =
+ new HashMap<>();
+ sgSlotsMap.put(sg + i, seriesSlotMap);
+ TDataPartitionTableResp dataPartitionTableResp =
+ client.getOrCreateDataPartitionTable(new TDataPartitionReq(sgSlotsMap));
+ Assert.assertEquals(
+ TSStatusCode.SUCCESS_STATUS.getStatusCode(),
+ dataPartitionTableResp.getStatus().getCode());
+ }
+
+ // Check the number of Region-leader in each DataNode.
+ Map<Integer, AtomicInteger> leaderCounter = new ConcurrentHashMap<>();
+ TShowRegionResp showRegionResp = client.showRegion(new TShowRegionReq());
+ showRegionResp
+ .getRegionInfoList()
+ .forEach(
+ regionInfo -> {
+ if (RegionRoleType.Leader.getRoleType().equals(regionInfo.getRoleType())) {
+ leaderCounter
+ .computeIfAbsent(regionInfo.getDataNodeId(), empty -> new AtomicInteger(0))
+ .getAndIncrement();
+ }
+ });
+ // The number of Region-leader in each DataNode should be exactly 1
+ Assert.assertEquals(testDataNodeNum, leaderCounter.size());
+ leaderCounter.values().forEach(leaderCount -> Assert.assertEquals(1, leaderCount.get()));
+ }
+ }
+}
diff --git a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeSnapshotIT.java b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeSnapshotIT.java
index 06c2db1a2a..751999daaa 100644
--- a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeSnapshotIT.java
+++ b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeSnapshotIT.java
@@ -97,8 +97,8 @@ public class IoTDBConfigNodeSnapshotIT {
originalTimePartitionInterval = ConfigFactory.getConfig().getTimePartitionInterval();
ConfigFactory.getConfig().setTimePartitionIntervalForRouting(testTimePartitionInterval);
- // Init 3C3D cluster environment
- EnvFactory.getEnv().initClusterEnvironment(3, 3);
+ // Init 2C2D cluster environment
+ EnvFactory.getEnv().initClusterEnvironment(2, 2);
}
@After
diff --git a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeSwitchLeaderIT.java b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeSwitchLeaderIT.java
index a119ff60b0..98307358b6 100644
--- a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeSwitchLeaderIT.java
+++ b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBConfigNodeSwitchLeaderIT.java
@@ -18,17 +18,18 @@
*/
package org.apache.iotdb.confignode.it;
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupId;
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.common.rpc.thrift.TSeriesPartitionSlot;
import org.apache.iotdb.common.rpc.thrift.TTimePartitionSlot;
import org.apache.iotdb.commons.client.sync.SyncConfigNodeIServiceClient;
-import org.apache.iotdb.commons.cluster.NodeStatus;
import org.apache.iotdb.commons.exception.IllegalPathException;
import org.apache.iotdb.commons.path.PartialPath;
import org.apache.iotdb.commons.path.PathPatternTree;
-import org.apache.iotdb.confignode.rpc.thrift.TDataNodeInfo;
import org.apache.iotdb.confignode.rpc.thrift.TDataPartitionReq;
import org.apache.iotdb.confignode.rpc.thrift.TDataPartitionTableResp;
+import org.apache.iotdb.confignode.rpc.thrift.TRegionInfo;
import org.apache.iotdb.confignode.rpc.thrift.TSchemaPartitionReq;
import org.apache.iotdb.confignode.rpc.thrift.TSchemaPartitionTableResp;
import org.apache.iotdb.confignode.rpc.thrift.TSetStorageGroupReq;
@@ -88,7 +89,8 @@ public class IoTDBConfigNodeSwitchLeaderIT {
ConfigFactory.getConfig().setConfigNodeConsesusProtocolClass(ConsensusFactory.RatisConsensus);
ConfigFactory.getConfig()
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RatisConsensus);
- ConfigFactory.getConfig().setDataRegionConsensusProtocolClass(ConsensusFactory.RatisConsensus);
+ ConfigFactory.getConfig()
+ .setDataRegionConsensusProtocolClass(ConsensusFactory.MultiLeaderConsensus);
originalSchemaReplicationFactor = ConfigFactory.getConfig().getSchemaReplicationFactor();
originalDataReplicationFactor = ConfigFactory.getConfig().getDataReplicationFactor();
@@ -121,7 +123,7 @@ public class IoTDBConfigNodeSwitchLeaderIT {
// The ConfigNode-Group will elect a new leader after the current ConfigNode-Leader is shutdown
EnvFactory.getEnv().shutdownConfigNode(EnvFactory.getEnv().getLeaderConfigNodeIndex());
// Waiting for leader election
- TimeUnit.MILLISECONDS.sleep(2L * partitionRegionRatisRPCLeaderElectionTimeoutMaxMs);
+ TimeUnit.MILLISECONDS.sleep(partitionRegionRatisRPCLeaderElectionTimeoutMaxMs);
}
/** Generate a PatternTree and serialize it into a ByteBuffer */
@@ -151,8 +153,8 @@ public class IoTDBConfigNodeSwitchLeaderIT {
TSStatus status;
TSchemaPartitionTableResp schemaPartitionTableResp0;
TDataPartitionTableResp dataPartitionTableResp0;
- TShowDataNodesResp showDataNodesResp0 = null;
- TShowRegionResp showRegionResp0 = null;
+ TShowDataNodesResp showDataNodesResp0;
+ Map<TConsensusGroupId, TRegionInfo> dataRegionInfoMap = new HashMap<>();
try (SyncConfigNodeIServiceClient client =
(SyncConfigNodeIServiceClient) EnvFactory.getEnv().getLeaderConfigNodeConnection()) {
@@ -162,7 +164,8 @@ public class IoTDBConfigNodeSwitchLeaderIT {
status = client.setStorageGroup(new TSetStorageGroupReq(new TStorageGroupSchema(sg1)));
Assert.assertEquals(TSStatusCode.SUCCESS_STATUS.getStatusCode(), status.getCode());
- // Create SchemaRegionGroups through getOrCreateSchemaPartition
+ // Create SchemaRegionGroups through getOrCreateSchemaPartition and record
+ // SchemaPartitionTable
ByteBuffer buffer = generatePatternTreeBuffer(new String[] {d00, d01, d10, d11});
schemaPartitionTableResp0 =
client.getOrCreateSchemaPartitionTable(
@@ -171,7 +174,7 @@ public class IoTDBConfigNodeSwitchLeaderIT {
TSStatusCode.SUCCESS_STATUS.getStatusCode(),
schemaPartitionTableResp0.getStatus().getCode());
- // Create DataRegionGroups through getOrCreateDataPartition
+ // Create DataRegionGroups through getOrCreateDataPartition and record DataPartitionTable
Map<TSeriesPartitionSlot, List<TTimePartitionSlot>> seriesSlotMap = new HashMap<>();
seriesSlotMap.put(
new TSeriesPartitionSlot(1), Collections.singletonList(new TTimePartitionSlot(100)));
@@ -184,27 +187,23 @@ public class IoTDBConfigNodeSwitchLeaderIT {
TSStatusCode.SUCCESS_STATUS.getStatusCode(),
dataPartitionTableResp0.getStatus().getCode());
- // Shutdown a DataNode
- EnvFactory.getEnv().shutdownDataNode(0);
- // Waiting for DataNode shutdown
- TimeUnit.SECONDS.sleep(1);
-
- boolean isDetectedUnknown = false;
- for (int retry = 0; retry < 30; retry++) {
- showDataNodesResp0 = client.showDataNodes();
- showRegionResp0 = client.showRegion(new TShowRegionReq());
-
- for (TDataNodeInfo dataNodeInfo : showDataNodesResp0.getDataNodesInfoList()) {
- if (NodeStatus.Unknown.getStatus().equals(dataNodeInfo.getStatus())) {
- isDetectedUnknown = true;
- break;
- }
- }
-
- // Sleep 1s before next check
- TimeUnit.SECONDS.sleep(1);
- }
- Assert.assertTrue(isDetectedUnknown);
+ // Sleep to wait for UpdateLoadStatistics
+ TimeUnit.MILLISECONDS.sleep(partitionRegionRatisRPCLeaderElectionTimeoutMaxMs);
+
+ // Record showDataNodesResp
+ showDataNodesResp0 = client.showDataNodes();
+
+ // Record RegionInfo of DataRegions
+ TShowRegionResp showRegionResp = client.showRegion(new TShowRegionReq());
+ showRegionResp
+ .getRegionInfoList()
+ .forEach(
+ regionInfo -> {
+ if (TConsensusGroupType.DataRegion.equals(
+ regionInfo.getConsensusGroupId().getType())) {
+ dataRegionInfoMap.put(regionInfo.getConsensusGroupId(), regionInfo);
+ }
+ });
}
// Switch the current ConfigNode-Leader
@@ -228,9 +227,22 @@ public class IoTDBConfigNodeSwitchLeaderIT {
Assert.assertEquals(
dataPartitionTableResp0, client.getDataPartitionTable(new TDataPartitionReq(sgSlotsMap)));
- // TODO: Check RegionGroup leadership after the leader allocation policy is optimized
-
- // TODO: Check NodeStatus after the heartbeat check is optimized
+ // Check DataNodes' statuses
+ Assert.assertEquals(showDataNodesResp0, client.showDataNodes());
+
+ // Check DataRegions' RegionInfo
+ TShowRegionResp showRegionResp = client.showRegion(new TShowRegionReq());
+ Map<TConsensusGroupId, TRegionInfo> dataRegionInfoMap1 = new HashMap<>();
+ showRegionResp
+ .getRegionInfoList()
+ .forEach(
+ regionInfo -> {
+ if (TConsensusGroupType.DataRegion.equals(
+ regionInfo.getConsensusGroupId().getType())) {
+ dataRegionInfoMap1.put(regionInfo.getConsensusGroupId(), regionInfo);
+ }
+ });
+ Assert.assertEquals(dataRegionInfoMap, dataRegionInfoMap1);
}
}
}
diff --git a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBStorageGroupIT.java b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBStorageGroupIT.java
index 662d882321..6867a42d44 100644
--- a/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBStorageGroupIT.java
+++ b/integration-test/src/test/java/org/apache/iotdb/confignode/it/IoTDBStorageGroupIT.java
@@ -55,7 +55,8 @@ public class IoTDBStorageGroupIT {
@Before
public void setUp() throws Exception {
- EnvFactory.getEnv().initBeforeClass();
+ // Init 1C0D environment
+ EnvFactory.getEnv().initClusterEnvironment(1, 0);
}
@After
diff --git a/node-commons/src/main/java/org/apache/iotdb/commons/cluster/RegionRoleType.java b/node-commons/src/main/java/org/apache/iotdb/commons/cluster/RegionRoleType.java
index 1a9d59e1eb..6e65824f7d 100644
--- a/node-commons/src/main/java/org/apache/iotdb/commons/cluster/RegionRoleType.java
+++ b/node-commons/src/main/java/org/apache/iotdb/commons/cluster/RegionRoleType.java
@@ -25,13 +25,13 @@ public enum RegionRoleType {
// Region role type : Follower
Follower("Follower");
- private final String status;
+ private final String roleType;
- RegionRoleType(String status) {
- this.status = status;
+ RegionRoleType(String roleType) {
+ this.roleType = roleType;
}
- public String getStatus() {
- return status;
+ public String getRoleType() {
+ return roleType;
}
}
diff --git a/node-commons/src/main/java/org/apache/iotdb/commons/cluster/RegionStatus.java b/node-commons/src/main/java/org/apache/iotdb/commons/cluster/RegionStatus.java
index bc81946923..ade6136fb2 100644
--- a/node-commons/src/main/java/org/apache/iotdb/commons/cluster/RegionStatus.java
+++ b/node-commons/src/main/java/org/apache/iotdb/commons/cluster/RegionStatus.java
@@ -51,4 +51,9 @@ public enum RegionStatus {
}
throw new RuntimeException(String.format("RegionStatus %s doesn't exist.", status));
}
+
+ public static boolean isNormalStatus(RegionStatus status) {
+ // Currently, the only normal status is Running
+ return status != null && status.equals(RegionStatus.Running);
+ }
}