View Javadoc

1   /**
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one or more
5    * contributor license agreements. See the NOTICE file distributed with this
6    * work for additional information regarding copyright ownership. The ASF
7    * licenses this file to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   * http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16   * License for the specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.hadoop.hbase.regionserver;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertNull;
24  import static org.junit.Assert.assertTrue;
25  import static org.junit.Assert.fail;
26  
27  import java.io.IOException;
28  import java.util.ArrayList;
29  import java.util.List;
30  
31  import org.apache.commons.lang.math.RandomUtils;
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.conf.Configuration;
35  import org.apache.hadoop.fs.FileSystem;
36  import org.apache.hadoop.fs.Path;
37  import org.apache.hadoop.hbase.HBaseTestingUtility;
38  import org.apache.hadoop.hbase.HConstants;
39  import org.apache.hadoop.hbase.HRegionInfo;
40  import org.apache.hadoop.hbase.HTableDescriptor;
41  import org.apache.hadoop.hbase.MiniHBaseCluster;
42  import org.apache.hadoop.hbase.RegionTransition;
43  import org.apache.hadoop.hbase.ServerName;
44  import org.apache.hadoop.hbase.TableName;
45  import org.apache.hadoop.hbase.UnknownRegionException;
46  import org.apache.hadoop.hbase.MetaTableAccessor;
47  import org.apache.hadoop.hbase.Waiter;
48  import org.apache.hadoop.hbase.client.Admin;
49  import org.apache.hadoop.hbase.client.Put;
50  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
51  import org.apache.hadoop.hbase.client.Result;
52  import org.apache.hadoop.hbase.client.ResultScanner;
53  import org.apache.hadoop.hbase.client.Scan;
54  import org.apache.hadoop.hbase.client.Table;
55  import org.apache.hadoop.hbase.exceptions.MergeRegionException;
56  import org.apache.hadoop.hbase.executor.EventType;
57  import org.apache.hadoop.hbase.master.AssignmentManager;
58  import org.apache.hadoop.hbase.master.HMaster;
59  import org.apache.hadoop.hbase.master.RegionState.State;
60  import org.apache.hadoop.hbase.master.RegionStates;
61  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
62  import org.apache.hadoop.hbase.testclassification.LargeTests;
63  import org.apache.hadoop.hbase.util.Bytes;
64  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
65  import org.apache.hadoop.hbase.util.FSUtils;
66  import org.apache.hadoop.hbase.util.Pair;
67  import org.apache.hadoop.hbase.util.PairOfSameType;
68  import org.apache.hadoop.hbase.zookeeper.ZKAssign;
69  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
70  import org.apache.hadoop.util.StringUtils;
71  import org.apache.zookeeper.data.Stat;
72  import org.junit.AfterClass;
73  import org.junit.BeforeClass;
74  import org.junit.Test;
75  import org.junit.experimental.categories.Category;
76  
77  import com.google.common.base.Joiner;
78  
79  /**
80   * Like {@link TestRegionMergeTransaction} in that we're testing
81   * {@link RegionMergeTransactionImpl} only the below tests are against a running
82   * cluster where {@link TestRegionMergeTransaction} is tests against bare
83   * {@link HRegion}.
84   */
85  @Category(LargeTests.class)
86  public class TestRegionMergeTransactionOnCluster {
87    private static final Log LOG = LogFactory
88        .getLog(TestRegionMergeTransactionOnCluster.class);
89    private static final int NB_SERVERS = 3;
90  
91    private static final byte[] FAMILYNAME = Bytes.toBytes("fam");
92    private static final byte[] QUALIFIER = Bytes.toBytes("q");
93  
94    private static byte[] ROW = Bytes.toBytes("testRow");
95    private static final int INITIAL_REGION_NUM = 10;
96    private static final int ROWSIZE = 200;
97    private static byte[][] ROWS = makeN(ROW, ROWSIZE);
98  
99    private static int waitTime = 60 * 1000;
100 
101   static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
102 
103   private static HMaster master;
104   private static Admin admin;
105   static MiniHBaseCluster cluster;
106   static Configuration conf;
107 
108   static void setupOnce() throws Exception {
109     // Start a cluster
110     TEST_UTIL.startMiniCluster(NB_SERVERS);
111     cluster = TEST_UTIL.getHBaseCluster();
112     master = cluster.getMaster();
113     master.balanceSwitch(false);
114     admin = TEST_UTIL.getHBaseAdmin();
115   }
116 
117   @BeforeClass
118   public static void beforeAllTests() throws Exception {
119     conf = TEST_UTIL.getConfiguration();
120     // Use ZK for region assignment
121     conf.setBoolean("hbase.assignment.usezk", true);
122     setupOnce();
123   }
124 
125   @AfterClass
126   public static void afterAllTests() throws Exception {
127     TEST_UTIL.shutdownMiniCluster();
128   }
129 
130   @Test
131   public void testWholesomeMerge() throws Exception {
132     LOG.info("Starting testWholesomeMerge");
133     final TableName tableName =
134         TableName.valueOf("testWholesomeMerge");
135 
136     // Create table and load data.
137     Table table = createTableAndLoadData(master, tableName);
138     // Merge 1st and 2nd region
139     mergeRegionsAndVerifyRegionNum(master, tableName, 0, 1,
140         INITIAL_REGION_NUM - 1);
141 
142     // Merge 2nd and 3th region
143     PairOfSameType<HRegionInfo> mergedRegions =
144       mergeRegionsAndVerifyRegionNum(master, tableName, 1, 2,
145         INITIAL_REGION_NUM - 2);
146 
147     verifyRowCount(table, ROWSIZE);
148 
149     // Randomly choose one of the two merged regions
150     HRegionInfo hri = RandomUtils.nextBoolean() ?
151       mergedRegions.getFirst() : mergedRegions.getSecond();
152     MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
153     AssignmentManager am = cluster.getMaster().getAssignmentManager();
154     RegionStates regionStates = am.getRegionStates();
155     long start = EnvironmentEdgeManager.currentTime();
156     while (!regionStates.isRegionInState(hri, State.MERGED)) {
157       assertFalse("Timed out in waiting one merged region to be in state MERGED",
158         EnvironmentEdgeManager.currentTime() - start > 60000);
159       Thread.sleep(500);
160     }
161 
162     // We should not be able to assign it again
163     am.assign(hri, true, true);
164     assertFalse("Merged region can't be assigned",
165       regionStates.isRegionInTransition(hri));
166     assertTrue(regionStates.isRegionInState(hri, State.MERGED));
167 
168     // We should not be able to unassign it either
169     am.unassign(hri, true, null);
170     assertFalse("Merged region can't be unassigned",
171       regionStates.isRegionInTransition(hri));
172     assertTrue(regionStates.isRegionInState(hri, State.MERGED));
173 
174     table.close();
175   }
176 
177   @Test
178   public void testCleanMergeReference() throws Exception {
179     LOG.info("Starting testCleanMergeReference");
180     admin.enableCatalogJanitor(false);
181     try {
182       final TableName tableName =
183           TableName.valueOf("testCleanMergeReference");
184       // Create table and load data.
185       Table table = createTableAndLoadData(master, tableName);
186       // Merge 1st and 2nd region
187       mergeRegionsAndVerifyRegionNum(master, tableName, 0, 1,
188           INITIAL_REGION_NUM - 1);
189       verifyRowCount(table, ROWSIZE);
190       table.close();
191 
192       List<Pair<HRegionInfo, ServerName>> tableRegions = MetaTableAccessor
193           .getTableRegionsAndLocations(master.getZooKeeper(), master.getConnection(), tableName);
194       HRegionInfo mergedRegionInfo = tableRegions.get(0).getFirst();
195       HTableDescriptor tableDescritor = master.getTableDescriptors().get(
196           tableName);
197       Result mergedRegionResult = MetaTableAccessor.getRegionResult(
198         master.getConnection(), mergedRegionInfo.getRegionName());
199 
200       // contains merge reference in META
201       assertTrue(mergedRegionResult.getValue(HConstants.CATALOG_FAMILY,
202           HConstants.MERGEA_QUALIFIER) != null);
203       assertTrue(mergedRegionResult.getValue(HConstants.CATALOG_FAMILY,
204           HConstants.MERGEB_QUALIFIER) != null);
205 
206       // merging regions' directory are in the file system all the same
207       HRegionInfo regionA = HRegionInfo.getHRegionInfo(mergedRegionResult,
208           HConstants.MERGEA_QUALIFIER);
209       HRegionInfo regionB = HRegionInfo.getHRegionInfo(mergedRegionResult,
210           HConstants.MERGEB_QUALIFIER);
211       FileSystem fs = master.getMasterFileSystem().getFileSystem();
212       Path rootDir = master.getMasterFileSystem().getRootDir();
213 
214       Path tabledir = FSUtils.getTableDir(rootDir, mergedRegionInfo.getTable());
215       Path regionAdir = new Path(tabledir, regionA.getEncodedName());
216       Path regionBdir = new Path(tabledir, regionB.getEncodedName());
217       assertTrue(fs.exists(regionAdir));
218       assertTrue(fs.exists(regionBdir));
219 
220       admin.compactRegion(mergedRegionInfo.getRegionName());
221       // wait until merged region doesn't have reference file
222       long timeout = System.currentTimeMillis() + waitTime;
223       HRegionFileSystem hrfs = new HRegionFileSystem(
224           TEST_UTIL.getConfiguration(), fs, tabledir, mergedRegionInfo);
225       while (System.currentTimeMillis() < timeout) {
226         if (!hrfs.hasReferences(tableDescritor)) {
227           break;
228         }
229         Thread.sleep(50);
230       }
231       assertFalse(hrfs.hasReferences(tableDescritor));
232 
233       // run CatalogJanitor to clean merge references in hbase:meta and archive the
234       // files of merging regions
235       int cleaned = admin.runCatalogScan();
236       assertTrue(cleaned > 0);
237       assertFalse(fs.exists(regionAdir));
238       assertFalse(fs.exists(regionBdir));
239 
240       mergedRegionResult = MetaTableAccessor.getRegionResult(
241         master.getConnection(), mergedRegionInfo.getRegionName());
242       assertFalse(mergedRegionResult.getValue(HConstants.CATALOG_FAMILY,
243           HConstants.MERGEA_QUALIFIER) != null);
244       assertFalse(mergedRegionResult.getValue(HConstants.CATALOG_FAMILY,
245           HConstants.MERGEB_QUALIFIER) != null);
246 
247     } finally {
248       admin.enableCatalogJanitor(true);
249     }
250   }
251 
252   /**
253    * This test tests 1, merging region not online;
254    * 2, merging same two regions; 3, merging unknown regions.
255    * They are in one test case so that we don't have to create
256    * many tables, and these tests are simple.
257    */
258   @Test
259   public void testMerge() throws Exception {
260     LOG.info("Starting testMerge");
261     final TableName tableName = TableName.valueOf("testMerge");
262 
263     try {
264       // Create table and load data.
265       Table table = createTableAndLoadData(master, tableName);
266       RegionStates regionStates = master.getAssignmentManager().getRegionStates();
267       List<HRegionInfo> regions = regionStates.getRegionsOfTable(tableName);
268       // Fake offline one region
269       HRegionInfo a = regions.get(0);
270       HRegionInfo b = regions.get(1);
271       regionStates.regionOffline(a);
272       try {
273         // Merge offline region. Region a is offline here
274         admin.mergeRegions(a.getEncodedNameAsBytes(), b.getEncodedNameAsBytes(), false);
275         fail("Offline regions should not be able to merge");
276       } catch (IOException ie) {
277         System.out.println(ie);
278         assertTrue("Exception should mention regions not online",
279           StringUtils.stringifyException(ie).contains("regions not online")
280             && ie instanceof MergeRegionException);
281       }
282       try {
283         // Merge the same region: b and b.
284         admin.mergeRegions(b.getEncodedNameAsBytes(), b.getEncodedNameAsBytes(), true);
285         fail("A region should not be able to merge with itself, even forcifully");
286       } catch (IOException ie) {
287         assertTrue("Exception should mention regions not online",
288           StringUtils.stringifyException(ie).contains("region to itself")
289             && ie instanceof MergeRegionException);
290       }
291       try {
292         // Merge unknown regions
293         admin.mergeRegions(Bytes.toBytes("-f1"), Bytes.toBytes("-f2"), true);
294         fail("Unknown region could not be merged");
295       } catch (IOException ie) {
296         assertTrue("UnknownRegionException should be thrown",
297           ie instanceof UnknownRegionException);
298       }
299       table.close();
300     } finally {
301       TEST_UTIL.deleteTable(tableName);
302     }
303   }
304 
305   @Test
306   public void testMergeWithReplicas() throws Exception {
307     final TableName tableName = TableName.valueOf("testMergeWithReplicas");
308     // Create table and load data.
309     createTableAndLoadData(master, tableName, 5, 2);
310     List<Pair<HRegionInfo, ServerName>> initialRegionToServers =
311         MetaTableAccessor.getTableRegionsAndLocations(master.getZooKeeper(), master.getConnection(),
312            tableName);
313     // Merge 1st and 2nd region
314     PairOfSameType<HRegionInfo> mergedRegions = mergeRegionsAndVerifyRegionNum(master, tableName,
315         0, 2, 5 * 2 - 2);
316     List<Pair<HRegionInfo, ServerName>> currentRegionToServers =
317         MetaTableAccessor.getTableRegionsAndLocations(master.getZooKeeper(), master.getConnection(),
318            tableName);
319     List<HRegionInfo> initialRegions = new ArrayList<HRegionInfo>();
320     for (Pair<HRegionInfo, ServerName> p : initialRegionToServers) {
321       initialRegions.add(p.getFirst());
322     }
323     List<HRegionInfo> currentRegions = new ArrayList<HRegionInfo>();
324     for (Pair<HRegionInfo, ServerName> p : currentRegionToServers) {
325       currentRegions.add(p.getFirst());
326     }
327     assertTrue(initialRegions.contains(mergedRegions.getFirst())); //this is the first region
328     assertTrue(initialRegions.contains(RegionReplicaUtil.getRegionInfoForReplica(
329         mergedRegions.getFirst(), 1))); //this is the replica of the first region
330     assertTrue(initialRegions.contains(mergedRegions.getSecond())); //this is the second region
331     assertTrue(initialRegions.contains(RegionReplicaUtil.getRegionInfoForReplica(
332         mergedRegions.getSecond(), 1))); //this is the replica of the second region
333     assertTrue(!initialRegions.contains(currentRegions.get(0))); //this is the new region
334     assertTrue(!initialRegions.contains(RegionReplicaUtil.getRegionInfoForReplica(
335         currentRegions.get(0), 1))); //replica of the new region
336     assertTrue(currentRegions.contains(RegionReplicaUtil.getRegionInfoForReplica(
337         currentRegions.get(0), 1))); //replica of the new region
338     assertTrue(!currentRegions.contains(RegionReplicaUtil.getRegionInfoForReplica(
339         mergedRegions.getFirst(), 1))); //replica of the merged region
340     assertTrue(!currentRegions.contains(RegionReplicaUtil.getRegionInfoForReplica(
341         mergedRegions.getSecond(), 1))); //replica of the merged region
342   }
343 
344   private PairOfSameType<HRegionInfo> mergeRegionsAndVerifyRegionNum(
345       HMaster master, TableName tablename,
346       int regionAnum, int regionBnum, int expectedRegionNum) throws Exception {
347     PairOfSameType<HRegionInfo> mergedRegions =
348       requestMergeRegion(master, tablename, regionAnum, regionBnum);
349     waitAndVerifyRegionNum(master, tablename, expectedRegionNum);
350     return mergedRegions;
351   }
352 
353   private PairOfSameType<HRegionInfo> requestMergeRegion(
354       HMaster master, TableName tablename,
355       int regionAnum, int regionBnum) throws Exception {
356     List<Pair<HRegionInfo, ServerName>> tableRegions = MetaTableAccessor
357         .getTableRegionsAndLocations(master.getZooKeeper(),
358           master.getConnection(), tablename);
359     HRegionInfo regionA = tableRegions.get(regionAnum).getFirst();
360     HRegionInfo regionB = tableRegions.get(regionBnum).getFirst();
361     TEST_UTIL.getHBaseAdmin().mergeRegions(
362       regionA.getEncodedNameAsBytes(),
363       regionB.getEncodedNameAsBytes(), false);
364     return new PairOfSameType<HRegionInfo>(regionA, regionB);
365   }
366 
367   private void waitAndVerifyRegionNum(HMaster master, TableName tablename,
368       int expectedRegionNum) throws Exception {
369     List<Pair<HRegionInfo, ServerName>> tableRegionsInMeta;
370     List<HRegionInfo> tableRegionsInMaster;
371     long timeout = System.currentTimeMillis() + waitTime;
372     while (System.currentTimeMillis() < timeout) {
373       tableRegionsInMeta = MetaTableAccessor.getTableRegionsAndLocations(master.getZooKeeper(),
374         master.getConnection(), tablename);
375       tableRegionsInMaster = master.getAssignmentManager().getRegionStates()
376           .getRegionsOfTable(tablename);
377       if (tableRegionsInMeta.size() == expectedRegionNum
378           && tableRegionsInMaster.size() == expectedRegionNum) {
379         break;
380       }
381       Thread.sleep(250);
382     }
383 
384     tableRegionsInMeta = MetaTableAccessor.getTableRegionsAndLocations(master.getZooKeeper(),
385       master.getConnection(), tablename);
386     LOG.info("Regions after merge:" + Joiner.on(',').join(tableRegionsInMeta));
387     assertEquals(expectedRegionNum, tableRegionsInMeta.size());
388   }
389 
390   private Table createTableAndLoadData(HMaster master, TableName tablename)
391       throws Exception {
392     return createTableAndLoadData(master, tablename, INITIAL_REGION_NUM, 1);
393   }
394 
395   private Table createTableAndLoadData(HMaster master, TableName tablename,
396       int numRegions, int replication) throws Exception {
397     assertTrue("ROWSIZE must > numregions:" + numRegions, ROWSIZE > numRegions);
398     byte[][] splitRows = new byte[numRegions - 1][];
399     for (int i = 0; i < splitRows.length; i++) {
400       splitRows[i] = ROWS[(i + 1) * ROWSIZE / numRegions];
401     }
402 
403     Table table = TEST_UTIL.createTable(tablename, FAMILYNAME, splitRows);
404     if (replication > 1) {
405       HBaseTestingUtility.setReplicas(admin, tablename, replication);
406     }
407     loadData(table);
408     verifyRowCount(table, ROWSIZE);
409 
410     // sleep here is an ugly hack to allow region transitions to finish
411     long timeout = System.currentTimeMillis() + waitTime;
412     List<Pair<HRegionInfo, ServerName>> tableRegions;
413     while (System.currentTimeMillis() < timeout) {
414       tableRegions = MetaTableAccessor.getTableRegionsAndLocations(master.getZooKeeper(),
415         master.getConnection(), tablename);
416       if (tableRegions.size() == numRegions * replication)
417         break;
418       Thread.sleep(250);
419     }
420 
421     tableRegions = MetaTableAccessor.getTableRegionsAndLocations(
422       master.getZooKeeper(),
423       master.getConnection(), tablename);
424     LOG.info("Regions after load: " + Joiner.on(',').join(tableRegions));
425     assertEquals(numRegions * replication, tableRegions.size());
426     return table;
427   }
428 
429   private static byte[][] makeN(byte[] base, int n) {
430     byte[][] ret = new byte[n][];
431     for (int i = 0; i < n; i++) {
432       ret[i] = Bytes.add(base, Bytes.toBytes(String.format("%04d", i)));
433     }
434     return ret;
435   }
436 
437   private void loadData(Table table) throws IOException {
438     for (int i = 0; i < ROWSIZE; i++) {
439       Put put = new Put(ROWS[i]);
440       put.add(FAMILYNAME, QUALIFIER, Bytes.toBytes(i));
441       table.put(put);
442     }
443   }
444 
445   private void verifyRowCount(Table table, int expectedRegionNum)
446       throws IOException {
447     ResultScanner scanner = table.getScanner(new Scan());
448     int rowCount = 0;
449     while (scanner.next() != null) {
450       rowCount++;
451     }
452     assertEquals(expectedRegionNum, rowCount);
453     scanner.close();
454   }
455 
456   /**
457    * A test that intentionally has master fail the processing of the merge message.
458    * Tests that the regionserver merge ephemeral node gets cleaned up if it
459    * crashes and that after we process server shutdown, the parent regions are online and
460    * merged region is cleaned up.
461    */
462   @Test (timeout = 60000)
463   public void testMergeIsRolledBackOnMergeFailure() throws Exception {
464 
465     final RegionStates regionStates = master.getAssignmentManager().getRegionStates();
466     final ZooKeeperWatcher zkw = TEST_UTIL.getZooKeeperWatcher();
467 
468     final TableName tableName = TableName.valueOf("testMergeIsRolledBackOnMergeFailure");
469     // Create table with 2 regions as its easy for us to merge.
470     createTableAndLoadData(master, tableName, 2, 1);
471     List<HRegion> regions = cluster.getRegions(tableName);
472 
473     assertEquals("Table shudn't have more than 2 regions, " + regions, 2, regions.size());
474     final HRegionInfo regionA = regions.get(0).getRegionInfo();
475     final HRegionInfo regionB = regions.get(1).getRegionInfo();
476 
477     // Turn off balancer so it doesn't cut in and mess up our placements.
478     admin.setBalancerRunning(false, true);
479     // Turn off the meta scanner so it don't remove parent on us.
480     master.setCatalogJanitorEnabled(false);
481 
482     // Start a server and move both the regions to it. We kill this server later.
483     HRegionServer regionServer = cluster.startRegionServer().getRegionServer();
484     moveRegionToServer(regionA, regionServer);
485     moveRegionToServer(regionB, regionServer);
486 
487     int serverIndex = cluster.getServerWith(regionA.getRegionName());
488 
489     // This helps with server aborts later.
490     TEST_UTIL.compact(tableName, true);
491 
492     try {
493       printOutRegions(regionServer, "Initial regions: ");
494 
495       // Now, before we merge, set special flag in master, a flag that has
496       // it FAIL the processing of merge.
497       AssignmentManager.setTestSkipMergeHandling(true);
498       admin.mergeRegions(regionA.getRegionName(), regionB.getRegionName(), false);
499 
500       // Lets wait until we have a merge region.
501       TEST_UTIL.waitFor(60000, new Waiter.Predicate<Exception>() {
502         @Override
503         public boolean evaluate() throws Exception {
504           return regionStates.getRegionByStateOfTable(tableName).get(State.MERGING_NEW).size() > 0;
505         }
506       });
507 
508       List<HRegionInfo> mergedRegions =
509           regionStates.getRegionByStateOfTable(tableName).get(State.MERGING_NEW);
510       assertEquals("Only one region should be in MERGING_NEW state", 1, mergedRegions.size());
511       final HRegionInfo merge = mergedRegions.get(0);
512 
513       // Lets double check if we have the merge Znode with the appr. state.
514       final String path = ZKAssign.getNodeName(zkw, merge.getEncodedName());
515       // Wait till the znode moved to MERGED
516       TEST_UTIL.waitFor(60000, new Waiter.Predicate<Exception>() {
517         @Override public boolean evaluate() throws Exception {
518           Stat stats = zkw.getRecoverableZooKeeper().exists(path, false);
519           RegionTransition rt =
520               RegionTransition.parseFrom(ZKAssign.getData(zkw, merge.getEncodedName()));
521           return stats != null && rt.getEventType().equals(EventType.RS_ZK_REGION_MERGED);
522         }
523       });
524 
525       // Now crash the server
526       abortServerAndWaitForProcessingToComplete(serverIndex);
527       waitUntilRegionServerDead();
528 
529       TEST_UTIL.waitUntilNoRegionsInTransition(waitTime);
530 
531       // Lets wait until merge parents are online.
532       TEST_UTIL.waitFor(60000, new Waiter.Predicate<Exception>() {
533         @Override
534         public boolean evaluate() {
535           return cluster.getRegions(tableName).size() == 2;
536         }
537       });
538 
539       // Check if merge regions is cleaned up.
540       List<HRegionInfo> tableRegions = MetaTableAccessor.getTableRegions(zkw,
541           cluster.getMaster().getConnection(), tableName);
542       assertEquals("Only parent regions should be present, but we have: " + tableRegions,
543           2, tableRegions.size());
544       assertTrue("Merge A not present? " + regionA, tableRegions.contains(regionA));
545       assertTrue("Merge B not present? " + regionB, tableRegions.contains(regionB));
546 
547       // Are both merge parents online?
548       assertTrue("region should be online, " + regionA, regionStates.isRegionOnline(regionA));
549       assertTrue("region should be online, " + regionB, regionStates.isRegionOnline(regionB));
550 
551       // Have HDFS dirs been cleaned up?
552       Path tableDir = FSUtils.getTableDir(FSUtils.getRootDir(conf), tableName);
553       List<Path> regionDirs =
554           FSUtils.getRegionDirs(cluster.getMaster().getFileSystem(), tableDir);
555       assertEquals("Only two region dir should be present, we have, dirs: " + regionDirs,
556           2, regionDirs.size());
557 
558       assertTrue("Region dir doesn't belong to region: " + regionA + " dir: " + regionDirs,
559           regionDirs.get(0).getName().endsWith(regionA.getEncodedName())
560               || regionDirs.get(1).getName().endsWith(regionA.getEncodedName()));
561       assertTrue("Region dir doesn't belong to region: " + regionB + " dir: " + regionDirs,
562           regionDirs.get(0).getName().endsWith(regionB.getEncodedName())
563               || regionDirs.get(1).getName().endsWith(regionB.getEncodedName()));
564 
565       // The merged Znode should have been cleaned up.
566       Stat stat = zkw.getRecoverableZooKeeper().exists(path, false);
567       assertNull("Merged znode shouldn't exist, but we have stat: " + stat, stat);
568 
569     } finally {
570       // Set this flag back.
571       AssignmentManager.setTestSkipMergeHandling(false);
572       admin.setBalancerRunning(true, false);
573       master.setCatalogJanitorEnabled(true);
574       TEST_UTIL.deleteTable(tableName);
575     }
576   }
577 
578   private void moveRegionToServer(final HRegionInfo region, final HRegionServer rs)
579       throws Exception {
580     admin.move(region.getEncodedNameAsBytes(), rs.getServerName().toString().getBytes());
581     TEST_UTIL.waitUntilNoRegionsInTransition(waitTime);
582     TEST_UTIL.waitFor(60000, new Waiter.Predicate<Exception>() {
583       @Override
584       public boolean evaluate() throws Exception {
585         return rs.getOnlineRegion(region.getRegionName()) != null;
586       }
587     });
588   }
589 
590   private void waitUntilRegionServerDead() throws InterruptedException, IOException {
591     // Wait until the master processes the RS shutdown
592     for (int i=0; cluster.getMaster().getClusterStatus().
593         getServers().size() > NB_SERVERS && i<100; i++) {
594       LOG.info("Waiting on server to go down");
595       Thread.sleep(100);
596     }
597     assertFalse("Waited too long for RS to die", cluster.getMaster().getClusterStatus().
598         getServers().size() > NB_SERVERS);
599   }
600 
601   private void printOutRegions(final HRegionServer hrs, final String prefix)
602       throws IOException {
603     List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
604     for (HRegionInfo region: regions) {
605       LOG.info(prefix + region.getRegionNameAsString());
606     }
607   }
608 
609   private void abortServerAndWaitForProcessingToComplete(int serverIndex) throws Exception {
610 
611     final HMaster master = TEST_UTIL.getMiniHBaseCluster().getMaster();
612     cluster.abortRegionServer(serverIndex);
613     TEST_UTIL.waitFor(60000, new Waiter.Predicate<Exception>() {
614       @Override
615       public boolean evaluate() throws Exception {
616         return master.getServerManager().areDeadServersInProgress();
617       }
618     });
619   }
620 }