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 static org.junit.Assert.assertNotNull;
21  import static org.junit.Assert.assertNull;
22  import static org.junit.Assert.assertTrue;
23  
24  import java.util.ArrayList;
25  import java.util.HashMap;
26  import java.util.HashSet;
27  import java.util.LinkedList;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.Map.Entry;
31  import java.util.Queue;
32  import java.util.Random;
33  import java.util.Set;
34  import java.util.SortedSet;
35  import java.util.TreeMap;
36  import java.util.TreeSet;
37  
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.HBaseConfiguration;
42  import org.apache.hadoop.hbase.HRegionInfo;
43  import org.apache.hadoop.hbase.ServerName;
44  import org.apache.hadoop.hbase.TableName;
45  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
46  import org.apache.hadoop.hbase.master.RackManager;
47  import org.apache.hadoop.hbase.master.RegionPlan;
48  import org.apache.hadoop.hbase.util.Bytes;
49  import org.apache.hadoop.net.DNSToSwitchMapping;
50  import org.junit.Assert;
51  import org.junit.BeforeClass;
52  
53  /**
54   * Class used to be the base of unit tests on load balancers. It gives helper
55   * methods to create maps of {@link ServerName} to lists of {@link HRegionInfo}
56   * and to check list of region plans.
57   *
58   */
59  public class BalancerTestBase {
60    private static final Log LOG = LogFactory.getLog(BalancerTestBase.class);
61    protected static Random rand = new Random();
62    static int regionId = 0;
63    protected static Configuration conf;
64    protected static StochasticLoadBalancer loadBalancer;
65  
66    @BeforeClass
67    public static void beforeAllTests() throws Exception {
68      conf = HBaseConfiguration.create();
69      conf.setClass("hbase.util.ip.to.rack.determiner", MockMapping.class, DNSToSwitchMapping.class);
70      conf.setFloat("hbase.master.balancer.stochastic.maxMovePercent", 0.75f);
71      conf.setFloat("hbase.regions.slop", 0.0f);
72      conf.setFloat("hbase.master.balancer.stochastic.localityCost", 0);
73      loadBalancer = new StochasticLoadBalancer();
74      loadBalancer.setConf(conf);
75    }
76  
77    protected int[] largeCluster = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
78        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
79        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
80        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
81        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
82        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
83        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
84        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
86        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
89        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
90        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 56 };
91  
92    // int[testnum][servernumber] -> numregions
93    protected int[][] clusterStateMocks = new int[][]{
94        // 1 node
95        new int[]{0},
96        new int[]{1},
97        new int[]{10},
98        // 2 node
99        new int[]{0, 0},
100       new int[]{2, 0},
101       new int[]{2, 1},
102       new int[]{2, 2},
103       new int[]{2, 3},
104       new int[]{2, 4},
105       new int[]{1, 1},
106       new int[]{0, 1},
107       new int[]{10, 1},
108       new int[]{514, 1432},
109       new int[]{48, 53},
110       // 3 node
111       new int[]{0, 1, 2},
112       new int[]{1, 2, 3},
113       new int[]{0, 2, 2},
114       new int[]{0, 3, 0},
115       new int[]{0, 4, 0},
116       new int[]{20, 20, 0},
117       // 4 node
118       new int[]{0, 1, 2, 3},
119       new int[]{4, 0, 0, 0},
120       new int[]{5, 0, 0, 0},
121       new int[]{6, 6, 0, 0},
122       new int[]{6, 2, 0, 0},
123       new int[]{6, 1, 0, 0},
124       new int[]{6, 0, 0, 0},
125       new int[]{4, 4, 4, 7},
126       new int[]{4, 4, 4, 8},
127       new int[]{0, 0, 0, 7},
128       // 5 node
129       new int[]{1, 1, 1, 1, 4},
130       // 6 nodes
131       new int[]{1500, 500, 500, 500, 10, 0},
132       new int[]{1500, 500, 500, 500, 500, 0},
133       // more nodes
134       new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
135       new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 10},
136       new int[]{6, 6, 5, 6, 6, 6, 6, 6, 6, 1},
137       new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 54},
138       new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 55},
139       new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 56},
140       new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 16},
141       new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 8},
142       new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 9},
143       new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 10},
144       new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 123},
145       new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 155},
146       new int[]{10, 7, 12, 8, 11, 10, 9, 14},
147       new int[]{13, 14, 6, 10, 10, 10, 8, 10},
148       new int[]{130, 14, 60, 10, 100, 10, 80, 10},
149       new int[]{130, 140, 60, 100, 100, 100, 80, 100},
150       new int[]{0, 5 , 5, 5, 5},
151       largeCluster,
152 
153   };
154 
155 
156   // This class is introduced because IP to rack resolution can be lengthy.
157   public static class MockMapping implements DNSToSwitchMapping {
158     public MockMapping(Configuration conf) {
159     }
160 
161     public List<String> resolve(List<String> names) {
162       List<String> ret = new ArrayList<String>(names.size());
163       for (String name : names) {
164         ret.add("rack");
165       }
166       return ret;
167     }
168 
169     // do not add @Override annotations here. It mighty break compilation with earlier Hadoops
170     public void reloadCachedMappings() {
171     }
172 
173     // do not add @Override annotations here. It mighty break compilation with earlier Hadoops
174     public void reloadCachedMappings(List<String> arg0) {
175     }
176   }
177 
178   /**
179    * Invariant is that all servers have between floor(avg) and ceiling(avg)
180    * number of regions.
181    */
182   public void assertClusterAsBalanced(List<ServerAndLoad> servers) {
183     int numServers = servers.size();
184     int numRegions = 0;
185     int maxRegions = 0;
186     int minRegions = Integer.MAX_VALUE;
187     for (ServerAndLoad server : servers) {
188       int nr = server.getLoad();
189       if (nr > maxRegions) {
190         maxRegions = nr;
191       }
192       if (nr < minRegions) {
193         minRegions = nr;
194       }
195       numRegions += nr;
196     }
197     if (maxRegions - minRegions < 2) {
198       // less than 2 between max and min, can't balance
199       return;
200     }
201     int min = numRegions / numServers;
202     int max = numRegions % numServers == 0 ? min : min + 1;
203 
204     for (ServerAndLoad server : servers) {
205       assertTrue(server.getLoad() >= 0);
206       assertTrue(server.getLoad() <= max);
207       assertTrue(server.getLoad() >= min);
208     }
209   }
210 
211   /**
212    * Checks whether region replicas are not hosted on the same host.
213    */
214   public void assertRegionReplicaPlacement(Map<ServerName, List<HRegionInfo>> serverMap, RackManager rackManager) {
215     TreeMap<String, Set<HRegionInfo>> regionsPerHost = new TreeMap<String, Set<HRegionInfo>>();
216     TreeMap<String, Set<HRegionInfo>> regionsPerRack = new TreeMap<String, Set<HRegionInfo>>();
217 
218     for (Entry<ServerName, List<HRegionInfo>> entry : serverMap.entrySet()) {
219       String hostname = entry.getKey().getHostname();
220       Set<HRegionInfo> infos = regionsPerHost.get(hostname);
221       if (infos == null) {
222         infos = new HashSet<HRegionInfo>();
223         regionsPerHost.put(hostname, infos);
224       }
225 
226       for (HRegionInfo info : entry.getValue()) {
227         HRegionInfo primaryInfo = RegionReplicaUtil.getRegionInfoForDefaultReplica(info);
228         if (!infos.add(primaryInfo)) {
229           Assert.fail("Two or more region replicas are hosted on the same host after balance");
230         }
231       }
232     }
233 
234     if (rackManager == null) {
235       return;
236     }
237 
238     for (Entry<ServerName, List<HRegionInfo>> entry : serverMap.entrySet()) {
239       String rack = rackManager.getRack(entry.getKey());
240       Set<HRegionInfo> infos = regionsPerRack.get(rack);
241       if (infos == null) {
242         infos = new HashSet<HRegionInfo>();
243         regionsPerRack.put(rack, infos);
244       }
245 
246       for (HRegionInfo info : entry.getValue()) {
247         HRegionInfo primaryInfo = RegionReplicaUtil.getRegionInfoForDefaultReplica(info);
248         if (!infos.add(primaryInfo)) {
249           Assert.fail("Two or more region replicas are hosted on the same rack after balance");
250         }
251       }
252     }
253   }
254 
255   protected String printStats(List<ServerAndLoad> servers) {
256     int numServers = servers.size();
257     int totalRegions = 0;
258     for (ServerAndLoad server : servers) {
259       totalRegions += server.getLoad();
260     }
261     float average = (float) totalRegions / numServers;
262     int max = (int) Math.ceil(average);
263     int min = (int) Math.floor(average);
264     return "[srvr=" + numServers + " rgns=" + totalRegions + " avg=" + average + " max=" + max
265         + " min=" + min + "]";
266   }
267 
268   protected List<ServerAndLoad> convertToList(final Map<ServerName, List<HRegionInfo>> servers) {
269     List<ServerAndLoad> list = new ArrayList<ServerAndLoad>(servers.size());
270     for (Map.Entry<ServerName, List<HRegionInfo>> e : servers.entrySet()) {
271       list.add(new ServerAndLoad(e.getKey(), e.getValue().size()));
272     }
273     return list;
274   }
275 
276   protected String printMock(List<ServerAndLoad> balancedCluster) {
277     SortedSet<ServerAndLoad> sorted = new TreeSet<ServerAndLoad>(balancedCluster);
278     ServerAndLoad[] arr = sorted.toArray(new ServerAndLoad[sorted.size()]);
279     StringBuilder sb = new StringBuilder(sorted.size() * 4 + 4);
280     sb.append("{ ");
281     for (int i = 0; i < arr.length; i++) {
282       if (i != 0) {
283         sb.append(" , ");
284       }
285       sb.append(arr[i].getServerName().getHostname());
286       sb.append(":");
287       sb.append(arr[i].getLoad());
288     }
289     sb.append(" }");
290     return sb.toString();
291   }
292 
293   /**
294    * This assumes the RegionPlan HSI instances are the same ones in the map, so
295    * actually no need to even pass in the map, but I think it's clearer.
296    *
297    * @param list
298    * @param plans
299    * @return
300    */
301   protected List<ServerAndLoad> reconcile(List<ServerAndLoad> list,
302                                           List<RegionPlan> plans,
303                                           Map<ServerName, List<HRegionInfo>> servers) {
304     List<ServerAndLoad> result = new ArrayList<ServerAndLoad>(list.size());
305 
306     Map<ServerName, ServerAndLoad> map = new HashMap<ServerName, ServerAndLoad>(list.size());
307     for (ServerAndLoad sl : list) {
308       map.put(sl.getServerName(), sl);
309     }
310     if (plans != null) {
311       for (RegionPlan plan : plans) {
312         ServerName source = plan.getSource();
313 
314         updateLoad(map, source, -1);
315         ServerName destination = plan.getDestination();
316         updateLoad(map, destination, +1);
317 
318         servers.get(source).remove(plan.getRegionInfo());
319         servers.get(destination).add(plan.getRegionInfo());
320       }
321     }
322     result.clear();
323     result.addAll(map.values());
324     return result;
325   }
326 
327   protected void updateLoad(final Map<ServerName, ServerAndLoad> map,
328                             final ServerName sn,
329                             final int diff) {
330     ServerAndLoad sal = map.get(sn);
331     if (sal == null) sal = new ServerAndLoad(sn, 0);
332     sal = new ServerAndLoad(sn, sal.getLoad() + diff);
333     map.put(sn, sal);
334   }
335 
336   protected TreeMap<ServerName, List<HRegionInfo>> mockClusterServers(int[] mockCluster) {
337     return mockClusterServers(mockCluster, -1);
338   }
339 
340   protected BaseLoadBalancer.Cluster mockCluster(int[] mockCluster) {
341     return new BaseLoadBalancer.Cluster(
342       mockClusterServers(mockCluster, -1), null, null, null);
343   }
344 
345   protected TreeMap<ServerName, List<HRegionInfo>> mockClusterServers(int[] mockCluster, int numTables) {
346     int numServers = mockCluster.length;
347     TreeMap<ServerName, List<HRegionInfo>> servers = new TreeMap<ServerName, List<HRegionInfo>>();
348     for (int i = 0; i < numServers; i++) {
349       int numRegions = mockCluster[i];
350       ServerAndLoad sal = randomServer(0);
351       List<HRegionInfo> regions = randomRegions(numRegions, numTables);
352       servers.put(sal.getServerName(), regions);
353     }
354     return servers;
355   }
356 
357   private Queue<HRegionInfo> regionQueue = new LinkedList<HRegionInfo>();
358 
359   protected List<HRegionInfo> randomRegions(int numRegions) {
360     return randomRegions(numRegions, -1);
361   }
362 
363   protected List<HRegionInfo> randomRegions(int numRegions, int numTables) {
364     List<HRegionInfo> regions = new ArrayList<HRegionInfo>(numRegions);
365     byte[] start = new byte[16];
366     byte[] end = new byte[16];
367     rand.nextBytes(start);
368     rand.nextBytes(end);
369     for (int i = 0; i < numRegions; i++) {
370       if (!regionQueue.isEmpty()) {
371         regions.add(regionQueue.poll());
372         continue;
373       }
374       Bytes.putInt(start, 0, numRegions << 1);
375       Bytes.putInt(end, 0, (numRegions << 1) + 1);
376       TableName tableName =
377           TableName.valueOf("table" + (numTables > 0 ? rand.nextInt(numTables) : i));
378       HRegionInfo hri = new HRegionInfo(tableName, start, end, false, regionId++);
379       regions.add(hri);
380     }
381     return regions;
382   }
383 
384   protected void returnRegions(List<HRegionInfo> regions) {
385     regionQueue.addAll(regions);
386   }
387 
388   private Queue<ServerName> serverQueue = new LinkedList<ServerName>();
389 
390   protected ServerAndLoad randomServer(final int numRegionsPerServer) {
391     if (!this.serverQueue.isEmpty()) {
392       ServerName sn = this.serverQueue.poll();
393       return new ServerAndLoad(sn, numRegionsPerServer);
394     }
395     String host = "srv" + rand.nextInt(Integer.MAX_VALUE);
396     int port = rand.nextInt(60000);
397     long startCode = rand.nextLong();
398     ServerName sn = ServerName.valueOf(host, port, startCode);
399     return new ServerAndLoad(sn, numRegionsPerServer);
400   }
401 
402   protected List<ServerAndLoad> randomServers(int numServers, int numRegionsPerServer) {
403     List<ServerAndLoad> servers = new ArrayList<ServerAndLoad>(numServers);
404     for (int i = 0; i < numServers; i++) {
405       servers.add(randomServer(numRegionsPerServer));
406     }
407     return servers;
408   }
409 
410   protected void returnServer(ServerName server) {
411     serverQueue.add(server);
412   }
413 
414   protected void returnServers(List<ServerName> servers) {
415     this.serverQueue.addAll(servers);
416   }
417 
418   protected void testWithCluster(int numNodes,
419       int numRegions,
420       int numRegionsPerServer,
421       int replication,
422       int numTables,
423       boolean assertFullyBalanced, boolean assertFullyBalancedForReplicas) {
424     Map<ServerName, List<HRegionInfo>> serverMap =
425         createServerMap(numNodes, numRegions, numRegionsPerServer, replication, numTables);
426     testWithCluster(serverMap, null, assertFullyBalanced, assertFullyBalancedForReplicas);
427   }
428 
429   protected void testWithCluster(Map<ServerName, List<HRegionInfo>> serverMap,
430       RackManager rackManager, boolean assertFullyBalanced, boolean assertFullyBalancedForReplicas) {
431     List<ServerAndLoad> list = convertToList(serverMap);
432     LOG.info("Mock Cluster : " + printMock(list) + " " + printStats(list));
433 
434     loadBalancer.setRackManager(rackManager);
435     // Run the balancer.
436     List<RegionPlan> plans = loadBalancer.balanceCluster(serverMap);
437     assertNotNull(plans);
438 
439     // Check to see that this actually got to a stable place.
440     if (assertFullyBalanced || assertFullyBalancedForReplicas) {
441       // Apply the plan to the mock cluster.
442       List<ServerAndLoad> balancedCluster = reconcile(list, plans, serverMap);
443 
444       // Print out the cluster loads to make debugging easier.
445       LOG.info("Mock Balance : " + printMock(balancedCluster));
446 
447       if (assertFullyBalanced) {
448         assertClusterAsBalanced(balancedCluster);
449         List<RegionPlan> secondPlans =  loadBalancer.balanceCluster(serverMap);
450         assertNull(secondPlans);
451       }
452 
453       if (assertFullyBalancedForReplicas) {
454         assertRegionReplicaPlacement(serverMap, rackManager);
455       }
456     }
457   }
458 
459   protected Map<ServerName, List<HRegionInfo>> createServerMap(int numNodes,
460                                                              int numRegions,
461                                                              int numRegionsPerServer,
462                                                              int replication,
463                                                              int numTables) {
464     //construct a cluster of numNodes, having  a total of numRegions. Each RS will hold
465     //numRegionsPerServer many regions except for the last one, which will host all the
466     //remaining regions
467     int[] cluster = new int[numNodes];
468     for (int i =0; i < numNodes; i++) {
469       cluster[i] = numRegionsPerServer;
470     }
471     cluster[cluster.length - 1] = numRegions - ((cluster.length - 1) * numRegionsPerServer);
472     Map<ServerName, List<HRegionInfo>> clusterState = mockClusterServers(cluster, numTables);
473     if (replication > 0) {
474       // replicate the regions to the same servers
475       for (List<HRegionInfo> regions : clusterState.values()) {
476         int length = regions.size();
477         for (int i = 0; i < length; i++) {
478           for (int r = 1; r < replication ; r++) {
479             regions.add(RegionReplicaUtil.getRegionInfoForReplica(regions.get(i), r));
480           }
481         }
482       }
483     }
484 
485     return clusterState;
486   }
487 
488 }