1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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
126 private int maxSteps = 1000000;
127 private boolean runMaxSteps = false;
128 private int stepsPerRegion = 800;
129 private long maxRunningTime = 30 * 1000 * 1;
130 private int numRegionLoadsToRemember = 15;
131 private float minCostNeedBalance = 0.05f;
132
133 private CandidateGenerator[] candidateGenerators;
134 private CostFromRegionLoadFunction[] regionLoadFunctions;
135 private CostFunction[] costFunctions;
136
137
138 private Double curOverallCost = 0d;
139 private Double[] tempFunctionCosts;
140 private Double[] curFunctionCosts;
141
142
143
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
154
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
240 try {
241
242 int tablesCount = isByTable ? services.getTableDescriptors().getAll().size() : 1;
243 int functionsCount = getCostFunctionNames().length;
244
245 updateMetricsSize(tablesCount * (functionsCount + 1));
246 } catch (Exception e) {
247 LOG.error("failed to get the size of all tables", e);
248 }
249 }
250
251
252
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
333
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
352
353
354
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
362
363
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
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
419 if (newCost < currentCost) {
420 currentCost = newCost;
421
422
423 curOverallCost = currentCost;
424 for (int i = 0; i < this.curFunctionCosts.length; i++) {
425 curFunctionCosts[i] = tempFunctionCosts[i];
426 }
427 } else {
428
429
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
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
468
469 private void updateStochasticCosts(TableName tableName, Double overall, Double[] subCosts) {
470 if (tableName == null) return;
471
472
473 if (metricsBalancer instanceof MetricsStochasticBalancer) {
474 MetricsStochasticBalancer balancer = (MetricsStochasticBalancer) metricsBalancer;
475
476 balancer.updateStochasticCost(tableName.getNameAsString(),
477 "Overall", "Overall cost", overall);
478
479
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
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
506
507
508
509
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
536
537 private synchronized void updateRegionLoad() {
538
539
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
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
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
595
596
597
598
599
600
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
628 abstract static class CandidateGenerator {
629 abstract Cluster.Action generate(Cluster cluster);
630
631
632
633
634
635
636
637
638
639
640
641
642
643 protected int pickRandomRegion(Cluster cluster, int server, double chanceOfNoSwap) {
644
645 if (cluster.regionsPerServer[server].length == 0 || RANDOM.nextFloat() < chanceOfNoSwap) {
646
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
701 int thisRegionCount = cluster.getNumRegions(thisServer);
702 int otherRegionCount = cluster.getNumRegions(otherServer);
703
704
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
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
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
809 int otherServer = pickOtherRandomServer(cluster, thisServer);
810 return pickRandomRegions(cluster, thisServer, otherServer);
811 }
812
813
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
833
834
835 private Optional<Action> tryMoveOrSwap(Cluster cluster,
836 int fromServer,
837 int fromRegion,
838 int toServer) {
839
840 if (cluster.serverHasTooFewRegions(toServer)) {
841 return Optional.of(getAction(fromServer, fromRegion, toServer, -1));
842 }
843
844
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
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
871
872
873 static class RegionReplicaCandidateGenerator extends CandidateGenerator {
874
875 RandomCandidateGenerator randomGenerator = new RandomCandidateGenerator();
876
877
878
879
880
881
882
883
884
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
893
894
895 for (int j = 0; j <= primariesOfRegionsPerGroup.length; j++) {
896 int primary = j < primariesOfRegionsPerGroup.length
897 ? primariesOfRegionsPerGroup[j] : -1;
898 if (primary != currentPrimary) {
899 int numReplicas = j - currentPrimaryIndex;
900 if (numReplicas > 1) {
901
902 double currentRandom = RANDOM.nextDouble();
903
904
905 if (currentRandom > currentLargestRandom) {
906 selectedPrimaryIndex = currentPrimary;
907 currentLargestRandom = currentRandom;
908 }
909 }
910 currentPrimary = primary;
911 currentPrimaryIndex = j;
912 }
913 }
914
915
916
917 for (int j = 0; j < regionsPerGroup.length; j++) {
918 int regionIndex = regionsPerGroup[j];
919 if (selectedPrimaryIndex == regionIndexToPrimaryIndex[regionIndex]) {
920
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
942 if (regionIndex == -1) {
943
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
955
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
971 if (regionIndex == -1) {
972
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
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
1010
1011
1012 void init(Cluster cluster) {
1013 this.cluster = cluster;
1014 }
1015
1016
1017
1018
1019
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
1048
1049
1050
1051
1052
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
1062
1063 double max = ((count - 1) * mean) + (total - mean);
1064
1065
1066 double min;
1067 if (count > total) {
1068 min = ((count - total) * mean) + ((1 - mean) * total);
1069 } else {
1070
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
1098
1099
1100
1101
1102
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
1116
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
1132
1133 this.setMultiplier(conf.getFloat(MOVE_COST_KEY, DEFAULT_MOVE_COST));
1134
1135 maxMovesPercent = conf.getFloat(MAX_MOVES_PERCENT_KEY, DEFAULT_MAX_MOVE_PERCENT);
1136 }
1137
1138 @Override
1139 double cost() {
1140
1141 int maxMoves = Math.max((int) (cluster.numRegions * maxMovesPercent),
1142 DEFAULT_MAX_MOVES);
1143
1144 double moveCost = cluster.numMovedRegions;
1145
1146
1147
1148 if (moveCost > maxMoves) {
1149 return 1000000;
1150 }
1151
1152 return scale(0, Math.min(cluster.numRegions, maxMoves), moveCost);
1153 }
1154 }
1155
1156
1157
1158
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
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
1189
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
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
1234
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
1263
1264
1265 static abstract class LocalityBasedCostFunction extends CostFunction {
1266
1267 private final LocalityType type;
1268
1269 private double bestLocality;
1270 private double locality;
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
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
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
1313
1314
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
1389
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
1420 long cost = 0;
1421
1422
1423 for(int regionIndex:cluster.regionsPerServer[i]) {
1424 Collection<RegionLoad> regionLoadList = cluster.regionLoads[regionIndex];
1425
1426
1427 if (regionLoadList != null) {
1428 cost = (long) (cost + getRegionLoadCost(regionLoadList));
1429 }
1430 }
1431
1432
1433 stats[i] = cost;
1434 }
1435
1436
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
1455
1456
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
1484
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
1507
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
1528
1529
1530
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;
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
1551 maxCost = cluster.numHosts > 1 ? getMaxCost(cluster) : 0;
1552 costsPerGroup = new long[cluster.numHosts];
1553 primariesOfRegionsPerGroup = cluster.multiServersPerHost
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;
1564 }
1565
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
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
1596
1597
1598
1599
1600
1601
1602 protected long costPerGroup(int[] primariesOfRegions) {
1603 long cost = 0;
1604 int currentPrimary = -1;
1605 int currentPrimaryIndex = -1;
1606
1607
1608 for (int j = 0 ; j <= primariesOfRegions.length; j++) {
1609 int primary = j < primariesOfRegions.length ? primariesOfRegions[j] : -1;
1610 if (primary != currentPrimary) {
1611 int numReplicas = j - currentPrimaryIndex;
1612
1613 if (numReplicas > 1) {
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;
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
1645
1646
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;
1665 }
1666
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;
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
1690
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
1710
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
1731
1732 public static String composeAttributeName(String tableName, String costFunctionName) {
1733 return tableName + TABLE_FUNCTION_SEP + costFunctionName;
1734 }
1735 }