View Javadoc

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