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  @Override
030  BalanceAction generate(BalancerClusterState cluster) {
031    int rackIndex = pickRandomRack(cluster);
032    if (cluster.numRacks <= 1 || rackIndex == -1) {
033      return super.generate(cluster);
034    }
035
036    int regionIndex = selectCoHostedRegionPerGroup(cluster.colocatedReplicaCountsPerRack[rackIndex],
037      cluster.regionsPerRack[rackIndex], cluster.regionIndexToPrimaryIndex);
038
039    // if there are no pairs of region replicas co-hosted, default to random generator
040    if (regionIndex == -1) {
041      // default to randompicker
042      return randomGenerator.generate(cluster);
043    }
044
045    int serverIndex = cluster.regionIndexToServerIndex[regionIndex];
046    int toRackIndex = pickOtherRandomRack(cluster, rackIndex);
047
048    int rand = ThreadLocalRandom.current().nextInt(cluster.serversPerRack[toRackIndex].length);
049    int toServerIndex = cluster.serversPerRack[toRackIndex][rand];
050    int toRegionIndex = pickRandomRegion(cluster, toServerIndex, 0.9f);
051    return getAction(serverIndex, regionIndex, toServerIndex, toRegionIndex);
052  }
053}