View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.master.balancer;
19  
20  import com.google.common.annotations.VisibleForTesting;
21  import java.util.ArrayDeque;
22  import java.util.ArrayList;
23  import java.util.Arrays;
24  import java.util.Collection;
25  import java.util.Collections;
26  import java.util.Deque;
27  import java.util.HashMap;
28  import java.util.LinkedList;
29  import java.util.List;
30  import java.util.Map;
31  import java.util.Map.Entry;
32  import java.util.Random;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.hbase.classification.InterfaceAudience;
37  import org.apache.hadoop.conf.Configuration;
38  import org.apache.hadoop.hbase.ClusterStatus;
39  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
40  import org.apache.hadoop.hbase.HConstants;
41  import org.apache.hadoop.hbase.HRegionInfo;
42  import org.apache.hadoop.hbase.RegionLoad;
43  import org.apache.hadoop.hbase.ServerLoad;
44  import org.apache.hadoop.hbase.ServerName;
45  import org.apache.hadoop.hbase.TableName;
46  import org.apache.hadoop.hbase.master.MasterServices;
47  import org.apache.hadoop.hbase.master.RegionPlan;
48  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer.Cluster.Action;
49  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer.Cluster.Action.Type;
50  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer.Cluster.AssignRegionAction;
51  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer.Cluster.LocalityType;
52  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer.Cluster.MoveRegionAction;
53  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer.Cluster.SwapRegionsAction;
54  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
55  
56  import com.google.common.base.Optional;
57  
58  /**
59   * <p>This is a best effort load balancer. Given a Cost function F(C) =&gt; x It will
60   * randomly try and mutate the cluster to Cprime. If F(Cprime) &lt; F(C) then the
61   * new cluster state becomes the plan. It includes costs functions to compute the cost of:</p>
62   * <ul>
63   * <li>Region Load</li>
64   * <li>Table Load</li>
65   * <li>Data Locality</li>
66   * <li>Memstore Sizes</li>
67   * <li>Storefile Sizes</li>
68   * </ul>
69   *
70   *
71   * <p>Every cost function returns a number between 0 and 1 inclusive; where 0 is the lowest cost
72   * best solution, and 1 is the highest possible cost and the worst solution.  The computed costs are
73   * scaled by their respective multipliers:</p>
74   *
75   * <ul>
76   *   <li>hbase.master.balancer.stochastic.regionLoadCost</li>
77   *   <li>hbase.master.balancer.stochastic.moveCost</li>
78   *   <li>hbase.master.balancer.stochastic.tableLoadCost</li>
79   *   <li>hbase.master.balancer.stochastic.localityCost</li>
80   *   <li>hbase.master.balancer.stochastic.memstoreSizeCost</li>
81   *   <li>hbase.master.balancer.stochastic.storefileSizeCost</li>
82   * </ul>
83   *
84   * <p>In addition to the above configurations, the balancer can be tuned by the following
85   * configuration values:</p>
86   * <ul>
87   *   <li>hbase.master.balancer.stochastic.maxMoveRegions which
88   *   controls what the max number of regions that can be moved in a single invocation of this
89   *   balancer.</li>
90   *   <li>hbase.master.balancer.stochastic.stepsPerRegion is the coefficient by which the number of
91   *   regions is multiplied to try and get the number of times the balancer will
92   *   mutate all servers.</li>
93   *   <li>hbase.master.balancer.stochastic.maxSteps which controls the maximum number of times that
94   *   the balancer will try and mutate all the servers. The balancer will use the minimum of this
95   *   value and the above computation.</li>
96   * </ul>
97   *
98   * <p>This balancer is best used with hbase.master.loadbalance.bytable set to false
99   * so that the balancer gets the full picture of all loads on the cluster.</p>
100  */
101 @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
102 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="IS2_INCONSISTENT_SYNC",
103   justification="Complaint is about costFunctions not being synchronized; not end of the world")
104 public class StochasticLoadBalancer extends BaseLoadBalancer {
105 
106   protected static final String STEPS_PER_REGION_KEY =
107       "hbase.master.balancer.stochastic.stepsPerRegion";
108   protected static final String MAX_STEPS_KEY =
109       "hbase.master.balancer.stochastic.maxSteps";
110   protected static final String RUN_MAX_STEPS_KEY =
111       "hbase.master.balancer.stochastic.runMaxSteps";
112   protected static final String MAX_RUNNING_TIME_KEY =
113       "hbase.master.balancer.stochastic.maxRunningTime";
114   protected static final String KEEP_REGION_LOADS =
115       "hbase.master.balancer.stochastic.numRegionLoadsToRemember";
116   private static final String TABLE_FUNCTION_SEP = "_";
117   protected static final String MIN_COST_NEED_BALANCE_KEY =
118       "hbase.master.balancer.stochastic.minCostNeedBalance";
119 
120   private static final Random RANDOM = new Random(System.currentTimeMillis());
121   private static final Log LOG = LogFactory.getLog(StochasticLoadBalancer.class);
122 
123   Map<String, Deque<RegionLoad>> loads = new HashMap<String, Deque<RegionLoad>>();
124 
125   // values are defaults
126   private int maxSteps = 1000000;
127   private boolean runMaxSteps = false;
128   private int stepsPerRegion = 800;
129   private long maxRunningTime = 30 * 1000 * 1; // 30 seconds.
130   private int numRegionLoadsToRemember = 15;
131   private float minCostNeedBalance = 0.05f;
132 
133   private CandidateGenerator[] candidateGenerators;
134   private CostFromRegionLoadFunction[] regionLoadFunctions;
135   private CostFunction[] costFunctions; // FindBugs: Wants this protected; IS2_INCONSISTENT_SYNC
136 
137   // to save and report costs to JMX
138   private Double curOverallCost = 0d;
139   private Double[] tempFunctionCosts;
140   private Double[] curFunctionCosts;
141 
142   // Keep locality based picker and cost function to alert them
143   // when new services are offered
144   private LocalityBasedCandidateGenerator localityCandidateGenerator;
145   private ServerLocalityCostFunction localityCost;
146   private RackLocalityCostFunction rackLocalityCost;
147   private RegionReplicaHostCostFunction regionReplicaHostCostFunction;
148   private RegionReplicaRackCostFunction regionReplicaRackCostFunction;
149   private boolean isByTable = false;
150   private TableName tableName = null;
151 
152   /**
153    * The constructor that pass a MetricsStochasticBalancer to BaseLoadBalancer to replace its
154    * default MetricsBalancer
155    */
156   public StochasticLoadBalancer() {
157     super(new MetricsStochasticBalancer());
158   }
159 
160   @Override
161   public void onConfigurationChange(Configuration conf) {
162     setConf(conf);
163   }
164 
165   @Override
166   public synchronized void setConf(Configuration conf) {
167     super.setConf(conf);
168     LOG.info("loading config");
169 
170     maxSteps = conf.getInt(MAX_STEPS_KEY, maxSteps);
171 
172     stepsPerRegion = conf.getInt(STEPS_PER_REGION_KEY, stepsPerRegion);
173     maxRunningTime = conf.getLong(MAX_RUNNING_TIME_KEY, maxRunningTime);
174     runMaxSteps = conf.getBoolean(RUN_MAX_STEPS_KEY, runMaxSteps);
175 
176     numRegionLoadsToRemember = conf.getInt(KEEP_REGION_LOADS, numRegionLoadsToRemember);
177     isByTable = conf.getBoolean(HConstants.HBASE_MASTER_LOADBALANCE_BYTABLE, isByTable);
178 
179     minCostNeedBalance = conf.getFloat(MIN_COST_NEED_BALANCE_KEY, minCostNeedBalance);
180 
181     if (localityCandidateGenerator == null) {
182       localityCandidateGenerator = new LocalityBasedCandidateGenerator(services);
183     }
184     localityCost = new ServerLocalityCostFunction(conf, services);
185     rackLocalityCost = new RackLocalityCostFunction(conf, services);
186 
187     if (candidateGenerators == null) {
188       candidateGenerators = new CandidateGenerator[] {
189           new RandomCandidateGenerator(),
190           new LoadCandidateGenerator(),
191           localityCandidateGenerator,
192           new RegionReplicaRackCandidateGenerator(),
193       };
194     }
195 
196     regionLoadFunctions = new CostFromRegionLoadFunction[] {
197       new ReadRequestCostFunction(conf),
198       new WriteRequestCostFunction(conf),
199       new MemstoreSizeCostFunction(conf),
200       new StoreFileCostFunction(conf)
201     };
202 
203     regionReplicaHostCostFunction = new RegionReplicaHostCostFunction(conf);
204     regionReplicaRackCostFunction = new RegionReplicaRackCostFunction(conf);
205 
206     costFunctions = new CostFunction[]{
207       new RegionCountSkewCostFunction(conf),
208       new PrimaryRegionCountSkewCostFunction(conf),
209       new MoveCostFunction(conf),
210       localityCost,
211       rackLocalityCost,
212       new TableSkewCostFunction(conf),
213       regionReplicaHostCostFunction,
214       regionReplicaRackCostFunction,
215       regionLoadFunctions[0],
216       regionLoadFunctions[1],
217       regionLoadFunctions[2],
218       regionLoadFunctions[3],
219     };
220 
221     curFunctionCosts= new Double[costFunctions.length];
222     tempFunctionCosts= new Double[costFunctions.length];
223 
224   }
225 
226   @Override
227   protected void setSlop(Configuration conf) {
228     this.slop = conf.getFloat("hbase.regions.slop", 0.001F);
229   }
230 
231   @Override
232   public synchronized void setClusterStatus(ClusterStatus st) {
233     super.setClusterStatus(st);
234     updateRegionLoad();
235     for(CostFromRegionLoadFunction cost : regionLoadFunctions) {
236       cost.setClusterStatus(st);
237     }
238 
239     // update metrics size
240     try {
241       // by-table or ensemble mode
242       int tablesCount = isByTable ? services.getTableDescriptors().getAll().size() : 1;
243       int functionsCount = getCostFunctionNames().length;
244 
245       updateMetricsSize(tablesCount * (functionsCount + 1)); // +1 for overall
246     } catch (Exception e) {
247       LOG.error("failed to get the size of all tables", e);
248     }
249   }
250 
251   /**
252    * Update the number of metrics that are reported to JMX
253    */
254   public void updateMetricsSize(int size) {
255     if (metricsBalancer instanceof MetricsStochasticBalancer) {
256         ((MetricsStochasticBalancer) metricsBalancer).updateMetricsSize(size);
257     }
258   }
259 
260   @Override
261   public synchronized void setMasterServices(MasterServices masterServices) {
262     super.setMasterServices(masterServices);
263     this.localityCost.setServices(masterServices);
264     this.rackLocalityCost.setServices(masterServices);
265     this.localityCandidateGenerator.setServices(masterServices);
266   }
267 
268   @Override
269   protected synchronized boolean areSomeRegionReplicasColocated(Cluster c) {
270     regionReplicaHostCostFunction.init(c);
271     if (regionReplicaHostCostFunction.cost() > 0) return true;
272     regionReplicaRackCostFunction.init(c);
273     if (regionReplicaRackCostFunction.cost() > 0) return true;
274     return false;
275   }
276 
277   @Override
278   protected boolean needsBalance(Cluster cluster) {
279     ClusterLoadState cs = new ClusterLoadState(cluster.clusterState);
280     if (cs.getNumServers() < MIN_SERVER_BALANCE) {
281       if (LOG.isDebugEnabled()) {
282         LOG.debug("Not running balancer because only " + cs.getNumServers()
283             + " active regionserver(s)");
284       }
285       return false;
286     }
287     if (areSomeRegionReplicasColocated(cluster)) {
288       return true;
289     }
290 
291     double total = 0.0;
292     float sumMultiplier = 0.0f;
293     for (CostFunction c : costFunctions) {
294       float multiplier = c.getMultiplier();
295       if (multiplier <= 0) {
296         continue;
297       }
298       if (!c.isNeeded()) {
299         LOG.debug(c.getClass().getName() + " indicated that its cost should not be considered");
300         continue;
301       }
302       sumMultiplier += multiplier;
303       total += c.cost() * multiplier;
304     }
305 
306     if (total <= 0 || sumMultiplier <= 0
307         || (sumMultiplier > 0 && (total / sumMultiplier) < minCostNeedBalance)) {
308       final String loadBalanceTarget =
309           isByTable ? String.format("table (%s)", tableName) : "cluster";
310       LOG.info(String.format("Skipping load balancing because the %s is balanced. Total cost: %s, "
311           + "Sum multiplier: %s, Minimum cost needed for balance: %s", loadBalanceTarget, total,
312           sumMultiplier, minCostNeedBalance));
313       return false;
314     }
315     return true;
316   }
317 
318   @Override
319   public synchronized List<RegionPlan> balanceCluster(TableName tableName, Map<ServerName,
320     List<HRegionInfo>> clusterState) {
321     this.tableName = tableName;
322     return balanceCluster(clusterState);
323   }
324 
325   @VisibleForTesting
326   Cluster.Action nextAction(Cluster cluster) {
327     return candidateGenerators[(RANDOM.nextInt(candidateGenerators.length))]
328             .generate(cluster);
329   }
330 
331   /**
332    * Given the cluster state this will try and approach an optimal balance. This
333    * should always approach the optimal state given enough steps.
334    */
335   @Override
336   public synchronized List<RegionPlan> balanceCluster(Map<ServerName,
337     List<HRegionInfo>> clusterState) {
338     List<RegionPlan> plans = balanceMasterRegions(clusterState);
339     if (plans != null || clusterState == null || clusterState.size() <= 1) {
340       return plans;
341     }
342 
343     if (masterServerName != null && clusterState.containsKey(masterServerName)) {
344       if (clusterState.size() <= 2) {
345         return null;
346       }
347       clusterState = new HashMap<ServerName, List<HRegionInfo>>(clusterState);
348       clusterState.remove(masterServerName);
349     }
350 
351     // On clusters with lots of HFileLinks or lots of reference files,
352     // instantiating the storefile infos can be quite expensive.
353     // Allow turning this feature off if the locality cost is not going to
354     // be used in any computations.
355     RegionLocationFinder finder = null;
356     if ((this.localityCost != null && this.localityCost.getMultiplier() > 0)
357         || (this.rackLocalityCost != null && this.rackLocalityCost.getMultiplier() > 0)) {
358       finder = this.regionFinder;
359     }
360 
361     //The clusterState that is given to this method contains the state
362     //of all the regions in the table(s) (that's true today)
363     // Keep track of servers to iterate through them.
364     Cluster cluster = new Cluster(clusterState, loads, finder, rackManager);
365 
366     long startTime = EnvironmentEdgeManager.currentTime();
367 
368     initCosts(cluster);
369 
370     if (!needsBalance(cluster)) {
371       return null;
372     }
373 
374     double currentCost = computeCost(cluster, Double.MAX_VALUE);
375     curOverallCost = currentCost;
376     for (int i = 0; i < this.curFunctionCosts.length; i++) {
377       curFunctionCosts[i] = tempFunctionCosts[i];
378     }
379 
380     double initCost = currentCost;
381     double newCost = currentCost;
382 
383     long computedMaxSteps = 0;
384     if (runMaxSteps) {
385       computedMaxSteps = Math.max(this.maxSteps,
386           ((long)cluster.numRegions * (long)this.stepsPerRegion * (long)cluster.numServers));
387     } else {
388       long calculatedMaxSteps =
389           (long) cluster.numRegions * (long) this.stepsPerRegion * (long) cluster.numServers;
390       computedMaxSteps = Math.min(this.maxSteps, calculatedMaxSteps);
391       if (calculatedMaxSteps > maxSteps) {
392         LOG.warn(String.format("calculatedMaxSteps:%d for loadbalancer's stochastic walk is larger "
393                 + "than maxSteps:%d. Hence load balancing may not work well. Setting parameter "
394                 + "\"hbase.master.balancer.stochastic.runMaxSteps\" to true to overcome this issue."
395                 + "(This config change does not require service restart)", calculatedMaxSteps,
396             maxSteps));
397 
398       }
399     }
400     LOG.info("start StochasticLoadBalancer.balancer, initCost=" + currentCost + ", functionCost="
401         + functionCost() + " computedMaxSteps: " + computedMaxSteps);
402 
403     // Perform a stochastic walk to see if we can get a good fit.
404     long step;
405 
406     for (step = 0; step < computedMaxSteps; step++) {
407       Cluster.Action action = nextAction(cluster);
408 
409       if (action.type == Type.NULL) {
410         continue;
411       }
412 
413       cluster.doAction(action);
414       updateCostsWithAction(cluster, action);
415 
416       newCost = computeCost(cluster, currentCost);
417 
418       // Should this be kept?
419       if (newCost < currentCost) {
420         currentCost = newCost;
421 
422         // save for JMX
423         curOverallCost = currentCost;
424         for (int i = 0; i < this.curFunctionCosts.length; i++) {
425           curFunctionCosts[i] = tempFunctionCosts[i];
426         }
427       } else {
428         // Put things back the way they were before.
429         // TODO: undo by remembering old values
430         Action undoAction = action.undoAction();
431         cluster.doAction(undoAction);
432         updateCostsWithAction(cluster, undoAction);
433       }
434 
435       if (EnvironmentEdgeManager.currentTime() - startTime >
436           maxRunningTime) {
437         break;
438       }
439     }
440     long endTime = EnvironmentEdgeManager.currentTime();
441 
442     metricsBalancer.balanceCluster(endTime - startTime);
443 
444     // update costs metrics
445     updateStochasticCosts(tableName, curOverallCost, curFunctionCosts);
446     if (initCost > currentCost) {
447       plans = createRegionPlans(cluster);
448       if (LOG.isDebugEnabled()) {
449         LOG.debug("Finished computing new load balance plan.  Computation took "
450             + (endTime - startTime) + "ms to try " + step
451             + " different iterations.  Found a solution that moves "
452             + plans.size() + " regions; Going from a computed cost of "
453             + initCost + " to a new cost of " + currentCost);
454       }
455 
456       return plans;
457     }
458     if (LOG.isDebugEnabled()) {
459       LOG.debug("Could not find a better load balance plan.  Tried "
460           + step + " different configurations in " + (endTime - startTime)
461           + "ms, and did not find anything with a computed cost less than " + initCost);
462     }
463     return null;
464   }
465 
466   /**
467    * update costs to JMX
468    */
469   private void updateStochasticCosts(TableName tableName, Double overall, Double[] subCosts) {
470     if (tableName == null) return;
471 
472     // check if the metricsBalancer is MetricsStochasticBalancer before casting
473     if (metricsBalancer instanceof MetricsStochasticBalancer) {
474       MetricsStochasticBalancer balancer = (MetricsStochasticBalancer) metricsBalancer;
475       // overall cost
476       balancer.updateStochasticCost(tableName.getNameAsString(),
477         "Overall", "Overall cost", overall);
478 
479       // each cost function
480       for (int i = 0; i < costFunctions.length; i++) {
481         CostFunction costFunction = costFunctions[i];
482         String costFunctionName = costFunction.getClass().getSimpleName();
483         Double costPercent = (overall == 0) ? 0 : (subCosts[i] / overall);
484         // TODO: cost function may need a specific description
485         balancer.updateStochasticCost(tableName.getNameAsString(), costFunctionName,
486           "The percent of " + costFunctionName, costPercent);
487       }
488     }
489   }
490 
491   private String functionCost() {
492     StringBuilder builder = new StringBuilder();
493     for (CostFunction c:costFunctions) {
494       builder.append(c.getClass().getSimpleName());
495       builder.append(" : (");
496       builder.append(c.getMultiplier());
497       builder.append(", ");
498       builder.append(c.cost());
499       builder.append("); ");
500     }
501     return builder.toString();
502   }
503 
504   /**
505    * Create all of the RegionPlan's needed to move from the initial cluster state to the desired
506    * state.
507    *
508    * @param cluster The state of the cluster
509    * @return List of RegionPlan's that represent the moves needed to get to desired final state.
510    */
511   private List<RegionPlan> createRegionPlans(Cluster cluster) {
512     List<RegionPlan> plans = new LinkedList<RegionPlan>();
513     for (int regionIndex = 0;
514          regionIndex < cluster.regionIndexToServerIndex.length; regionIndex++) {
515       int initialServerIndex = cluster.initialRegionIndexToServerIndex[regionIndex];
516       int newServerIndex = cluster.regionIndexToServerIndex[regionIndex];
517 
518       if (initialServerIndex != newServerIndex) {
519         HRegionInfo region = cluster.regions[regionIndex];
520         ServerName initialServer = cluster.servers[initialServerIndex];
521         ServerName newServer = cluster.servers[newServerIndex];
522 
523         if (LOG.isTraceEnabled()) {
524           LOG.trace("Moving Region " + region.getEncodedName() + " from server "
525               + initialServer.getHostname() + " to " + newServer.getHostname());
526         }
527         RegionPlan rp = new RegionPlan(region, initialServer, newServer);
528         plans.add(rp);
529       }
530     }
531     return plans;
532   }
533 
534   /**
535    * Store the current region loads.
536    */
537   private synchronized void updateRegionLoad() {
538     // We create a new hashmap so that regions that are no longer there are removed.
539     // However we temporarily need the old loads so we can use them to keep the rolling average.
540     Map<String, Deque<RegionLoad>> oldLoads = loads;
541     loads = new HashMap<String, Deque<RegionLoad>>();
542 
543     for (ServerName sn : clusterStatus.getServers()) {
544       ServerLoad sl = clusterStatus.getLoad(sn);
545       if (sl == null) {
546         continue;
547       }
548       for (Entry<byte[], RegionLoad> entry : sl.getRegionsLoad().entrySet()) {
549         String regionNameAsString = HRegionInfo.getRegionNameAsString(entry.getKey());
550         Deque<RegionLoad> rLoads = oldLoads.get(regionNameAsString);
551         if (rLoads == null) {
552           // There was nothing there
553           rLoads = new ArrayDeque<RegionLoad>();
554         } else if (rLoads.size() >= numRegionLoadsToRemember) {
555           rLoads.remove();
556         }
557         rLoads.add(entry.getValue());
558         loads.put(regionNameAsString, rLoads);
559       }
560     }
561 
562     for(CostFromRegionLoadFunction cost : regionLoadFunctions) {
563       cost.setLoads(loads);
564     }
565   }
566 
567   protected void initCosts(Cluster cluster) {
568     for (CostFunction c:costFunctions) {
569       c.init(cluster);
570     }
571   }
572 
573   protected void updateCostsWithAction(Cluster cluster, Action action) {
574     for (CostFunction c : costFunctions) {
575       c.postAction(action);
576     }
577   }
578 
579   /**
580    * Get the names of the cost functions
581    */
582   public String[] getCostFunctionNames() {
583     if (costFunctions == null) return null;
584     String[] ret = new String[costFunctions.length];
585     for (int i = 0; i < costFunctions.length; i++) {
586       CostFunction c = costFunctions[i];
587       ret[i] = c.getClass().getSimpleName();
588     }
589 
590     return ret;
591   }
592 
593   /**
594    * This is the main cost function.  It will compute a cost associated with a proposed cluster
595    * state.  All different costs will be combined with their multipliers to produce a double cost.
596    *
597    * @param cluster The state of the cluster
598    * @param previousCost the previous cost. This is used as an early out.
599    * @return a double of a cost associated with the proposed cluster state.  This cost is an
600    *         aggregate of all individual cost functions.
601    */
602   protected double computeCost(Cluster cluster, double previousCost) {
603     double total = 0;
604 
605     for (int i = 0; i < costFunctions.length; i++) {
606       CostFunction c = costFunctions[i];
607       this.tempFunctionCosts[i] = 0.0;
608 
609       if (c.getMultiplier() <= 0) {
610         continue;
611       }
612 
613       Float multiplier = c.getMultiplier();
614       Double cost = c.cost();
615 
616       this.tempFunctionCosts[i] = multiplier*cost;
617       total += this.tempFunctionCosts[i];
618 
619       if (total > previousCost) {
620         break;
621       }
622     }
623 
624     return total;
625   }
626 
627   /** Generates a candidate action to be applied to the cluster for cost function search */
628   abstract static class CandidateGenerator {
629     abstract Cluster.Action generate(Cluster cluster);
630 
631     /**
632      * From a list of regions pick a random one. Null can be returned which
633      * {@link StochasticLoadBalancer#balanceCluster(Map)} recognize as signal to try a region move
634      * rather than swap.
635      *
636      * @param cluster        The state of the cluster
637      * @param server         index of the server
638      * @param chanceOfNoSwap Chance that this will decide to try a move rather
639      *                       than a swap.
640      * @return a random {@link HRegionInfo} or null if an asymmetrical move is
641      *         suggested.
642      */
643     protected int pickRandomRegion(Cluster cluster, int server, double chanceOfNoSwap) {
644       // Check to see if this is just a move.
645       if (cluster.regionsPerServer[server].length == 0 || RANDOM.nextFloat() < chanceOfNoSwap) {
646         // signal a move only.
647         return -1;
648       }
649       int rand = RANDOM.nextInt(cluster.regionsPerServer[server].length);
650       return cluster.regionsPerServer[server][rand];
651 
652     }
653     protected int pickRandomServer(Cluster cluster) {
654       if (cluster.numServers < 1) {
655         return -1;
656       }
657 
658       return RANDOM.nextInt(cluster.numServers);
659     }
660 
661     protected int pickRandomRack(Cluster cluster) {
662       if (cluster.numRacks < 1) {
663         return -1;
664       }
665 
666       return RANDOM.nextInt(cluster.numRacks);
667     }
668 
669     protected int pickOtherRandomServer(Cluster cluster, int serverIndex) {
670       if (cluster.numServers < 2) {
671         return -1;
672       }
673       while (true) {
674         int otherServerIndex = pickRandomServer(cluster);
675         if (otherServerIndex != serverIndex) {
676           return otherServerIndex;
677         }
678       }
679     }
680 
681     protected int pickOtherRandomRack(Cluster cluster, int rackIndex) {
682       if (cluster.numRacks < 2) {
683         return -1;
684       }
685       while (true) {
686         int otherRackIndex = pickRandomRack(cluster);
687         if (otherRackIndex != rackIndex) {
688           return otherRackIndex;
689         }
690       }
691     }
692 
693     protected Cluster.Action pickRandomRegions(Cluster cluster,
694                                                        int thisServer,
695                                                        int otherServer) {
696       if (thisServer < 0 || otherServer < 0) {
697         return Cluster.NullAction;
698       }
699 
700       // Decide who is most likely to need another region
701       int thisRegionCount = cluster.getNumRegions(thisServer);
702       int otherRegionCount = cluster.getNumRegions(otherServer);
703 
704       // Assign the chance based upon the above
705       double thisChance = (thisRegionCount > otherRegionCount) ? 0 : 0.5;
706       double otherChance = (thisRegionCount <= otherRegionCount) ? 0 : 0.5;
707 
708       int thisRegion = pickRandomRegion(cluster, thisServer, thisChance);
709       int otherRegion = pickRandomRegion(cluster, otherServer, otherChance);
710 
711       return getAction(thisServer, thisRegion, otherServer, otherRegion);
712     }
713 
714     protected Cluster.Action getAction(int fromServer, int fromRegion,
715         int toServer, int toRegion) {
716       if (fromServer < 0 || toServer < 0) {
717         return Cluster.NullAction;
718       }
719       if (fromRegion > 0 && toRegion > 0) {
720         return new Cluster.SwapRegionsAction(fromServer, fromRegion,
721           toServer, toRegion);
722       } else if (fromRegion > 0) {
723         return new Cluster.MoveRegionAction(fromRegion, fromServer, toServer);
724       } else if (toRegion > 0) {
725         return new Cluster.MoveRegionAction(toRegion, toServer, fromServer);
726       } else {
727         return Cluster.NullAction;
728       }
729     }
730 
731     /**
732      * Returns a random iteration order of indexes of an array with size length
733      */
734     protected List<Integer> getRandomIterationOrder(int length) {
735       ArrayList<Integer> order = new ArrayList<>(length);
736       for (int i = 0; i < length; i++) {
737         order.add(i);
738       }
739       Collections.shuffle(order);
740       return order;
741     }
742   }
743 
744   static class RandomCandidateGenerator extends CandidateGenerator {
745 
746     @Override
747     Cluster.Action generate(Cluster cluster) {
748 
749       int thisServer = pickRandomServer(cluster);
750 
751       // Pick the other server
752       int otherServer = pickOtherRandomServer(cluster, thisServer);
753 
754       return pickRandomRegions(cluster, thisServer, otherServer);
755     }
756   }
757 
758   static class LoadCandidateGenerator extends CandidateGenerator {
759 
760     @Override
761     Cluster.Action generate(Cluster cluster) {
762       cluster.sortServersByRegionCount();
763       int thisServer = pickMostLoadedServer(cluster, -1);
764       int otherServer = pickLeastLoadedServer(cluster, thisServer);
765 
766       return pickRandomRegions(cluster, thisServer, otherServer);
767     }
768 
769     private int pickLeastLoadedServer(final Cluster cluster, int thisServer) {
770       Integer[] servers = cluster.serverIndicesSortedByRegionCount;
771 
772       int index = 0;
773       while (servers[index] == null || servers[index] == thisServer) {
774         index++;
775         if (index == servers.length) {
776           return -1;
777         }
778       }
779       return servers[index];
780     }
781 
782     private int pickMostLoadedServer(final Cluster cluster, int thisServer) {
783       Integer[] servers = cluster.serverIndicesSortedByRegionCount;
784 
785       int index = servers.length - 1;
786       while (servers[index] == null || servers[index] == thisServer) {
787         index--;
788         if (index < 0) {
789           return -1;
790         }
791       }
792       return servers[index];
793     }
794   }
795 
796   static class LocalityBasedCandidateGenerator extends CandidateGenerator {
797 
798     private MasterServices masterServices;
799 
800     LocalityBasedCandidateGenerator(MasterServices masterServices) {
801       this.masterServices = masterServices;
802     }
803 
804     @Override
805     Cluster.Action generate(Cluster cluster) {
806       if (this.masterServices == null) {
807         int thisServer = pickRandomServer(cluster);
808         // Pick the other server
809         int otherServer = pickOtherRandomServer(cluster, thisServer);
810         return pickRandomRegions(cluster, thisServer, otherServer);
811       }
812 
813       // Randomly iterate through regions until you find one that is not on ideal host
814       for (int region : getRandomIterationOrder(cluster.numRegions)) {
815         int currentServer = cluster.regionIndexToServerIndex[region];
816         if (currentServer != cluster.getOrComputeRegionsToMostLocalEntities(LocalityType.SERVER)[region]) {
817           Optional<Action> potential = tryMoveOrSwap(
818               cluster,
819               currentServer,
820               region,
821               cluster.getOrComputeRegionsToMostLocalEntities(LocalityType.SERVER)[region]
822           );
823           if (potential.isPresent()) {
824             return potential.get();
825           }
826         }
827       }
828       return Cluster.NullAction;
829     }
830 
831     /**
832      * Try to generate a move/swap fromRegion between fromServer and toServer such that locality is improved.
833      * Returns empty optional if no move can be found
834      */
835     private Optional<Action> tryMoveOrSwap(Cluster cluster,
836                                            int fromServer,
837                                            int fromRegion,
838                                            int toServer) {
839       // Try move first. We know apriori fromRegion has the highest locality on toServer
840       if (cluster.serverHasTooFewRegions(toServer)) {
841         return Optional.of(getAction(fromServer, fromRegion, toServer, -1));
842       }
843 
844       // Compare locality gain/loss from swapping fromRegion with regions on toServer
845       double fromRegionLocalityDelta =
846           getWeightedLocality(cluster, fromRegion, toServer) - getWeightedLocality(cluster, fromRegion, fromServer);
847       for (int toRegionIndex : getRandomIterationOrder(cluster.regionsPerServer[toServer].length)) {
848         int toRegion = cluster.regionsPerServer[toServer][toRegionIndex];
849         double toRegionLocalityDelta =
850             getWeightedLocality(cluster, toRegion, fromServer) - getWeightedLocality(cluster, toRegion, toServer);
851         // If locality would remain neutral or improve, attempt the swap
852         if (fromRegionLocalityDelta + toRegionLocalityDelta >= 0) {
853           return Optional.of(getAction(fromServer, fromRegion, toServer, toRegion));
854         }
855       }
856 
857       return Optional.absent();
858     }
859 
860     private double getWeightedLocality(Cluster cluster, int region, int server) {
861       return cluster.getOrComputeWeightedLocality(region, server, LocalityType.SERVER);
862     }
863 
864     void setServices(MasterServices services) {
865       this.masterServices = services;
866     }
867   }
868 
869   /**
870    * Generates candidates which moves the replicas out of the region server for
871    * co-hosted region replicas
872    */
873   static class RegionReplicaCandidateGenerator extends CandidateGenerator {
874 
875     RandomCandidateGenerator randomGenerator = new RandomCandidateGenerator();
876 
877     /**
878      * Randomly select one regionIndex out of all region replicas co-hosted in the same group
879      * (a group is a server, host or rack)
880      * @param primariesOfRegionsPerGroup either Cluster.primariesOfRegionsPerServer,
881      * primariesOfRegionsPerHost or primariesOfRegionsPerRack
882      * @param regionsPerGroup either Cluster.regionsPerServer, regionsPerHost or regionsPerRack
883      * @param regionIndexToPrimaryIndex Cluster.regionsIndexToPrimaryIndex
884      * @return a regionIndex for the selected primary or -1 if there is no co-locating
885      */
886     int selectCoHostedRegionPerGroup(int[] primariesOfRegionsPerGroup, int[] regionsPerGroup
887         , int[] regionIndexToPrimaryIndex) {
888       int currentPrimary = -1;
889       int currentPrimaryIndex = -1;
890       int selectedPrimaryIndex = -1;
891       double currentLargestRandom = -1;
892       // primariesOfRegionsPerGroup is a sorted array. Since it contains the primary region
893       // ids for the regions hosted in server, a consecutive repetition means that replicas
894       // are co-hosted
895       for (int j = 0; j <= primariesOfRegionsPerGroup.length; j++) {
896         int primary = j < primariesOfRegionsPerGroup.length
897             ? primariesOfRegionsPerGroup[j] : -1;
898         if (primary != currentPrimary) { // check for whether we see a new primary
899           int numReplicas = j - currentPrimaryIndex;
900           if (numReplicas > 1) { // means consecutive primaries, indicating co-location
901             // decide to select this primary region id or not
902             double currentRandom = RANDOM.nextDouble();
903             // we don't know how many region replicas are co-hosted, we will randomly select one
904             // using reservoir sampling (http://gregable.com/2007/10/reservoir-sampling.html)
905             if (currentRandom > currentLargestRandom) {
906               selectedPrimaryIndex = currentPrimary;
907               currentLargestRandom = currentRandom;
908             }
909           }
910           currentPrimary = primary;
911           currentPrimaryIndex = j;
912         }
913       }
914 
915       // we have found the primary id for the region to move. Now find the actual regionIndex
916       // with the given primary, prefer to move the secondary region.
917       for (int j = 0; j < regionsPerGroup.length; j++) {
918         int regionIndex = regionsPerGroup[j];
919         if (selectedPrimaryIndex == regionIndexToPrimaryIndex[regionIndex]) {
920           // always move the secondary, not the primary
921           if (selectedPrimaryIndex != regionIndex) {
922             return regionIndex;
923           }
924         }
925       }
926       return -1;
927     }
928 
929     @Override
930     Cluster.Action generate(Cluster cluster) {
931       int serverIndex = pickRandomServer(cluster);
932       if (cluster.numServers <= 1 || serverIndex == -1) {
933         return Cluster.NullAction;
934       }
935 
936       int regionIndex = selectCoHostedRegionPerGroup(
937         cluster.primariesOfRegionsPerServer[serverIndex],
938         cluster.regionsPerServer[serverIndex],
939         cluster.regionIndexToPrimaryIndex);
940 
941       // if there are no pairs of region replicas co-hosted, default to random generator
942       if (regionIndex == -1) {
943         // default to randompicker
944         return randomGenerator.generate(cluster);
945       }
946 
947       int toServerIndex = pickOtherRandomServer(cluster, serverIndex);
948       int toRegionIndex = pickRandomRegion(cluster, toServerIndex, 0.9f);
949       return getAction(serverIndex, regionIndex, toServerIndex, toRegionIndex);
950     }
951   }
952 
953   /**
954    * Generates candidates which moves the replicas out of the rack for
955    * co-hosted region replicas in the same rack
956    */
957   static class RegionReplicaRackCandidateGenerator extends RegionReplicaCandidateGenerator {
958     @Override
959     Cluster.Action generate(Cluster cluster) {
960       int rackIndex = pickRandomRack(cluster);
961       if (cluster.numRacks <= 1 || rackIndex == -1) {
962         return super.generate(cluster);
963       }
964 
965       int regionIndex = selectCoHostedRegionPerGroup(
966         cluster.primariesOfRegionsPerRack[rackIndex],
967         cluster.regionsPerRack[rackIndex],
968         cluster.regionIndexToPrimaryIndex);
969 
970       // if there are no pairs of region replicas co-hosted, default to random generator
971       if (regionIndex == -1) {
972         // default to randompicker
973         return randomGenerator.generate(cluster);
974       }
975 
976       int serverIndex = cluster.regionIndexToServerIndex[regionIndex];
977       int toRackIndex = pickOtherRandomRack(cluster, rackIndex);
978 
979       int rand = RANDOM.nextInt(cluster.serversPerRack[toRackIndex].length);
980       int toServerIndex = cluster.serversPerRack[toRackIndex][rand];
981       int toRegionIndex = pickRandomRegion(cluster, toServerIndex, 0.9f);
982       return getAction(serverIndex, regionIndex, toServerIndex, toRegionIndex);
983     }
984   }
985 
986   /**
987    * Base class of StochasticLoadBalancer's Cost Functions.
988    */
989   abstract static class CostFunction {
990 
991     private float multiplier = 0;
992 
993     protected Cluster cluster;
994 
995     CostFunction(Configuration c) {
996     }
997 
998     boolean isNeeded() {
999       return true;
1000     }
1001     float getMultiplier() {
1002       return multiplier;
1003     }
1004 
1005     void setMultiplier(float m) {
1006       this.multiplier = m;
1007     }
1008 
1009     /** Called once per LB invocation to give the cost function
1010      * to initialize it's state, and perform any costly calculation.
1011      */
1012     void init(Cluster cluster) {
1013       this.cluster = cluster;
1014     }
1015 
1016     /** Called once per cluster Action to give the cost function
1017      * an opportunity to update it's state. postAction() is always
1018      * called at least once before cost() is called with the cluster
1019      * that this action is performed on. */
1020     void postAction(Action action) {
1021       switch (action.type) {
1022       case NULL: break;
1023       case ASSIGN_REGION:
1024         AssignRegionAction ar = (AssignRegionAction) action;
1025         regionMoved(ar.region, -1, ar.server);
1026         break;
1027       case MOVE_REGION:
1028         MoveRegionAction mra = (MoveRegionAction) action;
1029         regionMoved(mra.region, mra.fromServer, mra.toServer);
1030         break;
1031       case SWAP_REGIONS:
1032         SwapRegionsAction a = (SwapRegionsAction) action;
1033         regionMoved(a.fromRegion, a.fromServer, a.toServer);
1034         regionMoved(a.toRegion, a.toServer, a.fromServer);
1035         break;
1036       default:
1037         throw new RuntimeException("Uknown action:" + action.type);
1038       }
1039     }
1040 
1041     protected void regionMoved(int region, int oldServer, int newServer) {
1042     }
1043 
1044     abstract double cost();
1045 
1046     /**
1047      * Function to compute a scaled cost using {@link DescriptiveStatistics}. It
1048      * assumes that this is a zero sum set of costs.  It assumes that the worst case
1049      * possible is all of the elements in one region server and the rest having 0.
1050      *
1051      * @param stats the costs
1052      * @return a scaled set of costs.
1053      */
1054     protected double costFromArray(double[] stats) {
1055       double totalCost = 0;
1056       double total = getSum(stats);
1057 
1058       double count = stats.length;
1059       double mean = total/count;
1060 
1061       // Compute max as if all region servers had 0 and one had the sum of all costs.  This must be
1062       // a zero sum cost for this to make sense.
1063       double max = ((count - 1) * mean) + (total - mean);
1064 
1065       // It's possible that there aren't enough regions to go around
1066       double min;
1067       if (count > total) {
1068         min = ((count - total) * mean) + ((1 - mean) * total);
1069       } else {
1070         // Some will have 1 more than everything else.
1071         int numHigh = (int) (total - (Math.floor(mean) * count));
1072         int numLow = (int) (count - numHigh);
1073 
1074         min = (numHigh * (Math.ceil(mean) - mean)) + (numLow * (mean - Math.floor(mean)));
1075 
1076       }
1077       min = Math.max(0, min);
1078       for (int i=0; i<stats.length; i++) {
1079         double n = stats[i];
1080         double diff = Math.abs(mean - n);
1081         totalCost += diff;
1082       }
1083 
1084       double scaled =  scale(min, max, totalCost);
1085       return scaled;
1086     }
1087 
1088     private double getSum(double[] stats) {
1089       double total = 0;
1090       for(double s:stats) {
1091         total += s;
1092       }
1093       return total;
1094     }
1095 
1096     /**
1097      * Scale the value between 0 and 1.
1098      *
1099      * @param min   Min value
1100      * @param max   The Max value
1101      * @param value The value to be scaled.
1102      * @return The scaled value.
1103      */
1104     protected double scale(double min, double max, double value) {
1105       if (max <= min || value <= min) {
1106         return 0;
1107       }
1108       if ((max - min) == 0) return 0;
1109 
1110       return Math.max(0d, Math.min(1d, (value - min) / (max - min)));
1111     }
1112   }
1113 
1114   /**
1115    * Given the starting state of the regions and a potential ending state
1116    * compute cost based upon the number of regions that have moved.
1117    */
1118   static class MoveCostFunction extends CostFunction {
1119     private static final String MOVE_COST_KEY = "hbase.master.balancer.stochastic.moveCost";
1120     private static final String MAX_MOVES_PERCENT_KEY =
1121         "hbase.master.balancer.stochastic.maxMovePercent";
1122     private static final float DEFAULT_MOVE_COST = 7;
1123     private static final int DEFAULT_MAX_MOVES = 600;
1124     private static final float DEFAULT_MAX_MOVE_PERCENT = 0.25f;
1125 
1126     private final float maxMovesPercent;
1127 
1128     MoveCostFunction(Configuration conf) {
1129       super(conf);
1130 
1131       // Move cost multiplier should be the same cost or higher than the rest of the costs to ensure
1132       // that large benefits are need to overcome the cost of a move.
1133       this.setMultiplier(conf.getFloat(MOVE_COST_KEY, DEFAULT_MOVE_COST));
1134       // What percent of the number of regions a single run of the balancer can move.
1135       maxMovesPercent = conf.getFloat(MAX_MOVES_PERCENT_KEY, DEFAULT_MAX_MOVE_PERCENT);
1136     }
1137 
1138     @Override
1139     double cost() {
1140       // Try and size the max number of Moves, but always be prepared to move some.
1141       int maxMoves = Math.max((int) (cluster.numRegions * maxMovesPercent),
1142           DEFAULT_MAX_MOVES);
1143 
1144       double moveCost = cluster.numMovedRegions;
1145 
1146       // Don't let this single balance move more than the max moves.
1147       // This allows better scaling to accurately represent the actual cost of a move.
1148       if (moveCost > maxMoves) {
1149         return 1000000;   // return a number much greater than any of the other cost
1150       }
1151 
1152       return scale(0, Math.min(cluster.numRegions, maxMoves), moveCost);
1153     }
1154   }
1155 
1156   /**
1157    * Compute the cost of a potential cluster state from skew in number of
1158    * regions on a cluster.
1159    */
1160   static class RegionCountSkewCostFunction extends CostFunction {
1161     private static final String REGION_COUNT_SKEW_COST_KEY =
1162         "hbase.master.balancer.stochastic.regionCountCost";
1163     private static final float DEFAULT_REGION_COUNT_SKEW_COST = 500;
1164 
1165     private double[] stats = null;
1166 
1167     RegionCountSkewCostFunction(Configuration conf) {
1168       super(conf);
1169       // Load multiplier should be the greatest as it is the most general way to balance data.
1170       this.setMultiplier(conf.getFloat(REGION_COUNT_SKEW_COST_KEY, DEFAULT_REGION_COUNT_SKEW_COST));
1171     }
1172 
1173     @Override
1174     double cost() {
1175       if (stats == null || stats.length != cluster.numServers) {
1176         stats = new double[cluster.numServers];
1177       }
1178 
1179       for (int i =0; i < cluster.numServers; i++) {
1180         stats[i] = cluster.regionsPerServer[i].length;
1181       }
1182 
1183       return costFromArray(stats);
1184     }
1185   }
1186 
1187   /**
1188    * Compute the cost of a potential cluster state from skew in number of
1189    * primary regions on a cluster.
1190    */
1191   static class PrimaryRegionCountSkewCostFunction extends CostFunction {
1192     private static final String PRIMARY_REGION_COUNT_SKEW_COST_KEY =
1193         "hbase.master.balancer.stochastic.primaryRegionCountCost";
1194     private static final float DEFAULT_PRIMARY_REGION_COUNT_SKEW_COST = 500;
1195 
1196     private double[] stats = null;
1197 
1198     PrimaryRegionCountSkewCostFunction(Configuration conf) {
1199       super(conf);
1200       // Load multiplier should be the greatest as primary regions serve majority of reads/writes.
1201       this.setMultiplier(conf.getFloat(PRIMARY_REGION_COUNT_SKEW_COST_KEY,
1202         DEFAULT_PRIMARY_REGION_COUNT_SKEW_COST));
1203     }
1204 
1205     @Override
1206     boolean isNeeded() {
1207       return cluster.hasRegionReplicas;
1208     }
1209 
1210     @Override
1211     double cost() {
1212       if (!cluster.hasRegionReplicas) {
1213         return 0;
1214       }
1215       if (stats == null || stats.length != cluster.numServers) {
1216         stats = new double[cluster.numServers];
1217       }
1218 
1219       for (int i =0; i < cluster.numServers; i++) {
1220         stats[i] = 0;
1221         for (int regionIdx : cluster.regionsPerServer[i]) {
1222           if (regionIdx == cluster.regionIndexToPrimaryIndex[regionIdx]) {
1223             stats[i] ++;
1224           }
1225         }
1226       }
1227 
1228       return costFromArray(stats);
1229     }
1230   }
1231 
1232   /**
1233    * Compute the cost of a potential cluster configuration based upon how evenly
1234    * distributed tables are.
1235    */
1236   static class TableSkewCostFunction extends CostFunction {
1237 
1238     private static final String TABLE_SKEW_COST_KEY =
1239         "hbase.master.balancer.stochastic.tableSkewCost";
1240     private static final float DEFAULT_TABLE_SKEW_COST = 35;
1241 
1242     TableSkewCostFunction(Configuration conf) {
1243       super(conf);
1244       this.setMultiplier(conf.getFloat(TABLE_SKEW_COST_KEY, DEFAULT_TABLE_SKEW_COST));
1245     }
1246 
1247     @Override
1248     double cost() {
1249       double max = cluster.numRegions;
1250       double min = ((double) cluster.numRegions) / cluster.numServers;
1251       double value = 0;
1252 
1253       for (int i = 0; i < cluster.numMaxRegionsPerTable.length; i++) {
1254         value += cluster.numMaxRegionsPerTable[i];
1255       }
1256 
1257       return scale(min, max, value);
1258     }
1259   }
1260 
1261   /**
1262    * Compute a cost of a potential cluster configuration based upon where
1263    * {@link org.apache.hadoop.hbase.regionserver.StoreFile}s are located.
1264    */
1265   static abstract class LocalityBasedCostFunction extends CostFunction {
1266 
1267     private final LocalityType type;
1268 
1269     private double bestLocality; // best case locality across cluster weighted by local data size
1270     private double locality; // current locality across cluster weighted by local data size
1271 
1272     private MasterServices services;
1273 
1274     LocalityBasedCostFunction(Configuration conf,
1275                               MasterServices srv,
1276                               LocalityType type,
1277                               String localityCostKey,
1278                               float defaultLocalityCost) {
1279       super(conf);
1280       this.type = type;
1281       this.setMultiplier(conf.getFloat(localityCostKey, defaultLocalityCost));
1282       this.services = srv;
1283       this.locality = 0.0;
1284       this.bestLocality = 0.0;
1285     }
1286 
1287     /**
1288      * Maps region to the current entity (server or rack) on which it is stored
1289      */
1290     abstract int regionIndexToEntityIndex(int region);
1291 
1292     public void setServices(MasterServices srvc) {
1293       this.services = srvc;
1294     }
1295 
1296     @Override
1297     void init(Cluster cluster) {
1298       super.init(cluster);
1299       locality = 0.0;
1300       bestLocality = 0.0;
1301 
1302       // If no master, no computation will work, so assume 0 cost
1303       if (this.services == null) {
1304         return;
1305       }
1306 
1307       for (int region = 0; region < cluster.numRegions; region++) {
1308         locality += getWeightedLocality(region, regionIndexToEntityIndex(region));
1309         bestLocality += getWeightedLocality(region, getMostLocalEntityForRegion(region));
1310       }
1311 
1312       // We normalize locality to be a score between 0 and 1.0 representing how good it
1313       // is compared to how good it could be. If bestLocality is 0, assume locality is 100
1314       // (and the cost is 0)
1315       locality = bestLocality == 0 ? 1.0 : locality / bestLocality;
1316     }
1317 
1318     @Override
1319     protected void regionMoved(int region, int oldServer, int newServer) {
1320       int oldEntity = type == LocalityType.SERVER ? oldServer : cluster.serverIndexToRackIndex[oldServer];
1321       int newEntity = type == LocalityType.SERVER ? newServer : cluster.serverIndexToRackIndex[newServer];
1322       if (this.services == null) {
1323         return;
1324       }
1325       double localityDelta = getWeightedLocality(region, newEntity) - getWeightedLocality(region, oldEntity);
1326       double normalizedDelta = bestLocality == 0 ? 0.0 : localityDelta / bestLocality;
1327       locality += normalizedDelta;
1328     }
1329 
1330     @Override
1331     double cost() {
1332       return 1 - locality;
1333     }
1334 
1335     private int getMostLocalEntityForRegion(int region) {
1336       return cluster.getOrComputeRegionsToMostLocalEntities(type)[region];
1337     }
1338 
1339     private double getWeightedLocality(int region, int entity) {
1340       return cluster.getOrComputeWeightedLocality(region, entity, type);
1341     }
1342 
1343   }
1344 
1345   static class ServerLocalityCostFunction extends LocalityBasedCostFunction {
1346 
1347     private static final String LOCALITY_COST_KEY = "hbase.master.balancer.stochastic.localityCost";
1348     private static final float DEFAULT_LOCALITY_COST = 25;
1349 
1350     ServerLocalityCostFunction(Configuration conf, MasterServices srv) {
1351       super(
1352           conf,
1353           srv,
1354           LocalityType.SERVER,
1355           LOCALITY_COST_KEY,
1356           DEFAULT_LOCALITY_COST
1357       );
1358     }
1359 
1360     @Override
1361     int regionIndexToEntityIndex(int region) {
1362       return cluster.regionIndexToServerIndex[region];
1363     }
1364   }
1365 
1366   static class RackLocalityCostFunction extends LocalityBasedCostFunction {
1367 
1368     private static final String RACK_LOCALITY_COST_KEY = "hbase.master.balancer.stochastic.rackLocalityCost";
1369     private static final float DEFAULT_RACK_LOCALITY_COST = 15;
1370 
1371     public RackLocalityCostFunction(Configuration conf, MasterServices services) {
1372       super(
1373           conf,
1374           services,
1375           LocalityType.RACK,
1376           RACK_LOCALITY_COST_KEY,
1377           DEFAULT_RACK_LOCALITY_COST
1378       );
1379     }
1380 
1381     @Override
1382     int regionIndexToEntityIndex(int region) {
1383       return cluster.getRackForRegion(region);
1384     }
1385   }
1386 
1387   /**
1388    * Base class the allows writing costs functions from rolling average of some
1389    * number from RegionLoad.
1390    */
1391   abstract static class CostFromRegionLoadFunction extends CostFunction {
1392 
1393     private ClusterStatus clusterStatus = null;
1394     private Map<String, Deque<RegionLoad>> loads = null;
1395     private double[] stats = null;
1396     CostFromRegionLoadFunction(Configuration conf) {
1397       super(conf);
1398     }
1399 
1400     void setClusterStatus(ClusterStatus status) {
1401       this.clusterStatus = status;
1402     }
1403 
1404     void setLoads(Map<String, Deque<RegionLoad>> l) {
1405       this.loads = l;
1406     }
1407 
1408     @Override
1409     double cost() {
1410       if (clusterStatus == null || loads == null) {
1411         return 0;
1412       }
1413 
1414       if (stats == null || stats.length != cluster.numServers) {
1415         stats = new double[cluster.numServers];
1416       }
1417 
1418       for (int i =0; i < stats.length; i++) {
1419         //Cost this server has from RegionLoad
1420         long cost = 0;
1421 
1422         // for every region on this server get the rl
1423         for(int regionIndex:cluster.regionsPerServer[i]) {
1424           Collection<RegionLoad> regionLoadList =  cluster.regionLoads[regionIndex];
1425 
1426           // Now if we found a region load get the type of cost that was requested.
1427           if (regionLoadList != null) {
1428             cost = (long) (cost + getRegionLoadCost(regionLoadList));
1429           }
1430         }
1431 
1432         // Add the total cost to the stats.
1433         stats[i] = cost;
1434       }
1435 
1436       // Now return the scaled cost from data held in the stats object.
1437       return costFromArray(stats);
1438     }
1439 
1440     protected double getRegionLoadCost(Collection<RegionLoad> regionLoadList) {
1441       double cost = 0;
1442 
1443       for (RegionLoad rl : regionLoadList) {
1444         cost += getCostFromRl(rl);
1445       }
1446       return cost / regionLoadList.size();
1447     }
1448 
1449 
1450     protected abstract double getCostFromRl(RegionLoad rl);
1451   }
1452 
1453   /**
1454    * Class to be used for the subset of RegionLoad costs that should be treated as rates.
1455    * We do not compare about the actual rate in requests per second but rather the rate relative
1456    * to the rest of the regions.
1457    */
1458   abstract static class CostFromRegionLoadAsRateFunction extends CostFromRegionLoadFunction {
1459 
1460     CostFromRegionLoadAsRateFunction(Configuration conf) {
1461       super(conf);
1462     }
1463 
1464     @Override
1465     protected double getRegionLoadCost(Collection<RegionLoad> regionLoadList) {
1466       double cost = 0;
1467       double previous = 0;
1468       boolean isFirst = true;
1469       for (RegionLoad rl : regionLoadList) {
1470         double current = getCostFromRl(rl);
1471         if (isFirst) {
1472           isFirst = false;
1473         } else {
1474           cost += current - previous;
1475         }
1476         previous = current;
1477       }
1478       return Math.max(0, cost / (regionLoadList.size() - 1));
1479     }
1480   }
1481 
1482   /**
1483    * Compute the cost of total number of read requests  The more unbalanced the higher the
1484    * computed cost will be.  This uses a rolling average of regionload.
1485    */
1486 
1487   static class ReadRequestCostFunction extends CostFromRegionLoadAsRateFunction {
1488 
1489     private static final String READ_REQUEST_COST_KEY =
1490         "hbase.master.balancer.stochastic.readRequestCost";
1491     private static final float DEFAULT_READ_REQUEST_COST = 5;
1492 
1493     ReadRequestCostFunction(Configuration conf) {
1494       super(conf);
1495       this.setMultiplier(conf.getFloat(READ_REQUEST_COST_KEY, DEFAULT_READ_REQUEST_COST));
1496     }
1497 
1498 
1499     @Override
1500     protected double getCostFromRl(RegionLoad rl) {
1501       return rl.getReadRequestsCount();
1502     }
1503   }
1504 
1505   /**
1506    * Compute the cost of total number of write requests.  The more unbalanced the higher the
1507    * computed cost will be.  This uses a rolling average of regionload.
1508    */
1509   static class WriteRequestCostFunction extends CostFromRegionLoadAsRateFunction {
1510 
1511     private static final String WRITE_REQUEST_COST_KEY =
1512         "hbase.master.balancer.stochastic.writeRequestCost";
1513     private static final float DEFAULT_WRITE_REQUEST_COST = 5;
1514 
1515     WriteRequestCostFunction(Configuration conf) {
1516       super(conf);
1517       this.setMultiplier(conf.getFloat(WRITE_REQUEST_COST_KEY, DEFAULT_WRITE_REQUEST_COST));
1518     }
1519 
1520     @Override
1521     protected double getCostFromRl(RegionLoad rl) {
1522       return rl.getWriteRequestsCount();
1523     }
1524   }
1525 
1526   /**
1527    * A cost function for region replicas. We give a very high cost to hosting
1528    * replicas of the same region in the same host. We do not prevent the case
1529    * though, since if numReplicas > numRegionServers, we still want to keep the
1530    * replica open.
1531    */
1532   static class RegionReplicaHostCostFunction extends CostFunction {
1533     private static final String REGION_REPLICA_HOST_COST_KEY =
1534         "hbase.master.balancer.stochastic.regionReplicaHostCostKey";
1535     private static final float DEFAULT_REGION_REPLICA_HOST_COST_KEY = 100000;
1536 
1537     long maxCost = 0;
1538     long[] costsPerGroup; // group is either server, host or rack
1539     int[][] primariesOfRegionsPerGroup;
1540 
1541     public RegionReplicaHostCostFunction(Configuration conf) {
1542       super(conf);
1543       this.setMultiplier(conf.getFloat(REGION_REPLICA_HOST_COST_KEY,
1544         DEFAULT_REGION_REPLICA_HOST_COST_KEY));
1545     }
1546 
1547     @Override
1548     void init(Cluster cluster) {
1549       super.init(cluster);
1550       // max cost is the case where every region replica is hosted together regardless of host
1551       maxCost = cluster.numHosts > 1 ? getMaxCost(cluster) : 0;
1552       costsPerGroup = new long[cluster.numHosts];
1553       primariesOfRegionsPerGroup = cluster.multiServersPerHost // either server based or host based
1554           ? cluster.primariesOfRegionsPerHost
1555           : cluster.primariesOfRegionsPerServer;
1556       for (int i = 0 ; i < primariesOfRegionsPerGroup.length; i++) {
1557         costsPerGroup[i] = costPerGroup(primariesOfRegionsPerGroup[i]);
1558       }
1559     }
1560 
1561     long getMaxCost(Cluster cluster) {
1562       if (!cluster.hasRegionReplicas) {
1563         return 0; // short circuit
1564       }
1565       // max cost is the case where every region replica is hosted together regardless of host
1566       int[] primariesOfRegions = new int[cluster.numRegions];
1567       System.arraycopy(cluster.regionIndexToPrimaryIndex, 0, primariesOfRegions, 0,
1568           cluster.regions.length);
1569 
1570       Arrays.sort(primariesOfRegions);
1571 
1572       // compute numReplicas from the sorted array
1573       return costPerGroup(primariesOfRegions);
1574     }
1575 
1576     @Override
1577     boolean isNeeded() {
1578       return cluster.hasRegionReplicas;
1579     }
1580 
1581     @Override
1582     double cost() {
1583       if (maxCost <= 0) {
1584         return 0;
1585       }
1586 
1587       long totalCost = 0;
1588       for (int i = 0 ; i < costsPerGroup.length; i++) {
1589         totalCost += costsPerGroup[i];
1590       }
1591       return scale(0, maxCost, totalCost);
1592     }
1593 
1594     /**
1595      * For each primary region, it computes the total number of replicas in the array (numReplicas)
1596      * and returns a sum of numReplicas-1 squared. For example, if the server hosts
1597      * regions a, b, c, d, e, f where a and b are same replicas, and c,d,e are same replicas, it
1598      * returns (2-1) * (2-1) + (3-1) * (3-1) + (1-1) * (1-1).
1599      * @param primariesOfRegions a sorted array of primary regions ids for the regions hosted
1600      * @return a sum of numReplicas-1 squared for each primary region in the group.
1601      */
1602     protected long costPerGroup(int[] primariesOfRegions) {
1603       long cost = 0;
1604       int currentPrimary = -1;
1605       int currentPrimaryIndex = -1;
1606       // primariesOfRegions is a sorted array of primary ids of regions. Replicas of regions
1607       // sharing the same primary will have consecutive numbers in the array.
1608       for (int j = 0 ; j <= primariesOfRegions.length; j++) {
1609         int primary = j < primariesOfRegions.length ? primariesOfRegions[j] : -1;
1610         if (primary != currentPrimary) { // we see a new primary
1611           int numReplicas = j - currentPrimaryIndex;
1612           // square the cost
1613           if (numReplicas > 1) { // means consecutive primaries, indicating co-location
1614             cost += (numReplicas - 1) * (numReplicas - 1);
1615           }
1616           currentPrimary = primary;
1617           currentPrimaryIndex = j;
1618         }
1619       }
1620 
1621       return cost;
1622     }
1623 
1624     @Override
1625     protected void regionMoved(int region, int oldServer, int newServer) {
1626       if (maxCost <= 0) {
1627         return; // no need to compute
1628       }
1629       if (cluster.multiServersPerHost) {
1630         int oldHost = cluster.serverIndexToHostIndex[oldServer];
1631         int newHost = cluster.serverIndexToHostIndex[newServer];
1632         if (newHost != oldHost) {
1633           costsPerGroup[oldHost] = costPerGroup(cluster.primariesOfRegionsPerHost[oldHost]);
1634           costsPerGroup[newHost] = costPerGroup(cluster.primariesOfRegionsPerHost[newHost]);
1635         }
1636       } else {
1637         costsPerGroup[oldServer] = costPerGroup(cluster.primariesOfRegionsPerServer[oldServer]);
1638         costsPerGroup[newServer] = costPerGroup(cluster.primariesOfRegionsPerServer[newServer]);
1639       }
1640     }
1641   }
1642 
1643   /**
1644    * A cost function for region replicas for the rack distribution. We give a relatively high
1645    * cost to hosting replicas of the same region in the same rack. We do not prevent the case
1646    * though.
1647    */
1648   static class RegionReplicaRackCostFunction extends RegionReplicaHostCostFunction {
1649     private static final String REGION_REPLICA_RACK_COST_KEY =
1650         "hbase.master.balancer.stochastic.regionReplicaRackCostKey";
1651     private static final float DEFAULT_REGION_REPLICA_RACK_COST_KEY = 10000;
1652 
1653     public RegionReplicaRackCostFunction(Configuration conf) {
1654       super(conf);
1655       this.setMultiplier(conf.getFloat(REGION_REPLICA_RACK_COST_KEY,
1656         DEFAULT_REGION_REPLICA_RACK_COST_KEY));
1657     }
1658 
1659     @Override
1660     void init(Cluster cluster) {
1661       this.cluster = cluster;
1662       if (cluster.numRacks <= 1) {
1663         maxCost = 0;
1664         return; // disabled for 1 rack
1665       }
1666       // max cost is the case where every region replica is hosted together regardless of rack
1667       maxCost = getMaxCost(cluster);
1668       costsPerGroup = new long[cluster.numRacks];
1669       for (int i = 0 ; i < cluster.primariesOfRegionsPerRack.length; i++) {
1670         costsPerGroup[i] = costPerGroup(cluster.primariesOfRegionsPerRack[i]);
1671       }
1672     }
1673 
1674     @Override
1675     protected void regionMoved(int region, int oldServer, int newServer) {
1676       if (maxCost <= 0) {
1677         return; // no need to compute
1678       }
1679       int oldRack = cluster.serverIndexToRackIndex[oldServer];
1680       int newRack = cluster.serverIndexToRackIndex[newServer];
1681       if (newRack != oldRack) {
1682         costsPerGroup[oldRack] = costPerGroup(cluster.primariesOfRegionsPerRack[oldRack]);
1683         costsPerGroup[newRack] = costPerGroup(cluster.primariesOfRegionsPerRack[newRack]);
1684       }
1685     }
1686   }
1687 
1688   /**
1689    * Compute the cost of total memstore size.  The more unbalanced the higher the
1690    * computed cost will be.  This uses a rolling average of regionload.
1691    */
1692   static class MemstoreSizeCostFunction extends CostFromRegionLoadAsRateFunction {
1693 
1694     private static final String MEMSTORE_SIZE_COST_KEY =
1695         "hbase.master.balancer.stochastic.memstoreSizeCost";
1696     private static final float DEFAULT_MEMSTORE_SIZE_COST = 5;
1697 
1698     MemstoreSizeCostFunction(Configuration conf) {
1699       super(conf);
1700       this.setMultiplier(conf.getFloat(MEMSTORE_SIZE_COST_KEY, DEFAULT_MEMSTORE_SIZE_COST));
1701     }
1702 
1703     @Override
1704     protected double getCostFromRl(RegionLoad rl) {
1705       return rl.getMemStoreSizeMB();
1706     }
1707   }
1708   /**
1709    * Compute the cost of total open storefiles size.  The more unbalanced the higher the
1710    * computed cost will be.  This uses a rolling average of regionload.
1711    */
1712   static class StoreFileCostFunction extends CostFromRegionLoadFunction {
1713 
1714     private static final String STOREFILE_SIZE_COST_KEY =
1715         "hbase.master.balancer.stochastic.storefileSizeCost";
1716     private static final float DEFAULT_STOREFILE_SIZE_COST = 5;
1717 
1718     StoreFileCostFunction(Configuration conf) {
1719       super(conf);
1720       this.setMultiplier(conf.getFloat(STOREFILE_SIZE_COST_KEY, DEFAULT_STOREFILE_SIZE_COST));
1721     }
1722 
1723     @Override
1724     protected double getCostFromRl(RegionLoad rl) {
1725       return rl.getStorefileSizeMB();
1726     }
1727   }
1728 
1729   /**
1730    * A helper function to compose the attribute name from tablename and costfunction name
1731    */
1732   public static String composeAttributeName(String tableName, String costFunctionName) {
1733     return tableName + TABLE_FUNCTION_SEP + costFunctionName;
1734   }
1735 }