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