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.util;
20  
21  import static org.apache.hadoop.hbase.util.hbck.HbckTestingUtil.assertErrors;
22  import static org.apache.hadoop.hbase.util.hbck.HbckTestingUtil.assertNoErrors;
23  import static org.apache.hadoop.hbase.util.hbck.HbckTestingUtil.doFsck;
24  import static org.junit.Assert.assertEquals;
25  import static org.junit.Assert.assertFalse;
26  import static org.junit.Assert.assertNotEquals;
27  import static org.junit.Assert.assertNotNull;
28  import static org.junit.Assert.assertTrue;
29  import static org.junit.Assert.fail;
30  
31  import java.io.IOException;
32  import java.util.ArrayList;
33  import java.util.Arrays;
34  import java.util.Collection;
35  import java.util.HashMap;
36  import java.util.HashSet;
37  import java.util.LinkedList;
38  import java.util.List;
39  import java.util.Map;
40  import java.util.Random;
41  import java.util.Map.Entry;
42  import java.util.NavigableMap;
43  import java.util.Set;
44  import java.util.concurrent.Callable;
45  import java.util.concurrent.CountDownLatch;
46  import java.util.concurrent.ExecutorService;
47  import java.util.concurrent.Executors;
48  import java.util.concurrent.Future;
49  import java.util.concurrent.ScheduledThreadPoolExecutor;
50  import java.util.concurrent.SynchronousQueue;
51  import java.util.concurrent.ThreadPoolExecutor;
52  import java.util.concurrent.TimeUnit;
53  import java.util.concurrent.atomic.AtomicBoolean;
54  
55  import org.apache.commons.io.IOUtils;
56  import org.apache.commons.logging.Log;
57  import org.apache.commons.logging.LogFactory;
58  import org.apache.hadoop.conf.Configuration;
59  import org.apache.hadoop.fs.FileStatus;
60  import org.apache.hadoop.fs.FileSystem;
61  import org.apache.hadoop.fs.Path;
62  import org.apache.hadoop.hbase.ClusterStatus;
63  import org.apache.hadoop.hbase.HBaseTestingUtility;
64  import org.apache.hadoop.hbase.HColumnDescriptor;
65  import org.apache.hadoop.hbase.HConstants;
66  import org.apache.hadoop.hbase.HRegionInfo;
67  import org.apache.hadoop.hbase.HRegionLocation;
68  import org.apache.hadoop.hbase.HTableDescriptor;
69  import org.apache.hadoop.hbase.TableExistsException;
70  import org.apache.hadoop.hbase.testclassification.LargeTests;
71  import org.apache.hadoop.hbase.MiniHBaseCluster;
72  import org.apache.hadoop.hbase.RegionLocations;
73  import org.apache.hadoop.hbase.ServerName;
74  import org.apache.hadoop.hbase.TableName;
75  import org.apache.hadoop.hbase.MetaTableAccessor;
76  import org.apache.hadoop.hbase.client.Admin;
77  import org.apache.hadoop.hbase.client.ClusterConnection;
78  import org.apache.hadoop.hbase.client.Connection;
79  import org.apache.hadoop.hbase.client.ConnectionFactory;
80  import org.apache.hadoop.hbase.client.Delete;
81  import org.apache.hadoop.hbase.client.Durability;
82  import org.apache.hadoop.hbase.client.Get;
83  import org.apache.hadoop.hbase.client.HBaseAdmin;
84  import org.apache.hadoop.hbase.client.HConnection;
85  import org.apache.hadoop.hbase.client.HTable;
86  import org.apache.hadoop.hbase.client.MetaScanner;
87  import org.apache.hadoop.hbase.client.Mutation;
88  import org.apache.hadoop.hbase.client.Put;
89  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
90  import org.apache.hadoop.hbase.client.Result;
91  import org.apache.hadoop.hbase.client.ResultScanner;
92  import org.apache.hadoop.hbase.client.RowMutations;
93  import org.apache.hadoop.hbase.client.Scan;
94  import org.apache.hadoop.hbase.client.Table;
95  import org.apache.hadoop.hbase.coprocessor.BaseMasterObserver;
96  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
97  import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
98  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
99  import org.apache.hadoop.hbase.io.hfile.TestHFile;
100 import org.apache.hadoop.hbase.master.AssignmentManager;
101 import org.apache.hadoop.hbase.master.HMaster;
102 import org.apache.hadoop.hbase.master.RegionState;
103 import org.apache.hadoop.hbase.master.RegionStates;
104 import org.apache.hadoop.hbase.master.TableLockManager;
105 import org.apache.hadoop.hbase.master.TableLockManager.TableLock;
106 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
107 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos;
108 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos;
109 import org.apache.hadoop.hbase.regionserver.HRegion;
110 import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
111 import org.apache.hadoop.hbase.regionserver.HRegionServer;
112 import org.apache.hadoop.hbase.regionserver.SplitTransactionImpl;
113 import org.apache.hadoop.hbase.regionserver.TestEndToEndSplitTransaction;
114 import org.apache.hadoop.hbase.util.HBaseFsck.ErrorReporter;
115 import org.apache.hadoop.hbase.util.HBaseFsck.ErrorReporter.ERROR_CODE;
116 import org.apache.hadoop.hbase.util.HBaseFsck.HbckInfo;
117 import org.apache.hadoop.hbase.util.HBaseFsck.PrintingErrorReporter;
118 import org.apache.hadoop.hbase.util.HBaseFsck.TableInfo;
119 import org.apache.hadoop.hbase.util.hbck.HFileCorruptionChecker;
120 import org.apache.hadoop.hbase.util.hbck.HbckTestingUtil;
121 import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
122 import org.apache.hadoop.hbase.zookeeper.ZKAssign;
123 import org.apache.zookeeper.KeeperException;
124 import org.junit.AfterClass;
125 import org.junit.Assert;
126 import org.junit.Before;
127 import org.junit.BeforeClass;
128 import org.junit.Ignore;
129 import org.junit.Test;
130 import org.junit.experimental.categories.Category;
131 import org.junit.rules.TestName;
132 
133 import com.google.common.collect.Multimap;
134 
135 /**
136  * This tests HBaseFsck's ability to detect reasons for inconsistent tables.
137  */
138 @Category(LargeTests.class)
139 public class TestHBaseFsck {
140   static final int POOL_SIZE = 7;
141 
142   final static Log LOG = LogFactory.getLog(TestHBaseFsck.class);
143   private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
144   private final static Configuration conf = TEST_UTIL.getConfiguration();
145   private final static String FAM_STR = "fam";
146   private final static byte[] FAM = Bytes.toBytes(FAM_STR);
147   private final static int REGION_ONLINE_TIMEOUT = 800;
148   private static RegionStates regionStates;
149   private static ExecutorService tableExecutorService;
150   private static ScheduledThreadPoolExecutor hbfsckExecutorService;
151   private static ClusterConnection connection;
152   private static Admin admin;
153 
154   // for the instance, reset every test run
155   private HTable tbl;
156   private final static byte[][] SPLITS = new byte[][] { Bytes.toBytes("A"),
157     Bytes.toBytes("B"), Bytes.toBytes("C") };
158   // one row per region.
159   private final static byte[][] ROWKEYS= new byte[][] {
160     Bytes.toBytes("00"), Bytes.toBytes("50"), Bytes.toBytes("A0"), Bytes.toBytes("A5"),
161     Bytes.toBytes("B0"), Bytes.toBytes("B5"), Bytes.toBytes("C0"), Bytes.toBytes("C5") };
162 
163   @BeforeClass
164   public static void setUpBeforeClass() throws Exception {
165     TEST_UTIL.getConfiguration().set(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY,
166       MasterSyncObserver.class.getName());
167 
168     conf.setInt("hbase.regionserver.handler.count", 2);
169     conf.setInt("hbase.regionserver.metahandler.count", 30);
170 
171     conf.setInt("hbase.htable.threads.max", POOL_SIZE);
172     conf.setInt("hbase.hconnection.threads.max", 2 * POOL_SIZE);
173     conf.setInt("hbase.hconnection.threads.core", POOL_SIZE);
174     conf.setInt("hbase.hbck.close.timeout", 2 * REGION_ONLINE_TIMEOUT);
175     conf.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 8 * REGION_ONLINE_TIMEOUT);
176     TEST_UTIL.startMiniCluster(3);
177 
178     tableExecutorService = new ThreadPoolExecutor(1, POOL_SIZE, 60, TimeUnit.SECONDS,
179         new SynchronousQueue<Runnable>(), Threads.newDaemonThreadFactory("testhbck"));
180 
181     hbfsckExecutorService = new ScheduledThreadPoolExecutor(POOL_SIZE);
182 
183     AssignmentManager assignmentManager =
184       TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager();
185     regionStates = assignmentManager.getRegionStates();
186 
187     connection = (ClusterConnection) TEST_UTIL.getConnection();
188 
189     admin = connection.getAdmin();
190     admin.setBalancerRunning(false, true);
191 
192     TEST_UTIL.waitUntilAllRegionsAssigned(TableName.META_TABLE_NAME);
193     TEST_UTIL.waitUntilAllRegionsAssigned(TableName.NAMESPACE_TABLE_NAME);
194   }
195 
196   @AfterClass
197   public static void tearDownAfterClass() throws Exception {
198     tableExecutorService.shutdown();
199     hbfsckExecutorService.shutdown();
200     admin.close();
201     TEST_UTIL.shutdownMiniCluster();
202   }
203 
204   @Before
205   public void setUp() {
206     EnvironmentEdgeManager.reset();
207   }
208 
209   @Test (timeout=180000)
210   public void testHBaseFsck() throws Exception {
211     assertNoErrors(doFsck(conf, false));
212     TableName table = TableName.valueOf("tableBadMetaAssign");
213     HTableDescriptor desc = new HTableDescriptor(table);
214     HColumnDescriptor hcd = new HColumnDescriptor(Bytes.toString(FAM));
215     desc.addFamily(hcd); // If a table has no CF's it doesn't get checked
216     createTable(TEST_UTIL, desc, null);
217 
218     // We created 1 table, should be fine
219     assertNoErrors(doFsck(conf, false));
220 
221     // Now let's mess it up and change the assignment in hbase:meta to
222     // point to a different region server
223     Table meta = connection.getTable(TableName.META_TABLE_NAME, tableExecutorService);
224     Scan scan = new Scan();
225     scan.setStartRow(Bytes.toBytes(table+",,"));
226     ResultScanner scanner = meta.getScanner(scan);
227     HRegionInfo hri = null;
228 
229     Result res = scanner.next();
230     ServerName currServer =
231       ServerName.parseFrom(res.getValue(HConstants.CATALOG_FAMILY,
232           HConstants.SERVER_QUALIFIER));
233     long startCode = Bytes.toLong(res.getValue(HConstants.CATALOG_FAMILY,
234         HConstants.STARTCODE_QUALIFIER));
235 
236     for (JVMClusterUtil.RegionServerThread rs :
237         TEST_UTIL.getHBaseCluster().getRegionServerThreads()) {
238 
239       ServerName sn = rs.getRegionServer().getServerName();
240 
241       // When we find a diff RS, change the assignment and break
242       if (!currServer.getHostAndPort().equals(sn.getHostAndPort()) ||
243           startCode != sn.getStartcode()) {
244         Put put = new Put(res.getRow());
245         put.setDurability(Durability.SKIP_WAL);
246         put.add(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER,
247           Bytes.toBytes(sn.getHostAndPort()));
248         put.add(HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER,
249           Bytes.toBytes(sn.getStartcode()));
250         meta.put(put);
251         hri = MetaTableAccessor.getHRegionInfo(res);
252         break;
253       }
254     }
255 
256     // Try to fix the data
257     assertErrors(doFsck(conf, true), new ERROR_CODE[]{
258         ERROR_CODE.SERVER_DOES_NOT_MATCH_META});
259 
260     TEST_UTIL.getHBaseCluster().getMaster()
261       .getAssignmentManager().waitForAssignment(hri);
262 
263     // Should be fixed now
264     assertNoErrors(doFsck(conf, false));
265 
266     // comment needed - what is the purpose of this line
267     Table t = connection.getTable(table, tableExecutorService);
268     ResultScanner s = t.getScanner(new Scan());
269     s.close();
270     t.close();
271 
272     scanner.close();
273     meta.close();
274   }
275 
276   @Test(timeout=180000)
277   public void testFixAssignmentsWhenMETAinTransition() throws Exception {
278     MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
279     admin.closeRegion(cluster.getServerHoldingMeta(), HRegionInfo.FIRST_META_REGIONINFO);
280     regionStates.regionOffline(HRegionInfo.FIRST_META_REGIONINFO);
281     new MetaTableLocator().deleteMetaLocation(cluster.getMaster().getZooKeeper());
282     assertFalse(regionStates.isRegionOnline(HRegionInfo.FIRST_META_REGIONINFO));
283     HBaseFsck hbck = doFsck(conf, true);
284     assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.UNKNOWN, ERROR_CODE.NO_META_REGION,
285         ERROR_CODE.NULL_META_REGION });
286     assertNoErrors(doFsck(conf, false));
287   }
288 
289   /**
290    * Create a new region in META.
291    */
292   private HRegionInfo createRegion(final HTableDescriptor
293       htd, byte[] startKey, byte[] endKey)
294       throws IOException {
295     Table meta = connection.getTable(TableName.META_TABLE_NAME, tableExecutorService);
296     HRegionInfo hri = new HRegionInfo(htd.getTableName(), startKey, endKey);
297     MetaTableAccessor.addRegionToMeta(meta, hri);
298     meta.close();
299     return hri;
300   }
301 
302   /**
303    * Debugging method to dump the contents of meta.
304    */
305   private void dumpMeta(TableName tableName) throws IOException {
306     List<byte[]> metaRows = TEST_UTIL.getMetaTableRows(tableName);
307     for (byte[] row : metaRows) {
308       LOG.info(Bytes.toString(row));
309     }
310   }
311 
312   /**
313    * This method is used to undeploy a region -- close it and attempt to
314    * remove its state from the Master.
315    */
316   private void undeployRegion(Connection conn, ServerName sn,
317       HRegionInfo hri) throws IOException, InterruptedException {
318     try {
319       HBaseFsckRepair.closeRegionSilentlyAndWait((HConnection) conn, sn, hri);
320       if (!hri.isMetaTable()) {
321         admin.offline(hri.getRegionName());
322       }
323     } catch (IOException ioe) {
324       LOG.warn("Got exception when attempting to offline region "
325           + Bytes.toString(hri.getRegionName()), ioe);
326     }
327   }
328   /**
329    * Delete a region from assignments, meta, or completely from hdfs.
330    * @param unassign if true unassign region if assigned
331    * @param metaRow  if true remove region's row from META
332    * @param hdfs if true remove region's dir in HDFS
333    */
334   private void deleteRegion(Configuration conf, final HTableDescriptor htd,
335       byte[] startKey, byte[] endKey, boolean unassign, boolean metaRow,
336       boolean hdfs) throws IOException, InterruptedException {
337     deleteRegion(conf, htd, startKey, endKey, unassign, metaRow, hdfs, false, HRegionInfo.DEFAULT_REPLICA_ID);
338   }
339 
340   /**
341    * Delete a region from assignments, meta, or completely from hdfs.
342    * @param unassign if true unassign region if assigned
343    * @param metaRow  if true remove region's row from META
344    * @param hdfs if true remove region's dir in HDFS
345    * @param regionInfoOnly if true remove a region dir's .regioninfo file
346    * @param replicaId replica id
347    */
348   private void deleteRegion(Configuration conf, final HTableDescriptor htd,
349       byte[] startKey, byte[] endKey, boolean unassign, boolean metaRow,
350       boolean hdfs, boolean regionInfoOnly, int replicaId)
351           throws IOException, InterruptedException {
352     LOG.info("** Before delete:");
353     dumpMeta(htd.getTableName());
354 
355     List<HRegionLocation> locations = tbl.getAllRegionLocations();
356     for (HRegionLocation location : locations) {
357       HRegionInfo hri = location.getRegionInfo();
358       ServerName hsa = location.getServerName();
359       if (Bytes.compareTo(hri.getStartKey(), startKey) == 0
360           && Bytes.compareTo(hri.getEndKey(), endKey) == 0
361           && hri.getReplicaId() == replicaId) {
362 
363         LOG.info("RegionName: " +hri.getRegionNameAsString());
364         byte[] deleteRow = hri.getRegionName();
365 
366         if (unassign) {
367           LOG.info("Undeploying region " + hri + " from server " + hsa);
368           undeployRegion(connection, hsa, hri);
369         }
370 
371         if (regionInfoOnly) {
372           LOG.info("deleting hdfs .regioninfo data: " + hri.toString() + hsa.toString());
373           Path rootDir = FSUtils.getRootDir(conf);
374           FileSystem fs = rootDir.getFileSystem(conf);
375           Path p = new Path(FSUtils.getTableDir(rootDir, htd.getTableName()),
376               hri.getEncodedName());
377           Path hriPath = new Path(p, HRegionFileSystem.REGION_INFO_FILE);
378           fs.delete(hriPath, true);
379         }
380 
381         if (hdfs) {
382           LOG.info("deleting hdfs data: " + hri.toString() + hsa.toString());
383           Path rootDir = FSUtils.getRootDir(conf);
384           FileSystem fs = rootDir.getFileSystem(conf);
385           Path p = new Path(FSUtils.getTableDir(rootDir, htd.getTableName()),
386               hri.getEncodedName());
387           HBaseFsck.debugLsr(conf, p);
388           boolean success = fs.delete(p, true);
389           LOG.info("Deleted " + p + " sucessfully? " + success);
390           HBaseFsck.debugLsr(conf, p);
391         }
392 
393         if (metaRow) {
394           try (Table meta = connection.getTable(TableName.META_TABLE_NAME, tableExecutorService)) {
395             Delete delete = new Delete(deleteRow);
396             meta.delete(delete);
397           }
398         }
399       }
400       LOG.info(hri.toString() + hsa.toString());
401     }
402 
403     TEST_UTIL.getMetaTableRows(htd.getTableName());
404     LOG.info("*** After delete:");
405     dumpMeta(htd.getTableName());
406   }
407 
408   /**
409    * Setup a clean table before we start mucking with it.
410    *
411    * It will set tbl which needs to be closed after test
412    *
413    * @throws IOException
414    * @throws InterruptedException
415    * @throws KeeperException
416    */
417   void setupTable(TableName tablename) throws Exception {
418     setupTableWithRegionReplica(tablename, 1);
419   }
420 
421   /**
422    * Setup a clean table with a certain region_replica count
423    *
424    * It will set tbl which needs to be closed after test
425    *
426    * @param tableName
427    * @param replicaCount
428    * @throws Exception
429    */
430   void setupTableWithRegionReplica(TableName tablename, int replicaCount) throws Exception {
431     HTableDescriptor desc = new HTableDescriptor(tablename);
432     desc.setRegionReplication(replicaCount);
433     HColumnDescriptor hcd = new HColumnDescriptor(Bytes.toString(FAM));
434     desc.addFamily(hcd); // If a table has no CF's it doesn't get checked
435     createTable(TEST_UTIL, desc, SPLITS);
436 
437     tbl = (HTable) connection.getTable(tablename, tableExecutorService);
438     List<Put> puts = new ArrayList<Put>();
439     for (byte[] row : ROWKEYS) {
440       Put p = new Put(row);
441       p.add(FAM, Bytes.toBytes("val"), row);
442       puts.add(p);
443     }
444     tbl.put(puts);
445     tbl.flushCommits();
446   }
447 
448   /**
449    * Counts the number of row to verify data loss or non-dataloss.
450    */
451   int countRows() throws IOException {
452      Scan s = new Scan();
453      ResultScanner rs = tbl.getScanner(s);
454      int i = 0;
455      while(rs.next() !=null) {
456        i++;
457      }
458      return i;
459   }
460 
461   /**
462    * delete table in preparation for next test
463    *
464    * @param tablename
465    * @throws IOException
466    */
467   void cleanupTable(TableName tablename) throws Exception {
468     if (tbl != null) {
469       tbl.close();
470       tbl = null;
471     }
472 
473     ((ClusterConnection) connection).clearRegionCache();
474     deleteTable(TEST_UTIL, tablename);
475   }
476 
477   /**
478    * This creates a clean table and confirms that the table is clean.
479    */
480   @Test (timeout=180000)
481   public void testHBaseFsckClean() throws Exception {
482     assertNoErrors(doFsck(conf, false));
483     TableName table = TableName.valueOf("tableClean");
484     try {
485       HBaseFsck hbck = doFsck(conf, false);
486       assertNoErrors(hbck);
487 
488       setupTable(table);
489       assertEquals(ROWKEYS.length, countRows());
490 
491       // We created 1 table, should be fine
492       hbck = doFsck(conf, false);
493       assertNoErrors(hbck);
494       assertEquals(0, hbck.getOverlapGroups(table).size());
495       assertEquals(ROWKEYS.length, countRows());
496     } finally {
497       cleanupTable(table);
498     }
499   }
500 
501   /**
502    * Test thread pooling in the case where there are more regions than threads
503    */
504   @Test (timeout=180000)
505   public void testHbckThreadpooling() throws Exception {
506     TableName table =
507         TableName.valueOf("tableDupeStartKey");
508     try {
509       // Create table with 4 regions
510       setupTable(table);
511 
512       // limit number of threads to 1.
513       Configuration newconf = new Configuration(conf);
514       newconf.setInt("hbasefsck.numthreads", 1);
515       assertNoErrors(doFsck(newconf, false));
516 
517       // We should pass without triggering a RejectedExecutionException
518     } finally {
519       cleanupTable(table);
520     }
521   }
522 
523   @Test (timeout=180000)
524   public void testHbckFixOrphanTable() throws Exception {
525     TableName table = TableName.valueOf("tableInfo");
526     FileSystem fs = null;
527     Path tableinfo = null;
528     try {
529       setupTable(table);
530 
531       Path hbaseTableDir = FSUtils.getTableDir(
532           FSUtils.getRootDir(conf), table);
533       fs = hbaseTableDir.getFileSystem(conf);
534       FileStatus status = FSTableDescriptors.getTableInfoPath(fs, hbaseTableDir);
535       tableinfo = status.getPath();
536       fs.rename(tableinfo, new Path("/.tableinfo"));
537 
538       //to report error if .tableinfo is missing.
539       HBaseFsck hbck = doFsck(conf, false);
540       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.NO_TABLEINFO_FILE });
541 
542       // fix OrphanTable with default .tableinfo (htd not yet cached on master)
543       hbck = doFsck(conf, true);
544       assertNoErrors(hbck);
545       status = null;
546       status = FSTableDescriptors.getTableInfoPath(fs, hbaseTableDir);
547       assertNotNull(status);
548 
549       HTableDescriptor htd = admin.getTableDescriptor(table);
550       htd.setValue("NOT_DEFAULT", "true");
551       admin.disableTable(table);
552       admin.modifyTable(table, htd);
553       admin.enableTable(table);
554       fs.delete(status.getPath(), true);
555 
556       // fix OrphanTable with cache
557       htd = admin.getTableDescriptor(table); // warms up cached htd on master
558       hbck = doFsck(conf, true);
559       assertNoErrors(hbck);
560       status = FSTableDescriptors.getTableInfoPath(fs, hbaseTableDir);
561       assertNotNull(status);
562       htd = admin.getTableDescriptor(table);
563       assertEquals(htd.getValue("NOT_DEFAULT"), "true");
564     } finally {
565       fs.rename(new Path("/.tableinfo"), tableinfo);
566       cleanupTable(table);
567     }
568   }
569 
570   /**
571    * This test makes sure that parallel instances of Hbck is disabled.
572    *
573    * @throws Exception
574    */
575   @Test (timeout=180000)
576   public void testParallelHbck() throws Exception {
577     final ExecutorService service;
578     final Future<HBaseFsck> hbck1,hbck2;
579 
580     class RunHbck implements Callable<HBaseFsck>{
581       boolean fail = true;
582       @Override
583       public HBaseFsck call(){
584         Configuration c = new Configuration(conf);
585         c.setInt("hbase.hbck.lockfile.attempts", 1);
586         try{
587           return doFsck(c, false);
588         } catch(Exception e){
589           if (e.getMessage().contains("Duplicate hbck")) {
590             fail = false;
591           }
592         }
593         // If we reach here, then an exception was caught
594         if (fail) fail();
595         return null;
596       }
597     }
598     service = Executors.newFixedThreadPool(2);
599     hbck1 = service.submit(new RunHbck());
600     hbck2 = service.submit(new RunHbck());
601     service.shutdown();
602     //wait for 15 seconds, for both hbck calls finish
603     service.awaitTermination(15, TimeUnit.SECONDS);
604     HBaseFsck h1 = hbck1.get();
605     HBaseFsck h2 = hbck2.get();
606     // Make sure only one of the calls was successful
607     assert(h1 == null || h2 == null);
608     if (h1 != null) {
609       assert(h1.getRetCode() >= 0);
610     }
611     if (h2 != null) {
612       assert(h2.getRetCode() >= 0);
613     }
614   }
615 
616   /**
617    * This test makes sure that with 5 retries both parallel instances
618    * of hbck will be completed successfully.
619    *
620    * @throws Exception
621    */
622   @Ignore
623   @Test (timeout=180000)
624   public void testParallelWithRetriesHbck() throws Exception {
625     final ExecutorService service;
626     final Future<HBaseFsck> hbck1,hbck2;
627 
628     class RunHbck implements Callable<HBaseFsck>{
629 
630       @Override
631       public HBaseFsck call() throws Exception {
632         return doFsck(conf, false);
633       }
634     }
635     service = Executors.newFixedThreadPool(2);
636     hbck1 = service.submit(new RunHbck());
637     hbck2 = service.submit(new RunHbck());
638     service.shutdown();
639     //wait for 15 seconds, for both hbck calls finish
640     service.awaitTermination(15, TimeUnit.SECONDS);
641     HBaseFsck h1 = hbck1.get();
642     HBaseFsck h2 = hbck2.get();
643     // Both should be successful
644     assertNotNull(h1);
645     assertNotNull(h2);
646     assert(h1.getRetCode() >= 0);
647     assert(h2.getRetCode() >= 0);
648 
649   }
650 
651   /**
652    * This create and fixes a bad table with regions that have a duplicate
653    * start key
654    */
655   @Test (timeout=180000)
656   public void testDupeStartKey() throws Exception {
657     TableName table =
658         TableName.valueOf("tableDupeStartKey");
659     try {
660       setupTable(table);
661       assertNoErrors(doFsck(conf, false));
662       assertEquals(ROWKEYS.length, countRows());
663 
664       // Now let's mess it up, by adding a region with a duplicate startkey
665       HRegionInfo hriDupe =
666           createRegion(tbl.getTableDescriptor(), Bytes.toBytes("A"), Bytes.toBytes("A2"));
667       TEST_UTIL.getHBaseCluster().getMaster().assignRegion(hriDupe);
668       TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager()
669           .waitForAssignment(hriDupe);
670       ServerName server = regionStates.getRegionServerOfRegion(hriDupe);
671       TEST_UTIL.assertRegionOnServer(hriDupe, server, REGION_ONLINE_TIMEOUT);
672 
673       HBaseFsck hbck = doFsck(conf, false);
674       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.DUPE_STARTKEYS,
675             ERROR_CODE.DUPE_STARTKEYS});
676       assertEquals(2, hbck.getOverlapGroups(table).size());
677       assertEquals(ROWKEYS.length, countRows()); // seems like the "bigger" region won.
678 
679       // fix the degenerate region.
680       doFsck(conf,true);
681 
682       // check that the degenerate region is gone and no data loss
683       HBaseFsck hbck2 = doFsck(conf,false);
684       assertNoErrors(hbck2);
685       assertEquals(0, hbck2.getOverlapGroups(table).size());
686       assertEquals(ROWKEYS.length, countRows());
687     } finally {
688       cleanupTable(table);
689     }
690   }
691 
692   /*
693    * This creates a table with region_replica > 1 and verifies hbck runs
694    * successfully
695    */
696   @Test (timeout=180000)
697   public void testHbckWithRegionReplica() throws Exception {
698     TableName table =
699         TableName.valueOf("testHbckWithRegionReplica");
700     try {
701       setupTableWithRegionReplica(table, 2);
702       TEST_UTIL.getHBaseAdmin().flush(table.getName());
703       assertNoErrors(doFsck(conf, false));
704     } finally {
705       cleanupTable(table);
706     }
707   }
708 
709   @Test
710   public void testHbckWithFewerReplica() throws Exception {
711     TableName table =
712         TableName.valueOf("testHbckWithFewerReplica");
713     try {
714       setupTableWithRegionReplica(table, 2);
715       TEST_UTIL.getHBaseAdmin().flush(table.getName());
716       assertNoErrors(doFsck(conf, false));
717       assertEquals(ROWKEYS.length, countRows());
718       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
719           Bytes.toBytes("C"), true, false, false, false, 1); // unassign one replica
720       // check that problem exists
721       HBaseFsck hbck = doFsck(conf, false);
722       assertErrors(hbck, new ERROR_CODE[]{ERROR_CODE.NOT_DEPLOYED});
723       // fix the problem
724       hbck = doFsck(conf, true);
725       // run hbck again to make sure we don't see any errors
726       hbck = doFsck(conf, false);
727       assertErrors(hbck, new ERROR_CODE[]{});
728     } finally {
729       cleanupTable(table);
730     }
731   }
732 
733   @Test
734   public void testHbckWithExcessReplica() throws Exception {
735     TableName table =
736         TableName.valueOf("testHbckWithExcessReplica");
737     try {
738       setupTableWithRegionReplica(table, 2);
739       TEST_UTIL.getHBaseAdmin().flush(table.getName());
740       assertNoErrors(doFsck(conf, false));
741       assertEquals(ROWKEYS.length, countRows());
742       // the next few lines inject a location in meta for a replica, and then
743       // asks the master to assign the replica (the meta needs to be injected
744       // for the master to treat the request for assignment as valid; the master
745       // checks the region is valid either from its memory or meta)
746       HTable meta = new HTable(conf, TableName.META_TABLE_NAME);
747       List<HRegionInfo> regions = TEST_UTIL.getHBaseAdmin().getTableRegions(table);
748       byte[] startKey = Bytes.toBytes("B");
749       byte[] endKey = Bytes.toBytes("C");
750       byte[] metaKey = null;
751       HRegionInfo newHri = null;
752       for (HRegionInfo h : regions) {
753         if (Bytes.compareTo(h.getStartKey(), startKey) == 0  &&
754             Bytes.compareTo(h.getEndKey(), endKey) == 0 &&
755             h.getReplicaId() == HRegionInfo.DEFAULT_REPLICA_ID) {
756           metaKey = h.getRegionName();
757           //create a hri with replicaId as 2 (since we already have replicas with replicaid 0 and 1)
758           newHri = RegionReplicaUtil.getRegionInfoForReplica(h, 2);
759           break;
760         }
761       }
762       Put put = new Put(metaKey);
763       ServerName sn = TEST_UTIL.getHBaseAdmin().getClusterStatus().getServers()
764           .toArray(new ServerName[0])[0];
765       //add a location with replicaId as 2 (since we already have replicas with replicaid 0 and 1)
766       MetaTableAccessor.addLocation(put, sn, sn.getStartcode(), 2);
767       meta.put(put);
768       meta.flushCommits();
769       // assign the new replica
770       HBaseFsckRepair.fixUnassigned((HBaseAdmin)TEST_UTIL.getHBaseAdmin(), newHri);
771       HBaseFsckRepair.waitUntilAssigned((HBaseAdmin)TEST_UTIL.getHBaseAdmin(), newHri);
772       // now reset the meta row to its original value
773       Delete delete = new Delete(metaKey);
774       delete.deleteColumns(HConstants.CATALOG_FAMILY, MetaTableAccessor.getServerColumn(2));
775       delete.deleteColumns(HConstants.CATALOG_FAMILY, MetaTableAccessor.getStartCodeColumn(2));
776       delete.deleteColumns(HConstants.CATALOG_FAMILY, MetaTableAccessor.getSeqNumColumn(2));
777       meta.delete(delete);
778       meta.flushCommits();
779       meta.close();
780       // check that problem exists
781       HBaseFsck hbck = doFsck(conf, false);
782       assertErrors(hbck, new ERROR_CODE[]{ERROR_CODE.NOT_IN_META});
783       // fix the problem
784       hbck = doFsck(conf, true);
785       // run hbck again to make sure we don't see any errors
786       hbck = doFsck(conf, false);
787       assertErrors(hbck, new ERROR_CODE[]{});
788     } finally {
789       cleanupTable(table);
790     }
791   }
792   /**
793    * Get region info from local cluster.
794    */
795   Map<ServerName, List<String>> getDeployedHRIs(final HBaseAdmin admin) throws IOException {
796     ClusterStatus status = admin.getClusterStatus();
797     Collection<ServerName> regionServers = status.getServers();
798     Map<ServerName, List<String>> mm =
799         new HashMap<ServerName, List<String>>();
800     for (ServerName hsi : regionServers) {
801       AdminProtos.AdminService.BlockingInterface server = ((HConnection) connection).getAdmin(hsi);
802 
803       // list all online regions from this region server
804       List<HRegionInfo> regions = ProtobufUtil.getOnlineRegions(server);
805       List<String> regionNames = new ArrayList<String>();
806       for (HRegionInfo hri : regions) {
807         regionNames.add(hri.getRegionNameAsString());
808       }
809       mm.put(hsi, regionNames);
810     }
811     return mm;
812   }
813 
814   /**
815    * Returns the HSI a region info is on.
816    */
817   ServerName findDeployedHSI(Map<ServerName, List<String>> mm, HRegionInfo hri) {
818     for (Map.Entry<ServerName,List <String>> e : mm.entrySet()) {
819       if (e.getValue().contains(hri.getRegionNameAsString())) {
820         return e.getKey();
821       }
822     }
823     return null;
824   }
825 
826   /**
827    * This create and fixes a bad table with regions that have a duplicate
828    * start key
829    */
830   @Test (timeout=180000)
831   public void testDupeRegion() throws Exception {
832     TableName table =
833         TableName.valueOf("tableDupeRegion");
834     try {
835       setupTable(table);
836       assertNoErrors(doFsck(conf, false));
837       assertEquals(ROWKEYS.length, countRows());
838 
839       // Now let's mess it up, by adding a region with a duplicate startkey
840       HRegionInfo hriDupe =
841           createRegion(tbl.getTableDescriptor(), Bytes.toBytes("A"), Bytes.toBytes("B"));
842 
843       TEST_UTIL.getHBaseCluster().getMaster().assignRegion(hriDupe);
844       TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager()
845           .waitForAssignment(hriDupe);
846       ServerName server = regionStates.getRegionServerOfRegion(hriDupe);
847       TEST_UTIL.assertRegionOnServer(hriDupe, server, REGION_ONLINE_TIMEOUT);
848 
849       // Yikes! The assignment manager can't tell between diff between two
850       // different regions with the same start/endkeys since it doesn't
851       // differentiate on ts/regionId!  We actually need to recheck
852       // deployments!
853       while (findDeployedHSI(getDeployedHRIs((HBaseAdmin) admin), hriDupe) == null) {
854         Thread.sleep(250);
855       }
856 
857       LOG.debug("Finished assignment of dupe region");
858 
859       // TODO why is dupe region different from dupe start keys?
860       HBaseFsck hbck = doFsck(conf, false);
861       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.DUPE_STARTKEYS,
862             ERROR_CODE.DUPE_STARTKEYS});
863       assertEquals(2, hbck.getOverlapGroups(table).size());
864       assertEquals(ROWKEYS.length, countRows()); // seems like the "bigger" region won.
865 
866       // fix the degenerate region.
867       doFsck(conf,true);
868 
869       // check that the degenerate region is gone and no data loss
870       HBaseFsck hbck2 = doFsck(conf,false);
871       assertNoErrors(hbck2);
872       assertEquals(0, hbck2.getOverlapGroups(table).size());
873       assertEquals(ROWKEYS.length, countRows());
874     } finally {
875       cleanupTable(table);
876     }
877   }
878 
879   /**
880    * This creates and fixes a bad table with regions that has startkey == endkey
881    */
882   @Test (timeout=180000)
883   public void testDegenerateRegions() throws Exception {
884     TableName table = TableName.valueOf("tableDegenerateRegions");
885     try {
886       setupTable(table);
887       assertNoErrors(doFsck(conf,false));
888       assertEquals(ROWKEYS.length, countRows());
889 
890       // Now let's mess it up, by adding a region with a duplicate startkey
891       HRegionInfo hriDupe =
892           createRegion(tbl.getTableDescriptor(), Bytes.toBytes("B"), Bytes.toBytes("B"));
893       TEST_UTIL.getHBaseCluster().getMaster().assignRegion(hriDupe);
894       TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager()
895           .waitForAssignment(hriDupe);
896       ServerName server = regionStates.getRegionServerOfRegion(hriDupe);
897       TEST_UTIL.assertRegionOnServer(hriDupe, server, REGION_ONLINE_TIMEOUT);
898 
899       HBaseFsck hbck = doFsck(conf,false);
900       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.DEGENERATE_REGION, ERROR_CODE.DUPE_STARTKEYS,
901           ERROR_CODE.DUPE_STARTKEYS });
902       assertEquals(2, hbck.getOverlapGroups(table).size());
903       assertEquals(ROWKEYS.length, countRows());
904 
905       // fix the degenerate region.
906       doFsck(conf,true);
907 
908       // check that the degenerate region is gone and no data loss
909       HBaseFsck hbck2 = doFsck(conf,false);
910       assertNoErrors(hbck2);
911       assertEquals(0, hbck2.getOverlapGroups(table).size());
912       assertEquals(ROWKEYS.length, countRows());
913     } finally {
914       cleanupTable(table);
915     }
916   }
917 
918   /**
919    * This creates and fixes a bad table where a region is completely contained
920    * by another region.
921    */
922   @Test (timeout=180000)
923   public void testContainedRegionOverlap() throws Exception {
924     TableName table =
925         TableName.valueOf("tableContainedRegionOverlap");
926     try {
927       setupTable(table);
928       assertEquals(ROWKEYS.length, countRows());
929 
930       // Mess it up by creating an overlap in the metadata
931       HRegionInfo hriOverlap =
932           createRegion(tbl.getTableDescriptor(), Bytes.toBytes("A2"), Bytes.toBytes("B"));
933       TEST_UTIL.getHBaseCluster().getMaster().assignRegion(hriOverlap);
934       TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager()
935           .waitForAssignment(hriOverlap);
936       ServerName server = regionStates.getRegionServerOfRegion(hriOverlap);
937       TEST_UTIL.assertRegionOnServer(hriOverlap, server, REGION_ONLINE_TIMEOUT);
938 
939       HBaseFsck hbck = doFsck(conf, false);
940       assertErrors(hbck, new ERROR_CODE[] {
941           ERROR_CODE.OVERLAP_IN_REGION_CHAIN });
942       assertEquals(2, hbck.getOverlapGroups(table).size());
943       assertEquals(ROWKEYS.length, countRows());
944 
945       // fix the problem.
946       doFsck(conf, true);
947 
948       // verify that overlaps are fixed
949       HBaseFsck hbck2 = doFsck(conf,false);
950       assertNoErrors(hbck2);
951       assertEquals(0, hbck2.getOverlapGroups(table).size());
952       assertEquals(ROWKEYS.length, countRows());
953     } finally {
954       cleanupTable(table);
955     }
956   }
957 
958   /**
959    * This creates and fixes a bad table where an overlap group of
960    * 3 regions. Set HBaseFsck.maxMerge to 2 to trigger sideline overlapped
961    * region. Mess around the meta data so that closeRegion/offlineRegion
962    * throws exceptions.
963    */
964   @Test (timeout=180000)
965   public void testSidelineOverlapRegion() throws Exception {
966     TableName table =
967         TableName.valueOf("testSidelineOverlapRegion");
968     try {
969       setupTable(table);
970       assertEquals(ROWKEYS.length, countRows());
971 
972       // Mess it up by creating an overlap
973       MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
974       HMaster master = cluster.getMaster();
975       HRegionInfo hriOverlap1 =
976           createRegion(tbl.getTableDescriptor(), Bytes.toBytes("A"), Bytes.toBytes("AB"));
977       master.assignRegion(hriOverlap1);
978       master.getAssignmentManager().waitForAssignment(hriOverlap1);
979       HRegionInfo hriOverlap2 =
980           createRegion(tbl.getTableDescriptor(), Bytes.toBytes("AB"), Bytes.toBytes("B"));
981       master.assignRegion(hriOverlap2);
982       master.getAssignmentManager().waitForAssignment(hriOverlap2);
983 
984       HBaseFsck hbck = doFsck(conf, false);
985       assertErrors(hbck, new ERROR_CODE[] {ERROR_CODE.DUPE_STARTKEYS,
986         ERROR_CODE.DUPE_STARTKEYS, ERROR_CODE.OVERLAP_IN_REGION_CHAIN});
987       assertEquals(3, hbck.getOverlapGroups(table).size());
988       assertEquals(ROWKEYS.length, countRows());
989 
990       // mess around the overlapped regions, to trigger NotServingRegionException
991       Multimap<byte[], HbckInfo> overlapGroups = hbck.getOverlapGroups(table);
992       ServerName serverName = null;
993       byte[] regionName = null;
994       for (HbckInfo hbi: overlapGroups.values()) {
995         if ("A".equals(Bytes.toString(hbi.getStartKey()))
996             && "B".equals(Bytes.toString(hbi.getEndKey()))) {
997           regionName = hbi.getRegionName();
998 
999           // get an RS not serving the region to force bad assignment info in to META.
1000           int k = cluster.getServerWith(regionName);
1001           for (int i = 0; i < 3; i++) {
1002             if (i != k) {
1003               HRegionServer rs = cluster.getRegionServer(i);
1004               serverName = rs.getServerName();
1005               break;
1006             }
1007           }
1008 
1009           HBaseFsckRepair.closeRegionSilentlyAndWait((HConnection) connection,
1010               cluster.getRegionServer(k).getServerName(), hbi.getHdfsHRI());
1011           admin.offline(regionName);
1012           break;
1013         }
1014       }
1015 
1016       assertNotNull(regionName);
1017       assertNotNull(serverName);
1018       try (Table meta = connection.getTable(TableName.META_TABLE_NAME, tableExecutorService)) {
1019         Put put = new Put(regionName);
1020         put.add(HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER,
1021             Bytes.toBytes(serverName.getHostAndPort()));
1022         meta.put(put);
1023       }
1024 
1025       // fix the problem.
1026       HBaseFsck fsck = new HBaseFsck(conf, hbfsckExecutorService);
1027       fsck.connect();
1028       fsck.setDisplayFullReport(); // i.e. -details
1029       fsck.setTimeLag(0);
1030       fsck.setFixAssignments(true);
1031       fsck.setFixMeta(true);
1032       fsck.setFixHdfsHoles(true);
1033       fsck.setFixHdfsOverlaps(true);
1034       fsck.setFixHdfsOrphans(true);
1035       fsck.setFixVersionFile(true);
1036       fsck.setSidelineBigOverlaps(true);
1037       fsck.setMaxMerge(2);
1038       fsck.onlineHbck();
1039       fsck.close();
1040 
1041       // verify that overlaps are fixed, and there are less rows
1042       // since one region is sidelined.
1043       HBaseFsck hbck2 = doFsck(conf,false);
1044       assertNoErrors(hbck2);
1045       assertEquals(0, hbck2.getOverlapGroups(table).size());
1046       assertTrue(ROWKEYS.length > countRows());
1047     } finally {
1048       cleanupTable(table);
1049     }
1050   }
1051 
1052   /**
1053    * This creates and fixes a bad table where a region is completely contained
1054    * by another region, and there is a hole (sort of like a bad split)
1055    */
1056   @Test (timeout=180000)
1057   public void testOverlapAndOrphan() throws Exception {
1058     TableName table =
1059         TableName.valueOf("tableOverlapAndOrphan");
1060     try {
1061       setupTable(table);
1062       assertEquals(ROWKEYS.length, countRows());
1063 
1064       // Mess it up by creating an overlap in the metadata
1065       admin.disableTable(table);
1066       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("A"),
1067           Bytes.toBytes("B"), true, true, false, true, HRegionInfo.DEFAULT_REPLICA_ID);
1068       TEST_UTIL.getHBaseAdmin().enableTable(table);
1069 
1070       HRegionInfo hriOverlap =
1071           createRegion(tbl.getTableDescriptor(), Bytes.toBytes("A2"), Bytes.toBytes("B"));
1072       TEST_UTIL.getHBaseCluster().getMaster().assignRegion(hriOverlap);
1073       TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager()
1074           .waitForAssignment(hriOverlap);
1075       ServerName server = regionStates.getRegionServerOfRegion(hriOverlap);
1076       TEST_UTIL.assertRegionOnServer(hriOverlap, server, REGION_ONLINE_TIMEOUT);
1077 
1078       HBaseFsck hbck = doFsck(conf, false);
1079       assertErrors(hbck, new ERROR_CODE[] {
1080           ERROR_CODE.ORPHAN_HDFS_REGION, ERROR_CODE.NOT_IN_META_OR_DEPLOYED,
1081           ERROR_CODE.HOLE_IN_REGION_CHAIN});
1082 
1083       // fix the problem.
1084       doFsck(conf, true);
1085 
1086       // verify that overlaps are fixed
1087       HBaseFsck hbck2 = doFsck(conf,false);
1088       assertNoErrors(hbck2);
1089       assertEquals(0, hbck2.getOverlapGroups(table).size());
1090       assertEquals(ROWKEYS.length, countRows());
1091     } finally {
1092       cleanupTable(table);
1093     }
1094   }
1095 
1096   /**
1097    * This creates and fixes a bad table where a region overlaps two regions --
1098    * a start key contained in another region and its end key is contained in
1099    * yet another region.
1100    */
1101   @Test (timeout=180000)
1102   public void testCoveredStartKey() throws Exception {
1103     TableName table =
1104         TableName.valueOf("tableCoveredStartKey");
1105     try {
1106       setupTable(table);
1107       assertEquals(ROWKEYS.length, countRows());
1108 
1109       // Mess it up by creating an overlap in the metadata
1110       HRegionInfo hriOverlap =
1111           createRegion(tbl.getTableDescriptor(), Bytes.toBytes("A2"), Bytes.toBytes("B2"));
1112       TEST_UTIL.getHBaseCluster().getMaster().assignRegion(hriOverlap);
1113       TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager()
1114           .waitForAssignment(hriOverlap);
1115       ServerName server = regionStates.getRegionServerOfRegion(hriOverlap);
1116       TEST_UTIL.assertRegionOnServer(hriOverlap, server, REGION_ONLINE_TIMEOUT);
1117 
1118       HBaseFsck hbck = doFsck(conf, false);
1119       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.OVERLAP_IN_REGION_CHAIN,
1120           ERROR_CODE.OVERLAP_IN_REGION_CHAIN });
1121       assertEquals(3, hbck.getOverlapGroups(table).size());
1122       assertEquals(ROWKEYS.length, countRows());
1123 
1124       // fix the problem.
1125       doFsck(conf, true);
1126 
1127       // verify that overlaps are fixed
1128       HBaseFsck hbck2 = doFsck(conf, false);
1129       assertErrors(hbck2, new ERROR_CODE[0]);
1130       assertEquals(0, hbck2.getOverlapGroups(table).size());
1131       assertEquals(ROWKEYS.length, countRows());
1132     } finally {
1133       cleanupTable(table);
1134     }
1135   }
1136 
1137   /**
1138    * This creates and fixes a bad table with a missing region -- hole in meta
1139    * and data missing in the fs.
1140    */
1141   @Test (timeout=180000)
1142   public void testRegionHole() throws Exception {
1143     TableName table =
1144         TableName.valueOf("tableRegionHole");
1145     try {
1146       setupTable(table);
1147       assertEquals(ROWKEYS.length, countRows());
1148 
1149       // Mess it up by leaving a hole in the assignment, meta, and hdfs data
1150       admin.disableTable(table);
1151       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1152           Bytes.toBytes("C"), true, true, true);
1153       admin.enableTable(table);
1154 
1155       HBaseFsck hbck = doFsck(conf, false);
1156       assertErrors(hbck, new ERROR_CODE[] {
1157           ERROR_CODE.HOLE_IN_REGION_CHAIN});
1158       // holes are separate from overlap groups
1159       assertEquals(0, hbck.getOverlapGroups(table).size());
1160 
1161       // fix hole
1162       doFsck(conf, true);
1163 
1164       // check that hole fixed
1165       assertNoErrors(doFsck(conf,false));
1166       assertEquals(ROWKEYS.length - 2 , countRows()); // lost a region so lost a row
1167     } finally {
1168       cleanupTable(table);
1169     }
1170   }
1171 
1172   /**
1173    * This creates and fixes a bad table with a missing region -- hole in meta
1174    * and data present but .regioinfino missing (an orphan hdfs region)in the fs.
1175    */
1176   @Test (timeout=180000)
1177   public void testHDFSRegioninfoMissing() throws Exception {
1178     TableName table = TableName.valueOf("tableHDFSRegioninfoMissing");
1179     try {
1180       setupTable(table);
1181       assertEquals(ROWKEYS.length, countRows());
1182 
1183       // Mess it up by leaving a hole in the meta data
1184       admin.disableTable(table);
1185       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1186           Bytes.toBytes("C"), true, true, false, true, HRegionInfo.DEFAULT_REPLICA_ID);
1187       TEST_UTIL.getHBaseAdmin().enableTable(table);
1188 
1189       HBaseFsck hbck = doFsck(conf, false);
1190       assertErrors(hbck, new ERROR_CODE[] {
1191           ERROR_CODE.ORPHAN_HDFS_REGION,
1192           ERROR_CODE.NOT_IN_META_OR_DEPLOYED,
1193           ERROR_CODE.HOLE_IN_REGION_CHAIN});
1194       // holes are separate from overlap groups
1195       assertEquals(0, hbck.getOverlapGroups(table).size());
1196 
1197       // fix hole
1198       doFsck(conf, true);
1199 
1200       // check that hole fixed
1201       assertNoErrors(doFsck(conf, false));
1202       assertEquals(ROWKEYS.length, countRows());
1203     } finally {
1204       cleanupTable(table);
1205     }
1206   }
1207 
1208   /**
1209    * This creates and fixes a bad table with a region that is missing meta and
1210    * not assigned to a region server.
1211    */
1212   @Test (timeout=180000)
1213   public void testNotInMetaOrDeployedHole() throws Exception {
1214     TableName table =
1215         TableName.valueOf("tableNotInMetaOrDeployedHole");
1216     try {
1217       setupTable(table);
1218       assertEquals(ROWKEYS.length, countRows());
1219 
1220       // Mess it up by leaving a hole in the meta data
1221       admin.disableTable(table);
1222       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1223           Bytes.toBytes("C"), true, true, false); // don't rm from fs
1224       admin.enableTable(table);
1225 
1226       HBaseFsck hbck = doFsck(conf, false);
1227       assertErrors(hbck, new ERROR_CODE[] {
1228           ERROR_CODE.NOT_IN_META_OR_DEPLOYED, ERROR_CODE.HOLE_IN_REGION_CHAIN});
1229       // holes are separate from overlap groups
1230       assertEquals(0, hbck.getOverlapGroups(table).size());
1231 
1232       // fix hole
1233       assertErrors(doFsck(conf, true) , new ERROR_CODE[] {
1234           ERROR_CODE.NOT_IN_META_OR_DEPLOYED, ERROR_CODE.HOLE_IN_REGION_CHAIN});
1235 
1236       // check that hole fixed
1237       assertNoErrors(doFsck(conf,false));
1238       assertEquals(ROWKEYS.length, countRows());
1239     } finally {
1240       cleanupTable(table);
1241     }
1242   }
1243 
1244   /**
1245    * This creates fixes a bad table with a hole in meta.
1246    */
1247   @Test (timeout=180000)
1248   public void testNotInMetaHole() throws Exception {
1249     TableName table =
1250         TableName.valueOf("tableNotInMetaHole");
1251     try {
1252       setupTable(table);
1253       assertEquals(ROWKEYS.length, countRows());
1254 
1255       // Mess it up by leaving a hole in the meta data
1256       admin.disableTable(table);
1257       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1258           Bytes.toBytes("C"), false, true, false); // don't rm from fs
1259       admin.enableTable(table);
1260 
1261       HBaseFsck hbck = doFsck(conf, false);
1262       assertErrors(hbck, new ERROR_CODE[] {
1263           ERROR_CODE.NOT_IN_META_OR_DEPLOYED, ERROR_CODE.HOLE_IN_REGION_CHAIN});
1264       // holes are separate from overlap groups
1265       assertEquals(0, hbck.getOverlapGroups(table).size());
1266 
1267       // fix hole
1268       assertErrors(doFsck(conf, true) , new ERROR_CODE[] {
1269           ERROR_CODE.NOT_IN_META_OR_DEPLOYED, ERROR_CODE.HOLE_IN_REGION_CHAIN});
1270 
1271       // check that hole fixed
1272       assertNoErrors(doFsck(conf,false));
1273       assertEquals(ROWKEYS.length, countRows());
1274     } finally {
1275       cleanupTable(table);
1276     }
1277   }
1278 
1279   /**
1280    * This creates and fixes a bad table with a region that is in meta but has
1281    * no deployment or data hdfs
1282    */
1283   @Test (timeout=180000)
1284   public void testNotInHdfs() throws Exception {
1285     TableName table =
1286         TableName.valueOf("tableNotInHdfs");
1287     try {
1288       setupTable(table);
1289       assertEquals(ROWKEYS.length, countRows());
1290 
1291       // make sure data in regions, if in wal only there is no data loss
1292       admin.flush(table);
1293 
1294       // Mess it up by leaving a hole in the hdfs data
1295       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1296           Bytes.toBytes("C"), false, false, true); // don't rm meta
1297 
1298       HBaseFsck hbck = doFsck(conf, false);
1299       assertErrors(hbck, new ERROR_CODE[] {ERROR_CODE.NOT_IN_HDFS});
1300       // holes are separate from overlap groups
1301       assertEquals(0, hbck.getOverlapGroups(table).size());
1302 
1303       // fix hole
1304       doFsck(conf, true);
1305 
1306       // check that hole fixed
1307       assertNoErrors(doFsck(conf,false));
1308       assertEquals(ROWKEYS.length - 2, countRows());
1309     } finally {
1310       cleanupTable(table);
1311     }
1312   }
1313 
1314   /**
1315    * This creates and fixes a bad table with a region that is in meta but has
1316    * no deployment or data hdfs. The table has region_replication set to 2.
1317    */
1318   @Test (timeout=180000)
1319   public void testNotInHdfsWithReplicas() throws Exception {
1320     TableName table =
1321         TableName.valueOf("tableNotInHdfs");
1322     HBaseAdmin admin = new HBaseAdmin(conf);
1323     try {
1324       HRegionInfo[] oldHris = new HRegionInfo[2];
1325       setupTableWithRegionReplica(table, 2);
1326       assertEquals(ROWKEYS.length, countRows());
1327       NavigableMap<HRegionInfo, ServerName> map = MetaScanner.allTableRegions(TEST_UTIL.getConnection(),
1328           tbl.getName());
1329       int i = 0;
1330       // store the HRIs of the regions we will mess up
1331       for (Map.Entry<HRegionInfo, ServerName> m : map.entrySet()) {
1332         if (m.getKey().getStartKey().length > 0 &&
1333             m.getKey().getStartKey()[0] == Bytes.toBytes("B")[0]) {
1334           LOG.debug("Initially server hosting " + m.getKey() + " is " + m.getValue());
1335           oldHris[i++] = m.getKey();
1336         }
1337       }
1338       // make sure data in regions
1339       TEST_UTIL.getHBaseAdmin().flush(table.getName());
1340 
1341       // Mess it up by leaving a hole in the hdfs data
1342       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1343           Bytes.toBytes("C"), false, false, true); // don't rm meta
1344 
1345       HBaseFsck hbck = doFsck(conf, false);
1346       assertErrors(hbck, new ERROR_CODE[] {ERROR_CODE.NOT_IN_HDFS});
1347 
1348       // fix hole
1349       doFsck(conf, true);
1350 
1351       // check that hole fixed
1352       assertNoErrors(doFsck(conf,false));
1353       assertEquals(ROWKEYS.length - 2, countRows());
1354 
1355       // the following code checks whether the old primary/secondary has
1356       // been unassigned and the new primary/secondary has been assigned
1357       i = 0;
1358       HRegionInfo[] newHris = new HRegionInfo[2];
1359       // get all table's regions from meta
1360       map = MetaScanner.allTableRegions(TEST_UTIL.getConnection(), tbl.getName());
1361       // get the HRIs of the new regions (hbck created new regions for fixing the hdfs mess-up)
1362       for (Map.Entry<HRegionInfo, ServerName> m : map.entrySet()) {
1363         if (m.getKey().getStartKey().length > 0 &&
1364             m.getKey().getStartKey()[0] == Bytes.toBytes("B")[0]) {
1365           newHris[i++] = m.getKey();
1366         }
1367       }
1368       // get all the online regions in the regionservers
1369       Collection<ServerName> servers = admin.getClusterStatus().getServers();
1370       Set<HRegionInfo> onlineRegions = new HashSet<HRegionInfo>();
1371       for (ServerName s : servers) {
1372         List<HRegionInfo> list = admin.getOnlineRegions(s);
1373         onlineRegions.addAll(list);
1374       }
1375       // the new HRIs must be a subset of the online regions
1376       assertTrue(onlineRegions.containsAll(Arrays.asList(newHris)));
1377       // the old HRIs must not be part of the set (removeAll would return false if
1378       // the set didn't change)
1379       assertFalse(onlineRegions.removeAll(Arrays.asList(oldHris)));
1380     } finally {
1381       cleanupTable(table);
1382       admin.close();
1383     }
1384   }
1385 
1386 
1387   /**
1388    * This creates entries in hbase:meta with no hdfs data.  This should cleanly
1389    * remove the table.
1390    */
1391   @Test (timeout=180000)
1392   public void testNoHdfsTable() throws Exception {
1393     TableName table = TableName.valueOf("NoHdfsTable");
1394     setupTable(table);
1395     assertEquals(ROWKEYS.length, countRows());
1396 
1397     // make sure data in regions, if in wal only there is no data loss
1398     admin.flush(table);
1399 
1400     // Mess it up by deleting hdfs dirs
1401     deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes(""),
1402         Bytes.toBytes("A"), false, false, true); // don't rm meta
1403     deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("A"),
1404         Bytes.toBytes("B"), false, false, true); // don't rm meta
1405     deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1406         Bytes.toBytes("C"), false, false, true); // don't rm meta
1407     deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("C"),
1408         Bytes.toBytes(""), false, false, true); // don't rm meta
1409 
1410     // also remove the table directory in hdfs
1411     deleteTableDir(table);
1412 
1413     HBaseFsck hbck = doFsck(conf, false);
1414     assertErrors(hbck, new ERROR_CODE[] {ERROR_CODE.NOT_IN_HDFS,
1415         ERROR_CODE.NOT_IN_HDFS, ERROR_CODE.NOT_IN_HDFS,
1416         ERROR_CODE.NOT_IN_HDFS,});
1417     // holes are separate from overlap groups
1418     assertEquals(0, hbck.getOverlapGroups(table).size());
1419 
1420     // fix hole
1421     doFsck(conf, true); // detect dangling regions and remove those
1422 
1423     // check that hole fixed
1424     assertNoErrors(doFsck(conf,false));
1425     assertFalse("Table " + table + " should have been deleted", admin.tableExists(table));
1426   }
1427 
1428   public void deleteTableDir(TableName table) throws IOException {
1429     Path rootDir = FSUtils.getRootDir(conf);
1430     FileSystem fs = rootDir.getFileSystem(conf);
1431     Path p = FSUtils.getTableDir(rootDir, table);
1432     HBaseFsck.debugLsr(conf, p);
1433     boolean success = fs.delete(p, true);
1434     LOG.info("Deleted " + p + " sucessfully? " + success);
1435   }
1436 
1437   /**
1438    * when the hbase.version file missing, It is fix the fault.
1439    */
1440   @Test (timeout=180000)
1441   public void testNoVersionFile() throws Exception {
1442     // delete the hbase.version file
1443     Path rootDir = FSUtils.getRootDir(conf);
1444     FileSystem fs = rootDir.getFileSystem(conf);
1445     Path versionFile = new Path(rootDir, HConstants.VERSION_FILE_NAME);
1446     fs.delete(versionFile, true);
1447 
1448     // test
1449     HBaseFsck hbck = doFsck(conf, false);
1450     assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.NO_VERSION_FILE });
1451     // fix hbase.version missing
1452     doFsck(conf, true);
1453 
1454     // no version file fixed
1455     assertNoErrors(doFsck(conf, false));
1456   }
1457 
1458   /**
1459    * The region is not deployed when the table is disabled.
1460    */
1461   @Test (timeout=180000)
1462   public void testRegionShouldNotBeDeployed() throws Exception {
1463     TableName table =
1464         TableName.valueOf("tableRegionShouldNotBeDeployed");
1465     try {
1466       LOG.info("Starting testRegionShouldNotBeDeployed.");
1467       MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
1468       assertTrue(cluster.waitForActiveAndReadyMaster());
1469 
1470 
1471       byte[][] SPLIT_KEYS = new byte[][] { new byte[0], Bytes.toBytes("aaa"),
1472           Bytes.toBytes("bbb"), Bytes.toBytes("ccc"), Bytes.toBytes("ddd") };
1473       HTableDescriptor htdDisabled = new HTableDescriptor(table);
1474       htdDisabled.addFamily(new HColumnDescriptor(FAM));
1475 
1476       // Write the .tableinfo
1477       FSTableDescriptors fstd = new FSTableDescriptors(conf);
1478       fstd.createTableDescriptor(htdDisabled);
1479       List<HRegionInfo> disabledRegions =
1480           TEST_UTIL.createMultiRegionsInMeta(conf, htdDisabled, SPLIT_KEYS);
1481 
1482       // Let's just assign everything to first RS
1483       HRegionServer hrs = cluster.getRegionServer(0);
1484 
1485       // Create region files.
1486       admin.disableTable(table);
1487       admin.enableTable(table);
1488 
1489       // Disable the table and close its regions
1490       admin.disableTable(table);
1491       HRegionInfo region = disabledRegions.remove(0);
1492       byte[] regionName = region.getRegionName();
1493 
1494       // The region should not be assigned currently
1495       assertTrue(cluster.getServerWith(regionName) == -1);
1496 
1497       // Directly open a region on a region server.
1498       // If going through AM/ZK, the region won't be open.
1499       // Even it is opened, AM will close it which causes
1500       // flakiness of this test.
1501       HRegion r = HRegion.openHRegion(
1502         region, htdDisabled, hrs.getWAL(region), conf);
1503       hrs.addToOnlineRegions(r);
1504 
1505       HBaseFsck hbck = doFsck(conf, false);
1506       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.SHOULD_NOT_BE_DEPLOYED });
1507 
1508       // fix this fault
1509       doFsck(conf, true);
1510 
1511       // check result
1512       assertNoErrors(doFsck(conf, false));
1513     } finally {
1514       admin.enableTable(table);
1515       cleanupTable(table);
1516     }
1517   }
1518 
1519   /**
1520    * This creates two tables and mess both of them and fix them one by one
1521    */
1522   @Test (timeout=180000)
1523   public void testFixByTable() throws Exception {
1524     TableName table1 =
1525         TableName.valueOf("testFixByTable1");
1526     TableName table2 =
1527         TableName.valueOf("testFixByTable2");
1528     try {
1529       setupTable(table1);
1530       // make sure data in regions, if in wal only there is no data loss
1531       admin.flush(table1);
1532       // Mess them up by leaving a hole in the hdfs data
1533       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1534         Bytes.toBytes("C"), false, false, true); // don't rm meta
1535 
1536       setupTable(table2);
1537       // make sure data in regions, if in wal only there is no data loss
1538       admin.flush(table2);
1539       // Mess them up by leaving a hole in the hdfs data
1540       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1541         Bytes.toBytes("C"), false, false, true); // don't rm meta
1542 
1543       HBaseFsck hbck = doFsck(conf, false);
1544       assertErrors(hbck, new ERROR_CODE[] {
1545         ERROR_CODE.NOT_IN_HDFS, ERROR_CODE.NOT_IN_HDFS});
1546 
1547       // fix hole in table 1
1548       doFsck(conf, true, table1);
1549       // check that hole in table 1 fixed
1550       assertNoErrors(doFsck(conf, false, table1));
1551       // check that hole in table 2 still there
1552       assertErrors(doFsck(conf, false, table2),
1553         new ERROR_CODE[] {ERROR_CODE.NOT_IN_HDFS});
1554 
1555       // fix hole in table 2
1556       doFsck(conf, true, table2);
1557       // check that hole in both tables fixed
1558       assertNoErrors(doFsck(conf, false));
1559       assertEquals(ROWKEYS.length - 2, countRows());
1560     } finally {
1561       cleanupTable(table1);
1562       cleanupTable(table2);
1563     }
1564   }
1565   /**
1566    * A split parent in meta, in hdfs, and not deployed
1567    */
1568   @Test (timeout=180000)
1569   public void testLingeringSplitParent() throws Exception {
1570     TableName table =
1571         TableName.valueOf("testLingeringSplitParent");
1572     Table meta = null;
1573     try {
1574       setupTable(table);
1575       assertEquals(ROWKEYS.length, countRows());
1576 
1577       // make sure data in regions, if in wal only there is no data loss
1578       admin.flush(table);
1579       HRegionLocation location = tbl.getRegionLocation("B");
1580 
1581       // Delete one region from meta, but not hdfs, unassign it.
1582       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("B"),
1583         Bytes.toBytes("C"), true, true, false);
1584 
1585       // Create a new meta entry to fake it as a split parent.
1586       meta = connection.getTable(TableName.META_TABLE_NAME, tableExecutorService);
1587       HRegionInfo hri = location.getRegionInfo();
1588 
1589       HRegionInfo a = new HRegionInfo(tbl.getName(),
1590         Bytes.toBytes("B"), Bytes.toBytes("BM"));
1591       HRegionInfo b = new HRegionInfo(tbl.getName(),
1592         Bytes.toBytes("BM"), Bytes.toBytes("C"));
1593 
1594       hri.setOffline(true);
1595       hri.setSplit(true);
1596 
1597       MetaTableAccessor.addRegionToMeta(meta, hri, a, b);
1598       meta.close();
1599       admin.flush(TableName.META_TABLE_NAME);
1600 
1601       HBaseFsck hbck = doFsck(conf, false);
1602       assertErrors(hbck, new ERROR_CODE[] {
1603         ERROR_CODE.LINGERING_SPLIT_PARENT, ERROR_CODE.HOLE_IN_REGION_CHAIN});
1604 
1605       // regular repair cannot fix lingering split parent
1606       hbck = doFsck(conf, true);
1607       assertErrors(hbck, new ERROR_CODE[] {
1608         ERROR_CODE.LINGERING_SPLIT_PARENT, ERROR_CODE.HOLE_IN_REGION_CHAIN });
1609       assertFalse(hbck.shouldRerun());
1610       hbck = doFsck(conf, false);
1611       assertErrors(hbck, new ERROR_CODE[] {
1612         ERROR_CODE.LINGERING_SPLIT_PARENT, ERROR_CODE.HOLE_IN_REGION_CHAIN});
1613 
1614       // fix lingering split parent
1615       hbck = new HBaseFsck(conf, hbfsckExecutorService);
1616       hbck.connect();
1617       hbck.setDisplayFullReport(); // i.e. -details
1618       hbck.setTimeLag(0);
1619       hbck.setFixSplitParents(true);
1620       hbck.onlineHbck();
1621       assertTrue(hbck.shouldRerun());
1622       hbck.close();
1623 
1624       Get get = new Get(hri.getRegionName());
1625       Result result = meta.get(get);
1626       assertTrue(result.getColumnCells(HConstants.CATALOG_FAMILY,
1627         HConstants.SPLITA_QUALIFIER).isEmpty());
1628       assertTrue(result.getColumnCells(HConstants.CATALOG_FAMILY,
1629         HConstants.SPLITB_QUALIFIER).isEmpty());
1630       admin.flush(TableName.META_TABLE_NAME);
1631 
1632       // fix other issues
1633       doFsck(conf, true);
1634 
1635       // check that all are fixed
1636       assertNoErrors(doFsck(conf, false));
1637       assertEquals(ROWKEYS.length, countRows());
1638     } finally {
1639       cleanupTable(table);
1640       IOUtils.closeQuietly(meta);
1641     }
1642   }
1643 
1644   /**
1645    * Tests that LINGERING_SPLIT_PARENT is not erroneously reported for
1646    * valid cases where the daughters are there.
1647    */
1648   @Test (timeout=180000)
1649   public void testValidLingeringSplitParent() throws Exception {
1650     TableName table =
1651         TableName.valueOf("testLingeringSplitParent");
1652     Table meta = null;
1653     try {
1654       setupTable(table);
1655       assertEquals(ROWKEYS.length, countRows());
1656 
1657       // make sure data in regions, if in wal only there is no data loss
1658       admin.flush(table);
1659       HRegionLocation location = tbl.getRegionLocation(Bytes.toBytes("B"));
1660 
1661       meta = connection.getTable(TableName.META_TABLE_NAME, tableExecutorService);
1662       HRegionInfo hri = location.getRegionInfo();
1663 
1664       // do a regular split
1665       byte[] regionName = location.getRegionInfo().getRegionName();
1666       admin.splitRegion(location.getRegionInfo().getRegionName(), Bytes.toBytes("BM"));
1667       TestEndToEndSplitTransaction.blockUntilRegionSplit(conf, 60000, regionName, true);
1668 
1669       // TODO: fixHdfsHoles does not work against splits, since the parent dir lingers on
1670       // for some time until children references are deleted. HBCK erroneously sees this as
1671       // overlapping regions
1672       HBaseFsck hbck = doFsck(
1673         conf, true, true, false, false, false, true, true, true, false, false, false, null);
1674       assertErrors(hbck, new ERROR_CODE[] {}); //no LINGERING_SPLIT_PARENT reported
1675 
1676       // assert that the split hbase:meta entry is still there.
1677       Get get = new Get(hri.getRegionName());
1678       Result result = meta.get(get);
1679       assertNotNull(result);
1680       assertNotNull(MetaTableAccessor.getHRegionInfo(result));
1681 
1682       assertEquals(ROWKEYS.length, countRows());
1683 
1684       // assert that we still have the split regions
1685       assertEquals(tbl.getStartKeys().length, SPLITS.length + 1 + 1); //SPLITS + 1 is # regions pre-split.
1686       assertNoErrors(doFsck(conf, false));
1687     } finally {
1688       cleanupTable(table);
1689       IOUtils.closeQuietly(meta);
1690     }
1691   }
1692 
1693   /**
1694    * Split crashed after write to hbase:meta finished for the parent region, but
1695    * failed to write daughters (pre HBASE-7721 codebase)
1696    */
1697   @Test(timeout=75000)
1698   public void testSplitDaughtersNotInMeta() throws Exception {
1699     TableName table = TableName.valueOf("testSplitdaughtersNotInMeta");
1700     Table meta = connection.getTable(TableName.META_TABLE_NAME, tableExecutorService);
1701     try {
1702       setupTable(table);
1703       assertEquals(ROWKEYS.length, countRows());
1704 
1705       // make sure data in regions, if in wal only there is no data loss
1706       admin.flush(table);
1707       HRegionLocation location = tbl.getRegionLocation(Bytes.toBytes("B"));
1708 
1709       HRegionInfo hri = location.getRegionInfo();
1710 
1711       // do a regular split
1712       byte[] regionName = location.getRegionInfo().getRegionName();
1713       admin.splitRegion(location.getRegionInfo().getRegionName(), Bytes.toBytes("BM"));
1714       TestEndToEndSplitTransaction.blockUntilRegionSplit(conf, 60000, regionName, true);
1715 
1716       PairOfSameType<HRegionInfo> daughters =
1717           MetaTableAccessor.getDaughterRegions(meta.get(new Get(regionName)));
1718 
1719       // Delete daughter regions from meta, but not hdfs, unassign it.
1720       Map<HRegionInfo, ServerName> hris = tbl.getRegionLocations();
1721       undeployRegion(connection, hris.get(daughters.getFirst()), daughters.getFirst());
1722       undeployRegion(connection, hris.get(daughters.getSecond()), daughters.getSecond());
1723 
1724       List<Delete> deletes = new ArrayList<>();
1725       deletes.add(new Delete(daughters.getFirst().getRegionName()));
1726       deletes.add(new Delete(daughters.getSecond().getRegionName()));
1727       meta.delete(deletes);
1728 
1729       // Remove daughters from regionStates
1730       RegionStates regionStates = TEST_UTIL.getMiniHBaseCluster().getMaster().
1731           getAssignmentManager().getRegionStates();
1732       regionStates.deleteRegion(daughters.getFirst());
1733       regionStates.deleteRegion(daughters.getSecond());
1734 
1735       HBaseFsck hbck = doFsck(conf, false);
1736       assertErrors(hbck,
1737           new ERROR_CODE[] { ERROR_CODE.NOT_IN_META_OR_DEPLOYED, ERROR_CODE.NOT_IN_META_OR_DEPLOYED,
1738               ERROR_CODE.HOLE_IN_REGION_CHAIN }); //no LINGERING_SPLIT_PARENT
1739 
1740       // now fix it. The fix should not revert the region split, but add daughters to META
1741       hbck = doFsck(
1742         conf, true, true, false, false, false, false, false, false, false, false, false, null);
1743       assertErrors(hbck,
1744           new ERROR_CODE[] { ERROR_CODE.NOT_IN_META_OR_DEPLOYED, ERROR_CODE.NOT_IN_META_OR_DEPLOYED,
1745               ERROR_CODE.HOLE_IN_REGION_CHAIN });
1746 
1747       // assert that the split hbase:meta entry is still there.
1748       Get get = new Get(hri.getRegionName());
1749       Result result = meta.get(get);
1750       assertNotNull(result);
1751       assertNotNull(MetaTableAccessor.getHRegionInfo(result));
1752 
1753       assertEquals(ROWKEYS.length, countRows());
1754 
1755       // assert that we still have the split regions
1756       assertEquals(tbl.getStartKeys().length, SPLITS.length + 1 + 1); //SPLITS + 1 is # regions pre-split.
1757       assertNoErrors(doFsck(conf, false)); //should be fixed by now
1758     } finally {
1759       meta.close();
1760       cleanupTable(table);
1761     }
1762   }
1763 
1764   /**
1765    * This creates and fixes a bad table with a missing region which is the 1st region -- hole in
1766    * meta and data missing in the fs.
1767    */
1768   @Test(timeout=120000)
1769   public void testMissingFirstRegion() throws Exception {
1770     TableName table = TableName.valueOf("testMissingFirstRegion");
1771     try {
1772       setupTable(table);
1773       assertEquals(ROWKEYS.length, countRows());
1774 
1775       // Mess it up by leaving a hole in the assignment, meta, and hdfs data
1776       admin.disableTable(table);
1777       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes(""), Bytes.toBytes("A"), true,
1778           true, true);
1779       admin.enableTable(table);
1780 
1781       HBaseFsck hbck = doFsck(conf, false);
1782       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.FIRST_REGION_STARTKEY_NOT_EMPTY });
1783       // fix hole
1784       doFsck(conf, true);
1785       // check that hole fixed
1786       assertNoErrors(doFsck(conf, false));
1787     } finally {
1788       cleanupTable(table);
1789     }
1790   }
1791 
1792   /**
1793    * This creates and fixes a bad table with a missing region which is the 1st region -- hole in
1794    * meta and data missing in the fs.
1795    */
1796   @Test(timeout=120000)
1797   public void testRegionDeployedNotInHdfs() throws Exception {
1798     TableName table =
1799         TableName.valueOf("testSingleRegionDeployedNotInHdfs");
1800     try {
1801       setupTable(table);
1802       admin.flush(table);
1803 
1804       // Mess it up by deleting region dir
1805       deleteRegion(conf, tbl.getTableDescriptor(),
1806         HConstants.EMPTY_START_ROW, Bytes.toBytes("A"), false,
1807         false, true);
1808 
1809       HBaseFsck hbck = doFsck(conf, false);
1810       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.NOT_IN_HDFS });
1811       // fix hole
1812       doFsck(conf, true);
1813       // check that hole fixed
1814       assertNoErrors(doFsck(conf, false));
1815     } finally {
1816       cleanupTable(table);
1817     }
1818   }
1819 
1820   /**
1821    * This creates and fixes a bad table with missing last region -- hole in meta and data missing in
1822    * the fs.
1823    */
1824   @Test(timeout=120000)
1825   public void testMissingLastRegion() throws Exception {
1826     TableName table =
1827         TableName.valueOf("testMissingLastRegion");
1828     try {
1829       setupTable(table);
1830       assertEquals(ROWKEYS.length, countRows());
1831 
1832       // Mess it up by leaving a hole in the assignment, meta, and hdfs data
1833       admin.disableTable(table);
1834       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("C"), Bytes.toBytes(""), true,
1835           true, true);
1836       admin.enableTable(table);
1837 
1838       HBaseFsck hbck = doFsck(conf, false);
1839       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.LAST_REGION_ENDKEY_NOT_EMPTY });
1840       // fix hole
1841       doFsck(conf, true);
1842       // check that hole fixed
1843       assertNoErrors(doFsck(conf, false));
1844     } finally {
1845       cleanupTable(table);
1846     }
1847   }
1848 
1849   /**
1850    * Test -noHdfsChecking option can detect and fix assignments issue.
1851    */
1852   @Test (timeout=180000)
1853   public void testFixAssignmentsAndNoHdfsChecking() throws Exception {
1854     TableName table =
1855         TableName.valueOf("testFixAssignmentsAndNoHdfsChecking");
1856     try {
1857       setupTable(table);
1858       assertEquals(ROWKEYS.length, countRows());
1859 
1860       // Mess it up by closing a region
1861       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("A"),
1862         Bytes.toBytes("B"), true, false, false, false, HRegionInfo.DEFAULT_REPLICA_ID);
1863 
1864       // verify there is no other errors
1865       HBaseFsck hbck = doFsck(conf, false);
1866       assertErrors(hbck, new ERROR_CODE[] {
1867         ERROR_CODE.NOT_DEPLOYED, ERROR_CODE.HOLE_IN_REGION_CHAIN});
1868 
1869       // verify that noHdfsChecking report the same errors
1870       HBaseFsck fsck = new HBaseFsck(conf, hbfsckExecutorService);
1871       fsck.connect();
1872       fsck.setDisplayFullReport(); // i.e. -details
1873       fsck.setTimeLag(0);
1874       fsck.setCheckHdfs(false);
1875       fsck.onlineHbck();
1876       assertErrors(fsck, new ERROR_CODE[] {
1877         ERROR_CODE.NOT_DEPLOYED, ERROR_CODE.HOLE_IN_REGION_CHAIN});
1878       fsck.close();
1879 
1880       // verify that fixAssignments works fine with noHdfsChecking
1881       fsck = new HBaseFsck(conf, hbfsckExecutorService);
1882       fsck.connect();
1883       fsck.setDisplayFullReport(); // i.e. -details
1884       fsck.setTimeLag(0);
1885       fsck.setCheckHdfs(false);
1886       fsck.setFixAssignments(true);
1887       fsck.onlineHbck();
1888       assertTrue(fsck.shouldRerun());
1889       fsck.onlineHbck();
1890       assertNoErrors(fsck);
1891 
1892       assertEquals(ROWKEYS.length, countRows());
1893 
1894       fsck.close();
1895     } finally {
1896       cleanupTable(table);
1897     }
1898   }
1899 
1900   /**
1901    * Test -noHdfsChecking option can detect region is not in meta but deployed.
1902    * However, it can not fix it without checking Hdfs because we need to get
1903    * the region info from Hdfs in this case, then to patch the meta.
1904    */
1905   @Test (timeout=180000)
1906   public void testFixMetaNotWorkingWithNoHdfsChecking() throws Exception {
1907     TableName table =
1908         TableName.valueOf("testFixMetaNotWorkingWithNoHdfsChecking");
1909     try {
1910       setupTable(table);
1911       assertEquals(ROWKEYS.length, countRows());
1912 
1913       // Mess it up by deleting a region from the metadata
1914       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("A"),
1915         Bytes.toBytes("B"), false, true, false, false, HRegionInfo.DEFAULT_REPLICA_ID);
1916 
1917       // verify there is no other errors
1918       HBaseFsck hbck = doFsck(conf, false);
1919       assertErrors(hbck,
1920           new ERROR_CODE[] { ERROR_CODE.NOT_IN_META, ERROR_CODE.HOLE_IN_REGION_CHAIN });
1921 
1922       // verify that noHdfsChecking report the same errors
1923       HBaseFsck fsck = new HBaseFsck(conf, hbfsckExecutorService);
1924       fsck.connect();
1925       fsck.setDisplayFullReport(); // i.e. -details
1926       fsck.setTimeLag(0);
1927       fsck.setCheckHdfs(false);
1928       fsck.onlineHbck();
1929       assertErrors(fsck,
1930           new ERROR_CODE[] { ERROR_CODE.NOT_IN_META, ERROR_CODE.HOLE_IN_REGION_CHAIN });
1931       fsck.close();
1932 
1933       // verify that fixMeta doesn't work with noHdfsChecking
1934       fsck = new HBaseFsck(conf, hbfsckExecutorService);
1935       fsck.connect();
1936       fsck.setDisplayFullReport(); // i.e. -details
1937       fsck.setTimeLag(0);
1938       fsck.setCheckHdfs(false);
1939       fsck.setFixAssignments(true);
1940       fsck.setFixMeta(true);
1941       fsck.onlineHbck();
1942       assertFalse(fsck.shouldRerun());
1943       assertErrors(fsck,
1944           new ERROR_CODE[] { ERROR_CODE.NOT_IN_META, ERROR_CODE.HOLE_IN_REGION_CHAIN });
1945       fsck.close();
1946 
1947       // fix the cluster so other tests won't be impacted
1948       fsck = doFsck(conf, true);
1949       assertTrue(fsck.shouldRerun());
1950       fsck = doFsck(conf, true);
1951       assertNoErrors(fsck);
1952     } finally {
1953       cleanupTable(table);
1954     }
1955   }
1956 
1957   /**
1958    * Test -fixHdfsHoles doesn't work with -noHdfsChecking option,
1959    * and -noHdfsChecking can't detect orphan Hdfs region.
1960    */
1961   @Test (timeout=180000)
1962   public void testFixHdfsHolesNotWorkingWithNoHdfsChecking() throws Exception {
1963     TableName table =
1964         TableName.valueOf("testFixHdfsHolesNotWorkingWithNoHdfsChecking");
1965     try {
1966       setupTable(table);
1967       assertEquals(ROWKEYS.length, countRows());
1968 
1969       // Mess it up by creating an overlap in the metadata
1970       admin.disableTable(table);
1971       deleteRegion(conf, tbl.getTableDescriptor(), Bytes.toBytes("A"),
1972         Bytes.toBytes("B"), true, true, false, true, HRegionInfo.DEFAULT_REPLICA_ID);
1973       TEST_UTIL.getHBaseAdmin().enableTable(table);
1974 
1975       HRegionInfo hriOverlap =
1976           createRegion(tbl.getTableDescriptor(), Bytes.toBytes("A2"), Bytes.toBytes("B"));
1977       TEST_UTIL.getHBaseCluster().getMaster().assignRegion(hriOverlap);
1978       TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager()
1979         .waitForAssignment(hriOverlap);
1980       ServerName server = regionStates.getRegionServerOfRegion(hriOverlap);
1981       TEST_UTIL.assertRegionOnServer(hriOverlap, server, REGION_ONLINE_TIMEOUT);
1982 
1983       HBaseFsck hbck = doFsck(conf, false);
1984       assertErrors(hbck, new ERROR_CODE[] {
1985         ERROR_CODE.ORPHAN_HDFS_REGION, ERROR_CODE.NOT_IN_META_OR_DEPLOYED,
1986         ERROR_CODE.HOLE_IN_REGION_CHAIN});
1987 
1988       // verify that noHdfsChecking can't detect ORPHAN_HDFS_REGION
1989       HBaseFsck fsck = new HBaseFsck(conf, hbfsckExecutorService);
1990       fsck.connect();
1991       fsck.setDisplayFullReport(); // i.e. -details
1992       fsck.setTimeLag(0);
1993       fsck.setCheckHdfs(false);
1994       fsck.onlineHbck();
1995       assertErrors(fsck, new ERROR_CODE[] {
1996         ERROR_CODE.HOLE_IN_REGION_CHAIN});
1997       fsck.close();
1998 
1999       // verify that fixHdfsHoles doesn't work with noHdfsChecking
2000       fsck = new HBaseFsck(conf, hbfsckExecutorService);
2001       fsck.connect();
2002       fsck.setDisplayFullReport(); // i.e. -details
2003       fsck.setTimeLag(0);
2004       fsck.setCheckHdfs(false);
2005       fsck.setFixHdfsHoles(true);
2006       fsck.setFixHdfsOverlaps(true);
2007       fsck.setFixHdfsOrphans(true);
2008       fsck.onlineHbck();
2009       assertFalse(fsck.shouldRerun());
2010       assertErrors(fsck, new ERROR_CODE[] { ERROR_CODE.HOLE_IN_REGION_CHAIN});
2011       fsck.close();
2012     } finally {
2013       if (admin.isTableDisabled(table)) {
2014         admin.enableTable(table);
2015       }
2016       cleanupTable(table);
2017     }
2018   }
2019 
2020   /**
2021    * We don't have an easy way to verify that a flush completed, so we loop until we find a
2022    * legitimate hfile and return it.
2023    * @param fs
2024    * @param table
2025    * @return Path of a flushed hfile.
2026    * @throws IOException
2027    */
2028   Path getFlushedHFile(FileSystem fs, TableName table) throws IOException {
2029     Path tableDir= FSUtils.getTableDir(FSUtils.getRootDir(conf), table);
2030     Path regionDir = FSUtils.getRegionDirs(fs, tableDir).get(0);
2031     Path famDir = new Path(regionDir, FAM_STR);
2032 
2033     // keep doing this until we get a legit hfile
2034     while (true) {
2035       FileStatus[] hfFss = fs.listStatus(famDir);
2036       if (hfFss.length == 0) {
2037         continue;
2038       }
2039       for (FileStatus hfs : hfFss) {
2040         if (!hfs.isDirectory()) {
2041           return hfs.getPath();
2042         }
2043       }
2044     }
2045   }
2046 
2047   /**
2048    * This creates a table and then corrupts an hfile.  Hbck should quarantine the file.
2049    */
2050   @Test(timeout=180000)
2051   public void testQuarantineCorruptHFile() throws Exception {
2052     TableName table = TableName.valueOf(name.getMethodName());
2053     try {
2054       setupTable(table);
2055       assertEquals(ROWKEYS.length, countRows());
2056       admin.flush(table); // flush is async.
2057 
2058       FileSystem fs = FileSystem.get(conf);
2059       Path hfile = getFlushedHFile(fs, table);
2060 
2061       // Mess it up by leaving a hole in the assignment, meta, and hdfs data
2062       admin.disableTable(table);
2063 
2064       // create new corrupt file called deadbeef (valid hfile name)
2065       Path corrupt = new Path(hfile.getParent(), "deadbeef");
2066       TestHFile.truncateFile(fs, hfile, corrupt);
2067       LOG.info("Created corrupted file " + corrupt);
2068       HBaseFsck.debugLsr(conf, FSUtils.getRootDir(conf));
2069 
2070       // we cannot enable here because enable never finished due to the corrupt region.
2071       HBaseFsck res = HbckTestingUtil.doHFileQuarantine(conf, table);
2072       assertEquals(res.getRetCode(), 0);
2073       HFileCorruptionChecker hfcc = res.getHFilecorruptionChecker();
2074       assertEquals(hfcc.getHFilesChecked(), 5);
2075       assertEquals(hfcc.getCorrupted().size(), 1);
2076       assertEquals(hfcc.getFailures().size(), 0);
2077       assertEquals(hfcc.getQuarantined().size(), 1);
2078       assertEquals(hfcc.getMissing().size(), 0);
2079 
2080       // Its been fixed, verify that we can enable.
2081       admin.enableTable(table);
2082     } finally {
2083       cleanupTable(table);
2084     }
2085   }
2086 
2087   /**
2088    * Test that use this should have a timeout, because this method could potentially wait forever.
2089   */
2090   private void doQuarantineTest(TableName table, HBaseFsck hbck, int check,
2091                                 int corrupt, int fail, int quar, int missing) throws Exception {
2092     try {
2093       setupTable(table);
2094       assertEquals(ROWKEYS.length, countRows());
2095       admin.flush(table); // flush is async.
2096 
2097       // Mess it up by leaving a hole in the assignment, meta, and hdfs data
2098       admin.disableTable(table);
2099 
2100       String[] args = {"-sidelineCorruptHFiles", "-repairHoles", "-ignorePreCheckPermission",
2101           table.getNameAsString()};
2102       HBaseFsck res = hbck.exec(hbfsckExecutorService, args);
2103 
2104       HFileCorruptionChecker hfcc = res.getHFilecorruptionChecker();
2105       assertEquals(hfcc.getHFilesChecked(), check);
2106       assertEquals(hfcc.getCorrupted().size(), corrupt);
2107       assertEquals(hfcc.getFailures().size(), fail);
2108       assertEquals(hfcc.getQuarantined().size(), quar);
2109       assertEquals(hfcc.getMissing().size(), missing);
2110 
2111       // its been fixed, verify that we can enable
2112       admin.enableTableAsync(table);
2113       while (!admin.isTableEnabled(table)) {
2114         try {
2115           Thread.sleep(250);
2116         } catch (InterruptedException e) {
2117           e.printStackTrace();
2118           fail("Interrupted when trying to enable table " + table);
2119         }
2120       }
2121     } finally {
2122       cleanupTable(table);
2123     }
2124   }
2125 
2126   /**
2127    * This creates a table and simulates the race situation where a concurrent compaction or split
2128    * has removed an hfile after the corruption checker learned about it.
2129    */
2130   @Test(timeout=180000)
2131   public void testQuarantineMissingHFile() throws Exception {
2132     TableName table = TableName.valueOf(name.getMethodName());
2133 
2134     // inject a fault in the hfcc created.
2135     final FileSystem fs = FileSystem.get(conf);
2136     HBaseFsck hbck = new HBaseFsck(conf, hbfsckExecutorService) {
2137       @Override
2138       public HFileCorruptionChecker createHFileCorruptionChecker(boolean sidelineCorruptHFiles) throws IOException {
2139         return new HFileCorruptionChecker(conf, executor, sidelineCorruptHFiles) {
2140           AtomicBoolean attemptedFirstHFile = new AtomicBoolean(false);
2141           @Override
2142           protected void checkHFile(Path p) throws IOException {
2143             if (attemptedFirstHFile.compareAndSet(false, true)) {
2144               assertTrue(fs.delete(p, true)); // make sure delete happened.
2145             }
2146             super.checkHFile(p);
2147           }
2148         };
2149       }
2150     };
2151     doQuarantineTest(table, hbck, 4, 0, 0, 0, 1); // 4 attempted, but 1 missing.
2152     hbck.close();
2153   }
2154 
2155   /**
2156    * This creates a table and simulates the race situation where a concurrent compaction or split
2157    * has removed an colfam dir before the corruption checker got to it.
2158    */
2159   // Disabled because fails sporadically.  Is this test right?  Timing-wise, there could be no
2160   // files in a column family on initial creation -- as suggested by Matteo.
2161   @Ignore @Test(timeout=180000)
2162   public void testQuarantineMissingFamdir() throws Exception {
2163     TableName table = TableName.valueOf(name.getMethodName());
2164     // inject a fault in the hfcc created.
2165     final FileSystem fs = FileSystem.get(conf);
2166     HBaseFsck hbck = new HBaseFsck(conf, hbfsckExecutorService) {
2167       @Override
2168       public HFileCorruptionChecker createHFileCorruptionChecker(boolean sidelineCorruptHFiles) throws IOException {
2169         return new HFileCorruptionChecker(conf, executor, sidelineCorruptHFiles) {
2170           AtomicBoolean attemptedFirstHFile = new AtomicBoolean(false);
2171           @Override
2172           protected void checkColFamDir(Path p) throws IOException {
2173             if (attemptedFirstHFile.compareAndSet(false, true)) {
2174               assertTrue(fs.delete(p, true)); // make sure delete happened.
2175             }
2176             super.checkColFamDir(p);
2177           }
2178         };
2179       }
2180     };
2181     doQuarantineTest(table, hbck, 3, 0, 0, 0, 1);
2182     hbck.close();
2183   }
2184 
2185   /**
2186    * This creates a table and simulates the race situation where a concurrent compaction or split
2187    * has removed a region dir before the corruption checker got to it.
2188    */
2189   @Test(timeout=180000)
2190   public void testQuarantineMissingRegionDir() throws Exception {
2191     TableName table = TableName.valueOf(name.getMethodName());
2192     // inject a fault in the hfcc created.
2193     final FileSystem fs = FileSystem.get(conf);
2194     HBaseFsck hbck = new HBaseFsck(conf, hbfsckExecutorService) {
2195       @Override
2196       public HFileCorruptionChecker createHFileCorruptionChecker(boolean sidelineCorruptHFiles)
2197       throws IOException {
2198         return new HFileCorruptionChecker(conf, executor, sidelineCorruptHFiles) {
2199           AtomicBoolean attemptedFirstHFile = new AtomicBoolean(false);
2200           @Override
2201           protected void checkRegionDir(Path p) throws IOException {
2202             if (attemptedFirstHFile.compareAndSet(false, true)) {
2203               assertTrue(fs.delete(p, true)); // make sure delete happened.
2204             }
2205             super.checkRegionDir(p);
2206           }
2207         };
2208       }
2209     };
2210     doQuarantineTest(table, hbck, 3, 0, 0, 0, 1);
2211     hbck.close();
2212   }
2213 
2214   /**
2215    * Test fixing lingering reference file.
2216    */
2217   @Test (timeout=180000)
2218   public void testLingeringReferenceFile() throws Exception {
2219     TableName table =
2220         TableName.valueOf("testLingeringReferenceFile");
2221     try {
2222       setupTable(table);
2223       assertEquals(ROWKEYS.length, countRows());
2224 
2225       // Mess it up by creating a fake reference file
2226       FileSystem fs = FileSystem.get(conf);
2227       Path tableDir= FSUtils.getTableDir(FSUtils.getRootDir(conf), table);
2228       Path regionDir = FSUtils.getRegionDirs(fs, tableDir).get(0);
2229       Path famDir = new Path(regionDir, FAM_STR);
2230       Path fakeReferenceFile = new Path(famDir, "fbce357483ceea.12144538");
2231       fs.create(fakeReferenceFile);
2232 
2233       HBaseFsck hbck = doFsck(conf, false);
2234       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.LINGERING_REFERENCE_HFILE });
2235       // fix reference file
2236       doFsck(conf, true);
2237       // check that reference file fixed
2238       assertNoErrors(doFsck(conf, false));
2239     } finally {
2240       cleanupTable(table);
2241     }
2242   }
2243 
2244   /**
2245    * Test mission REGIONINFO_QUALIFIER in hbase:meta
2246    */
2247   @Test (timeout=180000)
2248   public void testMissingRegionInfoQualifier() throws Exception {
2249     Connection connection = ConnectionFactory.createConnection(conf);
2250     TableName table = TableName.valueOf("testMissingRegionInfoQualifier");
2251     try {
2252       setupTable(table);
2253 
2254       // Mess it up by removing the RegionInfo for one region.
2255       final List<Delete> deletes = new LinkedList<Delete>();
2256       Table meta = connection.getTable(TableName.META_TABLE_NAME, hbfsckExecutorService);
2257       MetaScanner.metaScan(connection, new MetaScanner.MetaScannerVisitor() {
2258 
2259         @Override
2260         public boolean processRow(Result rowResult) throws IOException {
2261           HRegionInfo hri = MetaTableAccessor.getHRegionInfo(rowResult);
2262           if (hri != null && !hri.getTable().isSystemTable()) {
2263             Delete delete = new Delete(rowResult.getRow());
2264             delete.addColumn(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER);
2265             deletes.add(delete);
2266           }
2267           return true;
2268         }
2269 
2270         @Override
2271         public void close() throws IOException {
2272         }
2273       });
2274       meta.delete(deletes);
2275 
2276       // Mess it up by creating a fake hbase:meta entry with no associated RegionInfo
2277       meta.put(new Put(Bytes.toBytes(table + ",,1361911384013.810e28f59a57da91c66")).add(
2278         HConstants.CATALOG_FAMILY, HConstants.SERVER_QUALIFIER, Bytes.toBytes("node1:60020")));
2279       meta.put(new Put(Bytes.toBytes(table + ",,1361911384013.810e28f59a57da91c66")).add(
2280         HConstants.CATALOG_FAMILY, HConstants.STARTCODE_QUALIFIER, Bytes.toBytes(1362150791183L)));
2281       meta.close();
2282 
2283       HBaseFsck hbck = doFsck(conf, false);
2284       assertTrue(hbck.getErrors().getErrorList().contains(ERROR_CODE.EMPTY_META_CELL));
2285 
2286       // fix reference file
2287       hbck = doFsck(conf, true);
2288 
2289       // check that reference file fixed
2290       assertFalse(hbck.getErrors().getErrorList().contains(ERROR_CODE.EMPTY_META_CELL));
2291     } finally {
2292       cleanupTable(table);
2293     }
2294     connection.close();
2295   }
2296 
2297   /**
2298    * Test pluggable error reporter. It can be plugged in
2299    * from system property or configuration.
2300    */
2301   @Test (timeout=180000)
2302   public void testErrorReporter() throws Exception {
2303     try {
2304       MockErrorReporter.calledCount = 0;
2305       doFsck(conf, false);
2306       assertEquals(MockErrorReporter.calledCount, 0);
2307 
2308       conf.set("hbasefsck.errorreporter", MockErrorReporter.class.getName());
2309       doFsck(conf, false);
2310       assertTrue(MockErrorReporter.calledCount > 20);
2311     } finally {
2312       conf.set("hbasefsck.errorreporter",
2313         PrintingErrorReporter.class.getName());
2314       MockErrorReporter.calledCount = 0;
2315     }
2316   }
2317 
2318   static class MockErrorReporter implements ErrorReporter {
2319     static int calledCount = 0;
2320 
2321     @Override
2322     public void clear() {
2323       calledCount++;
2324     }
2325 
2326     @Override
2327     public void report(String message) {
2328       calledCount++;
2329     }
2330 
2331     @Override
2332     public void reportError(String message) {
2333       calledCount++;
2334     }
2335 
2336     @Override
2337     public void reportError(ERROR_CODE errorCode, String message) {
2338       calledCount++;
2339     }
2340 
2341     @Override
2342     public void reportError(ERROR_CODE errorCode, String message, TableInfo table) {
2343       calledCount++;
2344     }
2345 
2346     @Override
2347     public void reportError(ERROR_CODE errorCode,
2348         String message, TableInfo table, HbckInfo info) {
2349       calledCount++;
2350     }
2351 
2352     @Override
2353     public void reportError(ERROR_CODE errorCode, String message,
2354         TableInfo table, HbckInfo info1, HbckInfo info2) {
2355       calledCount++;
2356     }
2357 
2358     @Override
2359     public int summarize() {
2360       return ++calledCount;
2361     }
2362 
2363     @Override
2364     public void detail(String details) {
2365       calledCount++;
2366     }
2367 
2368     @Override
2369     public ArrayList<ERROR_CODE> getErrorList() {
2370       calledCount++;
2371       return new ArrayList<ERROR_CODE>();
2372     }
2373 
2374     @Override
2375     public void progress() {
2376       calledCount++;
2377     }
2378 
2379     @Override
2380     public void print(String message) {
2381       calledCount++;
2382     }
2383 
2384     @Override
2385     public void resetErrors() {
2386       calledCount++;
2387     }
2388 
2389     @Override
2390     public boolean tableHasErrors(TableInfo table) {
2391       calledCount++;
2392       return false;
2393     }
2394   }
2395 
2396   @Test(timeout=180000)
2397   public void testCheckTableLocks() throws Exception {
2398     IncrementingEnvironmentEdge edge = new IncrementingEnvironmentEdge(0);
2399     EnvironmentEdgeManager.injectEdge(edge);
2400     // check no errors
2401     HBaseFsck hbck = doFsck(conf, false);
2402     assertNoErrors(hbck);
2403 
2404     ServerName mockName = ServerName.valueOf("localhost", 60000, 1);
2405     final TableName tableName = TableName.valueOf("foo");
2406 
2407     // obtain one lock
2408     final TableLockManager tableLockManager =
2409       TableLockManager.createTableLockManager(conf, TEST_UTIL.getZooKeeperWatcher(), mockName);
2410     TableLock writeLock = tableLockManager.writeLock(tableName, "testCheckTableLocks");
2411     writeLock.acquire();
2412     hbck = doFsck(conf, false);
2413     assertNoErrors(hbck); // should not have expired, no problems
2414 
2415     edge.incrementTime(conf.getLong(TableLockManager.TABLE_LOCK_EXPIRE_TIMEOUT,
2416         TableLockManager.DEFAULT_TABLE_LOCK_EXPIRE_TIMEOUT_MS)); // let table lock expire
2417 
2418     hbck = doFsck(conf, false);
2419     assertErrors(hbck, new ERROR_CODE[] {ERROR_CODE.EXPIRED_TABLE_LOCK});
2420 
2421     final CountDownLatch latch = new CountDownLatch(1);
2422     new Thread() {
2423       @Override
2424       public void run() {
2425         TableLock readLock = tableLockManager.writeLock(tableName, "testCheckTableLocks");
2426         try {
2427           latch.countDown();
2428           readLock.acquire();
2429         } catch (IOException ex) {
2430           fail();
2431         } catch (IllegalStateException ex) {
2432           return; // expected, since this will be reaped under us.
2433         }
2434         fail("should not have come here");
2435       };
2436     }.start();
2437 
2438     latch.await(); // wait until thread starts
2439     Threads.sleep(300); // wait some more to ensure writeLock.acquire() is called
2440 
2441     hbck = doFsck(conf, false);
2442     assertErrors(hbck, new ERROR_CODE[] {ERROR_CODE.EXPIRED_TABLE_LOCK}); // still one expired, one not-expired
2443 
2444     edge.incrementTime(conf.getLong(TableLockManager.TABLE_LOCK_EXPIRE_TIMEOUT,
2445         TableLockManager.DEFAULT_TABLE_LOCK_EXPIRE_TIMEOUT_MS)); // let table lock expire
2446 
2447     hbck = doFsck(conf, false);
2448     assertErrors(hbck, new ERROR_CODE[] {ERROR_CODE.EXPIRED_TABLE_LOCK, ERROR_CODE.EXPIRED_TABLE_LOCK}); // both are expired
2449 
2450     conf.setLong(TableLockManager.TABLE_LOCK_EXPIRE_TIMEOUT, 1); // reaping from ZKInterProcessWriteLock uses znode cTime,
2451                                                                  // which is not injectable through EnvironmentEdge
2452     Threads.sleep(10);
2453     hbck = doFsck(conf, true); // now fix both cases
2454 
2455     hbck = doFsck(conf, false);
2456     assertNoErrors(hbck);
2457 
2458     // ensure that locks are deleted
2459     writeLock = tableLockManager.writeLock(tableName, "should acquire without blocking");
2460     writeLock.acquire(); // this should not block.
2461     writeLock.release(); // release for clean state
2462     tableLockManager.tableDeleted(tableName);
2463   }
2464 
2465   /**
2466    * Test orphaned table ZNode (for table states)
2467    */
2468   @Test
2469   public void testOrphanedTableZNode() throws Exception {
2470     TableName table = TableName.valueOf("testOrphanedZKTableEntry");
2471 
2472     try {
2473       TEST_UTIL.getHBaseCluster().getMaster().getAssignmentManager().getTableStateManager()
2474       .setTableState(table, ZooKeeperProtos.Table.State.ENABLING);
2475 
2476       try {
2477         setupTable(table);
2478         Assert.fail(
2479           "Create table should fail when its ZNode has already existed with ENABLING state.");
2480       } catch(TableExistsException t) {
2481         //Expected exception
2482       }
2483       // The setup table was interrupted in some state that needs to some cleanup.
2484       try {
2485         cleanupTable(table);
2486       } catch (IOException e) {
2487         // Because create table failed, it is expected that the cleanup table would
2488         // throw some exception.  Ignore and continue.
2489       }
2490 
2491       HBaseFsck hbck = doFsck(conf, false);
2492       assertTrue(hbck.getErrors().getErrorList().contains(ERROR_CODE.ORPHANED_ZK_TABLE_ENTRY));
2493 
2494       // fix the orphaned ZK entry
2495       hbck = doFsck(conf, true);
2496 
2497       // check that orpahned ZK table entry is gone.
2498       hbck = doFsck(conf, false);
2499       assertFalse(hbck.getErrors().getErrorList().contains(ERROR_CODE.ORPHANED_ZK_TABLE_ENTRY));
2500       // Now create table should succeed.
2501       setupTable(table);
2502     } finally {
2503       // This code could be called that either a table was created successfully or set up
2504       // table failed in some unknown state.  Therefore, clean up can either succeed or fail.
2505       try {
2506         cleanupTable(table);
2507       } catch (IOException e) {
2508         // The cleanup table would throw some exception if create table failed in some state.
2509         // Ignore this exception
2510       }
2511     }
2512   }
2513 
2514   @Test (timeout=180000)
2515   public void testMetaOffline() throws Exception {
2516     // check no errors
2517     HBaseFsck hbck = doFsck(conf, false);
2518     assertNoErrors(hbck);
2519     deleteMetaRegion(conf, true, false, false);
2520     hbck = doFsck(conf, false);
2521     // ERROR_CODE.UNKNOWN is coming because we reportError with a message for the hbase:meta
2522     // inconsistency and whether we will be fixing it or not.
2523     assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.NO_META_REGION, ERROR_CODE.UNKNOWN });
2524     hbck = doFsck(conf, true);
2525     assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.NO_META_REGION, ERROR_CODE.UNKNOWN });
2526     hbck = doFsck(conf, false);
2527     assertNoErrors(hbck);
2528   }
2529 
2530   private void deleteMetaRegion(Configuration conf, boolean unassign, boolean hdfs,
2531       boolean regionInfoOnly) throws IOException, InterruptedException {
2532     HRegionLocation metaLocation = connection.getRegionLocator(TableName.META_TABLE_NAME)
2533         .getRegionLocation(HConstants.EMPTY_START_ROW);
2534     ServerName hsa = metaLocation.getServerName();
2535     HRegionInfo hri = metaLocation.getRegionInfo();
2536     if (unassign) {
2537       LOG.info("Undeploying meta region " + hri + " from server " + hsa);
2538       try (Connection unmanagedConnection = ConnectionFactory.createConnection(conf)) {
2539         undeployRegion(unmanagedConnection, hsa, hri);
2540       }
2541     }
2542 
2543     if (regionInfoOnly) {
2544       LOG.info("deleting hdfs .regioninfo data: " + hri.toString() + hsa.toString());
2545       Path rootDir = FSUtils.getRootDir(conf);
2546       FileSystem fs = rootDir.getFileSystem(conf);
2547       Path p = new Path(rootDir + "/" + TableName.META_TABLE_NAME.getNameAsString(),
2548           hri.getEncodedName());
2549       Path hriPath = new Path(p, HRegionFileSystem.REGION_INFO_FILE);
2550       fs.delete(hriPath, true);
2551     }
2552 
2553     if (hdfs) {
2554       LOG.info("deleting hdfs data: " + hri.toString() + hsa.toString());
2555       Path rootDir = FSUtils.getRootDir(conf);
2556       FileSystem fs = rootDir.getFileSystem(conf);
2557       Path p = new Path(rootDir + "/" + TableName.META_TABLE_NAME.getNameAsString(),
2558           hri.getEncodedName());
2559       HBaseFsck.debugLsr(conf, p);
2560       boolean success = fs.delete(p, true);
2561       LOG.info("Deleted " + p + " sucessfully? " + success);
2562       HBaseFsck.debugLsr(conf, p);
2563     }
2564   }
2565 
2566   @Test (timeout=180000)
2567   public void testTableWithNoRegions() throws Exception {
2568     // We might end up with empty regions in a table
2569     // see also testNoHdfsTable()
2570     TableName table =
2571         TableName.valueOf(name.getMethodName());
2572     try {
2573       // create table with one region
2574       HTableDescriptor desc = new HTableDescriptor(table);
2575       HColumnDescriptor hcd = new HColumnDescriptor(Bytes.toString(FAM));
2576       desc.addFamily(hcd); // If a table has no CF's it doesn't get checked
2577       createTable(TEST_UTIL, desc, null);
2578       tbl = (HTable) connection.getTable(table, tableExecutorService);
2579 
2580       // Mess it up by leaving a hole in the assignment, meta, and hdfs data
2581       deleteRegion(conf, tbl.getTableDescriptor(), HConstants.EMPTY_START_ROW,
2582           HConstants.EMPTY_END_ROW, false, false, true);
2583 
2584       HBaseFsck hbck = doFsck(conf, false);
2585       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.NOT_IN_HDFS });
2586 
2587       doFsck(conf, true);
2588 
2589       // fix hole
2590       doFsck(conf, true);
2591 
2592       // check that hole fixed
2593       assertNoErrors(doFsck(conf, false));
2594     } finally {
2595       cleanupTable(table);
2596     }
2597 
2598   }
2599 
2600   @Test (timeout=180000)
2601   public void testHbckAfterRegionMerge() throws Exception {
2602     TableName table = TableName.valueOf("testMergeRegionFilesInHdfs");
2603     Table meta = null;
2604     try {
2605       // disable CatalogJanitor
2606       TEST_UTIL.getHBaseCluster().getMaster().setCatalogJanitorEnabled(false);
2607       setupTable(table);
2608       assertEquals(ROWKEYS.length, countRows());
2609 
2610       // make sure data in regions, if in wal only there is no data loss
2611       admin.flush(table);
2612       HRegionInfo region1 = tbl.getRegionLocation(Bytes.toBytes("A")).getRegionInfo();
2613       HRegionInfo region2 = tbl.getRegionLocation(Bytes.toBytes("B")).getRegionInfo();
2614 
2615       int regionCountBeforeMerge = tbl.getRegionLocations().size();
2616 
2617       assertNotEquals(region1, region2);
2618 
2619       // do a region merge
2620       admin.mergeRegions(region1.getEncodedNameAsBytes(),
2621           region2.getEncodedNameAsBytes(), false);
2622 
2623       // wait until region merged
2624       long timeout = System.currentTimeMillis() + 30 * 1000;
2625       while (true) {
2626         if (tbl.getRegionLocations().size() < regionCountBeforeMerge) {
2627           break;
2628         } else if (System.currentTimeMillis() > timeout) {
2629           fail("Time out waiting on region " + region1.getEncodedName()
2630               + " and " + region2.getEncodedName() + " be merged");
2631         }
2632         Thread.sleep(10);
2633       }
2634 
2635       assertEquals(ROWKEYS.length, countRows());
2636 
2637       HBaseFsck hbck = doFsck(conf, false);
2638       assertNoErrors(hbck); // no errors
2639 
2640     } finally {
2641       TEST_UTIL.getHBaseCluster().getMaster().setCatalogJanitorEnabled(true);
2642       cleanupTable(table);
2643       IOUtils.closeQuietly(meta);
2644     }
2645   }
2646 
2647   @Test (timeout = 180000)
2648   public void testRegionBoundariesCheck() throws Exception {
2649     HBaseFsck hbck = doFsck(conf, false);
2650     assertNoErrors(hbck); // no errors
2651     try {
2652       hbck.checkRegionBoundaries();
2653     } catch (IllegalArgumentException e) {
2654       if (e.getMessage().endsWith("not a valid DFS filename.")) {
2655         fail("Table directory path is not valid." + e.getMessage());
2656       }
2657     }
2658   }
2659 
2660   @org.junit.Rule
2661   public TestName name = new TestName();
2662 
2663   @Test (timeout=180000)
2664   public void testReadOnlyProperty() throws Exception {
2665     HBaseFsck hbck = doFsck(conf, false);
2666     Assert.assertEquals("shouldIgnorePreCheckPermission", true,
2667       hbck.shouldIgnorePreCheckPermission());
2668 
2669     hbck = doFsck(conf, true);
2670     Assert.assertEquals("shouldIgnorePreCheckPermission", false,
2671       hbck.shouldIgnorePreCheckPermission());
2672 
2673     hbck = doFsck(conf, true);
2674     hbck.setIgnorePreCheckPermission(true);
2675     Assert.assertEquals("shouldIgnorePreCheckPermission", true,
2676       hbck.shouldIgnorePreCheckPermission());
2677   }
2678 
2679   @Test (timeout=180000)
2680   public void testCleanUpDaughtersNotInMetaAfterFailedSplit() throws Exception {
2681     TableName table = TableName.valueOf("testCleanUpDaughtersNotInMetaAfterFailedSplit");
2682     MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
2683     try {
2684       HTableDescriptor desc = new HTableDescriptor(table);
2685       desc.addFamily(new HColumnDescriptor(Bytes.toBytes("f")));
2686       createTable(TEST_UTIL, desc, null);
2687       tbl = new HTable(cluster.getConfiguration(), desc.getTableName());
2688       for (int i = 0; i < 5; i++) {
2689         Put p1 = new Put(("r" + i).getBytes());
2690         p1.add(Bytes.toBytes("f"), "q1".getBytes(), "v".getBytes());
2691         tbl.put(p1);
2692       }
2693       admin.flush(desc.getTableName());
2694       List<HRegion> regions = cluster.getRegions(desc.getTableName());
2695       int serverWith = cluster.getServerWith(regions.get(0).getRegionInfo().getRegionName());
2696       HRegionServer regionServer = cluster.getRegionServer(serverWith);
2697       cluster.getServerWith(regions.get(0).getRegionInfo().getRegionName());
2698       SplitTransactionImpl st = new SplitTransactionImpl(regions.get(0), Bytes.toBytes("r3"));
2699       st.prepare();
2700       st.stepsBeforePONR(regionServer, regionServer, false);
2701       AssignmentManager am = cluster.getMaster().getAssignmentManager();
2702       Map<String, RegionState> regionsInTransition = am.getRegionStates().getRegionsInTransition();
2703       for (RegionState state : regionsInTransition.values()) {
2704         am.regionOffline(state.getRegion());
2705       }
2706       ZKAssign.deleteNodeFailSilent(regionServer.getZooKeeper(), regions.get(0).getRegionInfo());
2707       Map<HRegionInfo, ServerName> regionsMap = new HashMap<HRegionInfo, ServerName>();
2708       regionsMap.put(regions.get(0).getRegionInfo(), regionServer.getServerName());
2709       am.assign(regionsMap);
2710       am.waitForAssignment(regions.get(0).getRegionInfo());
2711       HBaseFsck hbck = doFsck(conf, false);
2712       assertErrors(hbck, new ERROR_CODE[] { ERROR_CODE.NOT_IN_META_OR_DEPLOYED,
2713           ERROR_CODE.NOT_IN_META_OR_DEPLOYED });
2714       // holes are separate from overlap groups
2715       assertEquals(0, hbck.getOverlapGroups(table).size());
2716 
2717       // fix hole
2718       assertErrors(
2719         doFsck(
2720           conf, false, true, false, false, false, false, false, false, false, false, false, null),
2721         new ERROR_CODE[] { ERROR_CODE.NOT_IN_META_OR_DEPLOYED,
2722           ERROR_CODE.NOT_IN_META_OR_DEPLOYED });
2723 
2724       // check that hole fixed
2725       assertNoErrors(doFsck(conf, false));
2726       assertEquals(5, countRows());
2727     } finally {
2728       if (tbl != null) {
2729         tbl.close();
2730         tbl = null;
2731       }
2732       cleanupTable(table);
2733     }
2734   }
2735 
2736 
2737   public static class MasterSyncObserver extends BaseMasterObserver {
2738     volatile CountDownLatch tableCreationLatch = null;
2739     volatile CountDownLatch tableDeletionLatch = null;
2740 
2741     @Override
2742     public void postCreateTableHandler(final ObserverContext<MasterCoprocessorEnvironment> ctx,
2743       HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
2744       // the AccessController test, some times calls only and directly the postCreateTableHandler()
2745       if (tableCreationLatch != null) {
2746         tableCreationLatch.countDown();
2747       }
2748     }
2749 
2750     @Override
2751     public void postDeleteTableHandler(final ObserverContext<MasterCoprocessorEnvironment> ctx,
2752                                        TableName tableName)
2753     throws IOException {
2754       // the AccessController test, some times calls only and directly the postDeleteTableHandler()
2755       if (tableDeletionLatch != null) {
2756         tableDeletionLatch.countDown();
2757       }
2758     }
2759   }
2760 
2761   public static void createTable(HBaseTestingUtility testUtil, HTableDescriptor htd,
2762     byte [][] splitKeys) throws Exception {
2763     // NOTE: We need a latch because admin is not sync,
2764     // so the postOp coprocessor method may be called after the admin operation returned.
2765     MasterSyncObserver observer = (MasterSyncObserver)testUtil.getHBaseCluster().getMaster()
2766       .getMasterCoprocessorHost().findCoprocessor(MasterSyncObserver.class.getName());
2767     observer.tableCreationLatch = new CountDownLatch(1);
2768     if (splitKeys != null) {
2769       admin.createTable(htd, splitKeys);
2770     } else {
2771       admin.createTable(htd);
2772     }
2773     observer.tableCreationLatch.await();
2774     observer.tableCreationLatch = null;
2775     testUtil.waitUntilAllRegionsAssigned(htd.getTableName());
2776   }
2777 
2778   public static void deleteTable(HBaseTestingUtility testUtil, TableName tableName)
2779     throws Exception {
2780     // NOTE: We need a latch because admin is not sync,
2781     // so the postOp coprocessor method may be called after the admin operation returned.
2782     MasterSyncObserver observer = (MasterSyncObserver)testUtil.getHBaseCluster().getMaster()
2783       .getMasterCoprocessorHost().findCoprocessor(MasterSyncObserver.class.getName());
2784     observer.tableDeletionLatch = new CountDownLatch(1);
2785     try {
2786       admin.disableTable(tableName);
2787     } catch (Exception e) {
2788       LOG.debug("Table: " + tableName + " already disabled, so just deleting it.");
2789     }
2790     admin.deleteTable(tableName);
2791     observer.tableDeletionLatch.await();
2792     observer.tableDeletionLatch = null;
2793   }
2794 }