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.assertEquals;
21  import static org.junit.Assert.assertNotNull;
22  import static org.junit.Assert.assertNull;
23  import static org.junit.Assert.assertTrue;
24  import static org.mockito.Mockito.mock;
25  import static org.mockito.Mockito.when;
26  
27  import java.util.ArrayList;
28  import java.util.Arrays;
29  import java.util.HashMap;
30  import java.util.Iterator;
31  import java.util.List;
32  import java.util.Map;
33  import java.util.Map.Entry;
34  import java.util.Queue;
35  import java.util.TreeMap;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.hadoop.conf.Configuration;
40  import org.apache.hadoop.hbase.ClusterStatus;
41  import org.apache.hadoop.hbase.HBaseConfiguration;
42  import org.apache.hadoop.hbase.HRegionInfo;
43  import org.apache.hadoop.hbase.RegionLoad;
44  import org.apache.hadoop.hbase.ServerLoad;
45  import org.apache.hadoop.hbase.ServerName;
46  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
47  import org.apache.hadoop.hbase.master.RackManager;
48  import org.apache.hadoop.hbase.master.RegionPlan;
49  import org.apache.hadoop.hbase.master.balancer.BaseLoadBalancer.Cluster;
50  import org.apache.hadoop.hbase.testclassification.FlakeyTests;
51  import org.apache.hadoop.hbase.testclassification.MediumTests;
52  import org.apache.hadoop.hbase.util.Bytes;
53  import org.junit.Test;
54  import org.junit.Ignore;
55  import org.junit.experimental.categories.Category;
56  
57  @Category({FlakeyTests.class, MediumTests.class})
58  public class TestStochasticLoadBalancer extends BalancerTestBase {
59    public static final String REGION_KEY = "testRegion";
60    private static final Log LOG = LogFactory.getLog(TestStochasticLoadBalancer.class);
61  
62    @Test
63    public void testKeepRegionLoad() throws Exception {
64  
65      ServerName sn = ServerName.valueOf("test:8080", 100);
66      int numClusterStatusToAdd = 20000;
67      for (int i = 0; i < numClusterStatusToAdd; i++) {
68        ServerLoad sl = mock(ServerLoad.class);
69  
70        RegionLoad rl = mock(RegionLoad.class);
71        when(rl.getStores()).thenReturn(i);
72  
73        Map<byte[], RegionLoad> regionLoadMap =
74            new TreeMap<byte[], RegionLoad>(Bytes.BYTES_COMPARATOR);
75        regionLoadMap.put(Bytes.toBytes(REGION_KEY), rl);
76        when(sl.getRegionsLoad()).thenReturn(regionLoadMap);
77  
78        ClusterStatus clusterStatus = mock(ClusterStatus.class);
79        when(clusterStatus.getServers()).thenReturn(Arrays.asList(sn));
80        when(clusterStatus.getLoad(sn)).thenReturn(sl);
81  
82        loadBalancer.setClusterStatus(clusterStatus);
83      }
84      assertTrue(loadBalancer.loads.get(REGION_KEY) != null);
85      assertTrue(loadBalancer.loads.get(REGION_KEY).size() == 15);
86  
87      Queue<RegionLoad> loads = loadBalancer.loads.get(REGION_KEY);
88      int i = 0;
89      while(loads.size() > 0) {
90        RegionLoad rl = loads.remove();
91        assertEquals(i + (numClusterStatusToAdd - 15), rl.getStores());
92        i ++;
93      }
94    }
95  
96    /**
97     * Test the load balancing algorithm.
98     *
99     * Invariant is that all servers should be hosting either floor(average) or
100    * ceiling(average)
101    *
102    * @throws Exception
103    */
104   @Test
105   public void testBalanceCluster() throws Exception {
106 
107     for (int[] mockCluster : clusterStateMocks) {
108       Map<ServerName, List<HRegionInfo>> servers = mockClusterServers(mockCluster);
109       List<ServerAndLoad> list = convertToList(servers);
110       LOG.info("Mock Cluster : " + printMock(list) + " " + printStats(list));
111       List<RegionPlan> plans = loadBalancer.balanceCluster(servers);
112       List<ServerAndLoad> balancedCluster = reconcile(list, plans, servers);
113       LOG.info("Mock Balance : " + printMock(balancedCluster));
114       assertClusterAsBalanced(balancedCluster);
115       List<RegionPlan> secondPlans =  loadBalancer.balanceCluster(servers);
116       assertNull(secondPlans);
117       for (Map.Entry<ServerName, List<HRegionInfo>> entry : servers.entrySet()) {
118         returnRegions(entry.getValue());
119         returnServer(entry.getKey());
120       }
121     }
122 
123   }
124 
125   @Test
126   public void testSkewCost() {
127     Configuration conf = HBaseConfiguration.create();
128     StochasticLoadBalancer.CostFunction
129         costFunction = new StochasticLoadBalancer.RegionCountSkewCostFunction(conf);
130     for (int[] mockCluster : clusterStateMocks) {
131       costFunction.init(mockCluster(mockCluster));
132       double cost = costFunction.cost();
133       assertTrue(cost >= 0);
134       assertTrue(cost <= 1.01);
135     }
136 
137     costFunction.init(mockCluster(new int[]{0, 0, 0, 0, 1}));
138     assertEquals(0,costFunction.cost(), 0.01);
139     costFunction.init(mockCluster(new int[]{0, 0, 0, 1, 1}));
140     assertEquals(0, costFunction.cost(), 0.01);
141     costFunction.init(mockCluster(new int[]{0, 0, 1, 1, 1}));
142     assertEquals(0, costFunction.cost(), 0.01);
143     costFunction.init(mockCluster(new int[]{0, 1, 1, 1, 1}));
144     assertEquals(0, costFunction.cost(), 0.01);
145     costFunction.init(mockCluster(new int[]{1, 1, 1, 1, 1}));
146     assertEquals(0, costFunction.cost(), 0.01);
147     costFunction.init(mockCluster(new int[]{10000, 0, 0, 0, 0}));
148     assertEquals(1, costFunction.cost(), 0.01);
149   }
150 
151   @Test
152   public void testCostAfterUndoAction() {
153     final int runs = 10;
154     loadBalancer.setConf(conf);
155     for (int[] mockCluster : clusterStateMocks) {
156       BaseLoadBalancer.Cluster cluster = mockCluster(mockCluster);
157       loadBalancer.initCosts(cluster);
158       for (int i = 0; i != runs; ++i) {
159         final double expectedCost = loadBalancer.computeCost(cluster, Double.MAX_VALUE);
160         Cluster.Action action = loadBalancer.nextAction(cluster);
161         cluster.doAction(action);
162         loadBalancer.updateCostsWithAction(cluster, action);
163         Cluster.Action undoAction = action.undoAction();
164         cluster.doAction(undoAction);
165         loadBalancer.updateCostsWithAction(cluster, undoAction);
166         final double actualCost = loadBalancer.computeCost(cluster, Double.MAX_VALUE);
167         assertEquals(expectedCost, actualCost, 0);
168       }
169     }
170   }
171 
172   @Test
173   public void testTableSkewCost() {
174     Configuration conf = HBaseConfiguration.create();
175     StochasticLoadBalancer.CostFunction
176         costFunction = new StochasticLoadBalancer.TableSkewCostFunction(conf);
177     for (int[] mockCluster : clusterStateMocks) {
178       BaseLoadBalancer.Cluster cluster = mockCluster(mockCluster);
179       costFunction.init(cluster);
180       double cost = costFunction.cost();
181       assertTrue(cost >= 0);
182       assertTrue(cost <= 1.01);
183     }
184   }
185 
186   @Test
187   public void testCostFromArray() {
188     Configuration conf = HBaseConfiguration.create();
189     StochasticLoadBalancer.CostFromRegionLoadFunction
190         costFunction = new StochasticLoadBalancer.MemstoreSizeCostFunction(conf);
191     costFunction.init(mockCluster(new int[]{0, 0, 0, 0, 1}));
192 
193     double[] statOne = new double[100];
194     for (int i =0; i < 100; i++) {
195       statOne[i] = 10;
196     }
197     assertEquals(0, costFunction.costFromArray(statOne), 0.01);
198 
199     double[] statTwo= new double[101];
200     for (int i =0; i < 100; i++) {
201       statTwo[i] = 0;
202     }
203     statTwo[100] = 100;
204     assertEquals(1, costFunction.costFromArray(statTwo), 0.01);
205 
206     double[] statThree = new double[200];
207     for (int i =0; i < 100; i++) {
208       statThree[i] = (0);
209       statThree[i+100] = 100;
210     }
211     assertEquals(0.5, costFunction.costFromArray(statThree), 0.01);
212   }
213 
214   @Test(timeout =  60000)
215   public void testLosingRs() throws Exception {
216     int numNodes = 3;
217     int numRegions = 20;
218     int numRegionsPerServer = 3; //all servers except one
219     int replication = 1;
220     int numTables = 2;
221 
222     Map<ServerName, List<HRegionInfo>> serverMap =
223         createServerMap(numNodes, numRegions, numRegionsPerServer, replication, numTables);
224     List<ServerAndLoad> list = convertToList(serverMap);
225 
226 
227     List<RegionPlan> plans = loadBalancer.balanceCluster(serverMap);
228     assertNotNull(plans);
229 
230     // Apply the plan to the mock cluster.
231     List<ServerAndLoad> balancedCluster = reconcile(list, plans, serverMap);
232 
233     assertClusterAsBalanced(balancedCluster);
234 
235     ServerName sn = serverMap.keySet().toArray(new ServerName[serverMap.size()])[0];
236 
237     ServerName deadSn = ServerName.valueOf(sn.getHostname(), sn.getPort(), sn.getStartcode() - 100);
238 
239     serverMap.put(deadSn, new ArrayList<HRegionInfo>(0));
240 
241     plans = loadBalancer.balanceCluster(serverMap);
242     assertNull(plans);
243   }
244 
245   @Test
246   public void testReplicaCost() {
247     Configuration conf = HBaseConfiguration.create();
248     StochasticLoadBalancer.CostFunction
249         costFunction = new StochasticLoadBalancer.RegionReplicaHostCostFunction(conf);
250     for (int[] mockCluster : clusterStateMocks) {
251       BaseLoadBalancer.Cluster cluster = mockCluster(mockCluster);
252       costFunction.init(cluster);
253       double cost = costFunction.cost();
254       assertTrue(cost >= 0);
255       assertTrue(cost <= 1.01);
256     }
257   }
258 
259   @Test
260   public void testReplicaCostForReplicas() {
261     Configuration conf = HBaseConfiguration.create();
262     StochasticLoadBalancer.CostFunction
263         costFunction = new StochasticLoadBalancer.RegionReplicaHostCostFunction(conf);
264 
265     int [] servers = new int[] {3,3,3,3,3};
266     TreeMap<ServerName, List<HRegionInfo>> clusterState = mockClusterServers(servers);
267 
268     BaseLoadBalancer.Cluster cluster;
269 
270     cluster = new BaseLoadBalancer.Cluster(clusterState, null, null, null);
271     costFunction.init(cluster);
272     double costWithoutReplicas = costFunction.cost();
273     assertEquals(0, costWithoutReplicas, 0);
274 
275     // replicate the region from first server to the last server
276     HRegionInfo replica1 = RegionReplicaUtil.getRegionInfoForReplica(
277       clusterState.firstEntry().getValue().get(0),1);
278     clusterState.lastEntry().getValue().add(replica1);
279 
280     cluster = new BaseLoadBalancer.Cluster(clusterState, null, null, null);
281     costFunction.init(cluster);
282     double costWith1ReplicaDifferentServer = costFunction.cost();
283 
284     assertEquals(0, costWith1ReplicaDifferentServer, 0);
285 
286     // add a third replica to the last server
287     HRegionInfo replica2 = RegionReplicaUtil.getRegionInfoForReplica(replica1, 2);
288     clusterState.lastEntry().getValue().add(replica2);
289 
290     cluster = new BaseLoadBalancer.Cluster(clusterState, null, null, null);
291     costFunction.init(cluster);
292     double costWith1ReplicaSameServer = costFunction.cost();
293 
294     assertTrue(costWith1ReplicaDifferentServer < costWith1ReplicaSameServer);
295 
296     // test with replication = 4 for following:
297 
298     HRegionInfo replica3;
299     Iterator<Entry<ServerName, List<HRegionInfo>>> it;
300     Entry<ServerName, List<HRegionInfo>> entry;
301 
302     clusterState = mockClusterServers(servers);
303     it = clusterState.entrySet().iterator();
304     entry = it.next(); //first server
305     HRegionInfo hri = entry.getValue().get(0);
306     replica1 = RegionReplicaUtil.getRegionInfoForReplica(hri, 1);
307     replica2 = RegionReplicaUtil.getRegionInfoForReplica(hri, 2);
308     replica3 = RegionReplicaUtil.getRegionInfoForReplica(hri, 3);
309     entry.getValue().add(replica1);
310     entry.getValue().add(replica2);
311     it.next().getValue().add(replica3); //2nd server
312 
313     cluster = new BaseLoadBalancer.Cluster(clusterState, null, null, null);
314     costFunction.init(cluster);
315     double costWith3ReplicasSameServer = costFunction.cost();
316 
317     clusterState = mockClusterServers(servers);
318     hri = clusterState.firstEntry().getValue().get(0);
319     replica1 = RegionReplicaUtil.getRegionInfoForReplica(hri, 1);
320     replica2 = RegionReplicaUtil.getRegionInfoForReplica(hri, 2);
321     replica3 = RegionReplicaUtil.getRegionInfoForReplica(hri, 3);
322 
323     clusterState.firstEntry().getValue().add(replica1);
324     clusterState.lastEntry().getValue().add(replica2);
325     clusterState.lastEntry().getValue().add(replica3);
326 
327     cluster = new BaseLoadBalancer.Cluster(clusterState, null, null, null);
328     costFunction.init(cluster);
329     double costWith2ReplicasOnTwoServers = costFunction.cost();
330 
331     assertTrue(costWith2ReplicasOnTwoServers < costWith3ReplicasSameServer);
332   }
333 
334   @Test
335   public void testNeedsBalanceForColocatedReplicas() {
336     // check for the case where there are two hosts and with one rack, and where
337     // both the replicas are hosted on the same server
338     List<HRegionInfo> regions = randomRegions(1);
339     ServerName s1 = ServerName.valueOf("host1", 1000, 11111);
340     ServerName s2 = ServerName.valueOf("host11", 1000, 11111);
341     Map<ServerName, List<HRegionInfo>> map = new HashMap<ServerName, List<HRegionInfo>>();
342     map.put(s1, regions);
343     regions.add(RegionReplicaUtil.getRegionInfoForReplica(regions.get(0), 1));
344     // until the step above s1 holds two replicas of a region
345     regions = randomRegions(1);
346     map.put(s2, regions);
347     assertTrue(loadBalancer.needsBalance(new Cluster(map, null, null, null)));
348     // check for the case where there are two hosts on the same rack and there are two racks
349     // and both the replicas are on the same rack
350     map.clear();
351     regions = randomRegions(1);
352     List<HRegionInfo> regionsOnS2 = new ArrayList<HRegionInfo>(1);
353     regionsOnS2.add(RegionReplicaUtil.getRegionInfoForReplica(regions.get(0), 1));
354     map.put(s1, regions);
355     map.put(s2, regionsOnS2);
356     // add another server so that the cluster has some host on another rack
357     map.put(ServerName.valueOf("host2", 1000, 11111), randomRegions(1));
358     assertTrue(loadBalancer.needsBalance(new Cluster(map, null, null,
359         new ForTestRackManagerOne())));
360   }
361 
362   @Test (timeout = 60000)
363   public void testSmallCluster() {
364     int numNodes = 10;
365     int numRegions = 1000;
366     int numRegionsPerServer = 40; //all servers except one
367     int replication = 1;
368     int numTables = 10;
369     testWithCluster(numNodes, numRegions, numRegionsPerServer, replication, numTables, true, true);
370   }
371 
372   @Test (timeout = 60000)
373   public void testSmallCluster2() {
374     int numNodes = 20;
375     int numRegions = 2000;
376     int numRegionsPerServer = 40; //all servers except one
377     int replication = 1;
378     int numTables = 10;
379     testWithCluster(numNodes, numRegions, numRegionsPerServer, replication, numTables, true, true);
380   }
381 
382   @Test (timeout = 60000)
383   public void testSmallCluster3() {
384     int numNodes = 20;
385     int numRegions = 2000;
386     int numRegionsPerServer = 1; // all servers except one
387     int replication = 1;
388     int numTables = 10;
389     /* fails because of max moves */
390     testWithCluster(numNodes, numRegions, numRegionsPerServer, replication, numTables, false, false);
391   }
392 
393   @Test (timeout = 800000)
394   public void testMidCluster() {
395     int numNodes = 100;
396     int numRegions = 10000;
397     int numRegionsPerServer = 60; // all servers except one
398     int replication = 1;
399     int numTables = 40;
400     testWithCluster(numNodes, numRegions, numRegionsPerServer, replication, numTables, true, true);
401   }
402 
403   @Test (timeout = 800000)
404   public void testMidCluster2() {
405     int numNodes = 200;
406     int numRegions = 100000;
407     int numRegionsPerServer = 40; // all servers except one
408     int replication = 1;
409     int numTables = 400;
410     testWithCluster(numNodes,
411         numRegions,
412         numRegionsPerServer,
413         replication,
414         numTables,
415         false, /* num large num regions means may not always get to best balance with one run */
416         false);
417   }
418 
419 
420   @Test (timeout = 800000)
421   public void testMidCluster3() {
422     int numNodes = 100;
423     int numRegions = 2000;
424     int numRegionsPerServer = 9; // all servers except one
425     int replication = 1;
426     int numTables = 110;
427     testWithCluster(numNodes, numRegions, numRegionsPerServer, replication, numTables, true, true);
428     // TODO(eclark): Make sure that the tables are well distributed.
429   }
430 
431   @Test
432   public void testLargeCluster() {
433     int numNodes = 1000;
434     int numRegions = 100000; //100 regions per RS
435     int numRegionsPerServer = 80; //all servers except one
436     int numTables = 100;
437     int replication = 1;
438     testWithCluster(numNodes, numRegions, numRegionsPerServer, replication, numTables, true, true);
439   }
440 
441   @Test (timeout = 800000)
442   public void testRegionReplicasOnSmallCluster() {
443     int numNodes = 10;
444     int numRegions = 1000;
445     int replication = 3; // 3 replicas per region
446     int numRegionsPerServer = 80; //all regions are mostly balanced
447     int numTables = 10;
448     testWithCluster(numNodes, numRegions, numRegionsPerServer, replication, numTables, true, true);
449   }
450 
451   // This test failed on 1.2 branch
452   @Ignore @Test (timeout = 800000)
453   public void testRegionReplicationOnMidClusterSameHosts() {
454     conf.setLong(StochasticLoadBalancer.MAX_STEPS_KEY, 2000000L);
455     conf.setLong("hbase.master.balancer.stochastic.maxRunningTime", 90 * 1000); // 90 sec
456     conf.setFloat("hbase.master.balancer.stochastic.maxMovePercent", 1.0f);
457     loadBalancer.setConf(conf);
458     int numHosts = 100;
459     int numRegions = 100 * 100;
460     int replication = 3; // 3 replicas per region
461     int numRegionsPerServer = 5;
462     int numTables = 10;
463     Map<ServerName, List<HRegionInfo>> serverMap =
464         createServerMap(numHosts, numRegions, numRegionsPerServer, replication, numTables);
465     int numNodesPerHost = 4;
466 
467     // create a new map with 4 RS per host.
468     Map<ServerName, List<HRegionInfo>> newServerMap = new TreeMap<ServerName, List<HRegionInfo>>(serverMap);
469     for (Map.Entry<ServerName, List<HRegionInfo>> entry : serverMap.entrySet()) {
470       for (int i=1; i < numNodesPerHost; i++) {
471         ServerName s1 = entry.getKey();
472         ServerName s2 = ServerName.valueOf(s1.getHostname(), s1.getPort() + i, 1); // create an RS for the same host
473         newServerMap.put(s2, new ArrayList<HRegionInfo>());
474       }
475     }
476 
477     testWithCluster(newServerMap, null, true, true);
478   }
479 
480   private static class ForTestRackManager extends RackManager {
481     int numRacks;
482     public ForTestRackManager(int numRacks) {
483       this.numRacks = numRacks;
484     }
485     @Override
486     public String getRack(ServerName server) {
487       return "rack_" + (server.hashCode() % numRacks);
488     }
489   }
490 
491   private static class ForTestRackManagerOne extends RackManager {
492   @Override
493     public String getRack(ServerName server) {
494       return server.getHostname().endsWith("1") ? "rack1" : "rack2";
495     }
496   }
497 
498   @Test (timeout = 800000)
499   public void testRegionReplicationOnMidClusterWithRacks() {
500     conf.setLong(StochasticLoadBalancer.MAX_STEPS_KEY, 10000000L);
501     conf.setFloat("hbase.master.balancer.stochastic.maxMovePercent", 1.0f);
502     conf.setLong("hbase.master.balancer.stochastic.maxRunningTime", 120 * 1000); // 120 sec
503     loadBalancer.setConf(conf);
504     int numNodes = 30;
505     int numRegions = numNodes * 30;
506     int replication = 3; // 3 replicas per region
507     int numRegionsPerServer = 28;
508     int numTables = 10;
509     int numRacks = 4; // all replicas should be on a different rack
510     Map<ServerName, List<HRegionInfo>> serverMap =
511         createServerMap(numNodes, numRegions, numRegionsPerServer, replication, numTables);
512     RackManager rm = new ForTestRackManager(numRacks);
513 
514     testWithCluster(serverMap, rm, false, true);
515   }
516 
517 }