View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  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,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations 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.assertNotNull;
24  import static org.junit.Assert.assertNotSame;
25  import static org.junit.Assert.assertNull;
26  import static org.junit.Assert.assertTrue;
27  import static org.junit.Assert.fail;
28  
29  import java.io.IOException;
30  import java.io.InterruptedIOException;
31  import java.util.Collection;
32  import java.util.List;
33  import java.util.Map;
34  import java.util.Set;
35  import java.util.concurrent.CountDownLatch;
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.fs.FileSystem;
41  import org.apache.hadoop.fs.Path;
42  import org.apache.hadoop.hbase.Abortable;
43  import org.apache.hadoop.hbase.CoordinatedStateManager;
44  import org.apache.hadoop.hbase.Coprocessor;
45  import org.apache.hadoop.hbase.CoprocessorEnvironment;
46  import org.apache.hadoop.hbase.HBaseTestingUtility;
47  import org.apache.hadoop.hbase.HColumnDescriptor;
48  import org.apache.hadoop.hbase.HConstants;
49  import org.apache.hadoop.hbase.HRegionInfo;
50  import org.apache.hadoop.hbase.HTableDescriptor;
51  import org.apache.hadoop.hbase.MasterNotRunningException;
52  import org.apache.hadoop.hbase.MetaTableAccessor;
53  import org.apache.hadoop.hbase.MiniHBaseCluster;
54  import org.apache.hadoop.hbase.RegionTransition;
55  import org.apache.hadoop.hbase.Server;
56  import org.apache.hadoop.hbase.ServerName;
57  import org.apache.hadoop.hbase.TableName;
58  import org.apache.hadoop.hbase.UnknownRegionException;
59  import org.apache.hadoop.hbase.Waiter;
60  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
61  import org.apache.hadoop.hbase.client.Admin;
62  import org.apache.hadoop.hbase.client.Connection;
63  import org.apache.hadoop.hbase.client.ConnectionFactory;
64  import org.apache.hadoop.hbase.client.Consistency;
65  import org.apache.hadoop.hbase.client.Delete;
66  import org.apache.hadoop.hbase.client.Get;
67  import org.apache.hadoop.hbase.client.HBaseAdmin;
68  import org.apache.hadoop.hbase.client.HTable;
69  import org.apache.hadoop.hbase.client.Mutation;
70  import org.apache.hadoop.hbase.client.Put;
71  import org.apache.hadoop.hbase.client.Result;
72  import org.apache.hadoop.hbase.client.ResultScanner;
73  import org.apache.hadoop.hbase.client.Scan;
74  import org.apache.hadoop.hbase.client.Table;
75  import org.apache.hadoop.hbase.client.TestReplicasClient.SlowMeCopro;
76  import org.apache.hadoop.hbase.coordination.ZKSplitTransactionCoordination;
77  import org.apache.hadoop.hbase.coordination.ZkCloseRegionCoordination;
78  import org.apache.hadoop.hbase.coordination.ZkCoordinatedStateManager;
79  import org.apache.hadoop.hbase.coordination.ZkOpenRegionCoordination;
80  import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
81  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
82  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
83  import org.apache.hadoop.hbase.exceptions.DeserializationException;
84  import org.apache.hadoop.hbase.executor.EventType;
85  import org.apache.hadoop.hbase.master.AssignmentManager;
86  import org.apache.hadoop.hbase.master.HMaster;
87  import org.apache.hadoop.hbase.master.RegionState;
88  import org.apache.hadoop.hbase.master.RegionState.State;
89  import org.apache.hadoop.hbase.master.RegionStates;
90  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
91  import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext;
92  import org.apache.hadoop.hbase.regionserver.throttle.NoLimitThroughputController;
93  import org.apache.hadoop.hbase.testclassification.LargeTests;
94  import org.apache.hadoop.hbase.util.Bytes;
95  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
96  import org.apache.hadoop.hbase.util.FSUtils;
97  import org.apache.hadoop.hbase.util.HBaseFsck;
98  import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
99  import org.apache.hadoop.hbase.util.PairOfSameType;
100 import org.apache.hadoop.hbase.util.Threads;
101 import org.apache.hadoop.hbase.zookeeper.ZKAssign;
102 import org.apache.hadoop.hbase.zookeeper.ZKUtil;
103 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
104 import org.apache.zookeeper.KeeperException;
105 import org.apache.zookeeper.KeeperException.NodeExistsException;
106 import org.apache.zookeeper.data.Stat;
107 import org.junit.After;
108 import org.junit.AfterClass;
109 import org.junit.Assert;
110 import org.junit.Before;
111 import org.junit.BeforeClass;
112 import org.junit.Test;
113 import org.junit.experimental.categories.Category;
114 
115 import com.google.protobuf.ServiceException;
116 
117 /**
118  * Like TestSplitTransaction in that we're testing {@link SplitTransactionImpl}
119  * only the below tests are against a running cluster where TestSplitTransaction
120  * is tests against a bare {@link HRegion}.
121  */
122 @Category(LargeTests.class)
123 @SuppressWarnings("deprecation")
124 public class TestSplitTransactionOnCluster {
125   private static final Log LOG =
126     LogFactory.getLog(TestSplitTransactionOnCluster.class);
127   private HBaseAdmin admin = null;
128   private MiniHBaseCluster cluster = null;
129   private static Configuration conf;
130   private static final int NB_SERVERS = 3;
131   private static CountDownLatch latch = new CountDownLatch(1);
132   private static volatile boolean secondSplit = false;
133   private static volatile boolean callRollBack = false;
134   private static volatile boolean firstSplitCompleted = false;
135   private static boolean useZKForAssignment;
136 
137   static final HBaseTestingUtility TESTING_UTIL =
138     new HBaseTestingUtility();
139 
140   static void setupOnce() throws Exception {
141     TESTING_UTIL.getConfiguration().setInt(HConstants.HBASE_BALANCER_PERIOD, 60000);
142     useZKForAssignment = TESTING_UTIL.getConfiguration().getBoolean(
143       "hbase.assignment.usezk", true);
144     TESTING_UTIL.startMiniCluster(NB_SERVERS);
145   }
146 
147   @BeforeClass
148   public static void before() throws Exception {
149     conf = TESTING_UTIL.getConfiguration();
150     // Use ZK for region assignment
151     conf.setBoolean("hbase.assignment.usezk", true);
152     setupOnce();
153   }
154 
155   @AfterClass public static void after() throws Exception {
156     TESTING_UTIL.shutdownMiniCluster();
157   }
158 
159   @Before public void setup() throws IOException {
160     TESTING_UTIL.ensureSomeNonStoppedRegionServersAvailable(NB_SERVERS);
161     this.admin = new HBaseAdmin(TESTING_UTIL.getConfiguration());
162     this.cluster = TESTING_UTIL.getMiniHBaseCluster();
163   }
164 
165   @After
166   public void tearDown() throws Exception {
167     this.admin.close();
168   }
169 
170   private HRegionInfo getAndCheckSingleTableRegion(final List<HRegion> regions)
171       throws IOException, InterruptedException {
172     assertEquals(1, regions.size());
173     HRegionInfo hri = regions.get(0).getRegionInfo();
174     TESTING_UTIL.getMiniHBaseCluster().getMaster().getAssignmentManager()
175       .waitOnRegionToClearRegionsInTransition(hri, 600000);
176     return hri;
177   }
178 
179   @Test(timeout = 60000)
180   public void testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack() throws Exception {
181     final TableName tableName =
182         TableName.valueOf("testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack");
183 
184     if (!useZKForAssignment) {
185       // This test doesn't apply if not using ZK for assignment
186       return;
187     }
188 
189     try {
190       // Create table then get the single region for our new table.
191       HTable t = createTableAndWait(tableName, Bytes.toBytes("cf"));
192       final List<HRegion> regions = cluster.getRegions(tableName);
193       HRegionInfo hri = getAndCheckSingleTableRegion(regions);
194       int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionInfo()
195         .getRegionName());
196       final HRegionServer regionServer = cluster.getRegionServer(regionServerIndex);
197       insertData(tableName, admin, t);
198       t.close();
199 
200       // Turn off balancer so it doesn't cut in and mess up our placements.
201       this.admin.setBalancerRunning(false, true);
202       // Turn off the meta scanner so it don't remove parent on us.
203       cluster.getMaster().setCatalogJanitorEnabled(false);
204 
205       // find a splittable region
206       final HRegion region = findSplittableRegion(regions);
207       assertTrue("not able to find a splittable region", region != null);
208       MockedCoordinatedStateManager cp = new MockedCoordinatedStateManager();
209       cp.initialize(regionServer, region);
210       cp.start();
211       regionServer.csm = cp;
212 
213       new Thread() {
214         @Override
215         public void run() {
216           SplitTransaction st = null;
217           st = new MockedSplitTransaction(region, Bytes.toBytes("row2"));
218           try {
219             st.prepare();
220             st.execute(regionServer, regionServer);
221           } catch (IOException e) {
222 
223           }
224         }
225       }.start();
226       for (int i = 0; !callRollBack && i < 100; i++) {
227         Thread.sleep(100);
228       }
229       assertTrue("Waited too long for rollback", callRollBack);
230       SplitTransaction st = new MockedSplitTransaction(region, Bytes.toBytes("row3"));
231       try {
232         secondSplit = true;
233         // make region splittable
234         region.initialize();
235         st.prepare();
236         st.execute(regionServer, regionServer);
237       } catch (IOException e) {
238         LOG.debug("Rollback started :"+ e.getMessage());
239         st.rollback(regionServer, regionServer);
240       }
241       for (int i=0; !firstSplitCompleted && i<100; i++) {
242         Thread.sleep(100);
243       }
244       assertTrue("fist split did not complete", firstSplitCompleted);
245 
246       RegionStates regionStates = cluster.getMaster().getAssignmentManager().getRegionStates();
247       for (int i = 0; regionStates.isRegionInTransition(hri) && i < 100; i++) {
248         Thread.sleep(100);
249       }
250       assertFalse("region still in transition", regionStates.isRegionInTransition(hri));
251 
252       List<Region> onlineRegions = regionServer.getOnlineRegions(tableName);
253       // Region server side split is successful.
254       assertEquals("The parent region should be splitted", 2, onlineRegions.size());
255       //Should be present in RIT
256       List<HRegionInfo> regionsOfTable = cluster.getMaster().getAssignmentManager()
257           .getRegionStates().getRegionsOfTable(tableName);
258       // Master side should also reflect the same
259       assertEquals("No of regions in master", 2, regionsOfTable.size());
260     } finally {
261       admin.setBalancerRunning(true, false);
262       secondSplit = false;
263       firstSplitCompleted = false;
264       callRollBack = false;
265       cluster.getMaster().setCatalogJanitorEnabled(true);
266       TESTING_UTIL.deleteTable(tableName);
267     }
268   }
269 
270   @Test(timeout = 60000)
271   public void testRITStateForRollback() throws Exception {
272     final TableName tableName =
273         TableName.valueOf("testRITStateForRollback");
274     try {
275       // Create table then get the single region for our new table.
276       Table t = createTableAndWait(tableName, Bytes.toBytes("cf"));
277       final List<HRegion> regions = cluster.getRegions(tableName);
278       final HRegionInfo hri = getAndCheckSingleTableRegion(regions);
279       insertData(tableName, admin, t);
280       t.close();
281 
282       // Turn off balancer so it doesn't cut in and mess up our placements.
283       this.admin.setBalancerRunning(false, true);
284       // Turn off the meta scanner so it don't remove parent on us.
285       cluster.getMaster().setCatalogJanitorEnabled(false);
286 
287       // find a splittable region
288       final HRegion region = findSplittableRegion(regions);
289       assertTrue("not able to find a splittable region", region != null);
290 
291       // install region co-processor to fail splits
292       region.getCoprocessorHost().load(FailingSplitRegionObserver.class,
293         Coprocessor.PRIORITY_USER, region.getBaseConf());
294 
295       // split async
296       this.admin.split(region.getRegionInfo().getRegionName(), new byte[] {42});
297 
298       // we have to wait until the SPLITTING state is seen by the master
299       FailingSplitRegionObserver observer = (FailingSplitRegionObserver) region
300           .getCoprocessorHost().findCoprocessor(FailingSplitRegionObserver.class.getName());
301       assertNotNull(observer);
302       observer.latch.await();
303 
304       LOG.info("Waiting for region to come out of RIT");
305       TESTING_UTIL.waitUntilNoRegionsInTransition(60000);
306     } finally {
307       admin.setBalancerRunning(true, false);
308       cluster.getMaster().setCatalogJanitorEnabled(true);
309       TESTING_UTIL.deleteTable(tableName);
310     }
311   }
312   @Test(timeout = 60000)
313   public void testSplitFailedCompactionAndSplit() throws Exception {
314     final TableName tableName = TableName.valueOf("testSplitFailedCompactionAndSplit");
315     Configuration conf = TESTING_UTIL.getConfiguration();
316     try {
317       HBaseAdmin admin = new HBaseAdmin(conf);
318       // Create table then get the single region for our new table.
319       HTableDescriptor htd = new HTableDescriptor(tableName);
320       byte[] cf = Bytes.toBytes("cf");
321       htd.addFamily(new HColumnDescriptor(cf));
322       admin.createTable(htd);
323 
324       for (int i = 0; cluster.getRegions(tableName).size() == 0 && i < 100; i++) {
325         Thread.sleep(100);
326       }
327       assertEquals(1, cluster.getRegions(tableName).size());
328 
329       HRegion region = cluster.getRegions(tableName).get(0);
330       Store store = region.getStore(cf);
331       int regionServerIndex = cluster.getServerWith(region.getRegionInfo().getRegionName());
332       HRegionServer regionServer = cluster.getRegionServer(regionServerIndex);
333 
334       Table t = new HTable(conf, tableName);
335       // insert data
336       insertData(tableName, admin, t);
337       insertData(tableName, admin, t);
338 
339       int fileNum = store.getStorefiles().size();
340       // 0, Compaction Request
341       store.triggerMajorCompaction();
342       CompactionContext cc = store.requestCompaction();
343       assertNotNull(cc);
344       // 1, A timeout split
345       // 1.1 close region
346       assertEquals(2, region.close(false).get(cf).size());
347       // 1.2 rollback and Region initialize again
348       region.initialize();
349 
350       // 2, Run Compaction cc
351       assertFalse(region.compact(cc, store, NoLimitThroughputController.INSTANCE));
352       assertTrue(fileNum > store.getStorefiles().size());
353 
354       // 3, Split
355       SplitTransaction st = new SplitTransactionImpl(region, Bytes.toBytes("row3"));
356       assertTrue(st.prepare());
357       st.execute(regionServer, regionServer);
358       LOG.info("Waiting for region to come out of RIT");
359       TESTING_UTIL.waitFor(60000, 1000, new Waiter.Predicate<Exception>() {
360         @Override
361         public boolean evaluate() throws Exception {
362           RegionStates regionStates = cluster.getMaster().getAssignmentManager().getRegionStates();
363           return !regionStates.isRegionsInTransition();
364         }
365       });
366       assertEquals(2, cluster.getRegions(tableName).size());
367     } finally {
368       TESTING_UTIL.deleteTable(tableName);
369     }
370   }
371 
372   public static class FailingSplitRegionObserver extends BaseRegionObserver {
373     volatile CountDownLatch latch;
374     volatile CountDownLatch postSplit;
375     @Override
376     public void start(CoprocessorEnvironment e) throws IOException {
377       latch = new CountDownLatch(1);
378       postSplit = new CountDownLatch(1);
379     }
380     @Override
381     public void preSplitBeforePONR(ObserverContext<RegionCoprocessorEnvironment> ctx,
382         byte[] splitKey, List<Mutation> metaEntries) throws IOException {
383       latch.countDown();
384       LOG.info("Causing rollback of region split");
385       throw new IOException("Causing rollback of region split");
386     }
387     @Override
388     public void postCompleteSplit(ObserverContext<RegionCoprocessorEnvironment> ctx)
389         throws IOException {
390       postSplit.countDown();
391       LOG.info("postCompleteSplit called");
392     }
393   }
394 
395   /*
396    * A test that intentionally has master fail the processing of the split message.
397    * Tests that the regionserver split ephemeral node gets cleaned up if it
398    * crashes and that after we process server shutdown, the parent region is online and
399    * daughters are cleaned up.
400    */
401   @Test (timeout = 60000)
402   public void testSplitIsRolledBackOnSplitFailure() throws Exception {
403     final TableName tableName = TableName.valueOf("testSplitIsRolledBackOnSplitFailure");
404 
405     // Create table then get the single region for our new table.
406     HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY);
407     List<HRegion> regions = cluster.getRegions(tableName);
408     final HRegionInfo hri = getAndCheckSingleTableRegion(regions);
409 
410     // Turn off balancer so it doesn't cut in and mess up our placements.
411     this.admin.setBalancerRunning(false, true);
412     // Turn off the meta scanner so it don't remove parent on us.
413     cluster.getMaster().setCatalogJanitorEnabled(false);
414 
415     int serverIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri);
416 
417     try {
418       // Add a bit of load up into the table so splittable.
419       TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY, false);
420       // Get region pre-split.
421       HRegionServer server = cluster.getRegionServer(serverIndex);
422       printOutRegions(server, "Initial regions: ");
423       int regionCount = ProtobufUtil.getOnlineRegions(server.getRSRpcServices()).size();
424       // Now, before we split, set special flag in master, a flag that has
425       // it FAIL the processing of split.
426       AssignmentManager.setTestSkipSplitHandling(true);
427       // Now try splitting and it should work.
428       split(hri, server, regionCount);
429 
430       ZooKeeperWatcher zkw = TESTING_UTIL.getZooKeeperWatcher();
431       String path = ZKAssign.getNodeName(zkw, hri.getEncodedName());
432       RegionTransition rt = null;
433       Stat stats = null;
434 
435       // Wait till the znode moved to SPLIT
436       for (int i = 0; i < 100; i++) {
437         stats = zkw.getRecoverableZooKeeper().exists(path, false);
438         rt = RegionTransition.parseFrom(ZKAssign.getData(zkw, hri.getEncodedName()));
439         if (rt.getEventType().equals(EventType.RS_ZK_REGION_SPLIT)) {
440           break;
441         }
442         Thread.sleep(100);
443       }
444       LOG.info("EPHEMERAL NODE BEFORE SERVER ABORT, path=" + path + ", stats=" + stats);
445       assertTrue(rt.getEventType().equals(EventType.RS_ZK_REGION_SPLIT));
446       // Now crash the server, for ZK-less assignment, the server is auto aborted
447       abortServerAndWaitForProcessingToComplete(serverIndex);
448       waitUntilRegionServerDead();
449 
450       TESTING_UTIL.waitUntilNoRegionsInTransition();
451 
452       // Lets wait until parent region is online.
453       TESTING_UTIL.waitFor(60000, new Waiter.Predicate<Exception>() {
454         @Override
455         public boolean evaluate() {
456           for (HRegion region : cluster.getRegions(tableName)) {
457             if (Bytes.equals(region.getRegionInfo().getRegionName(), hri.getRegionName())) {
458               return true;
459             } else {
460               LOG.debug("Wait for some more time, online region: " + region);
461             }
462           }
463           return false;
464         }
465       });
466 
467       RegionStates regionStates = cluster.getMaster().getAssignmentManager().getRegionStates();
468       assertTrue("Parent region should be online", regionStates.isRegionOnline(hri));
469       // Check if daughter regions are cleaned up.
470       List<HRegionInfo> tableRegions = MetaTableAccessor.getTableRegions(zkw,
471           cluster.getMaster().getConnection(), tableName);
472       assertEquals("Only parent region should be present, but we have: " + tableRegions,
473           1, tableRegions.size());
474       Path tableDir = FSUtils.getTableDir(FSUtils.getRootDir(conf), tableName);
475       List<Path> regionDirs =
476           FSUtils.getRegionDirs(cluster.getMaster().getFileSystem(), tableDir);
477       assertEquals("Only one region dir should be present, we have, dirs: " + regionDirs,
478           1, regionDirs.size());
479       assertTrue("Region dir doesn't belong to region: " + hri + " dir: " + regionDirs,
480           regionDirs.get(0).getName().endsWith(hri.getEncodedName()));
481     } finally {
482       // Set this flag back.
483       AssignmentManager.setTestSkipSplitHandling(false);
484       admin.setBalancerRunning(true, false);
485       cluster.getMaster().setCatalogJanitorEnabled(true);
486       cluster.startRegionServer();
487       t.close();
488       TESTING_UTIL.deleteTable(tableName);
489     }
490   }
491 
492   private void abortServerAndWaitForProcessingToComplete(int serverIndex) throws Exception {
493 
494     final HMaster master = TESTING_UTIL.getMiniHBaseCluster().getMaster();
495     cluster.abortRegionServer(serverIndex);
496     TESTING_UTIL.waitFor(60000, new Waiter.Predicate<Exception>() {
497       @Override
498       public boolean evaluate() throws Exception {
499         return master.getServerManager().areDeadServersInProgress();
500       }
501     });
502   }
503 
504   @Test (timeout = 300000) public void testExistingZnodeBlocksSplitAndWeRollback()
505   throws IOException, InterruptedException, NodeExistsException, KeeperException, ServiceException {
506     final TableName tableName =
507         TableName.valueOf("testExistingZnodeBlocksSplitAndWeRollback");
508 
509     // Create table then get the single region for our new table.
510     HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY);
511     List<HRegion> regions = cluster.getRegions(tableName);
512     HRegionInfo hri = getAndCheckSingleTableRegion(regions);
513 
514     int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri);
515 
516     RegionStates regionStates = cluster.getMaster().getAssignmentManager().getRegionStates();
517 
518     // Turn off balancer so it doesn't cut in and mess up our placements.
519     this.admin.setBalancerRunning(false, true);
520     // Turn off the meta scanner so it don't remove parent on us.
521     cluster.getMaster().setCatalogJanitorEnabled(false);
522     try {
523       // Add a bit of load up into the table so splittable.
524       TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY, false);
525       // Get region pre-split.
526       HRegionServer server = cluster.getRegionServer(tableRegionIndex);
527       printOutRegions(server, "Initial regions: ");
528       int regionCount = ProtobufUtil.getOnlineRegions(server.getRSRpcServices()).size();
529       // Insert into zk a blocking znode, a znode of same name as region
530       // so it gets in way of our splitting.
531       ServerName fakedServer = ServerName.valueOf("any.old.server", 1234, -1);
532       if (useZKForAssignment) {
533         ZKAssign.createNodeClosing(TESTING_UTIL.getZooKeeperWatcher(),
534           hri, fakedServer);
535       } else {
536         regionStates.updateRegionState(hri, RegionState.State.CLOSING);
537       }
538       // Now try splitting.... should fail.  And each should successfully
539       // rollback.
540       this.admin.split(hri.getRegionNameAsString());
541       this.admin.split(hri.getRegionNameAsString());
542       this.admin.split(hri.getRegionNameAsString());
543       // Wait around a while and assert count of regions remains constant.
544       for (int i = 0; i < 10; i++) {
545         Thread.sleep(100);
546         assertEquals(regionCount, ProtobufUtil.getOnlineRegions(
547           server.getRSRpcServices()).size());
548       }
549       if (useZKForAssignment) {
550         // Now clear the zknode
551         ZKAssign.deleteClosingNode(TESTING_UTIL.getZooKeeperWatcher(),
552           hri, fakedServer);
553       } else {
554         regionStates.regionOnline(hri, server.getServerName());
555       }
556       // Now try splitting and it should work.
557       split(hri, server, regionCount);
558       // Get daughters
559       checkAndGetDaughters(tableName);
560       // OK, so split happened after we cleared the blocking node.
561     } finally {
562       admin.setBalancerRunning(true, false);
563       cluster.getMaster().setCatalogJanitorEnabled(true);
564       t.close();
565     }
566   }
567 
568   /**
569    * Test that if daughter split on us, we won't do the shutdown handler fixup
570    * just because we can't find the immediate daughter of an offlined parent.
571    * @throws IOException
572    * @throws InterruptedException
573    */
574   @Test (timeout=300000) public void testShutdownFixupWhenDaughterHasSplit()
575   throws IOException, InterruptedException, ServiceException {
576     final TableName tableName =
577         TableName.valueOf("testShutdownFixupWhenDaughterHasSplit");
578 
579     // Create table then get the single region for our new table.
580     HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY);
581     List<HRegion> regions = cluster.getRegions(tableName);
582     HRegionInfo hri = getAndCheckSingleTableRegion(regions);
583 
584     int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri);
585 
586     // Turn off balancer so it doesn't cut in and mess up our placements.
587     this.admin.setBalancerRunning(false, true);
588     // Turn off the meta scanner so it don't remove parent on us.
589     cluster.getMaster().setCatalogJanitorEnabled(false);
590     try {
591       // Add a bit of load up into the table so splittable.
592       TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY);
593       // Get region pre-split.
594       HRegionServer server = cluster.getRegionServer(tableRegionIndex);
595       printOutRegions(server, "Initial regions: ");
596       int regionCount = ProtobufUtil.getOnlineRegions(server.getRSRpcServices()).size();
597       // Now split.
598       split(hri, server, regionCount);
599       // Get daughters
600       List<HRegion> daughters = checkAndGetDaughters(tableName);
601       // Now split one of the daughters.
602       regionCount = ProtobufUtil.getOnlineRegions(server.getRSRpcServices()).size();
603       HRegionInfo daughter = daughters.get(0).getRegionInfo();
604       LOG.info("Daughter we are going to split: " + daughter);
605       // Compact first to ensure we have cleaned up references -- else the split
606       // will fail.
607       this.admin.compact(daughter.getRegionName());
608       daughters = cluster.getRegions(tableName);
609       HRegion daughterRegion = null;
610       for (HRegion r: daughters) {
611         if (r.getRegionInfo().equals(daughter)) {
612           daughterRegion = r;
613           LOG.info("Found matching HRI: " + daughterRegion);
614           break;
615         }
616       }
617       assertTrue(daughterRegion != null);
618       for (int i=0; i<100; i++) {
619         if (!daughterRegion.hasReferences()) break;
620         Threads.sleep(100);
621       }
622       assertFalse("Waiting for reference to be compacted", daughterRegion.hasReferences());
623       LOG.info("Daughter hri before split (has been compacted): " + daughter);
624       split(daughter, server, regionCount);
625       // Get list of daughters
626       daughters = cluster.getRegions(tableName);
627       for (HRegion d: daughters) {
628         LOG.info("Regions before crash: " + d);
629       }
630       // Now crash the server
631       cluster.abortRegionServer(tableRegionIndex);
632       waitUntilRegionServerDead();
633       awaitDaughters(tableName, daughters.size());
634       // Assert daughters are online and ONLY the original daughters -- that
635       // fixup didn't insert one during server shutdown recover.
636       regions = cluster.getRegions(tableName);
637       for (HRegion d: daughters) {
638         LOG.info("Regions after crash: " + d);
639       }
640       assertEquals(daughters.size(), regions.size());
641       for (HRegion r: regions) {
642         LOG.info("Regions post crash " + r);
643         assertTrue("Missing region post crash " + r, daughters.contains(r));
644       }
645     } finally {
646       admin.setBalancerRunning(true, false);
647       cluster.getMaster().setCatalogJanitorEnabled(true);
648       t.close();
649     }
650   }
651 
652   @Test(timeout = 180000)
653   public void testSplitShouldNotThrowNPEEvenARegionHasEmptySplitFiles() throws Exception {
654     TableName userTableName =
655         TableName.valueOf("testSplitShouldNotThrowNPEEvenARegionHasEmptySplitFiles");
656     HTableDescriptor htd = new HTableDescriptor(userTableName);
657     HColumnDescriptor hcd = new HColumnDescriptor("col");
658     htd.addFamily(hcd);
659     admin.createTable(htd);
660     Table table = new HTable(TESTING_UTIL.getConfiguration(), userTableName);
661     try {
662       for (int i = 0; i <= 5; i++) {
663         String row = "row" + i;
664         Put p = new Put(row.getBytes());
665         String val = "Val" + i;
666         p.add("col".getBytes(), "ql".getBytes(), val.getBytes());
667         table.put(p);
668         admin.flush(userTableName.getName());
669         Delete d = new Delete(row.getBytes());
670         // Do a normal delete
671         table.delete(d);
672         admin.flush(userTableName.getName());
673       }
674       admin.majorCompact(userTableName.getName());
675       List<HRegionInfo> regionsOfTable = TESTING_UTIL.getMiniHBaseCluster()
676           .getMaster().getAssignmentManager().getRegionStates()
677           .getRegionsOfTable(userTableName);
678       HRegionInfo hRegionInfo = regionsOfTable.get(0);
679       Put p = new Put("row6".getBytes());
680       p.add("col".getBytes(), "ql".getBytes(), "val".getBytes());
681       table.put(p);
682       p = new Put("row7".getBytes());
683       p.add("col".getBytes(), "ql".getBytes(), "val".getBytes());
684       table.put(p);
685       p = new Put("row8".getBytes());
686       p.add("col".getBytes(), "ql".getBytes(), "val".getBytes());
687       table.put(p);
688       admin.flush(userTableName.getName());
689       admin.split(hRegionInfo.getRegionName(), "row7".getBytes());
690       regionsOfTable = TESTING_UTIL.getMiniHBaseCluster().getMaster()
691           .getAssignmentManager().getRegionStates()
692           .getRegionsOfTable(userTableName);
693 
694       while (regionsOfTable.size() != 2) {
695         Thread.sleep(2000);
696         regionsOfTable = TESTING_UTIL.getMiniHBaseCluster().getMaster()
697             .getAssignmentManager().getRegionStates()
698             .getRegionsOfTable(userTableName);
699       }
700       Assert.assertEquals(2, regionsOfTable.size());
701       Scan s = new Scan();
702       ResultScanner scanner = table.getScanner(s);
703       int mainTableCount = 0;
704       for (Result rr = scanner.next(); rr != null; rr = scanner.next()) {
705         mainTableCount++;
706       }
707       Assert.assertEquals(3, mainTableCount);
708     } finally {
709       table.close();
710     }
711   }
712 
713   /**
714    * Noop Abortable implementation used below in tests.
715    */
716   static class UselessTestAbortable implements Abortable {
717     boolean aborted = false;
718     @Override
719     public void abort(String why, Throwable e) {
720       LOG.warn("ABORTED (But nothing to abort): why=" + why, e);
721       aborted = true;
722     }
723 
724     @Override
725     public boolean isAborted() {
726       return this.aborted;
727     }
728   }
729 
730   /**
731    * Verifies HBASE-5806.  When splitting is partially done and the master goes down
732    * when the SPLIT node is in either SPLIT or SPLITTING state.
733    *
734    * @throws IOException
735    * @throws InterruptedException
736    * @throws NodeExistsException
737    * @throws KeeperException
738    * @throws DeserializationException
739    */
740   @Test(timeout = 400000)
741   public void testMasterRestartWhenSplittingIsPartial()
742       throws IOException, InterruptedException, NodeExistsException,
743       KeeperException, DeserializationException, ServiceException {
744     final TableName tableName = TableName.valueOf("testMasterRestartWhenSplittingIsPartial");
745 
746     if (!useZKForAssignment) {
747       // This test doesn't apply if not using ZK for assignment
748       return;
749     }
750 
751     // Create table then get the single region for our new table.
752     HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY);
753     List<HRegion> regions = cluster.getRegions(tableName);
754     HRegionInfo hri = getAndCheckSingleTableRegion(regions);
755 
756     int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri);
757 
758     // Turn off balancer so it doesn't cut in and mess up our placements.
759     this.admin.setBalancerRunning(false, true);
760     // Turn off the meta scanner so it don't remove parent on us.
761     cluster.getMaster().setCatalogJanitorEnabled(false);
762     ZooKeeperWatcher zkw = new ZooKeeperWatcher(t.getConfiguration(),
763       "testMasterRestartWhenSplittingIsPartial", new UselessTestAbortable());
764     try {
765       // Add a bit of load up into the table so splittable.
766       TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY, false);
767       // Get region pre-split.
768       HRegionServer server = cluster.getRegionServer(tableRegionIndex);
769       printOutRegions(server, "Initial regions: ");
770       // Now, before we split, set special flag in master, a flag that has
771       // it FAIL the processing of split.
772       AssignmentManager.setTestSkipSplitHandling(true);
773       // Now try splitting and it should work.
774 
775       this.admin.split(hri.getRegionNameAsString());
776       checkAndGetDaughters(tableName);
777       // Assert the ephemeral node is up in zk.
778       String path = ZKAssign.getNodeName(zkw, hri.getEncodedName());
779       Stat stats = zkw.getRecoverableZooKeeper().exists(path, false);
780       LOG.info("EPHEMERAL NODE BEFORE SERVER ABORT, path=" + path + ", stats="
781           + stats);
782       byte[] bytes = ZKAssign.getData(zkw, hri.getEncodedName());
783       RegionTransition rtd = RegionTransition.parseFrom(bytes);
784       // State could be SPLIT or SPLITTING.
785       assertTrue(rtd.getEventType().equals(EventType.RS_ZK_REGION_SPLIT)
786           || rtd.getEventType().equals(EventType.RS_ZK_REGION_SPLITTING));
787 
788       // abort and wait for new master.
789       MockMasterWithoutCatalogJanitor master = abortAndWaitForMaster();
790 
791       this.admin = new HBaseAdmin(TESTING_UTIL.getConfiguration());
792 
793       // Update the region to be offline and split, so that HRegionInfo#equals
794       // returns true in checking rebuilt region states map.
795       hri.setOffline(true);
796       hri.setSplit(true);
797       ServerName regionServerOfRegion = master.getAssignmentManager()
798         .getRegionStates().getRegionServerOfRegion(hri);
799       assertTrue(regionServerOfRegion != null);
800 
801       // Remove the block so that split can move ahead.
802       AssignmentManager.setTestSkipSplitHandling(false);
803       String node = ZKAssign.getNodeName(zkw, hri.getEncodedName());
804       Stat stat = new Stat();
805       byte[] data = ZKUtil.getDataNoWatch(zkw, node, stat);
806       // ZKUtil.create
807       for (int i=0; data != null && i<60; i++) {
808         Thread.sleep(1000);
809         data = ZKUtil.getDataNoWatch(zkw, node, stat);
810       }
811       assertNull("Waited too long for ZK node to be removed: "+node, data);
812       RegionStates regionStates = master.getAssignmentManager().getRegionStates();
813       assertTrue("Split parent should be in SPLIT state",
814         regionStates.isRegionInState(hri, State.SPLIT));
815       regionServerOfRegion = regionStates.getRegionServerOfRegion(hri);
816       assertTrue(regionServerOfRegion == null);
817     } finally {
818       // Set this flag back.
819       AssignmentManager.setTestSkipSplitHandling(false);
820       admin.setBalancerRunning(true, false);
821       cluster.getMaster().setCatalogJanitorEnabled(true);
822       t.close();
823       zkw.close();
824     }
825   }
826 
827   /**
828    * Verifies HBASE-5806.  Here the case is that splitting is completed but before the
829    * CJ could remove the parent region the master is killed and restarted.
830    * @throws IOException
831    * @throws InterruptedException
832    * @throws NodeExistsException
833    * @throws KeeperException
834    */
835   @Test (timeout = 300000)
836   public void testMasterRestartAtRegionSplitPendingCatalogJanitor()
837       throws IOException, InterruptedException, NodeExistsException,
838       KeeperException, ServiceException {
839     final TableName tableName = TableName
840         .valueOf("testMasterRestartAtRegionSplitPendingCatalogJanitor");
841 
842     // Create table then get the single region for our new table.
843     HTable t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY);
844     List<HRegion> regions = cluster.getRegions(tableName);
845     HRegionInfo hri = getAndCheckSingleTableRegion(regions);
846 
847     int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri);
848 
849     // Turn off balancer so it doesn't cut in and mess up our placements.
850     this.admin.setBalancerRunning(false, true);
851     // Turn off the meta scanner so it don't remove parent on us.
852     cluster.getMaster().setCatalogJanitorEnabled(false);
853     ZooKeeperWatcher zkw = new ZooKeeperWatcher(t.getConfiguration(),
854       "testMasterRestartAtRegionSplitPendingCatalogJanitor", new UselessTestAbortable());
855     try {
856       // Add a bit of load up into the table so splittable.
857       TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY, false);
858       // Get region pre-split.
859       HRegionServer server = cluster.getRegionServer(tableRegionIndex);
860       printOutRegions(server, "Initial regions: ");
861 
862       this.admin.split(hri.getRegionNameAsString());
863       checkAndGetDaughters(tableName);
864       // Assert the ephemeral node is up in zk.
865       String path = ZKAssign.getNodeName(zkw, hri.getEncodedName());
866       Stat stats = zkw.getRecoverableZooKeeper().exists(path, false);
867       LOG.info("EPHEMERAL NODE BEFORE SERVER ABORT, path=" + path + ", stats="
868           + stats);
869       String node = ZKAssign.getNodeName(zkw, hri.getEncodedName());
870       Stat stat = new Stat();
871       byte[] data = ZKUtil.getDataNoWatch(zkw, node, stat);
872       // ZKUtil.create
873       for (int i=0; data != null && i<60; i++) {
874         Thread.sleep(1000);
875         data = ZKUtil.getDataNoWatch(zkw, node, stat);
876       }
877       assertNull("Waited too long for ZK node to be removed: "+node, data);
878 
879       MockMasterWithoutCatalogJanitor master = abortAndWaitForMaster();
880 
881       this.admin = new HBaseAdmin(TESTING_UTIL.getConfiguration());
882 
883       // Update the region to be offline and split, so that HRegionInfo#equals
884       // returns true in checking rebuilt region states map.
885       hri.setOffline(true);
886       hri.setSplit(true);
887       RegionStates regionStates = master.getAssignmentManager().getRegionStates();
888       assertTrue("Split parent should be in SPLIT state",
889         regionStates.isRegionInState(hri, State.SPLIT));
890       ServerName regionServerOfRegion = regionStates.getRegionServerOfRegion(hri);
891       assertTrue(regionServerOfRegion == null);
892     } finally {
893       this.admin.setBalancerRunning(true, false);
894       cluster.getMaster().setCatalogJanitorEnabled(true);
895       t.close();
896       zkw.close();
897     }
898   }
899 
900   /**
901    *
902    * While transitioning node from RS_ZK_REGION_SPLITTING to
903    * RS_ZK_REGION_SPLITTING during region split,if zookeper went down split always
904    * fails for the region. HBASE-6088 fixes this scenario.
905    * This test case is to test the znode is deleted(if created) or not in roll back.
906    *
907    * @throws IOException
908    * @throws InterruptedException
909    * @throws KeeperException
910    */
911   @Test(timeout = 60000)
912   public void testSplitBeforeSettingSplittingInZK() throws Exception,
913       InterruptedException, KeeperException {
914     testSplitBeforeSettingSplittingInZKInternals();
915   }
916 
917   @Test(timeout = 60000)
918   public void testTableExistsIfTheSpecifiedTableRegionIsSplitParent() throws Exception {
919     ZooKeeperWatcher zkw = HBaseTestingUtility.getZooKeeperWatcher(TESTING_UTIL);
920     final TableName tableName =
921         TableName.valueOf("testTableExistsIfTheSpecifiedTableRegionIsSplitParent");
922     // Create table then get the single region for our new table.
923     Table t = createTableAndWait(tableName, Bytes.toBytes("cf"));
924     List<HRegion> regions = null;
925     try {
926       regions = cluster.getRegions(tableName);
927       int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionInfo()
928         .getRegionName());
929       HRegionServer regionServer = cluster.getRegionServer(regionServerIndex);
930       insertData(tableName, admin, t);
931       // Turn off balancer so it doesn't cut in and mess up our placements.
932       admin.setBalancerRunning(false, true);
933       // Turn off the meta scanner so it don't remove parent on us.
934       cluster.getMaster().setCatalogJanitorEnabled(false);
935       boolean tableExists = MetaTableAccessor.tableExists(regionServer.getConnection(),
936         tableName);
937       assertEquals("The specified table should present.", true, tableExists);
938       final HRegion region = findSplittableRegion(regions);
939       assertTrue("not able to find a splittable region", region != null);
940       SplitTransactionImpl st = new SplitTransactionImpl(region, Bytes.toBytes("row2"));
941       try {
942         st.prepare();
943         st.createDaughters(regionServer, regionServer, null);
944       } catch (IOException e) {
945 
946       }
947       tableExists = MetaTableAccessor.tableExists(regionServer.getConnection(),
948         tableName);
949       assertEquals("The specified table should present.", true, tableExists);
950       Set<RegionState> rit = cluster.getMaster().getAssignmentManager().getRegionStates()
951           .getRegionsInTransition();
952       assertTrue(rit.size() == 3);
953       cluster.getMaster().getAssignmentManager().regionOffline(st.getFirstDaughter());
954       cluster.getMaster().getAssignmentManager().regionOffline(st.getSecondDaughter());
955       cluster.getMaster().getAssignmentManager().regionOffline(region.getRegionInfo());
956       rit = cluster.getMaster().getAssignmentManager().getRegionStates().getRegionsInTransition();
957       assertTrue(rit.size() == 0);
958     }
959     finally {
960       admin.setBalancerRunning(true, false);
961       cluster.getMaster().setCatalogJanitorEnabled(true);
962       t.close();
963       TESTING_UTIL.deleteTable(tableName);
964     }
965   }
966 
967   @Test
968   public void testSplitWithRegionReplicas() throws Exception {
969     ZooKeeperWatcher zkw = HBaseTestingUtility.getZooKeeperWatcher(TESTING_UTIL);
970     final TableName tableName =
971         TableName.valueOf("foobar");
972     HTableDescriptor htd = TESTING_UTIL.createTableDescriptor("foobar");
973     htd.setRegionReplication(2);
974     htd.addCoprocessor(SlowMeCopro.class.getName());
975     // Create table then get the single region for our new table.
976     HTable t = TESTING_UTIL.createTable(htd, new byte[][]{Bytes.toBytes("cf")},
977         TESTING_UTIL.getConfiguration());
978     int count;
979     List<HRegion> oldRegions;
980     do {
981       oldRegions = cluster.getRegions(tableName);
982       Thread.sleep(10);
983     } while (oldRegions.size() != 2);
984     for (HRegion h : oldRegions) LOG.debug("OLDREGION " + h.getRegionInfo());
985     try {
986       int regionServerIndex = cluster.getServerWith(oldRegions.get(0).getRegionInfo()
987         .getRegionName());
988       HRegionServer regionServer = cluster.getRegionServer(regionServerIndex);
989       insertData(tableName, admin, t);
990       // Turn off balancer so it doesn't cut in and mess up our placements.
991       admin.setBalancerRunning(false, true);
992       // Turn off the meta scanner so it don't remove parent on us.
993       cluster.getMaster().setCatalogJanitorEnabled(false);
994       boolean tableExists = MetaTableAccessor.tableExists(regionServer.getConnection(),
995           tableName);
996       assertEquals("The specified table should be present.", true, tableExists);
997       final HRegion region = findSplittableRegion(oldRegions);
998       regionServerIndex = cluster.getServerWith(region.getRegionInfo().getRegionName());
999       regionServer = cluster.getRegionServer(regionServerIndex);
1000       assertTrue("not able to find a splittable region", region != null);
1001       String node = ZKAssign.getNodeName(regionServer.getZooKeeper(),
1002           region.getRegionInfo().getEncodedName());
1003       regionServer.getZooKeeper().sync(node);
1004       SplitTransactionImpl st = new SplitTransactionImpl(region, Bytes.toBytes("row2"));
1005       try {
1006         st.prepare();
1007         st.execute(regionServer, regionServer);
1008       } catch (IOException e) {
1009         e.printStackTrace();
1010         fail("Split execution should have succeeded with no exceptions thrown " + e);
1011       }
1012       //TESTING_UTIL.waitUntilAllRegionsAssigned(tableName);
1013       List<HRegion> newRegions;
1014       do {
1015         newRegions = cluster.getRegions(tableName);
1016         for (HRegion h : newRegions) LOG.debug("NEWREGION " + h.getRegionInfo());
1017         Thread.sleep(1000);
1018       } while ((newRegions.contains(oldRegions.get(0)) || newRegions.contains(oldRegions.get(1)))
1019           || newRegions.size() != 4);
1020       tableExists = MetaTableAccessor.tableExists(regionServer.getConnection(),
1021           tableName);
1022       assertEquals("The specified table should be present.", true, tableExists);
1023       // exists works on stale and we see the put after the flush
1024       byte[] b1 = "row1".getBytes();
1025       Get g = new Get(b1);
1026       g.setConsistency(Consistency.STRONG);
1027       // The following GET will make a trip to the meta to get the new location of the 1st daughter
1028       // In the process it will also get the location of the replica of the daughter (initially
1029       // pointing to the parent's replica)
1030       Result r = t.get(g);
1031       Assert.assertFalse(r.isStale());
1032       LOG.info("exists stale after flush done");
1033 
1034       SlowMeCopro.getPrimaryCdl().set(new CountDownLatch(1));
1035       g = new Get(b1);
1036       g.setConsistency(Consistency.TIMELINE);
1037       // This will succeed because in the previous GET we get the location of the replica
1038       r = t.get(g);
1039       Assert.assertTrue(r.isStale());
1040       SlowMeCopro.getPrimaryCdl().get().countDown();
1041     } finally {
1042       SlowMeCopro.getPrimaryCdl().get().countDown();
1043       admin.setBalancerRunning(true, false);
1044       cluster.getMaster().setCatalogJanitorEnabled(true);
1045       t.close();
1046     }
1047   }
1048 
1049   private void insertData(final TableName tableName, HBaseAdmin admin, Table t) throws IOException,
1050       InterruptedException {
1051     Put p = new Put(Bytes.toBytes("row1"));
1052     p.add(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("1"));
1053     t.put(p);
1054     p = new Put(Bytes.toBytes("row2"));
1055     p.add(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("2"));
1056     t.put(p);
1057     p = new Put(Bytes.toBytes("row3"));
1058     p.add(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("3"));
1059     t.put(p);
1060     p = new Put(Bytes.toBytes("row4"));
1061     p.add(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("4"));
1062     t.put(p);
1063     admin.flush(tableName);
1064   }
1065 
1066   /**
1067    * If a table has regions that have no store files in a region, they should split successfully
1068    * into two regions with no store files.
1069    */
1070   @Test(timeout = 60000)
1071   public void testSplitRegionWithNoStoreFiles()
1072       throws Exception {
1073     final TableName tableName =
1074         TableName.valueOf("testSplitRegionWithNoStoreFiles");
1075     // Create table then get the single region for our new table.
1076     createTableAndWait(tableName, HConstants.CATALOG_FAMILY);
1077     List<HRegion> regions = cluster.getRegions(tableName);
1078     HRegionInfo hri = getAndCheckSingleTableRegion(regions);
1079     ensureTableRegionNotOnSameServerAsMeta(admin, hri);
1080     int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionInfo()
1081       .getRegionName());
1082     HRegionServer regionServer = cluster.getRegionServer(regionServerIndex);
1083     // Turn off balancer so it doesn't cut in and mess up our placements.
1084     this.admin.setBalancerRunning(false, true);
1085     // Turn off the meta scanner so it don't remove parent on us.
1086     cluster.getMaster().setCatalogJanitorEnabled(false);
1087     try {
1088       // Precondition: we created a table with no data, no store files.
1089       printOutRegions(regionServer, "Initial regions: ");
1090       Configuration conf = cluster.getConfiguration();
1091       HBaseFsck.debugLsr(conf, new Path("/"));
1092       Path rootDir = FSUtils.getRootDir(conf);
1093       FileSystem fs = TESTING_UTIL.getDFSCluster().getFileSystem();
1094       Map<String, Path> storefiles =
1095           FSUtils.getTableStoreFilePathMap(null, fs, rootDir, tableName);
1096       assertEquals("Expected nothing but found " + storefiles.toString(), storefiles.size(), 0);
1097 
1098       // find a splittable region.  Refresh the regions list
1099       regions = cluster.getRegions(tableName);
1100       final HRegion region = findSplittableRegion(regions);
1101       assertTrue("not able to find a splittable region", region != null);
1102 
1103       // Now split.
1104       SplitTransactionImpl st = new MockedSplitTransaction(region, Bytes.toBytes("row2"));
1105       try {
1106         st.prepare();
1107         st.execute(regionServer, regionServer);
1108       } catch (IOException e) {
1109         fail("Split execution should have succeeded with no exceptions thrown");
1110       }
1111 
1112       // Postcondition: split the table with no store files into two regions, but still have not
1113       // store files
1114       List<HRegion> daughters = cluster.getRegions(tableName);
1115       assertTrue(daughters.size() == 2);
1116 
1117       // check dirs
1118       HBaseFsck.debugLsr(conf, new Path("/"));
1119       Map<String, Path> storefilesAfter =
1120           FSUtils.getTableStoreFilePathMap(null, fs, rootDir, tableName);
1121       assertEquals("Expected nothing but found " + storefilesAfter.toString(),
1122           storefilesAfter.size(), 0);
1123 
1124       hri = region.getRegionInfo(); // split parent
1125       AssignmentManager am = cluster.getMaster().getAssignmentManager();
1126       RegionStates regionStates = am.getRegionStates();
1127       long start = EnvironmentEdgeManager.currentTime();
1128       while (!regionStates.isRegionInState(hri, State.SPLIT)) {
1129         assertFalse("Timed out in waiting split parent to be in state SPLIT",
1130           EnvironmentEdgeManager.currentTime() - start > 60000);
1131         Thread.sleep(500);
1132       }
1133 
1134       // We should not be able to assign it again
1135       am.assign(hri, true, true);
1136       assertFalse("Split region can't be assigned",
1137         regionStates.isRegionInTransition(hri));
1138       assertTrue(regionStates.isRegionInState(hri, State.SPLIT));
1139 
1140       // We should not be able to unassign it either
1141       am.unassign(hri, true, null);
1142       assertFalse("Split region can't be unassigned",
1143         regionStates.isRegionInTransition(hri));
1144       assertTrue(regionStates.isRegionInState(hri, State.SPLIT));
1145     } finally {
1146       admin.setBalancerRunning(true, false);
1147       cluster.getMaster().setCatalogJanitorEnabled(true);
1148     }
1149   }
1150 
1151   @Test(timeout = 180000)
1152   public void testSplitHooksBeforeAndAfterPONR() throws Exception {
1153     TableName firstTable = TableName.valueOf("testSplitHooksBeforeAndAfterPONR_1");
1154     TableName secondTable = TableName.valueOf("testSplitHooksBeforeAndAfterPONR_2");
1155     HColumnDescriptor hcd = new HColumnDescriptor("cf");
1156 
1157     HTableDescriptor desc = new HTableDescriptor(firstTable);
1158     desc.addCoprocessor(MockedRegionObserver.class.getName());
1159     desc.addFamily(hcd);
1160     admin.createTable(desc);
1161     TESTING_UTIL.waitUntilAllRegionsAssigned(firstTable);
1162 
1163     desc = new HTableDescriptor(secondTable);
1164     desc.addFamily(hcd);
1165     admin.createTable(desc);
1166     TESTING_UTIL.waitUntilAllRegionsAssigned(secondTable);
1167 
1168     List<HRegion> firstTableRegions = cluster.getRegions(firstTable);
1169     List<HRegion> secondTableRegions = cluster.getRegions(secondTable);
1170 
1171     // Check that both tables actually have regions.
1172     if (firstTableRegions.size() == 0 || secondTableRegions.size() == 0) {
1173       fail("Each table should have at least one region.");
1174     }
1175     ServerName serverName = cluster.getServerHoldingRegion(firstTable,
1176       firstTableRegions.get(0).getRegionInfo().getRegionName());
1177     admin.move(secondTableRegions.get(0).getRegionInfo().getEncodedNameAsBytes(),
1178       Bytes.toBytes(serverName.getServerName()));
1179     Table table1 = null;
1180     Table table2 = null;
1181     try {
1182       table1 = new HTable(TESTING_UTIL.getConfiguration(), firstTable);
1183       table2 = new HTable(TESTING_UTIL.getConfiguration(), firstTable);
1184       insertData(firstTable, admin, table1);
1185       insertData(secondTable, admin, table2);
1186       admin.split(firstTable, "row2".getBytes());
1187       firstTableRegions = cluster.getRegions(firstTable);
1188       while (firstTableRegions.size() != 2) {
1189         Thread.sleep(1000);
1190         firstTableRegions = cluster.getRegions(firstTable);
1191       }
1192       assertEquals("Number of regions after split should be 2.", 2, firstTableRegions.size());
1193       secondTableRegions = cluster.getRegions(secondTable);
1194       assertEquals("Number of regions after split should be 2.", 2, secondTableRegions.size());
1195     } finally {
1196       if (table1 != null) {
1197         table1.close();
1198       }
1199       if (table2 != null) {
1200         table2.close();
1201       }
1202       TESTING_UTIL.deleteTable(firstTable);
1203       TESTING_UTIL.deleteTable(secondTable);
1204     }
1205   }
1206 
1207   private void testSplitBeforeSettingSplittingInZKInternals() throws Exception {
1208     final TableName tableName = TableName.valueOf("testSplitBeforeSettingSplittingInZK");
1209     try {
1210       // Create table then get the single region for our new table.
1211       createTableAndWait(tableName, Bytes.toBytes("cf"));
1212 
1213       List<HRegion> regions = awaitTableRegions(tableName);
1214       assertTrue("Table not online", cluster.getRegions(tableName).size() != 0);
1215 
1216       int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionInfo()
1217         .getRegionName());
1218       HRegionServer regionServer = cluster.getRegionServer(regionServerIndex);
1219       final HRegion region = findSplittableRegion(regions);
1220       assertTrue("not able to find a splittable region", region != null);
1221       SplitTransactionImpl st = new MockedSplitTransaction(region, Bytes.toBytes("row2")) {
1222         @Override
1223         public PairOfSameType<Region> stepsBeforePONR(final Server server,
1224             final RegionServerServices services, boolean testing) throws IOException {
1225           throw new SplittingNodeCreationFailedException ();
1226         }
1227       };
1228       String node = ZKAssign.getNodeName(regionServer.getZooKeeper(),
1229           region.getRegionInfo().getEncodedName());
1230       regionServer.getZooKeeper().sync(node);
1231       for (int i = 0; i < 100; i++) {
1232         // We expect the znode to be deleted by this time. Here the
1233         // znode could be in OPENED state and the
1234         // master has not yet deleted the znode.
1235         if (ZKUtil.checkExists(regionServer.getZooKeeper(), node) != -1) {
1236           Thread.sleep(100);
1237         }
1238       }
1239       try {
1240         st.prepare();
1241         st.execute(regionServer, regionServer);
1242       } catch (IOException e) {
1243         // check for the specific instance in case the Split failed due to the
1244         // existence of the znode in OPENED state.
1245         // This will at least make the test to fail;
1246         assertTrue("Should be instance of CreateSplittingNodeFailedException",
1247             e instanceof SplittingNodeCreationFailedException );
1248         node = ZKAssign.getNodeName(regionServer.getZooKeeper(),
1249             region.getRegionInfo().getEncodedName());
1250         {
1251           assertTrue(ZKUtil.checkExists(regionServer.getZooKeeper(), node) == -1);
1252         }
1253         assertTrue(st.rollback(regionServer, regionServer));
1254         assertTrue(ZKUtil.checkExists(regionServer.getZooKeeper(), node) == -1);
1255       }
1256     } finally {
1257       TESTING_UTIL.deleteTable(tableName);
1258     }
1259   }
1260 
1261   @Test
1262   public void testStoreFileReferenceCreationWhenSplitPolicySaysToSkipRangeCheck()
1263       throws Exception {
1264     final TableName tableName =
1265         TableName.valueOf("testStoreFileReferenceCreationWhenSplitPolicySaysToSkipRangeCheck");
1266     try {
1267       HTableDescriptor htd = new HTableDescriptor(tableName);
1268       htd.addFamily(new HColumnDescriptor("f"));
1269       htd.addFamily(new HColumnDescriptor("i_f"));
1270       htd.setRegionSplitPolicyClassName(CustomSplitPolicy.class.getName());
1271       admin.createTable(htd);
1272       List<HRegion> regions = awaitTableRegions(tableName);
1273       HRegion region = regions.get(0);
1274       for(int i = 3;i<9;i++) {
1275         Put p = new Put(Bytes.toBytes("row"+i));
1276         p.add(Bytes.toBytes("f"), Bytes.toBytes("q"), Bytes.toBytes("value"+i));
1277         p.add(Bytes.toBytes("i_f"), Bytes.toBytes("q"), Bytes.toBytes("value"+i));
1278         region.put(p);
1279       }
1280       region.flush(true);
1281       Store store = region.getStore(Bytes.toBytes("f"));
1282       Collection<StoreFile> storefiles = store.getStorefiles();
1283       assertEquals(storefiles.size(), 1);
1284       assertFalse(region.hasReferences());
1285       Path referencePath =
1286           region.getRegionFileSystem().splitStoreFile(region.getRegionInfo(), "f",
1287             storefiles.iterator().next(), Bytes.toBytes("row1"), false, region.getSplitPolicy());
1288       assertNull(referencePath);
1289       referencePath =
1290           region.getRegionFileSystem().splitStoreFile(region.getRegionInfo(), "i_f",
1291             storefiles.iterator().next(), Bytes.toBytes("row1"), false, region.getSplitPolicy());
1292       assertNotNull(referencePath);
1293     } finally {
1294       TESTING_UTIL.deleteTable(tableName);
1295     }
1296   }
1297 
1298   @Test(timeout = 120000)
1299   public void testFailedSplit() throws Exception {
1300     TableName tableName = TableName.valueOf("testFailedSplit");
1301     byte[] colFamily = Bytes.toBytes("info");
1302     TESTING_UTIL.createTable(tableName, colFamily);
1303     Connection connection = ConnectionFactory.createConnection(TESTING_UTIL.getConfiguration());
1304     HTable table = (HTable) connection.getTable(tableName);
1305     try {
1306       TESTING_UTIL.loadTable(table, colFamily);
1307       List<HRegionInfo> regions = TESTING_UTIL.getHBaseAdmin().getTableRegions(tableName);
1308       assertTrue(regions.size() == 1);
1309       final HRegion actualRegion = cluster.getRegions(tableName).get(0);
1310       actualRegion.getCoprocessorHost().load(FailingSplitRegionObserver.class,
1311         Coprocessor.PRIORITY_USER, actualRegion.getBaseConf());
1312 
1313       // The following split would fail.
1314       admin.split(tableName);
1315       FailingSplitRegionObserver observer = (FailingSplitRegionObserver) actualRegion
1316           .getCoprocessorHost().findCoprocessor(FailingSplitRegionObserver.class.getName());
1317       assertNotNull(observer);
1318       observer.latch.await();
1319       observer.postSplit.await();
1320       LOG.info("Waiting for region to come out of RIT: " + actualRegion);
1321       TESTING_UTIL.waitFor(60000, 1000, new Waiter.Predicate<Exception>() {
1322         @Override
1323         public boolean evaluate() throws Exception {
1324           RegionStates regionStates = cluster.getMaster().getAssignmentManager().getRegionStates();
1325           return !regionStates.isRegionsInTransition();
1326         }
1327       });
1328       regions = TESTING_UTIL.getHBaseAdmin().getTableRegions(tableName);
1329       assertTrue(regions.size() == 1);
1330       RegionStates regionStates = cluster.getMaster().getAssignmentManager().getRegionStates();
1331       Set<RegionState> rit = regionStates.getRegionsInTransition();
1332       assertTrue(rit.size() == 0);
1333     } finally {
1334       table.close();
1335       connection.close();
1336       TESTING_UTIL.deleteTable(tableName);
1337     }
1338   }
1339 
1340   @Test (timeout=300000)
1341   public void testSSHCleanupDaugtherRegionsOfAbortedSplit() throws Exception {
1342     TableName table = TableName.valueOf("testSSHCleanupDaugtherRegionsOfAbortedSplit");
1343     try {
1344       HTableDescriptor desc = new HTableDescriptor(table);
1345       desc.addFamily(new HColumnDescriptor(Bytes.toBytes("f")));
1346       admin.createTable(desc);
1347       HTable hTable = new HTable(cluster.getConfiguration(), desc.getTableName());
1348       for(int i = 1; i < 5; i++) {
1349         Put p1 = new Put(("r"+i).getBytes());
1350         p1.add(Bytes.toBytes("f"), "q1".getBytes(), "v".getBytes());
1351         hTable.put(p1);
1352       }
1353       admin.flush(desc.getTableName());
1354       List<HRegion> regions = cluster.getRegions(desc.getTableName());
1355       int serverWith = cluster.getServerWith(regions.get(0).getRegionInfo().getRegionName());
1356       HRegionServer regionServer = cluster.getRegionServer(serverWith);
1357       cluster.getServerWith(regions.get(0).getRegionInfo().getRegionName());
1358       SplitTransactionImpl st = new SplitTransactionImpl(regions.get(0), Bytes.toBytes("r3"));
1359       st.prepare();
1360       st.stepsBeforePONR(regionServer, regionServer, false);
1361       Path tableDir =
1362           FSUtils.getTableDir(cluster.getMaster().getMasterFileSystem().getRootDir(),
1363             desc.getTableName());
1364       tableDir.getFileSystem(cluster.getConfiguration());
1365       List<Path> regionDirs =
1366           FSUtils.getRegionDirs(tableDir.getFileSystem(cluster.getConfiguration()), tableDir);
1367       assertEquals(3,regionDirs.size());
1368       cluster.startRegionServer();
1369       regionServer.kill();
1370       cluster.getRegionServerThreads().get(serverWith).join();
1371       // Wait until finish processing of shutdown
1372       while (cluster.getMaster().getServerManager().areDeadServersInProgress()) {
1373         Thread.sleep(10);
1374       }
1375       AssignmentManager am = cluster.getMaster().getAssignmentManager();
1376       while(am.getRegionStates().isRegionsInTransition()) {
1377         Thread.sleep(10);
1378       }
1379       assertEquals(am.getRegionStates().getRegionsInTransition().toString(), 0, am
1380           .getRegionStates().getRegionsInTransition().size());
1381       regionDirs =
1382           FSUtils.getRegionDirs(tableDir.getFileSystem(cluster.getConfiguration()), tableDir);
1383       assertEquals(1,regionDirs.size());
1384     } finally {
1385       TESTING_UTIL.deleteTable(table);
1386     }
1387   }
1388 
1389     public static class MockedCoordinatedStateManager extends ZkCoordinatedStateManager {
1390 
1391         public void initialize(Server server, HRegion region) {
1392           this.server = server;
1393           this.watcher = server.getZooKeeper();
1394           splitTransactionCoordination = new MockedSplitTransactionCoordination(this, watcher, region);
1395           closeRegionCoordination = new ZkCloseRegionCoordination(this, watcher);
1396           openRegionCoordination = new ZkOpenRegionCoordination(this, watcher);
1397         }
1398       }
1399 
1400       public static class MockedSplitTransaction extends SplitTransactionImpl {
1401 
1402         private HRegion currentRegion;
1403         public MockedSplitTransaction(HRegion region, byte[] splitrow) {
1404           super(region, splitrow);
1405           this.currentRegion = region;
1406         }
1407         @Override
1408         public boolean rollback(Server server, RegionServerServices services) throws IOException {
1409           if (this.currentRegion.getRegionInfo().getTable().getNameAsString()
1410               .equals("testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack")) {
1411             if(secondSplit){
1412               super.rollback(server, services);
1413               latch.countDown();
1414               return true;
1415             }
1416           }
1417           return super.rollback(server, services);
1418         }
1419 
1420 
1421       }
1422 
1423   public static class MockedSplitTransactionCoordination extends ZKSplitTransactionCoordination {
1424 
1425     private HRegion currentRegion;
1426 
1427     public MockedSplitTransactionCoordination(CoordinatedStateManager coordinationProvider,
1428         ZooKeeperWatcher watcher, HRegion region) {
1429       super(coordinationProvider, watcher);
1430       currentRegion = region;
1431     }
1432 
1433     @Override
1434     public void completeSplitTransaction(RegionServerServices services, Region a, Region b,
1435         SplitTransactionDetails std, Region parent) throws IOException {
1436       if (this.currentRegion.getRegionInfo().getTable().getNameAsString()
1437           .equals("testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack")) {
1438         try {
1439           if (!secondSplit){
1440             callRollBack = true;
1441             latch.await();
1442           }
1443         } catch (InterruptedException e) {
1444         }
1445 
1446       }
1447       super.completeSplitTransaction(services, a, b, std, parent);
1448       if (this.currentRegion.getRegionInfo().getTable().getNameAsString()
1449           .equals("testShouldFailSplitIfZNodeDoesNotExistDueToPrevRollBack")) {
1450         firstSplitCompleted = true;
1451       }
1452     }
1453   }
1454 
1455   private HRegion findSplittableRegion(final List<HRegion> regions) throws InterruptedException {
1456     for (int i = 0; i < 5; ++i) {
1457       for (HRegion r: regions) {
1458         if (r.isSplittable() && r.getRegionInfo().getReplicaId() == 0) {
1459           return(r);
1460         }
1461       }
1462       Thread.sleep(100);
1463     }
1464     return(null);
1465   }
1466 
1467   private List<HRegion> checkAndGetDaughters(TableName tableName)
1468       throws InterruptedException {
1469     List<HRegion> daughters = null;
1470     // try up to 10s
1471     for (int i=0; i<100; i++) {
1472       daughters = cluster.getRegions(tableName);
1473       if (daughters.size() >= 2) break;
1474       Thread.sleep(100);
1475     }
1476     assertTrue(daughters.size() >= 2);
1477     return daughters;
1478   }
1479 
1480   private MockMasterWithoutCatalogJanitor abortAndWaitForMaster()
1481   throws IOException, InterruptedException {
1482     cluster.abortMaster(0);
1483     cluster.waitOnMaster(0);
1484     cluster.getConfiguration().setClass(HConstants.MASTER_IMPL,
1485         MockMasterWithoutCatalogJanitor.class, HMaster.class);
1486     MockMasterWithoutCatalogJanitor master = null;
1487     master = (MockMasterWithoutCatalogJanitor) cluster.startMaster().getMaster();
1488     cluster.waitForActiveAndReadyMaster();
1489     return master;
1490   }
1491 
1492   private void split(final HRegionInfo hri, final HRegionServer server, final int regionCount)
1493       throws IOException, InterruptedException {
1494     this.admin.split(hri.getRegionNameAsString());
1495     try {
1496       for (int i = 0; ProtobufUtil.getOnlineRegions(
1497           server.getRSRpcServices()).size() <= regionCount && i < 300; i++) {
1498         LOG.debug("Waiting on region to split");
1499         Thread.sleep(100);
1500       }
1501 
1502       assertFalse("Waited too long for split",
1503         ProtobufUtil.getOnlineRegions(server.getRSRpcServices()).size() <= regionCount);
1504     } catch (RegionServerStoppedException e) {
1505       if (useZKForAssignment) {
1506         // If not using ZK for assignment, the exception may be expected.
1507         LOG.error(e);
1508         throw e;
1509       }
1510     }
1511   }
1512 
1513   /**
1514    * Ensure single table region is not on same server as the single hbase:meta table
1515    * region.
1516    * @param admin
1517    * @param hri
1518    * @return Index of the server hosting the single table region
1519    * @throws UnknownRegionException
1520    * @throws MasterNotRunningException
1521    * @throws org.apache.hadoop.hbase.ZooKeeperConnectionException
1522    * @throws InterruptedException
1523    */
1524   private int ensureTableRegionNotOnSameServerAsMeta(final Admin admin,
1525       final HRegionInfo hri)
1526   throws IOException, MasterNotRunningException,
1527   ZooKeeperConnectionException, InterruptedException {
1528     // Now make sure that the table region is not on same server as that hosting
1529     // hbase:meta  We don't want hbase:meta replay polluting our test when we later crash
1530     // the table region serving server.
1531     int metaServerIndex = cluster.getServerWithMeta();
1532     assertTrue(metaServerIndex != -1);
1533     HRegionServer metaRegionServer = cluster.getRegionServer(metaServerIndex);
1534     int tableRegionIndex = cluster.getServerWith(hri.getRegionName());
1535     assertTrue(tableRegionIndex != -1);
1536     HRegionServer tableRegionServer = cluster.getRegionServer(tableRegionIndex);
1537     if (metaRegionServer.getServerName().equals(tableRegionServer.getServerName())) {
1538       HRegionServer hrs = getOtherRegionServer(cluster, metaRegionServer);
1539       assertNotNull(hrs);
1540       assertNotNull(hri);
1541       LOG.info("Moving " + hri.getRegionNameAsString() + " from " +
1542         metaRegionServer.getServerName() + " to " +
1543         hrs.getServerName() + "; metaServerIndex=" + metaServerIndex);
1544       admin.move(hri.getEncodedNameAsBytes(), Bytes.toBytes(hrs.getServerName().toString()));
1545     }
1546     // Wait till table region is up on the server that is NOT carrying hbase:meta.
1547     for (int i = 0; i < 20; i++) {
1548       tableRegionIndex = cluster.getServerWith(hri.getRegionName());
1549       if (tableRegionIndex != -1 && tableRegionIndex != metaServerIndex) break;
1550       LOG.debug("Waiting on region move off the hbase:meta server; current index " +
1551         tableRegionIndex + " and metaServerIndex=" + metaServerIndex);
1552       Thread.sleep(1000);
1553     }
1554     assertTrue("Region not moved off hbase:meta server", tableRegionIndex != -1
1555         && tableRegionIndex != metaServerIndex);
1556     // Verify for sure table region is not on same server as hbase:meta
1557     tableRegionIndex = cluster.getServerWith(hri.getRegionName());
1558     assertTrue(tableRegionIndex != -1);
1559     assertNotSame(metaServerIndex, tableRegionIndex);
1560     return tableRegionIndex;
1561   }
1562 
1563   /**
1564    * Find regionserver other than the one passed.
1565    * Can't rely on indexes into list of regionservers since crashed servers
1566    * occupy an index.
1567    * @param cluster
1568    * @param notThisOne
1569    * @return A regionserver that is not <code>notThisOne</code> or null if none
1570    * found
1571    */
1572   private HRegionServer getOtherRegionServer(final MiniHBaseCluster cluster,
1573       final HRegionServer notThisOne) {
1574     for (RegionServerThread rst: cluster.getRegionServerThreads()) {
1575       HRegionServer hrs = rst.getRegionServer();
1576       if (hrs.getServerName().equals(notThisOne.getServerName())) continue;
1577       if (hrs.isStopping() || hrs.isStopped()) continue;
1578       return hrs;
1579     }
1580     return null;
1581   }
1582 
1583   private void printOutRegions(final HRegionServer hrs, final String prefix)
1584       throws IOException {
1585     List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices());
1586     for (HRegionInfo region: regions) {
1587       LOG.info(prefix + region.getRegionNameAsString());
1588     }
1589   }
1590 
1591   private void waitUntilRegionServerDead() throws InterruptedException, IOException {
1592     // Wait until the master processes the RS shutdown
1593     for (int i=0; cluster.getMaster().getClusterStatus().
1594         getServers().size() > NB_SERVERS && i<100; i++) {
1595       LOG.info("Waiting on server to go down");
1596       Thread.sleep(100);
1597     }
1598     assertFalse("Waited too long for RS to die", cluster.getMaster().getClusterStatus().
1599         getServers().size() > NB_SERVERS);
1600   }
1601 
1602   private void awaitDaughters(TableName tableName, int numDaughters) throws InterruptedException {
1603     // Wait till regions are back on line again.
1604     for (int i=0; cluster.getRegions(tableName).size() < numDaughters && i<60; i++) {
1605       LOG.info("Waiting for repair to happen");
1606       Thread.sleep(1000);
1607     }
1608     if (cluster.getRegions(tableName).size() < numDaughters) {
1609       fail("Waiting too long for daughter regions");
1610     }
1611   }
1612 
1613   private List<HRegion> awaitTableRegions(final TableName tableName) throws InterruptedException {
1614     List<HRegion> regions = null;
1615     for (int i = 0; i < 100; i++) {
1616       regions = cluster.getRegions(tableName);
1617       if (regions.size() > 0) break;
1618       Thread.sleep(100);
1619     }
1620     return regions;
1621   }
1622 
1623   private HTable createTableAndWait(TableName tableName, byte[] cf) throws IOException,
1624       InterruptedException {
1625     HTable t = TESTING_UTIL.createTable(tableName, cf);
1626     awaitTableRegions(tableName);
1627     assertTrue("Table not online: " + tableName,
1628       cluster.getRegions(tableName).size() != 0);
1629     return t;
1630   }
1631 
1632   public static class MockMasterWithoutCatalogJanitor extends HMaster {
1633 
1634     public MockMasterWithoutCatalogJanitor(Configuration conf, CoordinatedStateManager cp)
1635       throws IOException, KeeperException,
1636         InterruptedException {
1637       super(conf, cp);
1638     }
1639   }
1640 
1641   private static class SplittingNodeCreationFailedException  extends IOException {
1642     private static final long serialVersionUID = 1652404976265623004L;
1643 
1644     public SplittingNodeCreationFailedException () {
1645       super();
1646     }
1647   }
1648 
1649   public static class MockedRegionObserver extends BaseRegionObserver {
1650     private SplitTransactionImpl st = null;
1651     private PairOfSameType<Region> daughterRegions = null;
1652 
1653     @Override
1654     public void preSplitBeforePONR(ObserverContext<RegionCoprocessorEnvironment> ctx,
1655         byte[] splitKey, List<Mutation> metaEntries) throws IOException {
1656       RegionCoprocessorEnvironment environment = ctx.getEnvironment();
1657       HRegionServer rs = (HRegionServer) environment.getRegionServerServices();
1658       List<Region> onlineRegions =
1659           rs.getOnlineRegions(TableName.valueOf("testSplitHooksBeforeAndAfterPONR_2"));
1660       Region region = onlineRegions.get(0);
1661       for (Region r : onlineRegions) {
1662         if (r.getRegionInfo().containsRow(splitKey)) {
1663           region = r;
1664           break;
1665         }
1666       }
1667       st = new SplitTransactionImpl((HRegion) region, splitKey);
1668       if (!st.prepare()) {
1669         LOG.error("Prepare for the table " + region.getTableDesc().getNameAsString()
1670             + " failed. So returning null. ");
1671         ctx.bypass();
1672         return;
1673       }
1674       ((HRegion)region).forceSplit(splitKey);
1675       daughterRegions = st.stepsBeforePONR(rs, rs, false);
1676       HRegionInfo copyOfParent = new HRegionInfo(region.getRegionInfo());
1677       copyOfParent.setOffline(true);
1678       copyOfParent.setSplit(true);
1679       // Put for parent
1680       Put putParent = MetaTableAccessor.makePutFromRegionInfo(copyOfParent);
1681       MetaTableAccessor.addDaughtersToPut(putParent, daughterRegions.getFirst().getRegionInfo(),
1682         daughterRegions.getSecond().getRegionInfo());
1683       metaEntries.add(putParent);
1684       // Puts for daughters
1685       Put putA = MetaTableAccessor.makePutFromRegionInfo(
1686         daughterRegions.getFirst().getRegionInfo());
1687       Put putB = MetaTableAccessor.makePutFromRegionInfo(
1688         daughterRegions.getSecond().getRegionInfo());
1689       st.addLocation(putA, rs.getServerName(), 1);
1690       st.addLocation(putB, rs.getServerName(), 1);
1691       metaEntries.add(putA);
1692       metaEntries.add(putB);
1693     }
1694 
1695     @Override
1696     public void preSplitAfterPONR(ObserverContext<RegionCoprocessorEnvironment> ctx)
1697         throws IOException {
1698       RegionCoprocessorEnvironment environment = ctx.getEnvironment();
1699       HRegionServer rs = (HRegionServer) environment.getRegionServerServices();
1700       st.stepsAfterPONR(rs, rs, daughterRegions, null);
1701     }
1702 
1703   }
1704 
1705   static class CustomSplitPolicy extends RegionSplitPolicy {
1706 
1707     @Override
1708     protected boolean shouldSplit() {
1709       return true;
1710     }
1711 
1712     @Override
1713     public boolean skipStoreFileRangeCheck(String familyName) {
1714       if(familyName.startsWith("i_")) {
1715         return true;
1716       } else {
1717         return false;
1718       }
1719     }
1720   }
1721 }
1722