OneSizeFitsQuorum commented on code in PR #15022:
URL: https://github.com/apache/iotdb/pull/15022#discussion_r1984745180


##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/RemoveDataNodeHandler.java:
##########
@@ -193,6 +201,136 @@ public List<RegionMigrationPlan> getRegionMigrationPlans(
     return regionMigrationPlans;
   }
 
+  /**
+   * Retrieves all region migration plans for the specified removed DataNodes 
and selects the
+   * destination.
+   *
+   * @param removedDataNodes the list of DataNodes from which to obtain 
migration plans
+   * @return a list of region migration plans associated with the removed 
DataNodes
+   */
+  public List<RegionMigrationPlan> selectedRegionMigrationPlans(
+      List<TDataNodeLocation> removedDataNodes) {
+
+    Set<Integer> removedDataNodesSet = new HashSet<>();
+    for (TDataNodeLocation removedDataNode : removedDataNodes) {
+      removedDataNodesSet.add(removedDataNode.dataNodeId);
+    }
+
+    final List<TDataNodeConfiguration> availableDataNodes =
+        configManager
+            .getNodeManager()
+            .filterDataNodeThroughStatus(NodeStatus.Running, 
NodeStatus.Unknown)
+            .stream()
+            .filter(node -> 
!removedDataNodesSet.contains(node.getLocation().getDataNodeId()))
+            .collect(Collectors.toList());
+
+    List<RegionMigrationPlan> regionMigrationPlans = new ArrayList<>();
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(availableDataNodes, 
TConsensusGroupType.DataRegion, removedDataNodes));
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(
+            availableDataNodes, TConsensusGroupType.SchemaRegion, 
removedDataNodes));
+
+    return regionMigrationPlans;
+  }
+
+  public List<RegionMigrationPlan> selectMigrationPlans(
+      List<TDataNodeConfiguration> availableDataNodes,
+      TConsensusGroupType consensusGroupType,
+      List<TDataNodeLocation> removedDataNodes) {
+    List<TRegionReplicaSet> allocatedRegionGroups =
+        
configManager.getPartitionManager().getAllReplicaSets(consensusGroupType);
+
+    Map<TConsensusGroupId, TDataNodeLocation> replicaSetRemoved = new 
HashMap<>();
+    List<TRegionReplicaSet> migratedReplicas = new ArrayList<>();
+
+    for (TDataNodeLocation dataNodeLocation : removedDataNodes) {
+      List<TRegionReplicaSet> replicaSets =
+          allocatedRegionGroups.stream()
+              .filter(replicaSet -> 
replicaSet.getDataNodeLocations().contains(dataNodeLocation))
+              .collect(Collectors.toList());
+      for (TRegionReplicaSet replicaSet : replicaSets) {
+        replicaSetRemoved.put(replicaSet.getRegionId(), dataNodeLocation);
+      }
+      migratedReplicas.addAll(replicaSets);
+    }
+
+    List<TRegionReplicaSet> remainReplicas = new ArrayList<>();
+
+    for (TRegionReplicaSet replicaSet : migratedReplicas) {
+      allocatedRegionGroups.remove(replicaSet);
+      List<TDataNodeLocation> dataNodeLocations = 
replicaSet.getDataNodeLocations();
+      
dataNodeLocations.remove(replicaSetRemoved.get(replicaSet.getRegionId()));
+      replicaSet.setDataNodeLocations(dataNodeLocations);
+      allocatedRegionGroups.add(replicaSet);
+      remainReplicas.add(replicaSet);
+    }
+
+    List<RegionMigrationPlan> regionMigrationPlans = new ArrayList<>();
+
+    for (TRegionReplicaSet remainReplicaSet : remainReplicas) {
+      final Map<Integer, TDataNodeConfiguration> availableDataNodeMap =
+          new HashMap<>(availableDataNodes.size());
+      final Map<Integer, Double> freeDiskSpaceMap = new 
HashMap<>(availableDataNodes.size());
+      availableDataNodes.forEach(
+          dataNodeConfiguration -> {
+            int dataNodeId = 
dataNodeConfiguration.getLocation().getDataNodeId();
+            availableDataNodeMap.put(dataNodeId, dataNodeConfiguration);
+            freeDiskSpaceMap.put(
+                dataNodeId, 
configManager.getLoadManager().getFreeDiskSpace(dataNodeId));
+          });
+      String database =
+          
configManager.getPartitionManager().getRegionDatabase(remainReplicaSet.getRegionId());
+
+      List<TRegionReplicaSet> databaseAllocatedRegionGroups =
+          configManager.getPartitionManager().getAllReplicaSets(database, 
consensusGroupType);
+      int replicationFactor;
+      try {
+        replicationFactor =
+            configManager
+                .getClusterSchemaManager()
+                .getReplicationFactor(database, consensusGroupType);
+      } catch (DatabaseNotExistsException e) {
+        LOGGER.error(

Review Comment:
   use warn



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/RemoveDataNodeHandler.java:
##########
@@ -193,6 +201,136 @@ public List<RegionMigrationPlan> getRegionMigrationPlans(
     return regionMigrationPlans;
   }
 
+  /**
+   * Retrieves all region migration plans for the specified removed DataNodes 
and selects the
+   * destination.
+   *
+   * @param removedDataNodes the list of DataNodes from which to obtain 
migration plans
+   * @return a list of region migration plans associated with the removed 
DataNodes
+   */
+  public List<RegionMigrationPlan> selectedRegionMigrationPlans(
+      List<TDataNodeLocation> removedDataNodes) {
+
+    Set<Integer> removedDataNodesSet = new HashSet<>();
+    for (TDataNodeLocation removedDataNode : removedDataNodes) {
+      removedDataNodesSet.add(removedDataNode.dataNodeId);
+    }
+
+    final List<TDataNodeConfiguration> availableDataNodes =
+        configManager
+            .getNodeManager()
+            .filterDataNodeThroughStatus(NodeStatus.Running, 
NodeStatus.Unknown)
+            .stream()
+            .filter(node -> 
!removedDataNodesSet.contains(node.getLocation().getDataNodeId()))
+            .collect(Collectors.toList());
+
+    List<RegionMigrationPlan> regionMigrationPlans = new ArrayList<>();
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(availableDataNodes, 
TConsensusGroupType.DataRegion, removedDataNodes));
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(
+            availableDataNodes, TConsensusGroupType.SchemaRegion, 
removedDataNodes));
+
+    return regionMigrationPlans;
+  }
+
+  public List<RegionMigrationPlan> selectMigrationPlans(
+      List<TDataNodeConfiguration> availableDataNodes,
+      TConsensusGroupType consensusGroupType,
+      List<TDataNodeLocation> removedDataNodes) {
+    List<TRegionReplicaSet> allocatedRegionGroups =
+        
configManager.getPartitionManager().getAllReplicaSets(consensusGroupType);
+
+    Map<TConsensusGroupId, TDataNodeLocation> replicaSetRemoved = new 
HashMap<>();
+    List<TRegionReplicaSet> migratedReplicas = new ArrayList<>();
+
+    for (TDataNodeLocation dataNodeLocation : removedDataNodes) {
+      List<TRegionReplicaSet> replicaSets =
+          allocatedRegionGroups.stream()
+              .filter(replicaSet -> 
replicaSet.getDataNodeLocations().contains(dataNodeLocation))
+              .collect(Collectors.toList());
+      for (TRegionReplicaSet replicaSet : replicaSets) {
+        replicaSetRemoved.put(replicaSet.getRegionId(), dataNodeLocation);
+      }
+      migratedReplicas.addAll(replicaSets);

Review Comment:
   It looks like it might repeat when we support removing multiple nodes in the 
future, right? Maybe we should use a set



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/RemoveDataNodeHandler.java:
##########
@@ -193,6 +201,136 @@ public List<RegionMigrationPlan> getRegionMigrationPlans(
     return regionMigrationPlans;
   }
 
+  /**
+   * Retrieves all region migration plans for the specified removed DataNodes 
and selects the
+   * destination.
+   *
+   * @param removedDataNodes the list of DataNodes from which to obtain 
migration plans
+   * @return a list of region migration plans associated with the removed 
DataNodes
+   */
+  public List<RegionMigrationPlan> selectedRegionMigrationPlans(
+      List<TDataNodeLocation> removedDataNodes) {
+
+    Set<Integer> removedDataNodesSet = new HashSet<>();
+    for (TDataNodeLocation removedDataNode : removedDataNodes) {
+      removedDataNodesSet.add(removedDataNode.dataNodeId);
+    }
+
+    final List<TDataNodeConfiguration> availableDataNodes =
+        configManager
+            .getNodeManager()
+            .filterDataNodeThroughStatus(NodeStatus.Running, 
NodeStatus.Unknown)
+            .stream()
+            .filter(node -> 
!removedDataNodesSet.contains(node.getLocation().getDataNodeId()))
+            .collect(Collectors.toList());
+
+    List<RegionMigrationPlan> regionMigrationPlans = new ArrayList<>();
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(availableDataNodes, 
TConsensusGroupType.DataRegion, removedDataNodes));
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(
+            availableDataNodes, TConsensusGroupType.SchemaRegion, 
removedDataNodes));
+
+    return regionMigrationPlans;
+  }
+
+  public List<RegionMigrationPlan> selectMigrationPlans(
+      List<TDataNodeConfiguration> availableDataNodes,
+      TConsensusGroupType consensusGroupType,
+      List<TDataNodeLocation> removedDataNodes) {
+    List<TRegionReplicaSet> allocatedRegionGroups =
+        
configManager.getPartitionManager().getAllReplicaSets(consensusGroupType);
+
+    Map<TConsensusGroupId, TDataNodeLocation> replicaSetRemoved = new 
HashMap<>();
+    List<TRegionReplicaSet> migratedReplicas = new ArrayList<>();
+
+    for (TDataNodeLocation dataNodeLocation : removedDataNodes) {
+      List<TRegionReplicaSet> replicaSets =
+          allocatedRegionGroups.stream()
+              .filter(replicaSet -> 
replicaSet.getDataNodeLocations().contains(dataNodeLocation))
+              .collect(Collectors.toList());
+      for (TRegionReplicaSet replicaSet : replicaSets) {
+        replicaSetRemoved.put(replicaSet.getRegionId(), dataNodeLocation);
+      }
+      migratedReplicas.addAll(replicaSets);
+    }
+
+    List<TRegionReplicaSet> remainReplicas = new ArrayList<>();
+
+    for (TRegionReplicaSet replicaSet : migratedReplicas) {
+      allocatedRegionGroups.remove(replicaSet);
+      List<TDataNodeLocation> dataNodeLocations = 
replicaSet.getDataNodeLocations();
+      
dataNodeLocations.remove(replicaSetRemoved.get(replicaSet.getRegionId()));
+      replicaSet.setDataNodeLocations(dataNodeLocations);

Review Comment:
   do we need to do this as you just remove it from 
`replicaSet.getDataNodeLocations()`



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/RemoveDataNodeHandler.java:
##########
@@ -193,6 +201,136 @@ public List<RegionMigrationPlan> getRegionMigrationPlans(
     return regionMigrationPlans;
   }
 
+  /**
+   * Retrieves all region migration plans for the specified removed DataNodes 
and selects the
+   * destination.
+   *
+   * @param removedDataNodes the list of DataNodes from which to obtain 
migration plans
+   * @return a list of region migration plans associated with the removed 
DataNodes
+   */
+  public List<RegionMigrationPlan> selectedRegionMigrationPlans(
+      List<TDataNodeLocation> removedDataNodes) {
+
+    Set<Integer> removedDataNodesSet = new HashSet<>();
+    for (TDataNodeLocation removedDataNode : removedDataNodes) {
+      removedDataNodesSet.add(removedDataNode.dataNodeId);
+    }
+
+    final List<TDataNodeConfiguration> availableDataNodes =
+        configManager
+            .getNodeManager()
+            .filterDataNodeThroughStatus(NodeStatus.Running, 
NodeStatus.Unknown)
+            .stream()
+            .filter(node -> 
!removedDataNodesSet.contains(node.getLocation().getDataNodeId()))
+            .collect(Collectors.toList());
+
+    List<RegionMigrationPlan> regionMigrationPlans = new ArrayList<>();
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(availableDataNodes, 
TConsensusGroupType.DataRegion, removedDataNodes));
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(
+            availableDataNodes, TConsensusGroupType.SchemaRegion, 
removedDataNodes));
+
+    return regionMigrationPlans;
+  }
+
+  public List<RegionMigrationPlan> selectMigrationPlans(
+      List<TDataNodeConfiguration> availableDataNodes,
+      TConsensusGroupType consensusGroupType,
+      List<TDataNodeLocation> removedDataNodes) {
+    List<TRegionReplicaSet> allocatedRegionGroups =
+        
configManager.getPartitionManager().getAllReplicaSets(consensusGroupType);
+
+    Map<TConsensusGroupId, TDataNodeLocation> replicaSetRemoved = new 
HashMap<>();
+    List<TRegionReplicaSet> migratedReplicas = new ArrayList<>();
+
+    for (TDataNodeLocation dataNodeLocation : removedDataNodes) {
+      List<TRegionReplicaSet> replicaSets =
+          allocatedRegionGroups.stream()
+              .filter(replicaSet -> 
replicaSet.getDataNodeLocations().contains(dataNodeLocation))
+              .collect(Collectors.toList());
+      for (TRegionReplicaSet replicaSet : replicaSets) {
+        replicaSetRemoved.put(replicaSet.getRegionId(), dataNodeLocation);

Review Comment:
   Is there a problem with removing multiple datanodes? Or have we passed the 
check so that removeDataNodes has at most one peer per region?



##########
iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/region/DestNodeSelectorTest.java:
##########
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.confignode.manager.load.balancer.region;
+
+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.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class DestNodeSelectorTest {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(DestNodeSelectorTest.class);
+
+  private static final IDestNodeSelector SELECTOR = new 
PartiteGraphPlacementDestNodeSelector();
+  private static final IRegionGroupAllocator ALLOCATOR = new 
GreedyCopySetRegionGroupAllocator();
+
+  private static final TDataNodeLocation REMOVE_DATANODE_LOCATION =
+      new TDataNodeLocation().setDataNodeId(5);
+  private static final int TEST_DATA_NODE_NUM = 5;
+  private static final int DATA_REGION_PER_DATA_NODE = 4;
+  private static final int DATA_REPLICATION_FACTOR = 2;
+
+  private static final Map<Integer, TDataNodeConfiguration> 
AVAILABLE_DATA_NODE_MAP =
+      new HashMap<>();
+  private static final Map<Integer, Double> FREE_SPACE_MAP = new HashMap<>();
+
+  @BeforeClass
+  public static void setUp() {
+    // Construct TEST_DATA_NODE_NUM DataNodes
+    for (int i = 1; i <= TEST_DATA_NODE_NUM; i++) {
+      AVAILABLE_DATA_NODE_MAP.put(
+          i, new TDataNodeConfiguration().setLocation(new 
TDataNodeLocation().setDataNodeId(i)));
+      FREE_SPACE_MAP.put(i, Math.random());
+    }
+  }
+
+  @Test
+  public void testSelectDestNode() {
+    final int dataRegionGroupNum =
+        DATA_REGION_PER_DATA_NODE * TEST_DATA_NODE_NUM / 
DATA_REPLICATION_FACTOR;
+
+    List<TRegionReplicaSet> allocateResult = new ArrayList<>();
+    for (int index = 0; index < dataRegionGroupNum; index++) {
+      allocateResult.add(
+          ALLOCATOR.generateOptimalRegionReplicasDistribution(
+              AVAILABLE_DATA_NODE_MAP,
+              FREE_SPACE_MAP,
+              allocateResult,
+              allocateResult,
+              DATA_REPLICATION_FACTOR,
+              new TConsensusGroupId(TConsensusGroupType.DataRegion, index)));
+    }
+    List<TRegionReplicaSet> migratedReplicas =
+        allocateResult.stream()
+            .filter(
+                replicaSet -> 
replicaSet.getDataNodeLocations().contains(REMOVE_DATANODE_LOCATION))
+            .collect(Collectors.toList());
+
+    AVAILABLE_DATA_NODE_MAP.remove(REMOVE_DATANODE_LOCATION.getDataNodeId());
+    FREE_SPACE_MAP.remove(REMOVE_DATANODE_LOCATION.getDataNodeId());
+
+    List<TRegionReplicaSet> remainReplicas = new ArrayList<>();
+
+    for (TRegionReplicaSet replicaSet : migratedReplicas) {
+      List<TDataNodeLocation> dataNodeLocations = 
replicaSet.getDataNodeLocations();
+      allocateResult.remove(replicaSet);
+      dataNodeLocations.remove(REMOVE_DATANODE_LOCATION);
+      replicaSet.setDataNodeLocations(dataNodeLocations);
+      allocateResult.add(replicaSet);
+      remainReplicas.add(replicaSet);
+    }
+
+    Set<Integer> selectedNodeIds = new HashSet<>();
+
+    for (TRegionReplicaSet remainReplicaSet : remainReplicas) {
+      TDataNodeConfiguration selectedNode =
+          SELECTOR.selectDestDataNode(
+              AVAILABLE_DATA_NODE_MAP,
+              FREE_SPACE_MAP,
+              allocateResult,
+              allocateResult,
+              DATA_REPLICATION_FACTOR,
+              remainReplicaSet.regionId,
+              remainReplicaSet);
+      LOGGER.info(
+          "Selected DataNode {} for Region {}",
+          selectedNode.getLocation().getDataNodeId(),
+          remainReplicaSet.regionId);
+      allocateResult.remove(remainReplicaSet);
+      List<TDataNodeLocation> dataNodeLocations = 
remainReplicaSet.getDataNodeLocations();
+      dataNodeLocations.add(selectedNode.getLocation());
+      remainReplicaSet.setDataNodeLocations(dataNodeLocations);
+      allocateResult.add(remainReplicaSet);
+      selectedNodeIds.add(selectedNode.getLocation().getDataNodeId());
+    }
+
+    Assert.assertEquals(TEST_DATA_NODE_NUM - 1, selectedNodeIds.size());

Review Comment:
   Should we calculate how many new regions are added to each node, whether 
they are balanced, and so on? Otherwise this is a little bit broad at the 
moment?
   
   maybe something like this
   <img width="1066" alt="image" 
src="https://github.com/user-attachments/assets/b9459f85-b4e6-41d3-a7e3-7482fa24fb2e";
 />
   
   
   <img width="1062" alt="image" 
src="https://github.com/user-attachments/assets/1ebbbcb5-b6ce-4b30-9b8c-79976d7739fd";
 />
   



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/RemoveDataNodeHandler.java:
##########
@@ -193,6 +201,136 @@ public List<RegionMigrationPlan> getRegionMigrationPlans(
     return regionMigrationPlans;
   }
 
+  /**
+   * Retrieves all region migration plans for the specified removed DataNodes 
and selects the
+   * destination.
+   *
+   * @param removedDataNodes the list of DataNodes from which to obtain 
migration plans
+   * @return a list of region migration plans associated with the removed 
DataNodes
+   */
+  public List<RegionMigrationPlan> selectedRegionMigrationPlans(
+      List<TDataNodeLocation> removedDataNodes) {
+
+    Set<Integer> removedDataNodesSet = new HashSet<>();
+    for (TDataNodeLocation removedDataNode : removedDataNodes) {
+      removedDataNodesSet.add(removedDataNode.dataNodeId);
+    }
+
+    final List<TDataNodeConfiguration> availableDataNodes =
+        configManager
+            .getNodeManager()
+            .filterDataNodeThroughStatus(NodeStatus.Running, 
NodeStatus.Unknown)
+            .stream()
+            .filter(node -> 
!removedDataNodesSet.contains(node.getLocation().getDataNodeId()))
+            .collect(Collectors.toList());
+
+    List<RegionMigrationPlan> regionMigrationPlans = new ArrayList<>();
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(availableDataNodes, 
TConsensusGroupType.DataRegion, removedDataNodes));
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(
+            availableDataNodes, TConsensusGroupType.SchemaRegion, 
removedDataNodes));
+
+    return regionMigrationPlans;
+  }
+
+  public List<RegionMigrationPlan> selectMigrationPlans(

Review Comment:
   maybe you can use gpt to refactor and improve the code here



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/region/PartiteGraphPlacementDestNodeSelector.java:
##########
@@ -0,0 +1,166 @@
+/*
+ * 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.region;
+
+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 
org.apache.iotdb.confignode.manager.load.balancer.region.GreedyRegionGroupAllocator.DataNodeEntry;
+
+import org.apache.tsfile.utils.Pair;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+public class PartiteGraphPlacementDestNodeSelector implements 
IDestNodeSelector {
+  private int replicationFactor;
+
+  private int dataNodeNum;
+  // The number of allocated Regions in each DataNode
+  private int[] regionCounter;
+  // The number of edges in current cluster
+  private int[][] combinationCounter;
+  private Map<Integer, Integer> fakeToRealIdMap;
+  private Map<Integer, Integer> realToFakeIdMap;
+
+  private Set<Integer> remainDataNodesFakeId;
+
+  // Pair<combinationSum, RegionSum>
+  Pair<Integer, Integer> bestValue;
+
+  private Integer targetDataNode = -1;
+
+  @Override
+  public TDataNodeConfiguration selectDestDataNode(
+      Map<Integer, TDataNodeConfiguration> availableDataNodeMap,
+      Map<Integer, Double> freeDiskSpaceMap,
+      List<TRegionReplicaSet> allocatedRegionGroups,
+      List<TRegionReplicaSet> databaseAllocatedRegionGroups,
+      int replicationFactor,
+      TConsensusGroupId consensusGroupId,
+      TRegionReplicaSet remainReplicaSet) {
+    prepare(replicationFactor, availableDataNodeMap, allocatedRegionGroups, 
remainReplicaSet);
+
+    searchTargetDataNode(freeDiskSpaceMap);
+
+    return availableDataNodeMap.get(fakeToRealIdMap.get(targetDataNode));
+  }
+
+  private void prepare(
+      int replicationFactor,
+      Map<Integer, TDataNodeConfiguration> availableDataNodeMap,
+      List<TRegionReplicaSet> allocatedRegionGroups,
+      TRegionReplicaSet remainReplicaSet) {
+    this.replicationFactor = replicationFactor;
+    this.fakeToRealIdMap = new TreeMap<>();
+    this.realToFakeIdMap = new TreeMap<>();
+    this.dataNodeNum = availableDataNodeMap.size();
+    List<Integer> dataNodeIdList =
+        availableDataNodeMap.values().stream()
+            .map(c -> c.getLocation().getDataNodeId())
+            .collect(Collectors.toList());
+    for (int i = 0; i < dataNodeNum; i++) {
+      fakeToRealIdMap.put(i, dataNodeIdList.get(i));
+      realToFakeIdMap.put(dataNodeIdList.get(i), i);
+    }
+
+    remainDataNodesFakeId =
+        remainReplicaSet.dataNodeLocations.stream()
+            .map(TDataNodeLocation::getDataNodeId)
+            .map(realToFakeIdMap::get)
+            .collect(Collectors.toSet());
+
+    // Compute regionCounter and combinationCounter
+    this.regionCounter = new int[dataNodeNum];
+    Arrays.fill(regionCounter, 0);
+    this.combinationCounter = new int[dataNodeNum][dataNodeNum];
+    for (int i = 0; i < dataNodeNum; i++) {
+      Arrays.fill(combinationCounter[i], 0);
+    }
+    for (TRegionReplicaSet regionReplicaSet : allocatedRegionGroups) {
+      List<TDataNodeLocation> dataNodeLocations = 
regionReplicaSet.getDataNodeLocations();
+      for (int i = 0; i < dataNodeLocations.size(); i++) {
+        int fakeIId = 
realToFakeIdMap.get(dataNodeLocations.get(i).getDataNodeId());
+        regionCounter[fakeIId]++;
+        for (int j = i + 1; j < dataNodeLocations.size(); j++) {
+          int fakeJId = 
realToFakeIdMap.get(dataNodeLocations.get(j).getDataNodeId());
+          combinationCounter[fakeIId][fakeJId] = 1;
+          combinationCounter[fakeJId][fakeIId] = 1;
+        }
+      }
+    }
+
+    this.bestValue = new Pair<>(Integer.MAX_VALUE, Integer.MAX_VALUE);
+  }
+
+  private void searchTargetDataNode(Map<Integer, Double> freeDiskSpaceMap) {
+    List<DataNodeEntry> entryList = new ArrayList<>();
+
+    for (int i = 0; i < dataNodeNum; i++) {
+      if (remainDataNodesFakeId.contains(i)) {
+        continue;
+      }
+      entryList.add(
+          new DataNodeEntry(i, regionCounter[i], 
freeDiskSpaceMap.get(fakeToRealIdMap.get(i))));
+    }
+    Collections.sort(entryList);
+
+    int[] alternativeReplica = new int[replicationFactor];
+
+    int pos = 0;
+    for (Integer integer : remainDataNodesFakeId) {
+      alternativeReplica[pos] = integer;

Review Comment:
   It is desirable to add some protection mechanisms to improve robustness in 
future scenarios where the number of replicas can change dynamically



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/env/RemoveDataNodeHandler.java:
##########
@@ -193,6 +201,136 @@ public List<RegionMigrationPlan> getRegionMigrationPlans(
     return regionMigrationPlans;
   }
 
+  /**
+   * Retrieves all region migration plans for the specified removed DataNodes 
and selects the
+   * destination.
+   *
+   * @param removedDataNodes the list of DataNodes from which to obtain 
migration plans
+   * @return a list of region migration plans associated with the removed 
DataNodes
+   */
+  public List<RegionMigrationPlan> selectedRegionMigrationPlans(
+      List<TDataNodeLocation> removedDataNodes) {
+
+    Set<Integer> removedDataNodesSet = new HashSet<>();
+    for (TDataNodeLocation removedDataNode : removedDataNodes) {
+      removedDataNodesSet.add(removedDataNode.dataNodeId);
+    }
+
+    final List<TDataNodeConfiguration> availableDataNodes =
+        configManager
+            .getNodeManager()
+            .filterDataNodeThroughStatus(NodeStatus.Running, 
NodeStatus.Unknown)
+            .stream()
+            .filter(node -> 
!removedDataNodesSet.contains(node.getLocation().getDataNodeId()))
+            .collect(Collectors.toList());
+
+    List<RegionMigrationPlan> regionMigrationPlans = new ArrayList<>();
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(availableDataNodes, 
TConsensusGroupType.DataRegion, removedDataNodes));
+
+    regionMigrationPlans.addAll(
+        selectMigrationPlans(
+            availableDataNodes, TConsensusGroupType.SchemaRegion, 
removedDataNodes));
+
+    return regionMigrationPlans;
+  }
+
+  public List<RegionMigrationPlan> selectMigrationPlans(
+      List<TDataNodeConfiguration> availableDataNodes,
+      TConsensusGroupType consensusGroupType,
+      List<TDataNodeLocation> removedDataNodes) {
+    List<TRegionReplicaSet> allocatedRegionGroups =
+        
configManager.getPartitionManager().getAllReplicaSets(consensusGroupType);
+
+    Map<TConsensusGroupId, TDataNodeLocation> replicaSetRemoved = new 
HashMap<>();
+    List<TRegionReplicaSet> migratedReplicas = new ArrayList<>();
+
+    for (TDataNodeLocation dataNodeLocation : removedDataNodes) {
+      List<TRegionReplicaSet> replicaSets =
+          allocatedRegionGroups.stream()
+              .filter(replicaSet -> 
replicaSet.getDataNodeLocations().contains(dataNodeLocation))
+              .collect(Collectors.toList());
+      for (TRegionReplicaSet replicaSet : replicaSets) {
+        replicaSetRemoved.put(replicaSet.getRegionId(), dataNodeLocation);
+      }
+      migratedReplicas.addAll(replicaSets);
+    }
+
+    List<TRegionReplicaSet> remainReplicas = new ArrayList<>();
+
+    for (TRegionReplicaSet replicaSet : migratedReplicas) {
+      allocatedRegionGroups.remove(replicaSet);
+      List<TDataNodeLocation> dataNodeLocations = 
replicaSet.getDataNodeLocations();
+      
dataNodeLocations.remove(replicaSetRemoved.get(replicaSet.getRegionId()));
+      replicaSet.setDataNodeLocations(dataNodeLocations);
+      allocatedRegionGroups.add(replicaSet);
+      remainReplicas.add(replicaSet);
+    }
+
+    List<RegionMigrationPlan> regionMigrationPlans = new ArrayList<>();
+
+    for (TRegionReplicaSet remainReplicaSet : remainReplicas) {
+      final Map<Integer, TDataNodeConfiguration> availableDataNodeMap =
+          new HashMap<>(availableDataNodes.size());
+      final Map<Integer, Double> freeDiskSpaceMap = new 
HashMap<>(availableDataNodes.size());
+      availableDataNodes.forEach(
+          dataNodeConfiguration -> {
+            int dataNodeId = 
dataNodeConfiguration.getLocation().getDataNodeId();
+            availableDataNodeMap.put(dataNodeId, dataNodeConfiguration);
+            freeDiskSpaceMap.put(
+                dataNodeId, 
configManager.getLoadManager().getFreeDiskSpace(dataNodeId));
+          });
+      String database =
+          
configManager.getPartitionManager().getRegionDatabase(remainReplicaSet.getRegionId());
+
+      List<TRegionReplicaSet> databaseAllocatedRegionGroups =
+          configManager.getPartitionManager().getAllReplicaSets(database, 
consensusGroupType);
+      int replicationFactor;
+      try {
+        replicationFactor =
+            configManager
+                .getClusterSchemaManager()
+                .getReplicationFactor(database, consensusGroupType);
+      } catch (DatabaseNotExistsException e) {
+        LOGGER.error(
+            "Region {} 's database: {} not exists, use default value.",
+            remainReplicaSet.regionId,
+            database,
+            e);
+        replicationFactor =
+            consensusGroupType.equals(TConsensusGroupType.DataRegion)
+                ? 
ConfigNodeDescriptor.getInstance().getConf().getDataReplicationFactor()
+                : 
ConfigNodeDescriptor.getInstance().getConf().getSchemaReplicationFactor();
+      }
+
+      TDataNodeConfiguration selectedDestDataNode =
+          destNodeSelector.selectDestDataNode(
+              availableDataNodeMap,
+              freeDiskSpaceMap,
+              allocatedRegionGroups,
+              databaseAllocatedRegionGroups,
+              replicationFactor,
+              remainReplicaSet.regionId,
+              remainReplicaSet);
+      LOGGER.info(
+          "Selected DataNode {} for Region {}",
+          selectedDestDataNode.getLocation().getDataNodeId(),
+          remainReplicaSet.regionId);
+      allocatedRegionGroups.remove(remainReplicaSet);
+      List<TDataNodeLocation> dataNodeLocations = 
remainReplicaSet.getDataNodeLocations();
+      dataNodeLocations.add(selectedDestDataNode.getLocation());
+      remainReplicaSet.setDataNodeLocations(dataNodeLocations);

Review Comment:
   same as above



##########
iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/region/DestNodeSelectorTest.java:
##########
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.confignode.manager.load.balancer.region;
+
+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.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class DestNodeSelectorTest {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(DestNodeSelectorTest.class);
+
+  private static final IDestNodeSelector SELECTOR = new 
PartiteGraphPlacementDestNodeSelector();
+  private static final IRegionGroupAllocator ALLOCATOR = new 
GreedyCopySetRegionGroupAllocator();
+
+  private static final TDataNodeLocation REMOVE_DATANODE_LOCATION =
+      new TDataNodeLocation().setDataNodeId(5);
+  private static final int TEST_DATA_NODE_NUM = 5;
+  private static final int DATA_REGION_PER_DATA_NODE = 4;
+  private static final int DATA_REPLICATION_FACTOR = 2;
+
+  private static final Map<Integer, TDataNodeConfiguration> 
AVAILABLE_DATA_NODE_MAP =
+      new HashMap<>();
+  private static final Map<Integer, Double> FREE_SPACE_MAP = new HashMap<>();
+
+  @BeforeClass
+  public static void setUp() {
+    // Construct TEST_DATA_NODE_NUM DataNodes
+    for (int i = 1; i <= TEST_DATA_NODE_NUM; i++) {
+      AVAILABLE_DATA_NODE_MAP.put(
+          i, new TDataNodeConfiguration().setLocation(new 
TDataNodeLocation().setDataNodeId(i)));
+      FREE_SPACE_MAP.put(i, Math.random());
+    }
+  }
+
+  @Test
+  public void testSelectDestNode() {
+    final int dataRegionGroupNum =
+        DATA_REGION_PER_DATA_NODE * TEST_DATA_NODE_NUM / 
DATA_REPLICATION_FACTOR;
+
+    List<TRegionReplicaSet> allocateResult = new ArrayList<>();
+    for (int index = 0; index < dataRegionGroupNum; index++) {
+      allocateResult.add(
+          ALLOCATOR.generateOptimalRegionReplicasDistribution(
+              AVAILABLE_DATA_NODE_MAP,
+              FREE_SPACE_MAP,
+              allocateResult,
+              allocateResult,
+              DATA_REPLICATION_FACTOR,
+              new TConsensusGroupId(TConsensusGroupType.DataRegion, index)));
+    }
+    List<TRegionReplicaSet> migratedReplicas =
+        allocateResult.stream()
+            .filter(
+                replicaSet -> 
replicaSet.getDataNodeLocations().contains(REMOVE_DATANODE_LOCATION))
+            .collect(Collectors.toList());
+
+    AVAILABLE_DATA_NODE_MAP.remove(REMOVE_DATANODE_LOCATION.getDataNodeId());
+    FREE_SPACE_MAP.remove(REMOVE_DATANODE_LOCATION.getDataNodeId());
+
+    List<TRegionReplicaSet> remainReplicas = new ArrayList<>();
+
+    for (TRegionReplicaSet replicaSet : migratedReplicas) {
+      List<TDataNodeLocation> dataNodeLocations = 
replicaSet.getDataNodeLocations();
+      allocateResult.remove(replicaSet);
+      dataNodeLocations.remove(REMOVE_DATANODE_LOCATION);
+      replicaSet.setDataNodeLocations(dataNodeLocations);

Review Comment:
   duplicated?



##########
iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/load/balancer/region/PartiteGraphPlacementDestNodeSelector.java:
##########
@@ -0,0 +1,166 @@
+/*
+ * 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.region;
+
+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 
org.apache.iotdb.confignode.manager.load.balancer.region.GreedyRegionGroupAllocator.DataNodeEntry;
+
+import org.apache.tsfile.utils.Pair;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+public class PartiteGraphPlacementDestNodeSelector implements 
IDestNodeSelector {
+  private int replicationFactor;
+
+  private int dataNodeNum;
+  // The number of allocated Regions in each DataNode
+  private int[] regionCounter;
+  // The number of edges in current cluster
+  private int[][] combinationCounter;
+  private Map<Integer, Integer> fakeToRealIdMap;
+  private Map<Integer, Integer> realToFakeIdMap;
+
+  private Set<Integer> remainDataNodesFakeId;
+
+  // Pair<combinationSum, RegionSum>
+  Pair<Integer, Integer> bestValue;
+
+  private Integer targetDataNode = -1;
+
+  @Override
+  public TDataNodeConfiguration selectDestDataNode(
+      Map<Integer, TDataNodeConfiguration> availableDataNodeMap,
+      Map<Integer, Double> freeDiskSpaceMap,
+      List<TRegionReplicaSet> allocatedRegionGroups,
+      List<TRegionReplicaSet> databaseAllocatedRegionGroups,
+      int replicationFactor,
+      TConsensusGroupId consensusGroupId,
+      TRegionReplicaSet remainReplicaSet) {
+    prepare(replicationFactor, availableDataNodeMap, allocatedRegionGroups, 
remainReplicaSet);
+
+    searchTargetDataNode(freeDiskSpaceMap);
+
+    return availableDataNodeMap.get(fakeToRealIdMap.get(targetDataNode));
+  }
+
+  private void prepare(
+      int replicationFactor,
+      Map<Integer, TDataNodeConfiguration> availableDataNodeMap,
+      List<TRegionReplicaSet> allocatedRegionGroups,
+      TRegionReplicaSet remainReplicaSet) {
+    this.replicationFactor = replicationFactor;
+    this.fakeToRealIdMap = new TreeMap<>();
+    this.realToFakeIdMap = new TreeMap<>();
+    this.dataNodeNum = availableDataNodeMap.size();
+    List<Integer> dataNodeIdList =
+        availableDataNodeMap.values().stream()
+            .map(c -> c.getLocation().getDataNodeId())
+            .collect(Collectors.toList());
+    for (int i = 0; i < dataNodeNum; i++) {
+      fakeToRealIdMap.put(i, dataNodeIdList.get(i));
+      realToFakeIdMap.put(dataNodeIdList.get(i), i);
+    }
+
+    remainDataNodesFakeId =
+        remainReplicaSet.dataNodeLocations.stream()
+            .map(TDataNodeLocation::getDataNodeId)
+            .map(realToFakeIdMap::get)
+            .collect(Collectors.toSet());
+
+    // Compute regionCounter and combinationCounter
+    this.regionCounter = new int[dataNodeNum];
+    Arrays.fill(regionCounter, 0);
+    this.combinationCounter = new int[dataNodeNum][dataNodeNum];
+    for (int i = 0; i < dataNodeNum; i++) {
+      Arrays.fill(combinationCounter[i], 0);
+    }
+    for (TRegionReplicaSet regionReplicaSet : allocatedRegionGroups) {
+      List<TDataNodeLocation> dataNodeLocations = 
regionReplicaSet.getDataNodeLocations();
+      for (int i = 0; i < dataNodeLocations.size(); i++) {
+        int fakeIId = 
realToFakeIdMap.get(dataNodeLocations.get(i).getDataNodeId());
+        regionCounter[fakeIId]++;
+        for (int j = i + 1; j < dataNodeLocations.size(); j++) {
+          int fakeJId = 
realToFakeIdMap.get(dataNodeLocations.get(j).getDataNodeId());
+          combinationCounter[fakeIId][fakeJId] = 1;
+          combinationCounter[fakeJId][fakeIId] = 1;
+        }
+      }
+    }
+
+    this.bestValue = new Pair<>(Integer.MAX_VALUE, Integer.MAX_VALUE);
+  }
+
+  private void searchTargetDataNode(Map<Integer, Double> freeDiskSpaceMap) {
+    List<DataNodeEntry> entryList = new ArrayList<>();
+
+    for (int i = 0; i < dataNodeNum; i++) {
+      if (remainDataNodesFakeId.contains(i)) {
+        continue;
+      }
+      entryList.add(
+          new DataNodeEntry(i, regionCounter[i], 
freeDiskSpaceMap.get(fakeToRealIdMap.get(i))));
+    }
+    Collections.sort(entryList);
+
+    int[] alternativeReplica = new int[replicationFactor];
+
+    int pos = 0;
+    for (Integer integer : remainDataNodesFakeId) {
+      alternativeReplica[pos] = integer;
+      pos++;
+    }
+
+    double minFreeDiskSpace = entryList.get(0).freeDiskSpace;
+    for (DataNodeEntry dataNodeEntry : entryList) {
+      if (dataNodeEntry.freeDiskSpace > minFreeDiskSpace) {
+        break;
+      }
+      alternativeReplica[replicationFactor - 1] = dataNodeEntry.dataNodeId;
+      Pair<Integer, Integer> currentValue = valuation(alternativeReplica);

Review Comment:
   So should we consider the number of regions first instead of divergence?



##########
iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/manager/load/balancer/region/DestNodeSelectorTest.java:
##########
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.iotdb.confignode.manager.load.balancer.region;
+
+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.BeforeClass;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+public class DestNodeSelectorTest {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(DestNodeSelectorTest.class);
+
+  private static final IDestNodeSelector SELECTOR = new 
PartiteGraphPlacementDestNodeSelector();
+  private static final IRegionGroupAllocator ALLOCATOR = new 
GreedyCopySetRegionGroupAllocator();
+
+  private static final TDataNodeLocation REMOVE_DATANODE_LOCATION =
+      new TDataNodeLocation().setDataNodeId(5);
+  private static final int TEST_DATA_NODE_NUM = 5;
+  private static final int DATA_REGION_PER_DATA_NODE = 4;
+  private static final int DATA_REPLICATION_FACTOR = 2;
+
+  private static final Map<Integer, TDataNodeConfiguration> 
AVAILABLE_DATA_NODE_MAP =
+      new HashMap<>();
+  private static final Map<Integer, Double> FREE_SPACE_MAP = new HashMap<>();
+
+  @BeforeClass
+  public static void setUp() {
+    // Construct TEST_DATA_NODE_NUM DataNodes
+    for (int i = 1; i <= TEST_DATA_NODE_NUM; i++) {
+      AVAILABLE_DATA_NODE_MAP.put(
+          i, new TDataNodeConfiguration().setLocation(new 
TDataNodeLocation().setDataNodeId(i)));
+      FREE_SPACE_MAP.put(i, Math.random());
+    }
+  }
+
+  @Test
+  public void testSelectDestNode() {
+    final int dataRegionGroupNum =
+        DATA_REGION_PER_DATA_NODE * TEST_DATA_NODE_NUM / 
DATA_REPLICATION_FACTOR;
+
+    List<TRegionReplicaSet> allocateResult = new ArrayList<>();
+    for (int index = 0; index < dataRegionGroupNum; index++) {
+      allocateResult.add(
+          ALLOCATOR.generateOptimalRegionReplicasDistribution(
+              AVAILABLE_DATA_NODE_MAP,
+              FREE_SPACE_MAP,
+              allocateResult,
+              allocateResult,
+              DATA_REPLICATION_FACTOR,
+              new TConsensusGroupId(TConsensusGroupType.DataRegion, index)));
+    }
+    List<TRegionReplicaSet> migratedReplicas =
+        allocateResult.stream()
+            .filter(
+                replicaSet -> 
replicaSet.getDataNodeLocations().contains(REMOVE_DATANODE_LOCATION))
+            .collect(Collectors.toList());
+
+    AVAILABLE_DATA_NODE_MAP.remove(REMOVE_DATANODE_LOCATION.getDataNodeId());
+    FREE_SPACE_MAP.remove(REMOVE_DATANODE_LOCATION.getDataNodeId());
+
+    List<TRegionReplicaSet> remainReplicas = new ArrayList<>();
+
+    for (TRegionReplicaSet replicaSet : migratedReplicas) {
+      List<TDataNodeLocation> dataNodeLocations = 
replicaSet.getDataNodeLocations();
+      allocateResult.remove(replicaSet);
+      dataNodeLocations.remove(REMOVE_DATANODE_LOCATION);
+      replicaSet.setDataNodeLocations(dataNodeLocations);
+      allocateResult.add(replicaSet);
+      remainReplicas.add(replicaSet);
+    }
+
+    Set<Integer> selectedNodeIds = new HashSet<>();
+
+    for (TRegionReplicaSet remainReplicaSet : remainReplicas) {
+      TDataNodeConfiguration selectedNode =
+          SELECTOR.selectDestDataNode(
+              AVAILABLE_DATA_NODE_MAP,
+              FREE_SPACE_MAP,
+              allocateResult,
+              allocateResult,
+              DATA_REPLICATION_FACTOR,
+              remainReplicaSet.regionId,
+              remainReplicaSet);
+      LOGGER.info(
+          "Selected DataNode {} for Region {}",
+          selectedNode.getLocation().getDataNodeId(),
+          remainReplicaSet.regionId);
+      allocateResult.remove(remainReplicaSet);
+      List<TDataNodeLocation> dataNodeLocations = 
remainReplicaSet.getDataNodeLocations();
+      dataNodeLocations.add(selectedNode.getLocation());
+      remainReplicaSet.setDataNodeLocations(dataNodeLocations);

Review Comment:
   duplicated?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to