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