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