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