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