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.chaos.actions;
019
020import java.util.ArrayList;
021import java.util.List;
022import java.util.Random;
023import java.util.concurrent.ThreadLocalRandom;
024import org.apache.hadoop.hbase.ClusterMetrics;
025import org.apache.hadoop.hbase.ServerName;
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029/**
030 * Action that tries to unbalance the regions of a cluster.
031 */
032public class UnbalanceRegionsAction extends Action {
033  private static final Logger LOG = LoggerFactory.getLogger(UnbalanceRegionsAction.class);
034  private final double fractionOfRegions;
035  private final double fractionOfServers;
036
037  /**
038   * Unbalances the regions on the cluster by choosing "target" servers, and moving some regions
039   * from each of the non-target servers to random target servers.
040   * @param fractionOfRegions Fraction of regions to move from each server.
041   * @param fractionOfServers Fraction of servers to be chosen as targets.
042   */
043  public UnbalanceRegionsAction(double fractionOfRegions, double fractionOfServers) {
044    this.fractionOfRegions = fractionOfRegions;
045    this.fractionOfServers = fractionOfServers;
046  }
047
048  @Override
049  protected Logger getLogger() {
050    return LOG;
051  }
052
053  @Override
054  public void perform() throws Exception {
055    getLogger().info("Unbalancing regions");
056    ClusterMetrics status = this.cluster.getClusterMetrics();
057    List<ServerName> victimServers = new ArrayList<>(status.getLiveServerMetrics().keySet());
058    int targetServerCount = (int) Math.ceil(fractionOfServers * victimServers.size());
059    List<ServerName> targetServers = new ArrayList<>(targetServerCount);
060    Random rand = ThreadLocalRandom.current();
061    for (int i = 0; i < targetServerCount; ++i) {
062      int victimIx = rand.nextInt(victimServers.size());
063      targetServers.add(victimServers.remove(victimIx));
064    }
065    unbalanceRegions(status, victimServers, targetServers, fractionOfRegions);
066  }
067}