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.Collections;
23  import java.util.HashMap;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.NavigableMap;
27  import java.util.Random;
28  import java.util.TreeMap;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.hbase.classification.InterfaceAudience;
33  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
34  import org.apache.hadoop.hbase.HRegionInfo;
35  import org.apache.hadoop.hbase.ServerName;
36  import org.apache.hadoop.hbase.master.RegionPlan;
37  
38  import com.google.common.collect.MinMaxPriorityQueue;
39  
40  /**
41   * Makes decisions about the placement and movement of Regions across
42   * RegionServers.
43   *
44   * <p>Cluster-wide load balancing will occur only when there are no regions in
45   * transition and according to a fixed period of a time using {@link #balanceCluster(Map)}.
46   *
47   * <p>Inline region placement with {@link #immediateAssignment} can be used when
48   * the Master needs to handle closed regions that it currently does not have
49   * a destination set for.  This can happen during master failover.
50   *
51   * <p>On cluster startup, bulk assignment can be used to determine
52   * locations for all Regions in a cluster.
53   *
54   * <p>This classes produces plans for the 
55   * {@link org.apache.hadoop.hbase.master.AssignmentManager} to execute.
56   */
57  @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
58  public class SimpleLoadBalancer extends BaseLoadBalancer {
59    private static final Log LOG = LogFactory.getLog(SimpleLoadBalancer.class);
60    private static final Random RANDOM = new Random(System.currentTimeMillis());
61  
62    private RegionInfoComparator riComparator = new RegionInfoComparator();
63    private RegionPlan.RegionPlanComparator rpComparator = new RegionPlan.RegionPlanComparator();
64  
65  
66    /**
67     * Stores additional per-server information about the regions added/removed
68     * during the run of the balancing algorithm.
69     *
70     * For servers that shed regions, we need to track which regions we have already
71     * shed. <b>nextRegionForUnload</b> contains the index in the list of regions on
72     * the server that is the next to be shed.
73     */
74    static class BalanceInfo {
75  
76      private final int nextRegionForUnload;
77      private int numRegionsAdded;
78  
79      public BalanceInfo(int nextRegionForUnload, int numRegionsAdded) {
80        this.nextRegionForUnload = nextRegionForUnload;
81        this.numRegionsAdded = numRegionsAdded;
82      }
83  
84      int getNextRegionForUnload() {
85        return nextRegionForUnload;
86      }
87  
88      int getNumRegionsAdded() {
89        return numRegionsAdded;
90      }
91  
92      void setNumRegionsAdded(int numAdded) {
93        this.numRegionsAdded = numAdded;
94      }
95    }
96  
97    /**
98     * Generate a global load balancing plan according to the specified map of
99     * server information to the most loaded regions of each server.
100    *
101    * The load balancing invariant is that all servers are within 1 region of the
102    * average number of regions per server.  If the average is an integer number,
103    * all servers will be balanced to the average.  Otherwise, all servers will
104    * have either floor(average) or ceiling(average) regions.
105    *
106    * HBASE-3609 Modeled regionsToMove using Guava's MinMaxPriorityQueue so that
107    *   we can fetch from both ends of the queue.
108    * At the beginning, we check whether there was empty region server
109    *   just discovered by Master. If so, we alternately choose new / old
110    *   regions from head / tail of regionsToMove, respectively. This alternation
111    *   avoids clustering young regions on the newly discovered region server.
112    *   Otherwise, we choose new regions from head of regionsToMove.
113    *
114    * Another improvement from HBASE-3609 is that we assign regions from
115    *   regionsToMove to underloaded servers in round-robin fashion.
116    *   Previously one underloaded server would be filled before we move onto
117    *   the next underloaded server, leading to clustering of young regions.
118    *
119    * Finally, we randomly shuffle underloaded servers so that they receive
120    *   offloaded regions relatively evenly across calls to balanceCluster().
121    *
122    * The algorithm is currently implemented as such:
123    *
124    * <ol>
125    * <li>Determine the two valid numbers of regions each server should have,
126    *     <b>MIN</b>=floor(average) and <b>MAX</b>=ceiling(average).
127    *
128    * <li>Iterate down the most loaded servers, shedding regions from each so
129    *     each server hosts exactly <b>MAX</b> regions.  Stop once you reach a
130    *     server that already has &lt;= <b>MAX</b> regions.
131    *     <p>
132    *     Order the regions to move from most recent to least.
133    *
134    * <li>Iterate down the least loaded servers, assigning regions so each server
135    *     has exactly <b>MIN</b> regions.  Stop once you reach a server that
136    *     already has &gt;= <b>MIN</b> regions.
137    *
138    *     Regions being assigned to underloaded servers are those that were shed
139    *     in the previous step.  It is possible that there were not enough
140    *     regions shed to fill each underloaded server to <b>MIN</b>.  If so we
141    *     end up with a number of regions required to do so, <b>neededRegions</b>.
142    *
143    *     It is also possible that we were able to fill each underloaded but ended
144    *     up with regions that were unassigned from overloaded servers but that
145    *     still do not have assignment.
146    *
147    *     If neither of these conditions hold (no regions needed to fill the
148    *     underloaded servers, no regions leftover from overloaded servers),
149    *     we are done and return.  Otherwise we handle these cases below.
150    *
151    * <li>If <b>neededRegions</b> is non-zero (still have underloaded servers),
152    *     we iterate the most loaded servers again, shedding a single server from
153    *     each (this brings them from having <b>MAX</b> regions to having
154    *     <b>MIN</b> regions).
155    *
156    * <li>We now definitely have more regions that need assignment, either from
157    *     the previous step or from the original shedding from overloaded servers.
158    *     Iterate the least loaded servers filling each to <b>MIN</b>.
159    *
160    * <li>If we still have more regions that need assignment, again iterate the
161    *     least loaded servers, this time giving each one (filling them to
162    *     <b>MAX</b>) until we run out.
163    *
164    * <li>All servers will now either host <b>MIN</b> or <b>MAX</b> regions.
165    *
166    *     In addition, any server hosting &gt;= <b>MAX</b> regions is guaranteed
167    *     to end up with <b>MAX</b> regions at the end of the balancing.  This
168    *     ensures the minimal number of regions possible are moved.
169    * </ol>
170    *
171    * TODO: We can at-most reassign the number of regions away from a particular
172    *       server to be how many they report as most loaded.
173    *       Should we just keep all assignment in memory?  Any objections?
174    *       Does this mean we need HeapSize on HMaster?  Or just careful monitor?
175    *       (current thinking is we will hold all assignments in memory)
176    *
177    * @param clusterMap Map of regionservers and their load/region information to
178    *                   a list of their most loaded regions
179    * @return a list of regions to be moved, including source and destination,
180    *         or null if cluster is already balanced
181    */
182   @Override
183   public List<RegionPlan> balanceCluster(
184       Map<ServerName, List<HRegionInfo>> clusterMap) {
185     List<RegionPlan> regionsToReturn = balanceMasterRegions(clusterMap);
186     if (regionsToReturn != null || clusterMap == null || clusterMap.size() <= 1) {
187       return regionsToReturn;
188     }
189     if (masterServerName != null && clusterMap.containsKey(masterServerName)) {
190       if (clusterMap.size() <= 2) {
191         return null;
192       }
193       clusterMap = new HashMap<ServerName, List<HRegionInfo>>(clusterMap);
194       clusterMap.remove(masterServerName);
195     }
196 
197     long startTime = System.currentTimeMillis();
198 
199     // construct a Cluster object with clusterMap and rest of the
200     // argument as defaults
201     Cluster c = new Cluster(clusterMap, null, this.regionFinder, this.rackManager);
202     if (!this.needsBalance(c)) return null;
203 
204     ClusterLoadState cs = new ClusterLoadState(clusterMap);
205     int numServers = cs.getNumServers();
206     NavigableMap<ServerAndLoad, List<HRegionInfo>> serversByLoad = cs.getServersByLoad();
207     int numRegions = cs.getNumRegions();
208     float average = cs.getLoadAverage();
209     int max = (int)Math.ceil(average);
210     int min = (int)average;
211 
212     // Using to check balance result.
213     StringBuilder strBalanceParam = new StringBuilder();
214     strBalanceParam.append("Balance parameter: numRegions=").append(numRegions)
215         .append(", numServers=").append(numServers).append(", max=").append(max)
216         .append(", min=").append(min);
217     LOG.debug(strBalanceParam.toString());
218 
219     // Balance the cluster
220     // TODO: Look at data block locality or a more complex load to do this
221     MinMaxPriorityQueue<RegionPlan> regionsToMove =
222       MinMaxPriorityQueue.orderedBy(rpComparator).create();
223     regionsToReturn = new ArrayList<RegionPlan>();
224 
225     // Walk down most loaded, pruning each to the max
226     int serversOverloaded = 0;
227     // flag used to fetch regions from head and tail of list, alternately
228     boolean fetchFromTail = false;
229     Map<ServerName, BalanceInfo> serverBalanceInfo =
230       new TreeMap<ServerName, BalanceInfo>();
231     for (Map.Entry<ServerAndLoad, List<HRegionInfo>> server:
232         serversByLoad.descendingMap().entrySet()) {
233       ServerAndLoad sal = server.getKey();
234       int load = sal.getLoad();
235       if (load <= max) {
236         serverBalanceInfo.put(sal.getServerName(), new BalanceInfo(0, 0));
237         break;
238       }
239       serversOverloaded++;
240       List<HRegionInfo> regions = server.getValue();
241       int numToOffload = Math.min(load - max, regions.size());
242       // account for the out-of-band regions which were assigned to this server
243       // after some other region server crashed
244       Collections.sort(regions, riComparator);
245       int numTaken = 0;
246       for (int i = 0; i <= numToOffload; ) {
247         HRegionInfo hri = regions.get(i); // fetch from head
248         if (fetchFromTail) {
249           hri = regions.get(regions.size() - 1 - i);
250         }
251         i++;
252         // Don't rebalance special regions.
253         if (shouldBeOnMaster(hri)
254             && masterServerName.equals(sal.getServerName())) continue;
255         regionsToMove.add(new RegionPlan(hri, sal.getServerName(), null));
256         numTaken++;
257         if (numTaken >= numToOffload) break;
258       }
259       serverBalanceInfo.put(sal.getServerName(),
260         new BalanceInfo(numToOffload, (-1)*numTaken));
261     }
262     int totalNumMoved = regionsToMove.size();
263 
264     // Walk down least loaded, filling each to the min
265     int neededRegions = 0; // number of regions needed to bring all up to min
266     fetchFromTail = false;
267 
268     Map<ServerName, Integer> underloadedServers = new HashMap<ServerName, Integer>();
269     int maxToTake = numRegions - min;
270     for (Map.Entry<ServerAndLoad, List<HRegionInfo>> server:
271         serversByLoad.entrySet()) {
272       if (maxToTake == 0) break; // no more to take
273       int load = server.getKey().getLoad();
274       if (load >= min && load > 0) {
275         continue; // look for other servers which haven't reached min
276       }
277       int regionsToPut = min - load;
278       if (regionsToPut == 0)
279       {
280         regionsToPut = 1;
281       }
282       maxToTake -= regionsToPut;
283       underloadedServers.put(server.getKey().getServerName(), regionsToPut);
284     }
285     // number of servers that get new regions
286     int serversUnderloaded = underloadedServers.size();
287     int incr = 1;
288     List<ServerName> sns =
289       Arrays.asList(underloadedServers.keySet().toArray(new ServerName[serversUnderloaded]));
290     Collections.shuffle(sns, RANDOM);
291     while (regionsToMove.size() > 0) {
292       int cnt = 0;
293       int i = incr > 0 ? 0 : underloadedServers.size()-1;
294       for (; i >= 0 && i < underloadedServers.size(); i += incr) {
295         if (regionsToMove.isEmpty()) break;
296         ServerName si = sns.get(i);
297         int numToTake = underloadedServers.get(si);
298         if (numToTake == 0) continue;
299 
300         addRegionPlan(regionsToMove, fetchFromTail, si, regionsToReturn);
301 
302         underloadedServers.put(si, numToTake-1);
303         cnt++;
304         BalanceInfo bi = serverBalanceInfo.get(si);
305         if (bi == null) {
306           bi = new BalanceInfo(0, 0);
307           serverBalanceInfo.put(si, bi);
308         }
309         bi.setNumRegionsAdded(bi.getNumRegionsAdded()+1);
310       }
311       if (cnt == 0) break;
312       // iterates underloadedServers in the other direction
313       incr = -incr;
314     }
315     for (Integer i : underloadedServers.values()) {
316       // If we still want to take some, increment needed
317       neededRegions += i;
318     }
319 
320     // If none needed to fill all to min and none left to drain all to max,
321     // we are done
322     if (neededRegions == 0 && regionsToMove.isEmpty()) {
323       long endTime = System.currentTimeMillis();
324       LOG.info("Calculated a load balance in " + (endTime-startTime) + "ms. " +
325           "Moving " + totalNumMoved + " regions off of " +
326           serversOverloaded + " overloaded servers onto " +
327           serversUnderloaded + " less loaded servers");
328       return regionsToReturn;
329     }
330 
331     // Need to do a second pass.
332     // Either more regions to assign out or servers that are still underloaded
333 
334     // If we need more to fill min, grab one from each most loaded until enough
335     if (neededRegions != 0) {
336       // Walk down most loaded, grabbing one from each until we get enough
337       for (Map.Entry<ServerAndLoad, List<HRegionInfo>> server :
338         serversByLoad.descendingMap().entrySet()) {
339         BalanceInfo balanceInfo =
340           serverBalanceInfo.get(server.getKey().getServerName());
341         int idx =
342           balanceInfo == null ? 0 : balanceInfo.getNextRegionForUnload();
343         if (idx >= server.getValue().size()) break;
344         HRegionInfo region = server.getValue().get(idx);
345         if (region.isMetaRegion()) continue; // Don't move meta regions.
346         regionsToMove.add(new RegionPlan(region, server.getKey().getServerName(), null));
347         totalNumMoved++;
348         if (--neededRegions == 0) {
349           // No more regions needed, done shedding
350           break;
351         }
352       }
353     }
354 
355     // Now we have a set of regions that must be all assigned out
356     // Assign each underloaded up to the min, then if leftovers, assign to max
357 
358     // Walk down least loaded, assigning to each to fill up to min
359     for (Map.Entry<ServerAndLoad, List<HRegionInfo>> server :
360         serversByLoad.entrySet()) {
361       int regionCount = server.getKey().getLoad();
362       if (regionCount >= min) break;
363       BalanceInfo balanceInfo = serverBalanceInfo.get(server.getKey().getServerName());
364       if(balanceInfo != null) {
365         regionCount += balanceInfo.getNumRegionsAdded();
366       }
367       if(regionCount >= min) {
368         continue;
369       }
370       int numToTake = min - regionCount;
371       int numTaken = 0;
372       while(numTaken < numToTake && 0 < regionsToMove.size()) {
373         addRegionPlan(regionsToMove, fetchFromTail,
374           server.getKey().getServerName(), regionsToReturn);
375         numTaken++;
376       }
377     }
378 
379     // If we still have regions to dish out, assign underloaded to max
380     if (0 < regionsToMove.size()) {
381       for (Map.Entry<ServerAndLoad, List<HRegionInfo>> server :
382         serversByLoad.entrySet()) {
383         int regionCount = server.getKey().getLoad();
384         BalanceInfo balanceInfo = serverBalanceInfo.get(server.getKey().getServerName());
385         if(balanceInfo != null) {
386           regionCount += balanceInfo.getNumRegionsAdded();
387         }
388         if(regionCount >= max) {
389           break;
390         }
391         addRegionPlan(regionsToMove, fetchFromTail,
392           server.getKey().getServerName(), regionsToReturn);
393         if (regionsToMove.isEmpty()) {
394           break;
395         }
396       }
397     }
398 
399     long endTime = System.currentTimeMillis();
400 
401     if (!regionsToMove.isEmpty() || neededRegions != 0) {
402       // Emit data so can diagnose how balancer went astray.
403       LOG.warn("regionsToMove=" + totalNumMoved +
404         ", numServers=" + numServers + ", serversOverloaded=" + serversOverloaded +
405         ", serversUnderloaded=" + serversUnderloaded);
406       StringBuilder sb = new StringBuilder();
407       for (Map.Entry<ServerName, List<HRegionInfo>> e: clusterMap.entrySet()) {
408         if (sb.length() > 0) sb.append(", ");
409         sb.append(e.getKey().toString());
410         sb.append(" ");
411         sb.append(e.getValue().size());
412       }
413       LOG.warn("Input " + sb.toString());
414     }
415 
416     // All done!
417     LOG.info("Done. Calculated a load balance in " + (endTime-startTime) + "ms. " +
418         "Moving " + totalNumMoved + " regions off of " +
419         serversOverloaded + " overloaded servers onto " +
420         serversUnderloaded + " less loaded servers");
421 
422     return regionsToReturn;
423   }
424 
425   /**
426    * Add a region from the head or tail to the List of regions to return.
427    */
428   private void addRegionPlan(final MinMaxPriorityQueue<RegionPlan> regionsToMove,
429       final boolean fetchFromTail, final ServerName sn, List<RegionPlan> regionsToReturn) {
430     RegionPlan rp = null;
431     if (!fetchFromTail) rp = regionsToMove.remove();
432     else rp = regionsToMove.removeLast();
433     rp.setDestination(sn);
434     regionsToReturn.add(rp);
435   }
436 }