001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.master.balancer;
019
020import java.util.concurrent.ThreadLocalRandom;
021import org.apache.yetus.audience.InterfaceAudience;
022
023/**
024 * Generates candidates which moves the replicas out of the rack for co-hosted region replicas in
025 * the same rack
026 */
027@InterfaceAudience.Private
028class RegionReplicaRackCandidateGenerator extends RegionReplicaCandidateGenerator {
029
030  @Override
031  BalanceAction generate(BalancerClusterState cluster) {
032    int rackIndex = pickRandomRack(cluster);
033    if (cluster.numRacks <= 1 || rackIndex == -1) {
034      return super.generate(cluster);
035    }
036
037    int regionIndex = selectCoHostedRegionPerGroup(cluster.colocatedReplicaCountsPerRack[rackIndex],
038      cluster.regionsPerRack[rackIndex], cluster.regionIndexToPrimaryIndex);
039
040    // if there are no pairs of region replicas co-hosted, default to random generator
041    if (regionIndex == -1) {
042      // default to randompicker
043      return randomGenerator.generate(cluster);
044    }
045
046    int serverIndex = cluster.regionIndexToServerIndex[regionIndex];
047    int toRackIndex = pickOtherRandomRack(cluster, rackIndex);
048
049    int rand = ThreadLocalRandom.current().nextInt(cluster.serversPerRack[toRackIndex].length);
050    int toServerIndex = cluster.serversPerRack[toRackIndex][rand];
051    int toRegionIndex = pickRandomRegion(cluster, toServerIndex, 0.9f);
052    return getAction(serverIndex, regionIndex, toServerIndex, toRegionIndex);
053  }
054}