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 */
018
019package org.apache.hadoop.hbase.chaos.actions;
020
021import java.util.ArrayList;
022import java.util.LinkedList;
023import java.util.List;
024import org.apache.commons.lang3.RandomUtils;
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
040   * some regions 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 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 LinkedList<>(status.getLiveServerMetrics().keySet());
058    int targetServerCount = (int)Math.ceil(fractionOfServers * victimServers.size());
059    List<ServerName> targetServers = new ArrayList<>(targetServerCount);
060    for (int i = 0; i < targetServerCount; ++i) {
061      int victimIx = RandomUtils.nextInt(0, victimServers.size());
062      targetServers.add(victimServers.remove(victimIx));
063    }
064    unbalanceRegions(status, victimServers, targetServers, fractionOfRegions);
065  }
066}