1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.wal;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertFalse;
23 import static org.junit.Assert.assertTrue;
24 import static org.junit.Assert.fail;
25
26 import com.google.common.base.Joiner;
27 import com.google.common.collect.ImmutableList;
28 import com.google.common.collect.ImmutableMap;
29 import com.google.protobuf.ByteString;
30
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.lang.reflect.Method;
34 import java.security.PrivilegedExceptionAction;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.Collections;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.NavigableSet;
43 import java.util.Set;
44 import java.util.concurrent.atomic.AtomicBoolean;
45 import java.util.concurrent.atomic.AtomicInteger;
46 import java.util.concurrent.atomic.AtomicLong;
47
48 import org.apache.commons.logging.Log;
49 import org.apache.commons.logging.LogFactory;
50 import org.apache.hadoop.conf.Configuration;
51 import org.apache.hadoop.fs.FSDataInputStream;
52 import org.apache.hadoop.fs.FSDataOutputStream;
53 import org.apache.hadoop.fs.FileStatus;
54 import org.apache.hadoop.fs.FileSystem;
55 import org.apache.hadoop.fs.FileUtil;
56 import org.apache.hadoop.fs.Path;
57 import org.apache.hadoop.fs.PathFilter;
58 import org.apache.hadoop.hbase.Cell;
59 import org.apache.hadoop.hbase.HBaseConfiguration;
60 import org.apache.hadoop.hbase.HBaseTestingUtility;
61 import org.apache.hadoop.hbase.HConstants;
62 import org.apache.hadoop.hbase.HRegionInfo;
63 import org.apache.hadoop.hbase.KeyValue;
64 import org.apache.hadoop.hbase.ServerName;
65 import org.apache.hadoop.hbase.TableName;
66 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
67 import org.apache.hadoop.hbase.protobuf.generated.WALProtos;
68 import org.apache.hadoop.hbase.protobuf.generated.ZooKeeperProtos.SplitLogTask.RecoveryMode;
69 import org.apache.hadoop.hbase.regionserver.HRegion;
70 import org.apache.hadoop.hbase.regionserver.wal.FaultySequenceFileLogReader;
71 import org.apache.hadoop.hbase.regionserver.wal.InstrumentedLogWriter;
72 import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader;
73 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
74 import org.apache.hadoop.hbase.security.User;
75 import org.apache.hadoop.hbase.testclassification.LargeTests;
76 import org.apache.hadoop.hbase.testclassification.RegionServerTests;
77 import org.apache.hadoop.hbase.util.Bytes;
78 import org.apache.hadoop.hbase.util.CancelableProgressable;
79 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
80 import org.apache.hadoop.hbase.util.FSUtils;
81 import org.apache.hadoop.hbase.util.Threads;
82 import org.apache.hadoop.hbase.wal.WAL.Entry;
83 import org.apache.hadoop.hbase.wal.WAL.Reader;
84 import org.apache.hadoop.hbase.wal.WALProvider.Writer;
85 import org.apache.hadoop.hbase.wal.WALSplitter.CorruptedLogFileException;
86 import org.apache.hadoop.hdfs.DFSTestUtil;
87 import org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException;
88 import org.apache.hadoop.ipc.RemoteException;
89 import org.junit.After;
90 import org.junit.AfterClass;
91 import org.junit.Before;
92 import org.junit.BeforeClass;
93 import org.junit.Rule;
94 import org.junit.Test;
95 import org.junit.experimental.categories.Category;
96 import org.junit.rules.TestName;
97 import org.mockito.Mockito;
98 import org.mockito.invocation.InvocationOnMock;
99 import org.mockito.stubbing.Answer;
100
101
102
103
104 @Category({RegionServerTests.class, LargeTests.class})
105 public class TestWALSplit {
106 {
107
108
109
110
111
112 }
113 private final static Log LOG = LogFactory.getLog(TestWALSplit.class);
114
115 private static Configuration conf;
116 private FileSystem fs;
117
118 protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
119
120 private Path HBASEDIR;
121 private Path HBASELOGDIR;
122 private Path WALDIR;
123 private Path OLDLOGDIR;
124 private Path CORRUPTDIR;
125 private Path TABLEDIR;
126
127 private static final int NUM_WRITERS = 10;
128 private static final int ENTRIES = 10;
129
130 private static final String FILENAME_BEING_SPLIT = "testfile";
131 private static final TableName TABLE_NAME =
132 TableName.valueOf("t1");
133 private static final byte[] FAMILY = "f1".getBytes();
134 private static final byte[] QUALIFIER = "q1".getBytes();
135 private static final byte[] VALUE = "v1".getBytes();
136 private static final String WAL_FILE_PREFIX = "wal.dat.";
137 private static List<String> REGIONS = new ArrayList<String>();
138 private static final String HBASE_SKIP_ERRORS = "hbase.hlog.split.skip.errors";
139 private static String ROBBER;
140 private static String ZOMBIE;
141 private static String [] GROUP = new String [] {"supergroup"};
142 private RecoveryMode mode;
143
144 static enum Corruptions {
145 INSERT_GARBAGE_ON_FIRST_LINE,
146 INSERT_GARBAGE_IN_THE_MIDDLE,
147 APPEND_GARBAGE,
148 TRUNCATE,
149 TRUNCATE_TRAILER
150 }
151
152 @BeforeClass
153 public static void setUpBeforeClass() throws Exception {
154 conf = TEST_UTIL.getConfiguration();
155 conf.setClass("hbase.regionserver.hlog.writer.impl",
156 InstrumentedLogWriter.class, Writer.class);
157
158 System.setProperty("hbase.tests.use.shortcircuit.reads", "false");
159
160 Map<String, String []> u2g_map = new HashMap<String, String []>(2);
161 ROBBER = User.getCurrent().getName() + "-robber";
162 ZOMBIE = User.getCurrent().getName() + "-zombie";
163 u2g_map.put(ROBBER, GROUP);
164 u2g_map.put(ZOMBIE, GROUP);
165 DFSTestUtil.updateConfWithFakeGroupMapping(conf, u2g_map);
166 conf.setInt("dfs.heartbeat.interval", 1);
167 TEST_UTIL.startMiniDFSCluster(2);
168 }
169
170 @AfterClass
171 public static void tearDownAfterClass() throws Exception {
172 TEST_UTIL.shutdownMiniDFSCluster();
173 }
174
175 @Rule
176 public TestName name = new TestName();
177 private WALFactory wals = null;
178
179 @Before
180 public void setUp() throws Exception {
181 LOG.info("Cleaning up cluster for new test.");
182 fs = TEST_UTIL.getDFSCluster().getFileSystem();
183 HBASEDIR = TEST_UTIL.createRootDir();
184 HBASELOGDIR = TEST_UTIL.createWALRootDir();
185 OLDLOGDIR = new Path(HBASELOGDIR, HConstants.HREGION_OLDLOGDIR_NAME);
186 CORRUPTDIR = new Path(HBASELOGDIR, HConstants.CORRUPT_DIR_NAME);
187 TABLEDIR = FSUtils.getTableDir(HBASEDIR, TABLE_NAME);
188 REGIONS.clear();
189 Collections.addAll(REGIONS, "bbb", "ccc");
190 InstrumentedLogWriter.activateFailure = false;
191 this.mode = (conf.getBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, false) ?
192 RecoveryMode.LOG_REPLAY : RecoveryMode.LOG_SPLITTING);
193 wals = new WALFactory(conf, null, name.getMethodName());
194 WALDIR = new Path(HBASELOGDIR, DefaultWALProvider.getWALDirectoryName(name.getMethodName()));
195
196 }
197
198 @After
199 public void tearDown() throws Exception {
200 try {
201 wals.close();
202 } catch(IOException exception) {
203
204 LOG.info("Ignoring an error while closing down our WALFactory. Fine for some tests, but if" +
205 " you see a failure look here.");
206 LOG.debug("exception details", exception);
207 } finally {
208 wals = null;
209 fs.delete(HBASEDIR, true);
210 fs.delete(HBASELOGDIR, true);
211 }
212 }
213
214
215
216
217
218
219
220 @Test (timeout=300000)
221 public void testLogCannotBeWrittenOnceParsed() throws IOException, InterruptedException {
222 final AtomicLong counter = new AtomicLong(0);
223 AtomicBoolean stop = new AtomicBoolean(false);
224
225 final String region = REGIONS.get(0);
226 final int numWriters = 3;
227 Thread zombie = new ZombieLastLogWriterRegionServer(counter, stop, region, numWriters);
228 try {
229 long startCount = counter.get();
230 zombie.start();
231
232 while (startCount == counter.get()) Threads.sleep(1);
233
234 Threads.sleep(1000);
235 final Configuration conf2 = HBaseConfiguration.create(this.conf);
236 final User robber = User.createUserForTesting(conf2, ROBBER, GROUP);
237 int count = robber.runAs(new PrivilegedExceptionAction<Integer>() {
238 @Override
239 public Integer run() throws Exception {
240 StringBuilder ls = new StringBuilder("Contents of WALDIR (").append(WALDIR)
241 .append("):\n");
242 for (FileStatus status : fs.listStatus(WALDIR)) {
243 ls.append("\t").append(status.toString()).append("\n");
244 }
245 LOG.debug(ls);
246 LOG.info("Splitting WALs out from under zombie. Expecting " + numWriters + " files.");
247 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf2, wals);
248 LOG.info("Finished splitting out from under zombie.");
249 Path[] logfiles = getLogForRegion(HBASEDIR, TABLE_NAME, region);
250 assertEquals("wrong number of split files for region", numWriters, logfiles.length);
251 int count = 0;
252 for (Path logfile: logfiles) {
253 count += countWAL(logfile);
254 }
255 return count;
256 }
257 });
258 LOG.info("zombie=" + counter.get() + ", robber=" + count);
259 assertTrue("The log file could have at most 1 extra log entry, but can't have less. " +
260 "Zombie could write " + counter.get() + " and logfile had only " + count,
261 counter.get() == count || counter.get() + 1 == count);
262 } finally {
263 stop.set(true);
264 zombie.interrupt();
265 Threads.threadDumpingIsAlive(zombie);
266 }
267 }
268
269
270
271
272
273
274
275 class ZombieLastLogWriterRegionServer extends Thread {
276 final AtomicLong editsCount;
277 final AtomicBoolean stop;
278 final int numOfWriters;
279
280
281
282 final String region;
283 final User user;
284
285 public ZombieLastLogWriterRegionServer(AtomicLong counter, AtomicBoolean stop,
286 final String region, final int writers)
287 throws IOException, InterruptedException {
288 super("ZombieLastLogWriterRegionServer");
289 setDaemon(true);
290 this.stop = stop;
291 this.editsCount = counter;
292 this.region = region;
293 this.user = User.createUserForTesting(conf, ZOMBIE, GROUP);
294 numOfWriters = writers;
295 }
296
297 @Override
298 public void run() {
299 try {
300 doWriting();
301 } catch (IOException e) {
302 LOG.warn(getName() + " Writer exiting " + e);
303 } catch (InterruptedException e) {
304 LOG.warn(getName() + " Writer exiting " + e);
305 }
306 }
307
308 private void doWriting() throws IOException, InterruptedException {
309 this.user.runAs(new PrivilegedExceptionAction<Object>() {
310 @Override
311 public Object run() throws Exception {
312
313
314 int walToKeepOpen = numOfWriters - 1;
315
316
317 Writer writer = null;
318 try {
319 writer = generateWALs(numOfWriters, ENTRIES, walToKeepOpen);
320 } catch (IOException e1) {
321 throw new RuntimeException("Failed", e1);
322 }
323
324 editsCount.addAndGet(numOfWriters * ENTRIES);
325 loop(writer);
326
327
328 try {
329 writer.close();
330 fail("Writing closing after parsing should give an error.");
331 } catch (IOException exception) {
332 LOG.debug("ignoring error when closing final writer.", exception);
333 }
334 return null;
335 }
336 });
337 }
338
339 private void loop(final Writer writer) {
340 byte [] regionBytes = Bytes.toBytes(this.region);
341 while (!stop.get()) {
342 try {
343 long seq = appendEntry(writer, TABLE_NAME, regionBytes,
344 ("r" + editsCount.get()).getBytes(), regionBytes, QUALIFIER, VALUE, 0);
345 long count = editsCount.incrementAndGet();
346 LOG.info(getName() + " sync count=" + count + ", seq=" + seq);
347 try {
348 Thread.sleep(1);
349 } catch (InterruptedException e) {
350
351 }
352 } catch (IOException ex) {
353 LOG.error(getName() + " ex " + ex.toString());
354 if (ex instanceof RemoteException) {
355 LOG.error("Juliet: got RemoteException " + ex.getMessage() +
356 " while writing " + (editsCount.get() + 1));
357 } else {
358 LOG.error(getName() + " failed to write....at " + editsCount.get());
359 fail("Failed to write " + editsCount.get());
360 }
361 break;
362 } catch (Throwable t) {
363 LOG.error(getName() + " HOW? " + t);
364 LOG.debug("exception details", t);
365 break;
366 }
367 }
368 LOG.info(getName() + " Writer exiting");
369 }
370 }
371
372
373
374
375
376 @Test (timeout=300000)
377 public void testRecoveredEditsPathForMeta() throws IOException {
378 byte [] encoded = HRegionInfo.FIRST_META_REGIONINFO.getEncodedNameAsBytes();
379 Path tdir = FSUtils.getTableDir(HBASEDIR, TableName.META_TABLE_NAME);
380 Path regiondir = new Path(tdir,
381 HRegionInfo.FIRST_META_REGIONINFO.getEncodedName());
382 fs.mkdirs(regiondir);
383 long now = System.currentTimeMillis();
384 Entry entry =
385 new Entry(new WALKey(encoded,
386 TableName.META_TABLE_NAME, 1, now, HConstants.DEFAULT_CLUSTER_ID),
387 new WALEdit());
388 Path p = WALSplitter.getRegionSplitEditsPath(entry,
389 FILENAME_BEING_SPLIT, conf);
390 String parentOfParent = p.getParent().getParent().getName();
391 assertEquals(parentOfParent, HRegionInfo.FIRST_META_REGIONINFO.getEncodedName());
392 }
393
394
395
396
397
398 @Test (timeout=300000)
399 public void testOldRecoveredEditsFileSidelined() throws IOException {
400 byte [] encoded = HRegionInfo.FIRST_META_REGIONINFO.getEncodedNameAsBytes();
401 Path tdir = FSUtils.getTableDir(HBASEDIR, TableName.META_TABLE_NAME);
402 Path regiondir = new Path(tdir,
403 HRegionInfo.FIRST_META_REGIONINFO.getEncodedName());
404 fs.mkdirs(regiondir);
405 long now = System.currentTimeMillis();
406 Entry entry =
407 new Entry(new WALKey(encoded,
408 TableName.META_TABLE_NAME, 1, now, HConstants.DEFAULT_CLUSTER_ID),
409 new WALEdit());
410 Path parent = WALSplitter.getRegionDirRecoveredEditsDir(regiondir);
411 assertEquals(parent.getName(), HConstants.RECOVERED_EDITS_DIR);
412 fs.createNewFile(parent);
413
414 Path p = WALSplitter.getRegionSplitEditsPath(entry,
415 FILENAME_BEING_SPLIT, conf);
416 String parentOfParent = p.getParent().getParent().getName();
417 assertEquals(parentOfParent, HRegionInfo.FIRST_META_REGIONINFO.getEncodedName());
418 WALFactory.createRecoveredEditsWriter(fs, p, conf).close();
419 }
420
421 private void useDifferentDFSClient() throws IOException {
422
423
424 fs.initialize(fs.getUri(), conf);
425 }
426
427 @Test (timeout=300000)
428 public void testSplitPreservesEdits() throws IOException{
429 final String REGION = "region__1";
430 REGIONS.clear();
431 REGIONS.add(REGION);
432
433 generateWALs(1, 10, -1, 0);
434 useDifferentDFSClient();
435 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
436 Path originalLog = (fs.listStatus(OLDLOGDIR))[0].getPath();
437 Path[] splitLog = getLogForRegion(HBASEDIR, TABLE_NAME, REGION);
438 assertEquals(1, splitLog.length);
439
440 assertTrue("edits differ after split", logsAreEqual(originalLog, splitLog[0]));
441 }
442
443 @Test (timeout=300000)
444 public void testSplitRemovesRegionEventsEdits() throws IOException{
445 final String REGION = "region__1";
446 REGIONS.clear();
447 REGIONS.add(REGION);
448
449 generateWALs(1, 10, -1, 100);
450 useDifferentDFSClient();
451 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
452 Path originalLog = (fs.listStatus(OLDLOGDIR))[0].getPath();
453 Path[] splitLog = getLogForRegion(HBASEDIR, TABLE_NAME, REGION);
454 assertEquals(1, splitLog.length);
455
456 assertFalse("edits differ after split", logsAreEqual(originalLog, splitLog[0]));
457
458 assertEquals(10, countWAL(splitLog[0]));
459 }
460
461
462 @Test (timeout=300000)
463 public void testSplitLeavesCompactionEventsEdits() throws IOException{
464 HRegionInfo hri = new HRegionInfo(TABLE_NAME);
465 REGIONS.clear();
466 REGIONS.add(hri.getEncodedName());
467 Path regionDir = new Path(FSUtils.getTableDir(HBASEDIR, TABLE_NAME), hri.getEncodedName());
468 LOG.info("Creating region directory: " + regionDir);
469 assertTrue(fs.mkdirs(regionDir));
470
471 Writer writer = generateWALs(1, 10, 0, 10);
472 String[] compactInputs = new String[]{"file1", "file2", "file3"};
473 String compactOutput = "file4";
474 appendCompactionEvent(writer, hri, compactInputs, compactOutput);
475 writer.close();
476
477 useDifferentDFSClient();
478 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
479
480 Path originalLog = (fs.listStatus(OLDLOGDIR))[0].getPath();
481
482 assertEquals(21, countWAL(originalLog));
483
484 Path[] splitLog = getLogForRegion(HBASEDIR, TABLE_NAME, hri.getEncodedName());
485 assertEquals(1, splitLog.length);
486
487 assertFalse("edits differ after split", logsAreEqual(originalLog, splitLog[0]));
488
489 assertEquals(11, countWAL(splitLog[0]));
490 }
491
492
493
494
495
496 private int splitAndCount(final int expectedFiles, final int expectedEntries)
497 throws IOException {
498 useDifferentDFSClient();
499 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
500 int result = 0;
501 for (String region : REGIONS) {
502 Path[] logfiles = getLogForRegion(HBASEDIR, TABLE_NAME, region);
503 assertEquals(expectedFiles, logfiles.length);
504 int count = 0;
505 for (Path logfile: logfiles) {
506 count += countWAL(logfile);
507 }
508 if (-1 != expectedEntries) {
509 assertEquals(expectedEntries, count);
510 }
511 result += count;
512 }
513 return result;
514 }
515
516 @Test (timeout=300000)
517 public void testEmptyLogFiles() throws IOException {
518 testEmptyLogFiles(true);
519 }
520
521 @Test (timeout=300000)
522 public void testEmptyOpenLogFiles() throws IOException {
523 testEmptyLogFiles(false);
524 }
525
526 private void testEmptyLogFiles(final boolean close) throws IOException {
527
528
529 fs.mkdirs(WALDIR);
530 injectEmptyFile(".empty", close);
531 generateWALs(Integer.MAX_VALUE);
532 injectEmptyFile("empty", close);
533 splitAndCount(NUM_WRITERS, NUM_WRITERS * ENTRIES);
534 }
535
536 @Test (timeout=300000)
537 public void testOpenZeroLengthReportedFileButWithDataGetsSplit() throws IOException {
538
539 generateWALs(5);
540 splitAndCount(NUM_WRITERS, NUM_WRITERS * ENTRIES);
541 }
542
543 @Test (timeout=300000)
544 public void testTralingGarbageCorruptionFileSkipErrorsPasses() throws IOException {
545 conf.setBoolean(HBASE_SKIP_ERRORS, true);
546 generateWALs(Integer.MAX_VALUE);
547 corruptWAL(new Path(WALDIR, WAL_FILE_PREFIX + "5"),
548 Corruptions.APPEND_GARBAGE, true);
549 splitAndCount(NUM_WRITERS, NUM_WRITERS * ENTRIES);
550 }
551
552 @Test (timeout=300000)
553 public void testFirstLineCorruptionLogFileSkipErrorsPasses() throws IOException {
554 conf.setBoolean(HBASE_SKIP_ERRORS, true);
555 generateWALs(Integer.MAX_VALUE);
556 corruptWAL(new Path(WALDIR, WAL_FILE_PREFIX + "5"),
557 Corruptions.INSERT_GARBAGE_ON_FIRST_LINE, true);
558 splitAndCount(NUM_WRITERS - 1, (NUM_WRITERS - 1) * ENTRIES);
559 }
560
561 @Test (timeout=300000)
562 public void testMiddleGarbageCorruptionSkipErrorsReadsHalfOfFile() throws IOException {
563 conf.setBoolean(HBASE_SKIP_ERRORS, true);
564 generateWALs(Integer.MAX_VALUE);
565 corruptWAL(new Path(WALDIR, WAL_FILE_PREFIX + "5"),
566 Corruptions.INSERT_GARBAGE_IN_THE_MIDDLE, false);
567
568
569
570 int goodEntries = (NUM_WRITERS - 1) * ENTRIES;
571 int firstHalfEntries = (int) Math.ceil(ENTRIES / 2) - 1;
572 int allRegionsCount = splitAndCount(NUM_WRITERS, -1);
573 assertTrue("The file up to the corrupted area hasn't been parsed",
574 REGIONS.size() * (goodEntries + firstHalfEntries) <= allRegionsCount);
575 }
576
577 @Test (timeout=300000)
578 public void testCorruptedFileGetsArchivedIfSkipErrors() throws IOException {
579 conf.setBoolean(HBASE_SKIP_ERRORS, true);
580 for (FaultySequenceFileLogReader.FailureType failureType :
581 FaultySequenceFileLogReader.FailureType.values()) {
582 final Set<String> walDirContents = splitCorruptWALs(failureType);
583 final Set<String> archivedLogs = new HashSet<String>();
584 final StringBuilder archived = new StringBuilder("Archived logs in CORRUPTDIR:");
585 for (FileStatus log : fs.listStatus(CORRUPTDIR)) {
586 archived.append("\n\t").append(log.toString());
587 archivedLogs.add(log.getPath().getName());
588 }
589 LOG.debug(archived.toString());
590 assertEquals(failureType.name() + ": expected to find all of our wals corrupt.",
591 walDirContents, archivedLogs);
592 }
593 }
594
595
596
597
598
599 private Set<String> splitCorruptWALs(final FaultySequenceFileLogReader.FailureType failureType)
600 throws IOException {
601 Class<?> backupClass = conf.getClass("hbase.regionserver.hlog.reader.impl",
602 Reader.class);
603 InstrumentedLogWriter.activateFailure = false;
604
605 try {
606 conf.setClass("hbase.regionserver.hlog.reader.impl",
607 FaultySequenceFileLogReader.class, Reader.class);
608 conf.set("faultysequencefilelogreader.failuretype", failureType.name());
609
610 try {
611 wals.shutdown();
612 } catch (IOException exception) {
613
614 LOG.debug("Ignoring problem closing WALFactory.", exception);
615 }
616 wals.close();
617 try {
618 for (FileStatus log : fs.listStatus(CORRUPTDIR)) {
619 fs.delete(log.getPath(), true);
620 }
621 } catch (FileNotFoundException exception) {
622 LOG.debug("no previous CORRUPTDIR to clean.");
623 }
624
625 wals = new WALFactory(conf, null, name.getMethodName());
626 generateWALs(-1);
627
628 final Set<String> walDirContents = new HashSet<String>();
629 for (FileStatus status : fs.listStatus(WALDIR)) {
630 walDirContents.add(status.getPath().getName());
631 }
632 useDifferentDFSClient();
633 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
634 return walDirContents;
635 } finally {
636 conf.setClass("hbase.regionserver.hlog.reader.impl", backupClass,
637 Reader.class);
638 }
639 }
640
641 @Test (timeout=300000, expected = IOException.class)
642 public void testTrailingGarbageCorruptionLogFileSkipErrorsFalseThrows()
643 throws IOException {
644 conf.setBoolean(HBASE_SKIP_ERRORS, false);
645 splitCorruptWALs(FaultySequenceFileLogReader.FailureType.BEGINNING);
646 }
647
648 @Test (timeout=300000)
649 public void testCorruptedLogFilesSkipErrorsFalseDoesNotTouchLogs()
650 throws IOException {
651 conf.setBoolean(HBASE_SKIP_ERRORS, false);
652 try {
653 splitCorruptWALs(FaultySequenceFileLogReader.FailureType.BEGINNING);
654 } catch (IOException e) {
655 LOG.debug("split with 'skip errors' set to 'false' correctly threw");
656 }
657 assertEquals("if skip.errors is false all files should remain in place",
658 NUM_WRITERS, fs.listStatus(WALDIR).length);
659 }
660
661 private void ignoreCorruption(final Corruptions corruption, final int entryCount,
662 final int expectedCount) throws IOException {
663 conf.setBoolean(HBASE_SKIP_ERRORS, false);
664
665 final String REGION = "region__1";
666 REGIONS.clear();
667 REGIONS.add(REGION);
668
669 Path c1 = new Path(WALDIR, WAL_FILE_PREFIX + "0");
670 generateWALs(1, entryCount, -1, 0);
671 corruptWAL(c1, corruption, true);
672
673 useDifferentDFSClient();
674 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
675
676 Path[] splitLog = getLogForRegion(HBASEDIR, TABLE_NAME, REGION);
677 assertEquals(1, splitLog.length);
678
679 int actualCount = 0;
680 Reader in = wals.createReader(fs, splitLog[0]);
681 @SuppressWarnings("unused")
682 Entry entry;
683 while ((entry = in.next()) != null) ++actualCount;
684 assertEquals(expectedCount, actualCount);
685 in.close();
686
687
688 FileStatus[] archivedLogs = fs.listStatus(CORRUPTDIR);
689 assertEquals(archivedLogs.length, 0);
690
691 }
692
693 @Test (timeout=300000)
694 public void testEOFisIgnored() throws IOException {
695 int entryCount = 10;
696 ignoreCorruption(Corruptions.TRUNCATE, entryCount, entryCount-1);
697 }
698
699 @Test (timeout=300000)
700 public void testCorruptWALTrailer() throws IOException {
701 int entryCount = 10;
702 ignoreCorruption(Corruptions.TRUNCATE_TRAILER, entryCount, entryCount);
703 }
704
705 @Test (timeout=300000)
706 public void testLogsGetArchivedAfterSplit() throws IOException {
707 conf.setBoolean(HBASE_SKIP_ERRORS, false);
708 generateWALs(-1);
709 useDifferentDFSClient();
710 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
711 FileStatus[] archivedLogs = fs.listStatus(OLDLOGDIR);
712 assertEquals("wrong number of files in the archive log", NUM_WRITERS, archivedLogs.length);
713 }
714
715 @Test (timeout=300000)
716 public void testSplit() throws IOException {
717 generateWALs(-1);
718 splitAndCount(NUM_WRITERS, NUM_WRITERS * ENTRIES);
719 }
720
721 @Test (timeout=300000)
722 public void testLogDirectoryShouldBeDeletedAfterSuccessfulSplit()
723 throws IOException {
724 generateWALs(-1);
725 useDifferentDFSClient();
726 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
727 FileStatus [] statuses = null;
728 try {
729 statuses = fs.listStatus(WALDIR);
730 if (statuses != null) {
731 fail("Files left in log dir: " +
732 Joiner.on(",").join(FileUtil.stat2Paths(statuses)));
733 }
734 } catch (FileNotFoundException e) {
735
736 }
737 }
738
739 @Test(timeout=300000, expected = IOException.class)
740 public void testSplitWillFailIfWritingToRegionFails() throws Exception {
741
742 Writer writer = generateWALs(4);
743 useDifferentDFSClient();
744
745 String region = "break";
746 Path regiondir = new Path(TABLEDIR, region);
747 fs.mkdirs(regiondir);
748
749 InstrumentedLogWriter.activateFailure = false;
750 appendEntry(writer, TABLE_NAME, Bytes.toBytes(region),
751 ("r" + 999).getBytes(), FAMILY, QUALIFIER, VALUE, 0);
752 writer.close();
753
754 try {
755 InstrumentedLogWriter.activateFailure = true;
756 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
757 } catch (IOException e) {
758 assertTrue(e.getMessage().
759 contains("This exception is instrumented and should only be thrown for testing"));
760 throw e;
761 } finally {
762 InstrumentedLogWriter.activateFailure = false;
763 }
764 }
765
766 @Test (timeout=300000)
767 public void testSplitDeletedRegion() throws IOException {
768 REGIONS.clear();
769 String region = "region_that_splits";
770 REGIONS.add(region);
771
772 generateWALs(1);
773 useDifferentDFSClient();
774
775 Path regiondir = new Path(TABLEDIR, region);
776 fs.delete(regiondir, true);
777 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
778 assertFalse(fs.exists(regiondir));
779 }
780
781 @Test (timeout=300000)
782 public void testIOEOnOutputThread() throws Exception {
783 conf.setBoolean(HBASE_SKIP_ERRORS, false);
784
785 generateWALs(-1);
786 useDifferentDFSClient();
787 FileStatus[] logfiles = fs.listStatus(WALDIR);
788 assertTrue("There should be some log file",
789 logfiles != null && logfiles.length > 0);
790
791
792
793 int largestLogFile = 0;
794 long largestSize = 0;
795 for (int i = 0; i < logfiles.length; i++) {
796 if (logfiles[i].getLen() > largestSize) {
797 largestLogFile = i;
798 largestSize = logfiles[i].getLen();
799 }
800 }
801 assertTrue("There should be some log greater than size 0.", 0 < largestSize);
802
803 WALSplitter logSplitter = new WALSplitter(wals,
804 conf, HBASEDIR, fs, null, null, this.mode) {
805 @Override
806 protected Writer createWriter(Path logfile) throws IOException {
807 Writer mockWriter = Mockito.mock(Writer.class);
808 Mockito.doThrow(new IOException("Injected")).when(
809 mockWriter).append(Mockito.<Entry>any());
810 return mockWriter;
811 }
812 };
813
814
815 final AtomicBoolean stop = new AtomicBoolean(false);
816 final Thread someOldThread = new Thread("Some-old-thread") {
817 @Override
818 public void run() {
819 while(!stop.get()) Threads.sleep(10);
820 }
821 };
822 someOldThread.setDaemon(true);
823 someOldThread.start();
824 final Thread t = new Thread("Background-thread-dumper") {
825 public void run() {
826 try {
827 Threads.threadDumpingIsAlive(someOldThread);
828 } catch (InterruptedException e) {
829 e.printStackTrace();
830 }
831 }
832 };
833 t.setDaemon(true);
834 t.start();
835 try {
836 logSplitter.splitLogFile(logfiles[largestLogFile], null);
837 fail("Didn't throw!");
838 } catch (IOException ioe) {
839 assertTrue(ioe.toString().contains("Injected"));
840 } finally {
841
842 stop.set(true);
843 }
844 }
845
846
847
848
849 private void retryOverHdfsProblem(final FileSystem spiedFs) throws Exception {
850 generateWALs(-1);
851 useDifferentDFSClient();
852
853 try {
854 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, spiedFs, conf, wals);
855 assertEquals(NUM_WRITERS, fs.listStatus(OLDLOGDIR).length);
856 assertFalse(fs.exists(WALDIR));
857 } catch (IOException e) {
858 fail("There shouldn't be any exception but: " + e.toString());
859 }
860 }
861
862
863 @Test (timeout=300000)
864 public void testMovedWALDuringRecovery() throws Exception {
865
866
867 FileSystem spiedFs = Mockito.spy(fs);
868
869
870 Mockito.doThrow(new LeaseExpiredException("Injected: File does not exist")).
871 when(spiedFs).append(Mockito.<Path>any());
872 retryOverHdfsProblem(spiedFs);
873 }
874
875 @Test (timeout=300000)
876 public void testRetryOpenDuringRecovery() throws Exception {
877 FileSystem spiedFs = Mockito.spy(fs);
878
879
880
881
882
883
884
885
886
887 Mockito.doAnswer(new Answer<FSDataInputStream>() {
888 private final String[] errors = new String[] {
889 "Cannot obtain block length", "Could not obtain the last block",
890 "Blocklist for " + OLDLOGDIR + " has changed"};
891 private int count = 0;
892
893 public FSDataInputStream answer(InvocationOnMock invocation) throws Throwable {
894 if (count < 3) {
895 throw new IOException(errors[count++]);
896 }
897 return (FSDataInputStream)invocation.callRealMethod();
898 }
899 }).when(spiedFs).open(Mockito.<Path>any(), Mockito.anyInt());
900 retryOverHdfsProblem(spiedFs);
901 }
902
903 @Test (timeout=300000)
904 public void testTerminationAskedByReporter() throws IOException, CorruptedLogFileException {
905 generateWALs(1, 10, -1);
906 FileStatus logfile = fs.listStatus(WALDIR)[0];
907 useDifferentDFSClient();
908
909 final AtomicInteger count = new AtomicInteger();
910
911 CancelableProgressable localReporter
912 = new CancelableProgressable() {
913 @Override
914 public boolean progress() {
915 count.getAndIncrement();
916 return false;
917 }
918 };
919
920 FileSystem spiedFs = Mockito.spy(fs);
921 Mockito.doAnswer(new Answer<FSDataInputStream>() {
922 public FSDataInputStream answer(InvocationOnMock invocation) throws Throwable {
923 Thread.sleep(1500);
924 return (FSDataInputStream)invocation.callRealMethod();
925 }
926 }).when(spiedFs).open(Mockito.<Path>any(), Mockito.anyInt());
927
928 try {
929 conf.setInt("hbase.splitlog.report.period", 1000);
930 boolean ret = WALSplitter.splitLogFile(
931 HBASEDIR, logfile, spiedFs, conf, localReporter, null, null, this.mode, wals);
932 assertFalse("Log splitting should failed", ret);
933 assertTrue(count.get() > 0);
934 } catch (IOException e) {
935 fail("There shouldn't be any exception but: " + e.toString());
936 } finally {
937
938 conf.setInt("hbase.splitlog.report.period", 59000);
939 }
940 }
941
942
943
944
945
946 @Test (timeout=300000)
947 public void testThreading() throws Exception {
948 doTestThreading(20000, 128*1024*1024, 0);
949 }
950
951
952
953
954
955 @Test (timeout=300000)
956 public void testThreadingSlowWriterSmallBuffer() throws Exception {
957 doTestThreading(200, 1024, 50);
958 }
959
960
961
962
963
964
965
966
967
968
969
970
971
972 private void doTestThreading(final int numFakeEdits,
973 final int bufferSize,
974 final int writerSlowness) throws Exception {
975
976 Configuration localConf = new Configuration(conf);
977 localConf.setInt("hbase.regionserver.hlog.splitlog.buffersize", bufferSize);
978
979
980 Path logPath = new Path(WALDIR, WAL_FILE_PREFIX + ".fake");
981 FSDataOutputStream out = fs.create(logPath);
982 out.close();
983
984
985 final List<String> regions = ImmutableList.of("r0", "r1", "r2", "r3", "r4");
986 makeRegionDirs(regions);
987
988
989 WALSplitter logSplitter = new WALSplitter(wals,
990 localConf, HBASEDIR, fs, null, null, this.mode) {
991
992
993 @Override
994 protected Writer createWriter(Path logfile) throws IOException {
995 Writer mockWriter = Mockito.mock(Writer.class);
996 Mockito.doAnswer(new Answer<Void>() {
997 int expectedIndex = 0;
998
999 @Override
1000 public Void answer(InvocationOnMock invocation) {
1001 if (writerSlowness > 0) {
1002 try {
1003 Thread.sleep(writerSlowness);
1004 } catch (InterruptedException ie) {
1005 Thread.currentThread().interrupt();
1006 }
1007 }
1008 Entry entry = (Entry) invocation.getArguments()[0];
1009 WALEdit edit = entry.getEdit();
1010 List<Cell> cells = edit.getCells();
1011 assertEquals(1, cells.size());
1012 Cell cell = cells.get(0);
1013
1014
1015 assertEquals(expectedIndex, Bytes.toInt(cell.getRowArray(), cell.getRowOffset(),
1016 cell.getRowLength()));
1017 expectedIndex++;
1018 return null;
1019 }
1020 }).when(mockWriter).append(Mockito.<Entry>any());
1021 return mockWriter;
1022 }
1023
1024
1025 @Override
1026 protected Reader getReader(Path curLogFile, CancelableProgressable reporter)
1027 throws IOException {
1028 Reader mockReader = Mockito.mock(Reader.class);
1029 Mockito.doAnswer(new Answer<Entry>() {
1030 int index = 0;
1031
1032 @Override
1033 public Entry answer(InvocationOnMock invocation) throws Throwable {
1034 if (index >= numFakeEdits) return null;
1035
1036
1037 int regionIdx = index % regions.size();
1038 byte region[] = new byte[] {(byte)'r', (byte) (0x30 + regionIdx)};
1039
1040 Entry ret = createTestEntry(TABLE_NAME, region,
1041 Bytes.toBytes((int)(index / regions.size())),
1042 FAMILY, QUALIFIER, VALUE, index);
1043 index++;
1044 return ret;
1045 }
1046 }).when(mockReader).next();
1047 return mockReader;
1048 }
1049 };
1050
1051 logSplitter.splitLogFile(fs.getFileStatus(logPath), null);
1052
1053
1054 Map<byte[], Long> outputCounts = logSplitter.outputSink.getOutputCounts();
1055 for (Map.Entry<byte[], Long> entry : outputCounts.entrySet()) {
1056 LOG.info("Got " + entry.getValue() + " output edits for region " +
1057 Bytes.toString(entry.getKey()));
1058 assertEquals((long)entry.getValue(), numFakeEdits / regions.size());
1059 }
1060 assertEquals("Should have as many outputs as regions", regions.size(), outputCounts.size());
1061 }
1062
1063
1064 @Test (timeout=300000)
1065 public void testSplitLogFileDeletedRegionDir() throws IOException {
1066 LOG.info("testSplitLogFileDeletedRegionDir");
1067 final String REGION = "region__1";
1068 REGIONS.clear();
1069 REGIONS.add(REGION);
1070
1071 generateWALs(1, 10, -1);
1072 useDifferentDFSClient();
1073
1074 Path regiondir = new Path(TABLEDIR, REGION);
1075 LOG.info("Region directory is" + regiondir);
1076 fs.delete(regiondir, true);
1077 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
1078 assertFalse(fs.exists(regiondir));
1079 }
1080
1081 @Test (timeout=300000)
1082 public void testSplitLogFileEmpty() throws IOException {
1083 LOG.info("testSplitLogFileEmpty");
1084
1085
1086 fs.mkdirs(WALDIR);
1087 injectEmptyFile(".empty", true);
1088 useDifferentDFSClient();
1089
1090 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
1091 Path tdir = FSUtils.getTableDir(HBASEDIR, TABLE_NAME);
1092 assertFalse(fs.exists(tdir));
1093
1094 assertEquals(0, countWAL(fs.listStatus(OLDLOGDIR)[0].getPath()));
1095 }
1096
1097 @Test (timeout=300000)
1098 public void testSplitLogFileMultipleRegions() throws IOException {
1099 LOG.info("testSplitLogFileMultipleRegions");
1100 generateWALs(1, 10, -1);
1101 splitAndCount(1, 10);
1102 }
1103
1104 @Test (timeout=300000)
1105 public void testSplitLogFileFirstLineCorruptionLog()
1106 throws IOException {
1107 conf.setBoolean(HBASE_SKIP_ERRORS, true);
1108 generateWALs(1, 10, -1);
1109 FileStatus logfile = fs.listStatus(WALDIR)[0];
1110
1111 corruptWAL(logfile.getPath(),
1112 Corruptions.INSERT_GARBAGE_ON_FIRST_LINE, true);
1113
1114 useDifferentDFSClient();
1115 WALSplitter.split(HBASEDIR, WALDIR, OLDLOGDIR, fs, conf, wals);
1116
1117 final Path corruptDir = new Path(FSUtils.getWALRootDir(conf), HConstants.CORRUPT_DIR_NAME);
1118 assertEquals(1, fs.listStatus(corruptDir).length);
1119 }
1120
1121
1122
1123
1124
1125 @Test (timeout=300000)
1126 public void testConcurrentSplitLogAndReplayRecoverEdit() throws IOException {
1127 LOG.info("testConcurrentSplitLogAndReplayRecoverEdit");
1128
1129 String regionName = "r0";
1130 final Path regiondir = new Path(TABLEDIR, regionName);
1131 REGIONS.clear();
1132 REGIONS.add(regionName);
1133 generateWALs(-1);
1134
1135 wals.getWAL(Bytes.toBytes(regionName), null);
1136 FileStatus[] logfiles = fs.listStatus(WALDIR);
1137 assertTrue("There should be some log file",
1138 logfiles != null && logfiles.length > 0);
1139
1140 WALSplitter logSplitter = new WALSplitter(wals,
1141 conf, HBASEDIR, fs, null, null, this.mode) {
1142 @Override
1143 protected Writer createWriter(Path logfile)
1144 throws IOException {
1145 Writer writer = wals.createRecoveredEditsWriter(this.fs, logfile);
1146
1147
1148
1149 NavigableSet<Path> files = WALSplitter.getSplitEditFilesSorted(fs, regiondir);
1150 if (files != null && !files.isEmpty()) {
1151 for (Path file : files) {
1152 if (!this.fs.delete(file, false)) {
1153 LOG.error("Failed delete of " + file);
1154 } else {
1155 LOG.debug("Deleted recovered.edits file=" + file);
1156 }
1157 }
1158 }
1159 return writer;
1160 }
1161 };
1162 try{
1163 logSplitter.splitLogFile(logfiles[0], null);
1164 } catch (IOException e) {
1165 LOG.info(e);
1166 fail("Throws IOException when spliting "
1167 + "log, it is most likely because writing file does not "
1168 + "exist which is caused by concurrent replayRecoveredEditsIfAny()");
1169 }
1170 if (fs.exists(CORRUPTDIR)) {
1171 if (fs.listStatus(CORRUPTDIR).length > 0) {
1172 fail("There are some corrupt logs, "
1173 + "it is most likely caused by concurrent replayRecoveredEditsIfAny()");
1174 }
1175 }
1176 }
1177
1178 private Writer generateWALs(int leaveOpen) throws IOException {
1179 return generateWALs(NUM_WRITERS, ENTRIES, leaveOpen, 0);
1180 }
1181
1182 private Writer generateWALs(int writers, int entries, int leaveOpen) throws IOException {
1183 return generateWALs(writers, entries, leaveOpen, 7);
1184 }
1185
1186 private void makeRegionDirs(List<String> regions) throws IOException {
1187 for (String region : regions) {
1188 LOG.debug("Creating dir for region " + region);
1189 fs.mkdirs(new Path(TABLEDIR, region));
1190 }
1191 }
1192
1193
1194
1195
1196
1197 private Writer generateWALs(int writers, int entries, int leaveOpen, int regionEvents) throws IOException {
1198 makeRegionDirs(REGIONS);
1199 fs.mkdirs(WALDIR);
1200 Writer [] ws = new Writer[writers];
1201 int seq = 0;
1202 int numRegionEventsAdded = 0;
1203 for (int i = 0; i < writers; i++) {
1204 ws[i] = wals.createWALWriter(fs, new Path(WALDIR, WAL_FILE_PREFIX + i));
1205 for (int j = 0; j < entries; j++) {
1206 int prefix = 0;
1207 for (String region : REGIONS) {
1208 String row_key = region + prefix++ + i + j;
1209 appendEntry(ws[i], TABLE_NAME, region.getBytes(), row_key.getBytes(), FAMILY, QUALIFIER,
1210 VALUE, seq++);
1211
1212 if (numRegionEventsAdded < regionEvents) {
1213 numRegionEventsAdded ++;
1214 appendRegionEvent(ws[i], region);
1215 }
1216 }
1217 }
1218 if (i != leaveOpen) {
1219 ws[i].close();
1220 LOG.info("Closing writer " + i);
1221 }
1222 }
1223 if (leaveOpen < 0 || leaveOpen >= writers) {
1224 return null;
1225 }
1226 return ws[leaveOpen];
1227 }
1228
1229
1230
1231 private Path[] getLogForRegion(Path rootdir, TableName table, String region)
1232 throws IOException {
1233 Path tdir = FSUtils.getTableDir(rootdir, table);
1234 @SuppressWarnings("deprecation")
1235 Path editsdir = WALSplitter.getRegionDirRecoveredEditsDir(HRegion.getRegionDir(tdir,
1236 Bytes.toString(region.getBytes())));
1237 FileStatus[] files = fs.listStatus(editsdir, new PathFilter() {
1238 @Override
1239 public boolean accept(Path p) {
1240 if (WALSplitter.isSequenceIdFile(p)) {
1241 return false;
1242 }
1243 return true;
1244 }
1245 });
1246 Path[] paths = new Path[files.length];
1247 for (int i = 0; i < files.length; i++) {
1248 paths[i] = files[i].getPath();
1249 }
1250 return paths;
1251 }
1252
1253 private void corruptWAL(Path path, Corruptions corruption, boolean close) throws IOException {
1254 FSDataOutputStream out;
1255 int fileSize = (int) fs.listStatus(path)[0].getLen();
1256
1257 FSDataInputStream in = fs.open(path);
1258 byte[] corrupted_bytes = new byte[fileSize];
1259 in.readFully(0, corrupted_bytes, 0, fileSize);
1260 in.close();
1261
1262 switch (corruption) {
1263 case APPEND_GARBAGE:
1264 fs.delete(path, false);
1265 out = fs.create(path);
1266 out.write(corrupted_bytes);
1267 out.write("-----".getBytes());
1268 closeOrFlush(close, out);
1269 break;
1270
1271 case INSERT_GARBAGE_ON_FIRST_LINE:
1272 fs.delete(path, false);
1273 out = fs.create(path);
1274 out.write(0);
1275 out.write(corrupted_bytes);
1276 closeOrFlush(close, out);
1277 break;
1278
1279 case INSERT_GARBAGE_IN_THE_MIDDLE:
1280 fs.delete(path, false);
1281 out = fs.create(path);
1282 int middle = (int) Math.floor(corrupted_bytes.length / 2);
1283 out.write(corrupted_bytes, 0, middle);
1284 out.write(0);
1285 out.write(corrupted_bytes, middle, corrupted_bytes.length - middle);
1286 closeOrFlush(close, out);
1287 break;
1288
1289 case TRUNCATE:
1290 fs.delete(path, false);
1291 out = fs.create(path);
1292 out.write(corrupted_bytes, 0, fileSize
1293 - (32 + ProtobufLogReader.PB_WAL_COMPLETE_MAGIC.length + Bytes.SIZEOF_INT));
1294 closeOrFlush(close, out);
1295 break;
1296
1297 case TRUNCATE_TRAILER:
1298 fs.delete(path, false);
1299 out = fs.create(path);
1300 out.write(corrupted_bytes, 0, fileSize - Bytes.SIZEOF_INT);
1301 closeOrFlush(close, out);
1302 break;
1303 }
1304 }
1305
1306 private void closeOrFlush(boolean close, FSDataOutputStream out)
1307 throws IOException {
1308 if (close) {
1309 out.close();
1310 } else {
1311 Method syncMethod = null;
1312 try {
1313 syncMethod = out.getClass().getMethod("hflush", new Class<?> []{});
1314 } catch (NoSuchMethodException e) {
1315 try {
1316 syncMethod = out.getClass().getMethod("sync", new Class<?> []{});
1317 } catch (NoSuchMethodException ex) {
1318 throw new IOException("This version of Hadoop supports " +
1319 "neither Syncable.sync() nor Syncable.hflush().");
1320 }
1321 }
1322 try {
1323 syncMethod.invoke(out, new Object[]{});
1324 } catch (Exception e) {
1325 throw new IOException(e);
1326 }
1327
1328 }
1329 }
1330
1331 private int countWAL(Path log) throws IOException {
1332 int count = 0;
1333 Reader in = wals.createReader(fs, log);
1334 while (in.next() != null) {
1335 count++;
1336 }
1337 in.close();
1338 return count;
1339 }
1340
1341 private static void appendCompactionEvent(Writer w, HRegionInfo hri, String[] inputs,
1342 String output) throws IOException {
1343 WALProtos.CompactionDescriptor.Builder desc = WALProtos.CompactionDescriptor.newBuilder();
1344 desc.setTableName(ByteString.copyFrom(hri.getTable().toBytes()))
1345 .setEncodedRegionName(ByteString.copyFrom(hri.getEncodedNameAsBytes()))
1346 .setRegionName(ByteString.copyFrom(hri.getRegionName()))
1347 .setFamilyName(ByteString.copyFrom(FAMILY))
1348 .setStoreHomeDir(hri.getEncodedName() + "/" + Bytes.toString(FAMILY))
1349 .addAllCompactionInput(Arrays.asList(inputs))
1350 .addCompactionOutput(output);
1351
1352 WALEdit edit = WALEdit.createCompaction(hri, desc.build());
1353 WALKey key = new WALKey(hri.getEncodedNameAsBytes(), TABLE_NAME, 1,
1354 EnvironmentEdgeManager.currentTime(), HConstants.DEFAULT_CLUSTER_ID);
1355 w.append(new Entry(key, edit));
1356 w.sync();
1357 }
1358
1359 private static void appendRegionEvent(Writer w, String region) throws IOException {
1360 WALProtos.RegionEventDescriptor regionOpenDesc = ProtobufUtil.toRegionEventDescriptor(
1361 WALProtos.RegionEventDescriptor.EventType.REGION_OPEN,
1362 TABLE_NAME.toBytes(),
1363 region.getBytes(),
1364 String.valueOf(region.hashCode()).getBytes(),
1365 1,
1366 ServerName.parseServerName("ServerName:9099"), ImmutableMap.<byte[], List<Path>>of());
1367 final long time = EnvironmentEdgeManager.currentTime();
1368 KeyValue kv = new KeyValue(region.getBytes(), WALEdit.METAFAMILY, WALEdit.REGION_EVENT,
1369 time, regionOpenDesc.toByteArray());
1370 final WALKey walKey = new WALKey(region.getBytes(), TABLE_NAME, 1, time,
1371 HConstants.DEFAULT_CLUSTER_ID);
1372 w.append(
1373 new Entry(walKey, new WALEdit().add(kv)));
1374 w.sync();
1375 }
1376
1377 public static long appendEntry(Writer writer, TableName table, byte[] region,
1378 byte[] row, byte[] family, byte[] qualifier,
1379 byte[] value, long seq)
1380 throws IOException {
1381 LOG.info(Thread.currentThread().getName() + " append");
1382 writer.append(createTestEntry(table, region, row, family, qualifier, value, seq));
1383 LOG.info(Thread.currentThread().getName() + " sync");
1384 writer.sync();
1385 return seq;
1386 }
1387
1388 private static Entry createTestEntry(
1389 TableName table, byte[] region,
1390 byte[] row, byte[] family, byte[] qualifier,
1391 byte[] value, long seq) {
1392 long time = System.nanoTime();
1393
1394 seq++;
1395 final KeyValue cell = new KeyValue(row, family, qualifier, time, KeyValue.Type.Put, value);
1396 WALEdit edit = new WALEdit();
1397 edit.add(cell);
1398 return new Entry(new WALKey(region, table, seq, time,
1399 HConstants.DEFAULT_CLUSTER_ID), edit);
1400 }
1401
1402 private void injectEmptyFile(String suffix, boolean closeFile)
1403 throws IOException {
1404 Writer writer = wals.createWALWriter(fs, new Path(WALDIR, WAL_FILE_PREFIX + suffix),
1405 conf);
1406 if (closeFile) writer.close();
1407 }
1408
1409 private boolean logsAreEqual(Path p1, Path p2) throws IOException {
1410 Reader in1, in2;
1411 in1 = wals.createReader(fs, p1);
1412 in2 = wals.createReader(fs, p2);
1413 Entry entry1;
1414 Entry entry2;
1415 while ((entry1 = in1.next()) != null) {
1416 entry2 = in2.next();
1417 if ((entry1.getKey().compareTo(entry2.getKey()) != 0) ||
1418 (!entry1.getEdit().toString().equals(entry2.getEdit().toString()))) {
1419 return false;
1420 }
1421 }
1422 in1.close();
1423 in2.close();
1424 return true;
1425 }
1426 }