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 java.util.ArrayList;
21  import java.util.Arrays;
22  import java.util.Collection;
23  import java.util.Collections;
24  import java.util.Comparator;
25  import java.util.Deque;
26  import java.util.HashMap;
27  import java.util.HashSet;
28  import java.util.Iterator;
29  import java.util.List;
30  import java.util.Map;
31  import java.util.Map.Entry;
32  import java.util.NavigableMap;
33  import java.util.Random;
34  import java.util.Set;
35  import java.util.TreeMap;
36  
37  import org.apache.commons.lang.NotImplementedException;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.apache.hadoop.conf.Configuration;
41  import org.apache.hadoop.hbase.ClusterStatus;
42  import org.apache.hadoop.hbase.HBaseIOException;
43  import org.apache.hadoop.hbase.HRegionInfo;
44  import org.apache.hadoop.hbase.RegionLoad;
45  import org.apache.hadoop.hbase.ServerName;
46  import org.apache.hadoop.hbase.TableName;
47  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
48  import org.apache.hadoop.hbase.master.AssignmentManager;
49  import org.apache.hadoop.hbase.master.LoadBalancer;
50  import org.apache.hadoop.hbase.master.MasterServices;
51  import org.apache.hadoop.hbase.master.RackManager;
52  import org.apache.hadoop.hbase.master.RegionPlan;
53  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer.Cluster.Action.Type;
54  import org.apache.hadoop.hbase.security.access.AccessControlLists;
55  import org.apache.hadoop.util.StringUtils;
56  
57  import com.google.common.base.Joiner;
58  import com.google.common.collect.ArrayListMultimap;
59  import com.google.common.collect.Lists;
60  import com.google.common.collect.Sets;
61  
62  /**
63   * The base class for load balancers. It provides the the functions used to by
64   * {@link AssignmentManager} to assign regions in the edge cases. It doesn't
65   * provide an implementation of the actual balancing algorithm.
66   *
67   */
68  public abstract class BaseLoadBalancer implements LoadBalancer {
69    private static final int MIN_SERVER_BALANCE = 2;
70    private volatile boolean stopped = false;
71  
72    private static final List<HRegionInfo> EMPTY_REGION_LIST = new ArrayList<HRegionInfo>(0);
73  
74    protected final RegionLocationFinder regionFinder = new RegionLocationFinder();
75  
76    private static class DefaultRackManager extends RackManager {
77      @Override
78      public String getRack(ServerName server) {
79        return UNKNOWN_RACK;
80      }
81    }
82  
83    /**
84     * An efficient array based implementation similar to ClusterState for keeping
85     * the status of the cluster in terms of region assignment and distribution.
86     * LoadBalancers, such as StochasticLoadBalancer uses this Cluster object because of
87     * hundreds of thousands of hashmap manipulations are very costly, which is why this
88     * class uses mostly indexes and arrays.
89     *
90     * Cluster tracks a list of unassigned regions, region assignments, and the server
91     * topology in terms of server names, hostnames and racks.
92     */
93    protected static class Cluster {
94      ServerName[] servers;
95      String[] hosts; // ServerName uniquely identifies a region server. multiple RS can run on the same host
96      String[] racks;
97      boolean multiServersPerHost = false; // whether or not any host has more than one server
98  
99      ArrayList<String> tables;
100     HRegionInfo[] regions;
101     Deque<RegionLoad>[] regionLoads;
102 
103     int[][] regionLocations; //regionIndex -> list of serverIndex sorted by locality
104 
105     int[]   serverIndexToHostIndex;      //serverIndex -> host index
106     int[]   serverIndexToRackIndex;      //serverIndex -> rack index
107 
108     int[][] regionsPerServer;            //serverIndex -> region list
109     int[][] regionsPerHost;              //hostIndex -> list of regions
110     int[][] regionsPerRack;              //rackIndex -> region list
111     int[][] primariesOfRegionsPerServer; //serverIndex -> sorted list of regions by primary region index
112     int[][] primariesOfRegionsPerHost;   //hostIndex -> sorted list of regions by primary region index
113     int[][] primariesOfRegionsPerRack;   //rackIndex -> sorted list of regions by primary region index
114 
115     int[][] serversPerHost;              //hostIndex -> list of server indexes
116     int[][] serversPerRack;              //rackIndex -> list of server indexes
117     int[]   regionIndexToServerIndex;    //regionIndex -> serverIndex
118     int[]   initialRegionIndexToServerIndex;    //regionIndex -> serverIndex (initial cluster state)
119     int[]   regionIndexToTableIndex;     //regionIndex -> tableIndex
120     int[][] numRegionsPerServerPerTable; //serverIndex -> tableIndex -> # regions
121     int[]   numMaxRegionsPerTable;       //tableIndex -> max number of regions in a single RS
122     int[]   regionIndexToPrimaryIndex;   //regionIndex -> regionIndex of the primary
123     boolean hasRegionReplicas = false;   //whether there is regions with replicas
124 
125     Integer[] serverIndicesSortedByRegionCount;
126 
127     Map<String, Integer> serversToIndex;
128     Map<String, Integer> hostsToIndex;
129     Map<String, Integer> racksToIndex;
130     Map<String, Integer> tablesToIndex;
131     Map<HRegionInfo, Integer> regionsToIndex;
132 
133     int numServers;
134     int numHosts;
135     int numRacks;
136     int numTables;
137     int numRegions;
138 
139     int numMovedRegions = 0; //num moved regions from the initial configuration
140     // num of moved regions away from master that should be on the master
141     int numMovedMetaRegions = 0;       //num of moved regions that are META
142     Map<ServerName, List<HRegionInfo>> clusterState;
143 
144     protected final RackManager rackManager;
145 
146     protected Cluster(
147         Map<ServerName, List<HRegionInfo>> clusterState,
148         Map<String, Deque<RegionLoad>> loads,
149         RegionLocationFinder regionFinder,
150         RackManager rackManager) {
151       this(null, clusterState, loads, regionFinder,
152         rackManager);
153     }
154 
155     @SuppressWarnings("unchecked")
156     protected Cluster(
157         Collection<HRegionInfo> unassignedRegions,
158         Map<ServerName, List<HRegionInfo>> clusterState,
159         Map<String, Deque<RegionLoad>> loads,
160         RegionLocationFinder regionFinder,
161         RackManager rackManager) {
162 
163       if (unassignedRegions == null) {
164         unassignedRegions = EMPTY_REGION_LIST;
165       }
166 
167       serversToIndex = new HashMap<String, Integer>();
168       hostsToIndex = new HashMap<String, Integer>();
169       racksToIndex = new HashMap<String, Integer>();
170       tablesToIndex = new HashMap<String, Integer>();
171 
172       //TODO: We should get the list of tables from master
173       tables = new ArrayList<String>();
174       this.rackManager = rackManager != null ? rackManager : new DefaultRackManager();
175 
176       numRegions = 0;
177 
178       List<List<Integer>> serversPerHostList = new ArrayList<List<Integer>>();
179       List<List<Integer>> serversPerRackList = new ArrayList<List<Integer>>();
180       this.clusterState = clusterState;
181 
182       // Use servername and port as there can be dead servers in this list. We want everything with
183       // a matching hostname and port to have the same index.
184       for (ServerName sn : clusterState.keySet()) {
185         if (serversToIndex.get(sn.getHostAndPort()) == null) {
186           serversToIndex.put(sn.getHostAndPort(), numServers++);
187         }
188         if (!hostsToIndex.containsKey(sn.getHostname())) {
189           hostsToIndex.put(sn.getHostname(), numHosts++);
190           serversPerHostList.add(new ArrayList<Integer>(1));
191         }
192 
193         int serverIndex = serversToIndex.get(sn.getHostAndPort());
194         int hostIndex = hostsToIndex.get(sn.getHostname());
195         serversPerHostList.get(hostIndex).add(serverIndex);
196 
197         String rack = this.rackManager.getRack(sn);
198         if (!racksToIndex.containsKey(rack)) {
199           racksToIndex.put(rack, numRacks++);
200           serversPerRackList.add(new ArrayList<Integer>());
201         }
202         int rackIndex = racksToIndex.get(rack);
203         serversPerRackList.get(rackIndex).add(serverIndex);
204       }
205 
206       // Count how many regions there are.
207       for (Entry<ServerName, List<HRegionInfo>> entry : clusterState.entrySet()) {
208         numRegions += entry.getValue().size();
209       }
210       numRegions += unassignedRegions.size();
211 
212       regionsToIndex = new HashMap<HRegionInfo, Integer>(numRegions);
213       servers = new ServerName[numServers];
214       serversPerHost = new int[numHosts][];
215       serversPerRack = new int[numRacks][];
216       regions = new HRegionInfo[numRegions];
217       regionIndexToServerIndex = new int[numRegions];
218       initialRegionIndexToServerIndex = new int[numRegions];
219       regionIndexToTableIndex = new int[numRegions];
220       regionIndexToPrimaryIndex = new int[numRegions];
221       regionLoads = new Deque[numRegions];
222       regionLocations = new int[numRegions][];
223       serverIndicesSortedByRegionCount = new Integer[numServers];
224 
225       serverIndexToHostIndex = new int[numServers];
226       serverIndexToRackIndex = new int[numServers];
227       regionsPerServer = new int[numServers][];
228       regionsPerHost = new int[numHosts][];
229       regionsPerRack = new int[numRacks][];
230       primariesOfRegionsPerServer = new int[numServers][];
231       primariesOfRegionsPerHost = new int[numHosts][];
232       primariesOfRegionsPerRack = new int[numRacks][];
233 
234       int tableIndex = 0, regionIndex = 0, regionPerServerIndex = 0;
235 
236       for (Entry<ServerName, List<HRegionInfo>> entry : clusterState.entrySet()) {
237         int serverIndex = serversToIndex.get(entry.getKey().getHostAndPort());
238 
239         // keep the servername if this is the first server name for this hostname
240         // or this servername has the newest startcode.
241         if (servers[serverIndex] == null ||
242             servers[serverIndex].getStartcode() < entry.getKey().getStartcode()) {
243           servers[serverIndex] = entry.getKey();
244         }
245 
246         if (regionsPerServer[serverIndex] != null) {
247           // there is another server with the same hostAndPort in ClusterState.
248           // allocate the array for the total size
249           regionsPerServer[serverIndex] = new int[entry.getValue().size() + regionsPerServer[serverIndex].length];
250         } else {
251           regionsPerServer[serverIndex] = new int[entry.getValue().size()];
252         }
253         primariesOfRegionsPerServer[serverIndex] = new int[regionsPerServer[serverIndex].length];
254         serverIndicesSortedByRegionCount[serverIndex] = serverIndex;
255       }
256 
257       hosts = new String[numHosts];
258       for (Entry<String, Integer> entry : hostsToIndex.entrySet()) {
259         hosts[entry.getValue()] = entry.getKey();
260       }
261       racks = new String[numRacks];
262       for (Entry<String, Integer> entry : racksToIndex.entrySet()) {
263         racks[entry.getValue()] = entry.getKey();
264       }
265 
266       for (Entry<ServerName, List<HRegionInfo>> entry : clusterState.entrySet()) {
267         int serverIndex = serversToIndex.get(entry.getKey().getHostAndPort());
268         regionPerServerIndex = 0;
269 
270         int hostIndex = hostsToIndex.get(entry.getKey().getHostname());
271         serverIndexToHostIndex[serverIndex] = hostIndex;
272 
273         int rackIndex = racksToIndex.get(this.rackManager.getRack(entry.getKey()));
274         serverIndexToRackIndex[serverIndex] = rackIndex;
275 
276         for (HRegionInfo region : entry.getValue()) {
277           registerRegion(region, regionIndex, serverIndex, loads, regionFinder);
278 
279           regionsPerServer[serverIndex][regionPerServerIndex++] = regionIndex;
280           regionIndex++;
281         }
282       }
283       for (HRegionInfo region : unassignedRegions) {
284         registerRegion(region, regionIndex, -1, loads, regionFinder);
285         regionIndex++;
286       }
287 
288       for (int i = 0; i < serversPerHostList.size(); i++) {
289         serversPerHost[i] = new int[serversPerHostList.get(i).size()];
290         for (int j = 0; j < serversPerHost[i].length; j++) {
291           serversPerHost[i][j] = serversPerHostList.get(i).get(j);
292         }
293         if (serversPerHost[i].length > 1) {
294           multiServersPerHost = true;
295         }
296       }
297 
298       for (int i = 0; i < serversPerRackList.size(); i++) {
299         serversPerRack[i] = new int[serversPerRackList.get(i).size()];
300         for (int j = 0; j < serversPerRack[i].length; j++) {
301           serversPerRack[i][j] = serversPerRackList.get(i).get(j);
302         }
303       }
304 
305       numTables = tables.size();
306       numRegionsPerServerPerTable = new int[numServers][numTables];
307 
308       for (int i = 0; i < numServers; i++) {
309         for (int j = 0; j < numTables; j++) {
310           numRegionsPerServerPerTable[i][j] = 0;
311         }
312       }
313 
314       for (int i=0; i < regionIndexToServerIndex.length; i++) {
315         if (regionIndexToServerIndex[i] >= 0) {
316           numRegionsPerServerPerTable[regionIndexToServerIndex[i]][regionIndexToTableIndex[i]]++;
317         }
318       }
319 
320       numMaxRegionsPerTable = new int[numTables];
321       for (int serverIndex = 0 ; serverIndex < numRegionsPerServerPerTable.length; serverIndex++) {
322         for (tableIndex = 0 ; tableIndex < numRegionsPerServerPerTable[serverIndex].length; tableIndex++) {
323           if (numRegionsPerServerPerTable[serverIndex][tableIndex] > numMaxRegionsPerTable[tableIndex]) {
324             numMaxRegionsPerTable[tableIndex] = numRegionsPerServerPerTable[serverIndex][tableIndex];
325           }
326         }
327       }
328 
329       for (int i = 0; i < regions.length; i ++) {
330         HRegionInfo info = regions[i];
331         if (RegionReplicaUtil.isDefaultReplica(info)) {
332           regionIndexToPrimaryIndex[i] = i;
333         } else {
334           hasRegionReplicas = true;
335           HRegionInfo primaryInfo = RegionReplicaUtil.getRegionInfoForDefaultReplica(info);
336           regionIndexToPrimaryIndex[i] =
337               regionsToIndex.containsKey(primaryInfo) ?
338               regionsToIndex.get(primaryInfo):
339               -1;
340         }
341       }
342 
343       for (int i = 0; i < regionsPerServer.length; i++) {
344         primariesOfRegionsPerServer[i] = new int[regionsPerServer[i].length];
345         for (int j = 0; j < regionsPerServer[i].length; j++) {
346           int primaryIndex = regionIndexToPrimaryIndex[regionsPerServer[i][j]];
347           primariesOfRegionsPerServer[i][j] = primaryIndex;
348         }
349         // sort the regions by primaries.
350         Arrays.sort(primariesOfRegionsPerServer[i]);
351       }
352 
353       // compute regionsPerHost
354       if (multiServersPerHost) {
355         for (int i = 0 ; i < serversPerHost.length; i++) {
356           int numRegionsPerHost = 0;
357           for (int j = 0; j < serversPerHost[i].length; j++) {
358             numRegionsPerHost += regionsPerServer[serversPerHost[i][j]].length;
359           }
360           regionsPerHost[i] = new int[numRegionsPerHost];
361           primariesOfRegionsPerHost[i] = new int[numRegionsPerHost];
362         }
363         for (int i = 0 ; i < serversPerHost.length; i++) {
364           int numRegionPerHostIndex = 0;
365           for (int j = 0; j < serversPerHost[i].length; j++) {
366             for (int k = 0; k < regionsPerServer[serversPerHost[i][j]].length; k++) {
367               int region = regionsPerServer[serversPerHost[i][j]][k];
368               regionsPerHost[i][numRegionPerHostIndex] = region;
369               int primaryIndex = regionIndexToPrimaryIndex[region];
370               primariesOfRegionsPerHost[i][numRegionPerHostIndex] = primaryIndex;
371               numRegionPerHostIndex++;
372             }
373           }
374           // sort the regions by primaries.
375           Arrays.sort(primariesOfRegionsPerHost[i]);
376         }
377       }
378 
379       // compute regionsPerRack
380       if (numRacks > 1) {
381         for (int i = 0 ; i < serversPerRack.length; i++) {
382           int numRegionsPerRack = 0;
383           for (int j = 0; j < serversPerRack[i].length; j++) {
384             numRegionsPerRack += regionsPerServer[serversPerRack[i][j]].length;
385           }
386           regionsPerRack[i] = new int[numRegionsPerRack];
387           primariesOfRegionsPerRack[i] = new int[numRegionsPerRack];
388         }
389 
390         for (int i = 0 ; i < serversPerRack.length; i++) {
391           int numRegionPerRackIndex = 0;
392           for (int j = 0; j < serversPerRack[i].length; j++) {
393             for (int k = 0; k < regionsPerServer[serversPerRack[i][j]].length; k++) {
394               int region = regionsPerServer[serversPerRack[i][j]][k];
395               regionsPerRack[i][numRegionPerRackIndex] = region;
396               int primaryIndex = regionIndexToPrimaryIndex[region];
397               primariesOfRegionsPerRack[i][numRegionPerRackIndex] = primaryIndex;
398               numRegionPerRackIndex++;
399             }
400           }
401           // sort the regions by primaries.
402           Arrays.sort(primariesOfRegionsPerRack[i]);
403         }
404       }
405     }
406 
407     /** Helper for Cluster constructor to handle a region */
408     private void registerRegion(HRegionInfo region, int regionIndex, int serverIndex,
409         Map<String, Deque<RegionLoad>> loads, RegionLocationFinder regionFinder) {
410       String tableName = region.getTable().getNameAsString();
411       if (!tablesToIndex.containsKey(tableName)) {
412         tables.add(tableName);
413         tablesToIndex.put(tableName, tablesToIndex.size());
414       }
415       int tableIndex = tablesToIndex.get(tableName);
416 
417       regionsToIndex.put(region, regionIndex);
418       regions[regionIndex] = region;
419       regionIndexToServerIndex[regionIndex] = serverIndex;
420       initialRegionIndexToServerIndex[regionIndex] = serverIndex;
421       regionIndexToTableIndex[regionIndex] = tableIndex;
422 
423       // region load
424       if (loads != null) {
425         Deque<RegionLoad> rl = loads.get(region.getRegionNameAsString());
426         // That could have failed if the RegionLoad is using the other regionName
427         if (rl == null) {
428           // Try getting the region load using encoded name.
429           rl = loads.get(region.getEncodedName());
430         }
431         regionLoads[regionIndex] = rl;
432       }
433 
434       if (regionFinder != null) {
435         //region location
436         List<ServerName> loc = regionFinder.getTopBlockLocations(region);
437         regionLocations[regionIndex] = new int[loc.size()];
438         for (int i=0; i < loc.size(); i++) {
439           regionLocations[regionIndex][i] =
440               loc.get(i) == null ? -1 :
441                 (serversToIndex.get(loc.get(i).getHostAndPort()) == null ? -1
442                     : serversToIndex.get(loc.get(i).getHostAndPort()));
443         }
444       }
445     }
446 
447     /** An action to move or swap a region */
448     public static class Action {
449       public static enum Type {
450         ASSIGN_REGION,
451         MOVE_REGION,
452         SWAP_REGIONS,
453         NULL,
454       }
455 
456       public Type type;
457       public Action (Type type) {this.type = type;}
458       /** Returns an Action which would undo this action */
459       public Action undoAction() { return this; }
460       @Override
461       public String toString() { return type + ":";}
462     }
463 
464     public static class AssignRegionAction extends Action {
465       public int region;
466       public int server;
467       public AssignRegionAction(int region, int server) {
468         super(Type.ASSIGN_REGION);
469         this.region = region;
470         this.server = server;
471       }
472       @Override
473       public Action undoAction() {
474         // TODO implement this. This action is not being used by the StochasticLB for now
475         // in case it uses it, we should implement this function.
476         throw new NotImplementedException();
477       }
478       @Override
479       public String toString() {
480         return type + ": " + region + ":" + server;
481       }
482     }
483 
484     public static class MoveRegionAction extends Action {
485       public int region;
486       public int fromServer;
487       public int toServer;
488 
489       public MoveRegionAction(int region, int fromServer, int toServer) {
490         super(Type.MOVE_REGION);
491         this.fromServer = fromServer;
492         this.region = region;
493         this.toServer = toServer;
494       }
495       @Override
496       public Action undoAction() {
497         return new MoveRegionAction (region, toServer, fromServer);
498       }
499       @Override
500       public String toString() {
501         return type + ": " + region + ":" + fromServer + " -> " + toServer;
502       }
503     }
504 
505     public static class SwapRegionsAction extends Action {
506       public int fromServer;
507       public int fromRegion;
508       public int toServer;
509       public int toRegion;
510       public SwapRegionsAction(int fromServer, int fromRegion, int toServer, int toRegion) {
511         super(Type.SWAP_REGIONS);
512         this.fromServer = fromServer;
513         this.fromRegion = fromRegion;
514         this.toServer = toServer;
515         this.toRegion = toRegion;
516       }
517       @Override
518       public Action undoAction() {
519         return new SwapRegionsAction (fromServer, toRegion, toServer, fromRegion);
520       }
521       @Override
522       public String toString() {
523         return type + ": " + fromRegion + ":" + fromServer + " <-> " + toRegion + ":" + toServer;
524       }
525     }
526 
527     @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="NM_FIELD_NAMING_CONVENTION",
528         justification="Mistake. Too disruptive to change now")
529     public static Action NullAction = new Action(Type.NULL);
530 
531     public void doAction(Action action) {
532       switch (action.type) {
533       case NULL: break;
534       case ASSIGN_REGION:
535         AssignRegionAction ar = (AssignRegionAction) action;
536         regionsPerServer[ar.server] = addRegion(regionsPerServer[ar.server], ar.region);
537         regionMoved(ar.region, -1, ar.server);
538         break;
539       case MOVE_REGION:
540         MoveRegionAction mra = (MoveRegionAction) action;
541         regionsPerServer[mra.fromServer] = removeRegion(regionsPerServer[mra.fromServer], mra.region);
542         regionsPerServer[mra.toServer] = addRegion(regionsPerServer[mra.toServer], mra.region);
543         regionMoved(mra.region, mra.fromServer, mra.toServer);
544         break;
545       case SWAP_REGIONS:
546         SwapRegionsAction a = (SwapRegionsAction) action;
547         regionsPerServer[a.fromServer] = replaceRegion(regionsPerServer[a.fromServer], a.fromRegion, a.toRegion);
548         regionsPerServer[a.toServer] = replaceRegion(regionsPerServer[a.toServer], a.toRegion, a.fromRegion);
549         regionMoved(a.fromRegion, a.fromServer, a.toServer);
550         regionMoved(a.toRegion, a.toServer, a.fromServer);
551         break;
552       default:
553         throw new RuntimeException("Uknown action:" + action.type);
554       }
555     }
556 
557     /**
558      * Return true if the placement of region on server would lower the availability
559      * of the region in question
560      * @param server
561      * @param region
562      * @return true or false
563      */
564     boolean wouldLowerAvailability(HRegionInfo regionInfo, ServerName serverName) {
565       if (!serversToIndex.containsKey(serverName.getHostAndPort())) {
566         return false; // safeguard against race between cluster.servers and servers from LB method args
567       }
568       int server = serversToIndex.get(serverName.getHostAndPort());
569       int region = regionsToIndex.get(regionInfo);
570 
571       int primary = regionIndexToPrimaryIndex[region];
572 
573       // there is a subset relation for server < host < rack
574       // check server first
575 
576       if (contains(primariesOfRegionsPerServer[server], primary)) {
577         // check for whether there are other servers that we can place this region
578         for (int i = 0; i < primariesOfRegionsPerServer.length; i++) {
579           if (i != server && !contains(primariesOfRegionsPerServer[i], primary)) {
580             return true; // meaning there is a better server
581           }
582         }
583         return false; // there is not a better server to place this
584       }
585 
586       // check host
587       if (multiServersPerHost) { // these arrays would only be allocated if we have more than one server per host
588         int host = serverIndexToHostIndex[server];
589         if (contains(primariesOfRegionsPerHost[host], primary)) {
590           // check for whether there are other hosts that we can place this region
591           for (int i = 0; i < primariesOfRegionsPerHost.length; i++) {
592             if (i != host && !contains(primariesOfRegionsPerHost[i], primary)) {
593               return true; // meaning there is a better host
594             }
595           }
596           return false; // there is not a better host to place this
597         }
598       }
599 
600       // check rack
601       if (numRacks > 1) {
602         int rack = serverIndexToRackIndex[server];
603         if (contains(primariesOfRegionsPerRack[rack], primary)) {
604           // check for whether there are other racks that we can place this region
605           for (int i = 0; i < primariesOfRegionsPerRack.length; i++) {
606             if (i != rack && !contains(primariesOfRegionsPerRack[i], primary)) {
607               return true; // meaning there is a better rack
608             }
609           }
610           return false; // there is not a better rack to place this
611         }
612       }
613       return false;
614     }
615 
616     void doAssignRegion(HRegionInfo regionInfo, ServerName serverName) {
617       if (!serversToIndex.containsKey(serverName.getHostAndPort())) {
618         return;
619       }
620       int server = serversToIndex.get(serverName.getHostAndPort());
621       int region = regionsToIndex.get(regionInfo);
622       doAction(new AssignRegionAction(region, server));
623     }
624 
625     void regionMoved(int region, int oldServer, int newServer) {
626       regionIndexToServerIndex[region] = newServer;
627       if (initialRegionIndexToServerIndex[region] == newServer) {
628         numMovedRegions--; //region moved back to original location
629       } else if (oldServer >= 0 && initialRegionIndexToServerIndex[region] == oldServer) {
630         numMovedRegions++; //region moved from original location
631       }
632       int tableIndex = regionIndexToTableIndex[region];
633       if (oldServer >= 0) {
634         numRegionsPerServerPerTable[oldServer][tableIndex]--;
635       }
636       numRegionsPerServerPerTable[newServer][tableIndex]++;
637 
638       //check whether this caused maxRegionsPerTable in the new Server to be updated
639       if (numRegionsPerServerPerTable[newServer][tableIndex] > numMaxRegionsPerTable[tableIndex]) {
640         numRegionsPerServerPerTable[newServer][tableIndex] = numMaxRegionsPerTable[tableIndex];
641       } else if (oldServer >= 0 && (numRegionsPerServerPerTable[oldServer][tableIndex] + 1)
642           == numMaxRegionsPerTable[tableIndex]) {
643         //recompute maxRegionsPerTable since the previous value was coming from the old server
644         for (int serverIndex = 0 ; serverIndex < numRegionsPerServerPerTable.length; serverIndex++) {
645           if (numRegionsPerServerPerTable[serverIndex][tableIndex] > numMaxRegionsPerTable[tableIndex]) {
646             numMaxRegionsPerTable[tableIndex] = numRegionsPerServerPerTable[serverIndex][tableIndex];
647           }
648         }
649       }
650 
651       // update for servers
652       int primary = regionIndexToPrimaryIndex[region];
653       if (oldServer >= 0) {
654         primariesOfRegionsPerServer[oldServer] = removeRegion(
655           primariesOfRegionsPerServer[oldServer], primary);
656       }
657       primariesOfRegionsPerServer[newServer] = addRegionSorted(
658         primariesOfRegionsPerServer[newServer], primary);
659 
660       // update for hosts
661       if (multiServersPerHost) {
662         int oldHost = oldServer >= 0 ? serverIndexToHostIndex[oldServer] : -1;
663         int newHost = serverIndexToHostIndex[newServer];
664         if (newHost != oldHost) {
665           regionsPerHost[newHost] = addRegion(regionsPerHost[newHost], region);
666           primariesOfRegionsPerHost[newHost] = addRegionSorted(primariesOfRegionsPerHost[newHost], primary);
667           if (oldHost >= 0) {
668             regionsPerHost[oldHost] = removeRegion(regionsPerHost[oldHost], region);
669             primariesOfRegionsPerHost[oldHost] = removeRegion(
670               primariesOfRegionsPerHost[oldHost], primary); // will still be sorted
671           }
672         }
673       }
674 
675       // update for racks
676       if (numRacks > 1) {
677         int oldRack = oldServer >= 0 ? serverIndexToRackIndex[oldServer] : -1;
678         int newRack = serverIndexToRackIndex[newServer];
679         if (newRack != oldRack) {
680           regionsPerRack[newRack] = addRegion(regionsPerRack[newRack], region);
681           primariesOfRegionsPerRack[newRack] = addRegionSorted(primariesOfRegionsPerRack[newRack], primary);
682           if (oldRack >= 0) {
683             regionsPerRack[oldRack] = removeRegion(regionsPerRack[oldRack], region);
684             primariesOfRegionsPerRack[oldRack] = removeRegion(
685               primariesOfRegionsPerRack[oldRack], primary); // will still be sorted
686           }
687         }
688       }
689     }
690 
691     int[] removeRegion(int[] regions, int regionIndex) {
692       //TODO: this maybe costly. Consider using linked lists
693       int[] newRegions = new int[regions.length - 1];
694       int i = 0;
695       for (i = 0; i < regions.length; i++) {
696         if (regions[i] == regionIndex) {
697           break;
698         }
699         newRegions[i] = regions[i];
700       }
701       System.arraycopy(regions, i+1, newRegions, i, newRegions.length - i);
702       return newRegions;
703     }
704 
705     int[] addRegion(int[] regions, int regionIndex) {
706       int[] newRegions = new int[regions.length + 1];
707       System.arraycopy(regions, 0, newRegions, 0, regions.length);
708       newRegions[newRegions.length - 1] = regionIndex;
709       return newRegions;
710     }
711 
712     int[] addRegionSorted(int[] regions, int regionIndex) {
713       int[] newRegions = new int[regions.length + 1];
714       int i = 0;
715       for (i = 0; i < regions.length; i++) { // find the index to insert
716         if (regions[i] > regionIndex) {
717           break;
718         }
719       }
720       System.arraycopy(regions, 0, newRegions, 0, i); // copy first half
721       System.arraycopy(regions, i, newRegions, i+1, regions.length - i); // copy second half
722       newRegions[i] = regionIndex;
723 
724       return newRegions;
725     }
726 
727     int[] replaceRegion(int[] regions, int regionIndex, int newRegionIndex) {
728       int i = 0;
729       for (i = 0; i < regions.length; i++) {
730         if (regions[i] == regionIndex) {
731           regions[i] = newRegionIndex;
732           break;
733         }
734       }
735       return regions;
736     }
737 
738     void sortServersByRegionCount() {
739       Arrays.sort(serverIndicesSortedByRegionCount, numRegionsComparator);
740     }
741 
742     int getNumRegions(int server) {
743       return regionsPerServer[server].length;
744     }
745 
746     boolean contains(int[] arr, int val) {
747       return Arrays.binarySearch(arr, val) >= 0;
748     }
749 
750     private Comparator<Integer> numRegionsComparator = new Comparator<Integer>() {
751       @Override
752       public int compare(Integer integer, Integer integer2) {
753         return Integer.valueOf(getNumRegions(integer)).compareTo(getNumRegions(integer2));
754       }
755     };
756 
757     @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="SBSC_USE_STRINGBUFFER_CONCATENATION",
758         justification="Not important but should be fixed")
759     @Override
760     public String toString() {
761       String desc = "Cluster{" +
762           "servers=[";
763           for(ServerName sn:servers) {
764              desc += sn.getHostAndPort() + ", ";
765           }
766           desc +=
767           ", serverIndicesSortedByRegionCount="+
768           Arrays.toString(serverIndicesSortedByRegionCount) +
769           ", regionsPerServer=[";
770 
771           for (int[]r:regionsPerServer) {
772             desc += Arrays.toString(r);
773           }
774           desc += "]" +
775           ", numMaxRegionsPerTable=" +
776           Arrays.toString(numMaxRegionsPerTable) +
777           ", numRegions=" +
778           numRegions +
779           ", numServers=" +
780           numServers +
781           ", numTables=" +
782           numTables +
783           ", numMovedRegions=" +
784           numMovedRegions +
785           '}';
786       return desc;
787     }
788   }
789 
790   // slop for regions
791   protected float slop;
792   protected Configuration config;
793   protected RackManager rackManager;
794   private static final Random RANDOM = new Random(System.currentTimeMillis());
795   private static final Log LOG = LogFactory.getLog(BaseLoadBalancer.class);
796 
797   // Regions of these tables are put on the master by default.
798   private static final String[] DEFAULT_TABLES_ON_MASTER =
799     new String[] {AccessControlLists.ACL_TABLE_NAME.getNameAsString(),
800       TableName.NAMESPACE_TABLE_NAME.getNameAsString(),
801       TableName.META_TABLE_NAME.getNameAsString()};
802 
803   public static final String TABLES_ON_MASTER =
804     "hbase.balancer.tablesOnMaster";
805 
806   protected final Set<String> tablesOnMaster = new HashSet<String>();
807   protected final MetricsBalancer metricsBalancer = new MetricsBalancer();
808   protected ClusterStatus clusterStatus = null;
809   protected ServerName masterServerName;
810   protected MasterServices services;
811 
812   /**
813    * By default, regions of some small system tables such as meta,
814    * namespace, and acl are assigned to the active master. If you don't
815    * want to assign any region to the active master, you need to
816    * configure "hbase.balancer.tablesOnMaster" to "none".
817    */
818   protected static String[] getTablesOnMaster(Configuration conf) {
819     String valueString = conf.get(TABLES_ON_MASTER);
820     if (valueString == null) {
821       return DEFAULT_TABLES_ON_MASTER;
822     }
823     valueString = valueString.trim();
824     if (valueString.equalsIgnoreCase("none")) {
825       return null;
826     }
827     return StringUtils.getStrings(valueString);
828   }
829 
830   /**
831    * Check if configured to put any tables on the active master
832    */
833   public static boolean tablesOnMaster(Configuration conf) {
834     String[] tables = getTablesOnMaster(conf);
835     return tables != null && tables.length > 0;
836   }
837 
838   @Override
839   public void setConf(Configuration conf) {
840     setSlop(conf);
841     if (slop < 0) slop = 0;
842     else if (slop > 1) slop = 1;
843 
844     this.config = conf;
845     String[] tables = getTablesOnMaster(conf);
846     if (tables != null && tables.length > 0) {
847       Collections.addAll(tablesOnMaster, tables);
848     }
849     this.rackManager = new RackManager(getConf());
850     regionFinder.setConf(conf);
851   }
852 
853   protected void setSlop(Configuration conf) {
854     this.slop = conf.getFloat("hbase.regions.slop", (float) 0.2);
855   }
856 
857   /**
858    * Check if a region belongs to some small system table.
859    * If so, it may be expected to be put on the master regionserver.
860    */
861   public boolean shouldBeOnMaster(HRegionInfo region) {
862     return tablesOnMaster.contains(region.getTable().getNameAsString());
863   }
864 
865   /**
866    * Balance the regions that should be on master regionserver.
867    */
868   protected List<RegionPlan> balanceMasterRegions(
869       Map<ServerName, List<HRegionInfo>> clusterMap) {
870     if (masterServerName == null
871         || clusterMap == null || clusterMap.size() <= 1) return null;
872     List<RegionPlan> plans = null;
873     List<HRegionInfo> regions = clusterMap.get(masterServerName);
874     if (regions != null) {
875       Iterator<ServerName> keyIt = null;
876       for (HRegionInfo region: regions) {
877         if (shouldBeOnMaster(region)) continue;
878 
879         // Find a non-master regionserver to host the region
880         if (keyIt == null || !keyIt.hasNext()) {
881           keyIt = clusterMap.keySet().iterator();
882         }
883         ServerName dest = keyIt.next();
884         if (masterServerName.equals(dest)) {
885           if (!keyIt.hasNext()) {
886             keyIt = clusterMap.keySet().iterator();
887           }
888           dest = keyIt.next();
889         }
890 
891         // Move this region away from the master regionserver
892         RegionPlan plan = new RegionPlan(region, masterServerName, dest);
893         if (plans == null) {
894           plans = new ArrayList<RegionPlan>();
895         }
896         plans.add(plan);
897       }
898     }
899     for (Map.Entry<ServerName, List<HRegionInfo>> server: clusterMap.entrySet()) {
900       if (masterServerName.equals(server.getKey())) continue;
901       for (HRegionInfo region: server.getValue()) {
902         if (!shouldBeOnMaster(region)) continue;
903 
904         // Move this region to the master regionserver
905         RegionPlan plan = new RegionPlan(region, server.getKey(), masterServerName);
906         if (plans == null) {
907           plans = new ArrayList<RegionPlan>();
908         }
909         plans.add(plan);
910       }
911     }
912     return plans;
913   }
914 
915   /**
916    * Assign the regions that should be on master regionserver.
917    */
918   protected Map<ServerName, List<HRegionInfo>> assignMasterRegions(
919       Collection<HRegionInfo> regions, List<ServerName> servers) {
920     if (servers == null || regions == null || regions.isEmpty()) {
921       return null;
922     }
923     Map<ServerName, List<HRegionInfo>> assignments
924       = new TreeMap<ServerName, List<HRegionInfo>>();
925     if (masterServerName != null && servers.contains(masterServerName)) {
926       assignments.put(masterServerName, new ArrayList<HRegionInfo>());
927       for (HRegionInfo region: regions) {
928         if (shouldBeOnMaster(region)) {
929           assignments.get(masterServerName).add(region);
930         }
931       }
932     }
933     return assignments;
934   }
935 
936   @Override
937   public Configuration getConf() {
938     return this.config;
939   }
940 
941   @Override
942   public void setClusterStatus(ClusterStatus st) {
943     this.clusterStatus = st;
944     regionFinder.setClusterStatus(st);
945   }
946 
947   @Override
948   public void setMasterServices(MasterServices masterServices) {
949     masterServerName = masterServices.getServerName();
950     this.services = masterServices;
951     this.regionFinder.setServices(masterServices);
952   }
953 
954   public void setRackManager(RackManager rackManager) {
955     this.rackManager = rackManager;
956   }
957 
958   protected boolean needsBalance(Cluster c) {
959     ClusterLoadState cs = new ClusterLoadState(c.clusterState);
960     if (cs.getNumServers() < MIN_SERVER_BALANCE) {
961       if (LOG.isDebugEnabled()) {
962         LOG.debug("Not running balancer because only " + cs.getNumServers()
963             + " active regionserver(s)");
964       }
965       return false;
966     }
967     if(areSomeRegionReplicasColocated(c)) return true;
968     // Check if we even need to do any load balancing
969     // HBASE-3681 check sloppiness first
970     float average = cs.getLoadAverage(); // for logging
971     int floor = (int) Math.floor(average * (1 - slop));
972     int ceiling = (int) Math.ceil(average * (1 + slop));
973     if (!(cs.getMaxLoad() > ceiling || cs.getMinLoad() < floor)) {
974       NavigableMap<ServerAndLoad, List<HRegionInfo>> serversByLoad = cs.getServersByLoad();
975       if (LOG.isTraceEnabled()) {
976         // If nothing to balance, then don't say anything unless trace-level logging.
977         LOG.trace("Skipping load balancing because balanced cluster; " +
978           "servers=" + cs.getNumServers() +
979           " regions=" + cs.getNumRegions() + " average=" + average +
980           " mostloaded=" + serversByLoad.lastKey().getLoad() +
981           " leastloaded=" + serversByLoad.firstKey().getLoad());
982       }
983       return false;
984     }
985     return true;
986   }
987 
988   /**
989    * Subclasses should implement this to return true if the cluster has nodes that hosts
990    * multiple replicas for the same region, or, if there are multiple racks and the same
991    * rack hosts replicas of the same region
992    * @param c Cluster information
993    * @return whether region replicas are currently co-located
994    */
995   protected boolean areSomeRegionReplicasColocated(Cluster c) {
996     return false;
997   }
998 
999   /**
1000    * Generates a bulk assignment plan to be used on cluster startup using a
1001    * simple round-robin assignment.
1002    * <p>
1003    * Takes a list of all the regions and all the servers in the cluster and
1004    * returns a map of each server to the regions that it should be assigned.
1005    * <p>
1006    * Currently implemented as a round-robin assignment. Same invariant as load
1007    * balancing, all servers holding floor(avg) or ceiling(avg).
1008    *
1009    * TODO: Use block locations from HDFS to place regions with their blocks
1010    *
1011    * @param regions all regions
1012    * @param servers all servers
1013    * @return map of server to the regions it should take, or null if no
1014    *         assignment is possible (ie. no regions or no servers)
1015    */
1016   @Override
1017   public Map<ServerName, List<HRegionInfo>> roundRobinAssignment(List<HRegionInfo> regions,
1018       List<ServerName> servers) {
1019     metricsBalancer.incrMiscInvocations();
1020     Map<ServerName, List<HRegionInfo>> assignments = assignMasterRegions(regions, servers);
1021     if (assignments != null && !assignments.isEmpty()) {
1022       servers = new ArrayList<ServerName>(servers);
1023       // Guarantee not to put other regions on master
1024       servers.remove(masterServerName);
1025       List<HRegionInfo> masterRegions = assignments.get(masterServerName);
1026       if (!masterRegions.isEmpty()) {
1027         regions = new ArrayList<HRegionInfo>(regions);
1028         for (HRegionInfo region: masterRegions) {
1029           regions.remove(region);
1030         }
1031       }
1032     }
1033     if (regions == null || regions.isEmpty()) {
1034       return assignments;
1035     }
1036 
1037     int numServers = servers == null ? 0 : servers.size();
1038     if (numServers == 0) {
1039       LOG.warn("Wanted to do round robin assignment but no servers to assign to");
1040       return null;
1041     }
1042 
1043     // TODO: instead of retainAssignment() and roundRobinAssignment(), we should just run the
1044     // normal LB.balancerCluster() with unassignedRegions. We only need to have a candidate
1045     // generator for AssignRegionAction. The LB will ensure the regions are mostly local
1046     // and balanced. This should also run fast with fewer number of iterations.
1047 
1048     if (numServers == 1) { // Only one server, nothing fancy we can do here
1049       ServerName server = servers.get(0);
1050       assignments.put(server, new ArrayList<HRegionInfo>(regions));
1051       return assignments;
1052     }
1053 
1054     Cluster cluster = createCluster(servers, regions);
1055     List<HRegionInfo> unassignedRegions = new ArrayList<HRegionInfo>();
1056 
1057     roundRobinAssignment(cluster, regions, unassignedRegions,
1058       servers, assignments);
1059 
1060     List<HRegionInfo> lastFewRegions = new ArrayList<HRegionInfo>();
1061     // assign the remaining by going through the list and try to assign to servers one-by-one
1062     int serverIdx = RANDOM.nextInt(numServers);
1063     for (HRegionInfo region : unassignedRegions) {
1064       boolean assigned = false;
1065       for (int j = 0; j < numServers; j++) { // try all servers one by one
1066         ServerName serverName = servers.get((j + serverIdx) % numServers);
1067         if (!cluster.wouldLowerAvailability(region, serverName)) {
1068           List<HRegionInfo> serverRegions = assignments.get(serverName);
1069           if (serverRegions == null) {
1070             serverRegions = new ArrayList<HRegionInfo>();
1071             assignments.put(serverName, serverRegions);
1072           }
1073           serverRegions.add(region);
1074           cluster.doAssignRegion(region, serverName);
1075           serverIdx = (j + serverIdx + 1) % numServers; //remain from next server
1076           assigned = true;
1077           break;
1078         }
1079       }
1080       if (!assigned) {
1081         lastFewRegions.add(region);
1082       }
1083     }
1084     // just sprinkle the rest of the regions on random regionservers. The balanceCluster will
1085     // make it optimal later. we can end up with this if numReplicas > numServers.
1086     for (HRegionInfo region : lastFewRegions) {
1087       int i = RANDOM.nextInt(numServers);
1088       ServerName server = servers.get(i);
1089       List<HRegionInfo> serverRegions = assignments.get(server);
1090       if (serverRegions == null) {
1091         serverRegions = new ArrayList<HRegionInfo>();
1092         assignments.put(server, serverRegions);
1093       }
1094       serverRegions.add(region);
1095       cluster.doAssignRegion(region, server);
1096     }
1097     return assignments;
1098   }
1099 
1100   protected Cluster createCluster(List<ServerName> servers,
1101       Collection<HRegionInfo> regions) {
1102     // Get the snapshot of the current assignments for the regions in question, and then create
1103     // a cluster out of it. Note that we might have replicas already assigned to some servers
1104     // earlier. So we want to get the snapshot to see those assignments, but this will only contain
1105     // replicas of the regions that are passed (for performance).
1106     Map<ServerName, List<HRegionInfo>> clusterState = getRegionAssignmentsByServer(regions);
1107 
1108     for (ServerName server : servers) {
1109       if (!clusterState.containsKey(server)) {
1110         clusterState.put(server, EMPTY_REGION_LIST);
1111       }
1112     }
1113     return new Cluster(regions, clusterState, null, this.regionFinder,
1114       rackManager);
1115   }
1116 
1117   /**
1118    * Generates an immediate assignment plan to be used by a new master for
1119    * regions in transition that do not have an already known destination.
1120    *
1121    * Takes a list of regions that need immediate assignment and a list of all
1122    * available servers. Returns a map of regions to the server they should be
1123    * assigned to.
1124    *
1125    * This method will return quickly and does not do any intelligent balancing.
1126    * The goal is to make a fast decision not the best decision possible.
1127    *
1128    * Currently this is random.
1129    *
1130    * @param regions
1131    * @param servers
1132    * @return map of regions to the server it should be assigned to
1133    */
1134   @Override
1135   public Map<HRegionInfo, ServerName> immediateAssignment(List<HRegionInfo> regions,
1136       List<ServerName> servers) {
1137     metricsBalancer.incrMiscInvocations();
1138     if (servers == null || servers.isEmpty()) {
1139       LOG.warn("Wanted to do random assignment but no servers to assign to");
1140       return null;
1141     }
1142 
1143     Map<HRegionInfo, ServerName> assignments = new TreeMap<HRegionInfo, ServerName>();
1144     for (HRegionInfo region : regions) {
1145       assignments.put(region, randomAssignment(region, servers));
1146     }
1147     return assignments;
1148   }
1149 
1150   /**
1151    * Used to assign a single region to a random server.
1152    */
1153   @Override
1154   public ServerName randomAssignment(HRegionInfo regionInfo, List<ServerName> servers) {
1155     metricsBalancer.incrMiscInvocations();
1156     if (servers != null && servers.contains(masterServerName)) {
1157       if (shouldBeOnMaster(regionInfo)) {
1158         return masterServerName;
1159       }
1160       servers = new ArrayList<ServerName>(servers);
1161       // Guarantee not to put other regions on master
1162       servers.remove(masterServerName);
1163     }
1164 
1165     int numServers = servers == null ? 0 : servers.size();
1166     if (numServers == 0) {
1167       LOG.warn("Wanted to do retain assignment but no servers to assign to");
1168       return null;
1169     }
1170     if (numServers == 1) { // Only one server, nothing fancy we can do here
1171       return servers.get(0);
1172     }
1173 
1174     List<HRegionInfo> regions = Lists.newArrayList(regionInfo);
1175     Cluster cluster = createCluster(servers, regions);
1176     return randomAssignment(cluster, regionInfo, servers);
1177   }
1178 
1179   /**
1180    * Generates a bulk assignment startup plan, attempting to reuse the existing
1181    * assignment information from META, but adjusting for the specified list of
1182    * available/online servers available for assignment.
1183    * <p>
1184    * Takes a map of all regions to their existing assignment from META. Also
1185    * takes a list of online servers for regions to be assigned to. Attempts to
1186    * retain all assignment, so in some instances initial assignment will not be
1187    * completely balanced.
1188    * <p>
1189    * Any leftover regions without an existing server to be assigned to will be
1190    * assigned randomly to available servers.
1191    *
1192    * @param regions regions and existing assignment from meta
1193    * @param servers available servers
1194    * @return map of servers and regions to be assigned to them
1195    */
1196   @Override
1197   public Map<ServerName, List<HRegionInfo>> retainAssignment(Map<HRegionInfo, ServerName> regions,
1198       List<ServerName> servers) {
1199     // Update metrics
1200     metricsBalancer.incrMiscInvocations();
1201     Map<ServerName, List<HRegionInfo>> assignments
1202       = assignMasterRegions(regions.keySet(), servers);
1203     if (assignments != null && !assignments.isEmpty()) {
1204       servers = new ArrayList<ServerName>(servers);
1205       // Guarantee not to put other regions on master
1206       servers.remove(masterServerName);
1207       List<HRegionInfo> masterRegions = assignments.get(masterServerName);
1208       if (!masterRegions.isEmpty()) {
1209         regions = new HashMap<HRegionInfo, ServerName>(regions);
1210         for (HRegionInfo region: masterRegions) {
1211           regions.remove(region);
1212         }
1213       }
1214     }
1215     if (regions == null || regions.isEmpty()) {
1216       return assignments;
1217     }
1218 
1219     int numServers = servers == null ? 0 : servers.size();
1220     if (numServers == 0) {
1221       LOG.warn("Wanted to do retain assignment but no servers to assign to");
1222       return null;
1223     }
1224     if (numServers == 1) { // Only one server, nothing fancy we can do here
1225       ServerName server = servers.get(0);
1226       assignments.put(server, new ArrayList<HRegionInfo>(regions.keySet()));
1227       return assignments;
1228     }
1229 
1230     // Group all of the old assignments by their hostname.
1231     // We can't group directly by ServerName since the servers all have
1232     // new start-codes.
1233 
1234     // Group the servers by their hostname. It's possible we have multiple
1235     // servers on the same host on different ports.
1236     ArrayListMultimap<String, ServerName> serversByHostname = ArrayListMultimap.create();
1237     for (ServerName server : servers) {
1238       assignments.put(server, new ArrayList<HRegionInfo>());
1239       serversByHostname.put(server.getHostname(), server);
1240     }
1241 
1242     // Collection of the hostnames that used to have regions
1243     // assigned, but for which we no longer have any RS running
1244     // after the cluster restart.
1245     Set<String> oldHostsNoLongerPresent = Sets.newTreeSet();
1246 
1247     int numRandomAssignments = 0;
1248     int numRetainedAssigments = 0;
1249 
1250     Cluster cluster = createCluster(servers, regions.keySet());
1251 
1252     for (Map.Entry<HRegionInfo, ServerName> entry : regions.entrySet()) {
1253       HRegionInfo region = entry.getKey();
1254       ServerName oldServerName = entry.getValue();
1255       List<ServerName> localServers = new ArrayList<ServerName>();
1256       if (oldServerName != null) {
1257         localServers = serversByHostname.get(oldServerName.getHostname());
1258       }
1259       if (localServers.isEmpty()) {
1260         // No servers on the new cluster match up with this hostname,
1261         // assign randomly.
1262         ServerName randomServer = randomAssignment(cluster, region, servers);
1263         assignments.get(randomServer).add(region);
1264         numRandomAssignments++;
1265         if (oldServerName != null) oldHostsNoLongerPresent.add(oldServerName.getHostname());
1266       } else if (localServers.size() == 1) {
1267         // the usual case - one new server on same host
1268         ServerName target = localServers.get(0);
1269         assignments.get(target).add(region);
1270         cluster.doAssignRegion(region, target);
1271         numRetainedAssigments++;
1272       } else {
1273         // multiple new servers in the cluster on this same host
1274         if (localServers.contains(oldServerName)) {
1275           assignments.get(oldServerName).add(region);
1276           cluster.doAssignRegion(region, oldServerName);
1277         } else {
1278           ServerName target = null;
1279           for (ServerName tmp: localServers) {
1280             if (tmp.getPort() == oldServerName.getPort()) {
1281               target = tmp;
1282               break;
1283             }
1284           }
1285           if (target == null) {
1286             target = randomAssignment(cluster, region, localServers);
1287           }
1288           assignments.get(target).add(region);
1289         }
1290         numRetainedAssigments++;
1291       }
1292     }
1293 
1294     String randomAssignMsg = "";
1295     if (numRandomAssignments > 0) {
1296       randomAssignMsg =
1297           numRandomAssignments + " regions were assigned "
1298               + "to random hosts, since the old hosts for these regions are no "
1299               + "longer present in the cluster. These hosts were:\n  "
1300               + Joiner.on("\n  ").join(oldHostsNoLongerPresent);
1301     }
1302 
1303     LOG.info("Reassigned " + regions.size() + " regions. " + numRetainedAssigments
1304         + " retained the pre-restart assignment. " + randomAssignMsg);
1305     return assignments;
1306   }
1307 
1308   @Override
1309   public void initialize() throws HBaseIOException{
1310   }
1311 
1312   @Override
1313   public void regionOnline(HRegionInfo regionInfo, ServerName sn) {
1314   }
1315 
1316   @Override
1317   public void regionOffline(HRegionInfo regionInfo) {
1318   }
1319 
1320   @Override
1321   public boolean isStopped() {
1322     return stopped;
1323   }
1324 
1325   @Override
1326   public void stop(String why) {
1327     LOG.info("Load Balancer stop requested: "+why);
1328     stopped = true;
1329   }
1330 
1331   /**
1332    * Used to assign a single region to a random server.
1333    */
1334   private ServerName randomAssignment(Cluster cluster, HRegionInfo regionInfo,
1335       List<ServerName> servers) {
1336     int numServers = servers.size(); // servers is not null, numServers > 1
1337     ServerName sn = null;
1338     final int maxIterations = numServers * 4;
1339     int iterations = 0;
1340 
1341     do {
1342       int i = RANDOM.nextInt(numServers);
1343       sn = servers.get(i);
1344     } while (cluster.wouldLowerAvailability(regionInfo, sn)
1345         && iterations++ < maxIterations);
1346     cluster.doAssignRegion(regionInfo, sn);
1347     return sn;
1348   }
1349 
1350   /**
1351    * Round robin a list of regions to a list of servers
1352    */
1353   private void roundRobinAssignment(Cluster cluster, List<HRegionInfo> regions,
1354       List<HRegionInfo> unassignedRegions, List<ServerName> servers,
1355       Map<ServerName, List<HRegionInfo>> assignments) {
1356 
1357     int numServers = servers.size();
1358     int numRegions = regions.size();
1359     int max = (int) Math.ceil((float) numRegions / numServers);
1360     int serverIdx = 0;
1361     if (numServers > 1) {
1362       serverIdx = RANDOM.nextInt(numServers);
1363     }
1364     int regionIdx = 0;
1365 
1366     for (int j = 0; j < numServers; j++) {
1367       ServerName server = servers.get((j + serverIdx) % numServers);
1368       List<HRegionInfo> serverRegions = new ArrayList<HRegionInfo>(max);
1369       for (int i = regionIdx; i < numRegions; i += numServers) {
1370         HRegionInfo region = regions.get(i % numRegions);
1371         if (cluster.wouldLowerAvailability(region, server)) {
1372           unassignedRegions.add(region);
1373         } else {
1374           serverRegions.add(region);
1375           cluster.doAssignRegion(region, server);
1376         }
1377       }
1378       assignments.put(server, serverRegions);
1379       regionIdx++;
1380     }
1381   }
1382 
1383   protected Map<ServerName, List<HRegionInfo>> getRegionAssignmentsByServer(
1384     Collection<HRegionInfo> regions) {
1385     if (this.services != null && this.services.getAssignmentManager() != null) {
1386       return this.services.getAssignmentManager().getSnapShotOfAssignment(regions);
1387     } else {
1388       return new HashMap<ServerName, List<HRegionInfo>>();
1389     }
1390   }
1391 }