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.regionserver.wal;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertNotNull;
24  import static org.junit.Assert.assertTrue;
25  
26  import java.io.EOFException;
27  import java.io.IOException;
28  import java.util.ArrayList;
29  import java.util.HashSet;
30  import java.util.List;
31  import java.util.Set;
32  import java.util.concurrent.atomic.AtomicBoolean;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.fs.FileSystem;
38  import org.apache.hadoop.fs.Path;
39  import org.apache.hadoop.hbase.Cell;
40  import org.apache.hadoop.hbase.HBaseTestingUtility;
41  import org.apache.hadoop.hbase.HColumnDescriptor;
42  import org.apache.hadoop.hbase.HConstants;
43  import org.apache.hadoop.hbase.HTableDescriptor;
44  import org.apache.hadoop.hbase.testclassification.LargeTests;
45  import org.apache.hadoop.hbase.MiniHBaseCluster;
46  import org.apache.hadoop.hbase.ServerName;
47  import org.apache.hadoop.hbase.TableName;
48  import org.apache.hadoop.hbase.client.Admin;
49  import org.apache.hadoop.hbase.client.Get;
50  import org.apache.hadoop.hbase.client.HTable;
51  import org.apache.hadoop.hbase.client.Put;
52  import org.apache.hadoop.hbase.client.Result;
53  import org.apache.hadoop.hbase.client.ResultScanner;
54  import org.apache.hadoop.hbase.client.Scan;
55  import org.apache.hadoop.hbase.client.Table;
56  import org.apache.hadoop.hbase.fs.HFileSystem;
57  import org.apache.hadoop.hbase.regionserver.HRegionServer;
58  import org.apache.hadoop.hbase.regionserver.Region;
59  import org.apache.hadoop.hbase.regionserver.Store;
60  import org.apache.hadoop.hbase.util.Bytes;
61  import org.apache.hadoop.hbase.util.FSUtils;
62  import org.apache.hadoop.hbase.util.JVMClusterUtil;
63  import org.apache.hadoop.hbase.util.Threads;
64  import org.apache.hadoop.hbase.wal.DefaultWALProvider;
65  import org.apache.hadoop.hbase.wal.WAL;
66  import org.apache.hadoop.hbase.wal.WALFactory;
67  import org.apache.hadoop.hdfs.MiniDFSCluster;
68  import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
69  import org.apache.hadoop.hdfs.server.datanode.DataNode;
70  import org.junit.After;
71  import org.junit.Assert;
72  import org.junit.Before;
73  import org.junit.BeforeClass;
74  import org.junit.Test;
75  import org.junit.experimental.categories.Category;
76  
77  /**
78   * Test log deletion as logs are rolled.
79   */
80  @Category(LargeTests.class)
81  public class TestLogRolling  {
82    private static final Log LOG = LogFactory.getLog(TestLogRolling.class);
83    private HRegionServer server;
84    private String tableName;
85    private byte[] value;
86    private FileSystem fs;
87    private MiniDFSCluster dfsCluster;
88    private Admin admin;
89    private MiniHBaseCluster cluster;
90    private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
91  
92    /**
93     * constructor
94     * @throws Exception
95     */
96    public TestLogRolling()  {
97      this.server = null;
98      this.tableName = null;
99  
100     String className = this.getClass().getName();
101     StringBuilder v = new StringBuilder(className);
102     while (v.length() < 1000) {
103       v.append(className);
104     }
105     this.value = Bytes.toBytes(v.toString());
106   }
107 
108   // Need to override this setup so we can edit the config before it gets sent
109   // to the HDFS & HBase cluster startup.
110   @BeforeClass
111   public static void setUpBeforeClass() throws Exception {
112     // TODO: testLogRollOnDatanodeDeath fails if short circuit reads are on under the hadoop2
113     // profile. See HBASE-9337 for related issues.
114     System.setProperty("hbase.tests.use.shortcircuit.reads", "false");
115 
116     /**** configuration for testLogRolling ****/
117     // Force a region split after every 768KB
118     TEST_UTIL.getConfiguration().setLong(HConstants.HREGION_MAX_FILESIZE, 768L * 1024L);
119 
120     // We roll the log after every 32 writes
121     TEST_UTIL.getConfiguration().setInt("hbase.regionserver.maxlogentries", 32);
122 
123     TEST_UTIL.getConfiguration().setInt("hbase.regionserver.logroll.errors.tolerated", 2);
124     TEST_UTIL.getConfiguration().setInt("hbase.rpc.timeout", 10 * 1000);
125 
126     // For less frequently updated regions flush after every 2 flushes
127     TEST_UTIL.getConfiguration().setInt("hbase.hregion.memstore.optionalflushcount", 2);
128 
129     // We flush the cache after every 8192 bytes
130     TEST_UTIL.getConfiguration().setInt(
131         HConstants.HREGION_MEMSTORE_FLUSH_SIZE, 8192);
132 
133     // Increase the amount of time between client retries
134     TEST_UTIL.getConfiguration().setLong("hbase.client.pause", 10 * 1000);
135 
136     // Reduce thread wake frequency so that other threads can get
137     // a chance to run.
138     TEST_UTIL.getConfiguration().setInt(HConstants.THREAD_WAKE_FREQUENCY, 2 * 1000);
139 
140    /**** configuration for testLogRollOnDatanodeDeath ****/
141    // make sure log.hflush() calls syncFs() to open a pipeline
142     TEST_UTIL.getConfiguration().setBoolean("dfs.support.append", true);
143    // lower the namenode & datanode heartbeat so the namenode
144    // quickly detects datanode failures
145     TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000);
146     TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1);
147     // the namenode might still try to choose the recently-dead datanode
148     // for a pipeline, so try to a new pipeline multiple times
149      TEST_UTIL.getConfiguration().setInt("dfs.client.block.write.retries", 30);
150     TEST_UTIL.getConfiguration().setInt("hbase.regionserver.hlog.tolerable.lowreplication", 2);
151     TEST_UTIL.getConfiguration().setInt("hbase.regionserver.hlog.lowreplication.rolllimit", 3);
152   }
153 
154   @Before
155   public void setUp() throws Exception {
156     TEST_UTIL.startMiniCluster(1, 1, 2);
157 
158     cluster = TEST_UTIL.getHBaseCluster();
159     dfsCluster = TEST_UTIL.getDFSCluster();
160     fs = TEST_UTIL.getTestFileSystem();
161     admin = TEST_UTIL.getHBaseAdmin();
162 
163     // disable region rebalancing (interferes with log watching)
164     cluster.getMaster().balanceSwitch(false);
165   }
166 
167   @After
168   public void tearDown() throws Exception  {
169     TEST_UTIL.shutdownMiniCluster();
170   }
171 
172   private void startAndWriteData() throws IOException, InterruptedException {
173     // When the hbase:meta table can be opened, the region servers are running
174     new HTable(TEST_UTIL.getConfiguration(), TableName.META_TABLE_NAME);
175     this.server = cluster.getRegionServerThreads().get(0).getRegionServer();
176 
177     Table table = createTestTable(this.tableName);
178 
179     server = TEST_UTIL.getRSForFirstRegionInTable(table.getName());
180     for (int i = 1; i <= 256; i++) {    // 256 writes should cause 8 log rolls
181       doPut(table, i);
182       if (i % 32 == 0) {
183         // After every 32 writes sleep to let the log roller run
184         try {
185           Thread.sleep(2000);
186         } catch (InterruptedException e) {
187           // continue
188         }
189       }
190     }
191   }
192 
193   /**
194    * Tests that log rolling doesn't hang when no data is written.
195    */
196   @Test(timeout=120000)
197   public void testLogRollOnNothingWritten() throws Exception {
198     final Configuration conf = TEST_UTIL.getConfiguration();
199     final WALFactory wals = new WALFactory(conf, null,
200         ServerName.valueOf("test.com",8080, 1).toString());
201     final WAL newLog = wals.getWAL(new byte[]{});
202     try {
203       // Now roll the log before we write anything.
204       newLog.rollWriter(true);
205     } finally {
206       wals.close();
207     }
208   }
209 
210   /**
211    * Tests that logs are deleted
212    * @throws IOException
213    * @throws org.apache.hadoop.hbase.regionserver.wal.FailedLogCloseException
214    */
215   @Test
216   public void testLogRolling() throws Exception {
217     this.tableName = getName();
218       // TODO: Why does this write data take for ever?
219       startAndWriteData();
220     final WAL log = server.getWAL(null);
221     LOG.info("after writing there are " + DefaultWALProvider.getNumRolledLogFiles(log) +
222         " log files");
223 
224       // flush all regions
225       for (Region r: server.getOnlineRegionsLocalContext()) {
226         r.flush(true);
227       }
228 
229       // Now roll the log
230       log.rollWriter();
231 
232     int count = DefaultWALProvider.getNumRolledLogFiles(log);
233     LOG.info("after flushing all regions and rolling logs there are " + count + " log files");
234       assertTrue(("actual count: " + count), count <= 2);
235   }
236 
237   private static String getName() {
238     return "TestLogRolling";
239   }
240 
241   void writeData(Table table, int rownum) throws IOException {
242     doPut(table, rownum);
243 
244     // sleep to let the log roller run (if it needs to)
245     try {
246       Thread.sleep(2000);
247     } catch (InterruptedException e) {
248       // continue
249     }
250   }
251 
252   void validateData(Table table, int rownum) throws IOException {
253     String row = "row" + String.format("%1$04d", rownum);
254     Get get = new Get(Bytes.toBytes(row));
255     get.addFamily(HConstants.CATALOG_FAMILY);
256     Result result = table.get(get);
257     assertTrue(result.size() == 1);
258     assertTrue(Bytes.equals(value,
259                 result.getValue(HConstants.CATALOG_FAMILY, null)));
260     LOG.info("Validated row " + row);
261   }
262 
263   void batchWriteAndWait(Table table, final FSHLog log, int start, boolean expect, int timeout)
264       throws IOException {
265     for (int i = 0; i < 10; i++) {
266       Put put = new Put(Bytes.toBytes("row"
267           + String.format("%1$04d", (start + i))));
268       put.add(HConstants.CATALOG_FAMILY, null, value);
269       table.put(put);
270     }
271     Put tmpPut = new Put(Bytes.toBytes("tmprow"));
272     tmpPut.add(HConstants.CATALOG_FAMILY, null, value);
273     long startTime = System.currentTimeMillis();
274     long remaining = timeout;
275     while (remaining > 0) {
276       if (log.isLowReplicationRollEnabled() == expect) {
277         break;
278       } else {
279         // Trigger calling FSHlog#checkLowReplication()
280         table.put(tmpPut);
281         try {
282           Thread.sleep(200);
283         } catch (InterruptedException e) {
284           // continue
285         }
286         remaining = timeout - (System.currentTimeMillis() - startTime);
287       }
288     }
289   }
290 
291   /**
292    * Tests that logs are rolled upon detecting datanode death
293    * Requires an HDFS jar with HDFS-826 & syncFs() support (HDFS-200)
294    */
295   @Test
296   public void testLogRollOnDatanodeDeath() throws Exception {
297     TEST_UTIL.ensureSomeRegionServersAvailable(2);
298     assertTrue("This test requires WAL file replication set to 2.",
299       fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()) == 2);
300     LOG.info("Replication=" +
301       fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()));
302 
303     this.server = cluster.getRegionServer(0);
304 
305     // Create the test table and open it
306     HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(getName()));
307     desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
308 
309     admin.createTable(desc);
310     Table table = TEST_UTIL.getConnection().getTable(desc.getTableName());
311     assertTrue(((HTable) table).isAutoFlush());
312 
313     server = TEST_UTIL.getRSForFirstRegionInTable(desc.getTableName());
314     final FSHLog log = (FSHLog) server.getWAL(null);
315     final AtomicBoolean lowReplicationHookCalled = new AtomicBoolean(false);
316 
317     log.registerWALActionsListener(new WALActionsListener.Base() {
318       @Override
319       public void logRollRequested(boolean lowReplication) {
320         if (lowReplication) {
321           lowReplicationHookCalled.lazySet(true);
322         }
323       }
324     });
325 
326     // don't run this test without append support (HDFS-200 & HDFS-142)
327     assertTrue("Need append support for this test", FSUtils
328         .isAppendSupported(TEST_UTIL.getConfiguration()));
329 
330     // add up the datanode count, to ensure proper replication when we kill 1
331     // This function is synchronous; when it returns, the dfs cluster is active
332     // We start 3 servers and then stop 2 to avoid a directory naming conflict
333     //  when we stop/start a namenode later, as mentioned in HBASE-5163
334     List<DataNode> existingNodes = dfsCluster.getDataNodes();
335     int numDataNodes = 3;
336     dfsCluster.startDataNodes(TEST_UTIL.getConfiguration(), numDataNodes, true,
337         null, null);
338     List<DataNode> allNodes = dfsCluster.getDataNodes();
339     for (int i = allNodes.size()-1; i >= 0; i--) {
340       if (existingNodes.contains(allNodes.get(i))) {
341         dfsCluster.stopDataNode( i );
342       }
343     }
344 
345     assertTrue("DataNodes " + dfsCluster.getDataNodes().size() +
346         " default replication " +
347         fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()),
348     dfsCluster.getDataNodes().size() >=
349       fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()) + 1);
350 
351     writeData(table, 2);
352 
353     long curTime = System.currentTimeMillis();
354     LOG.info("log.getCurrentFileName(): " + log.getCurrentFileName());
355     long oldFilenum = DefaultWALProvider.extractFileNumFromWAL(log);
356     assertTrue("Log should have a timestamp older than now",
357         curTime > oldFilenum && oldFilenum != -1);
358 
359     assertTrue("The log shouldn't have rolled yet",
360         oldFilenum == DefaultWALProvider.extractFileNumFromWAL(log));
361     final DatanodeInfo[] pipeline = log.getPipeLine();
362     assertTrue(pipeline.length ==
363         fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()));
364 
365     // kill a datanode in the pipeline to force a log roll on the next sync()
366     // This function is synchronous, when it returns the node is killed.
367     assertTrue(dfsCluster.stopDataNode(pipeline[0].getName()) != null);
368 
369     // this write should succeed, but trigger a log roll
370     writeData(table, 2);
371     long newFilenum = DefaultWALProvider.extractFileNumFromWAL(log);
372 
373     assertTrue("Missing datanode should've triggered a log roll",
374         newFilenum > oldFilenum && newFilenum > curTime);
375 
376     assertTrue("The log rolling hook should have been called with the low replication flag",
377         lowReplicationHookCalled.get());
378 
379     // write some more log data (this should use a new hdfs_out)
380     writeData(table, 3);
381     assertTrue("The log should not roll again.",
382         DefaultWALProvider.extractFileNumFromWAL(log) == newFilenum);
383     // kill another datanode in the pipeline, so the replicas will be lower than
384     // the configured value 2.
385     assertTrue(dfsCluster.stopDataNode(pipeline[1].getName()) != null);
386 
387     batchWriteAndWait(table, log, 3, false, 14000);
388     int replication = log.getLogReplication();
389     assertTrue("LowReplication Roller should've been disabled, current replication="
390             + replication, !log.isLowReplicationRollEnabled());
391 
392     dfsCluster
393         .startDataNodes(TEST_UTIL.getConfiguration(), 1, true, null, null);
394 
395     // Force roll writer. The new log file will have the default replications,
396     // and the LowReplication Roller will be enabled.
397     log.rollWriter(true);
398     batchWriteAndWait(table, log, 13, true, 10000);
399     replication = log.getLogReplication();
400     assertTrue("New log file should have the default replication instead of " +
401       replication,
402       replication == fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()));
403     assertTrue("LowReplication Roller should've been enabled", log.isLowReplicationRollEnabled());
404   }
405 
406   /**
407    * Test that WAL is rolled when all data nodes in the pipeline have been
408    * restarted.
409    * @throws Exception
410    */
411   @Test
412   public void testLogRollOnPipelineRestart() throws Exception {
413     LOG.info("Starting testLogRollOnPipelineRestart");
414     assertTrue("This test requires WAL file replication.",
415       fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()) > 1);
416     LOG.info("Replication=" +
417       fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()));
418     // When the hbase:meta table can be opened, the region servers are running
419     Table t = new HTable(TEST_UTIL.getConfiguration(), TableName.META_TABLE_NAME);
420     try {
421       this.server = cluster.getRegionServer(0);
422 
423       // Create the test table and open it
424       HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(getName()));
425       desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
426 
427       admin.createTable(desc);
428       Table table = new HTable(TEST_UTIL.getConfiguration(), desc.getTableName());
429 
430       server = TEST_UTIL.getRSForFirstRegionInTable(desc.getTableName());
431       final WAL log = server.getWAL(null);
432       final List<Path> paths = new ArrayList<Path>();
433       final List<Integer> preLogRolledCalled = new ArrayList<Integer>();
434 
435       paths.add(DefaultWALProvider.getCurrentFileName(log));
436       log.registerWALActionsListener(new WALActionsListener.Base() {
437 
438         @Override
439         public void preLogRoll(Path oldFile, Path newFile)  {
440           LOG.debug("preLogRoll: oldFile="+oldFile+" newFile="+newFile);
441           preLogRolledCalled.add(new Integer(1));
442         }
443         @Override
444         public void postLogRoll(Path oldFile, Path newFile) {
445           paths.add(newFile);
446         }
447       });
448 
449       // don't run this test without append support (HDFS-200 & HDFS-142)
450       assertTrue("Need append support for this test", FSUtils
451           .isAppendSupported(TEST_UTIL.getConfiguration()));
452 
453       writeData(table, 1002);
454 
455       long curTime = System.currentTimeMillis();
456       LOG.info("log.getCurrentFileName()): " + DefaultWALProvider.getCurrentFileName(log));
457       long oldFilenum = DefaultWALProvider.extractFileNumFromWAL(log);
458       assertTrue("Log should have a timestamp older than now",
459           curTime > oldFilenum && oldFilenum != -1);
460 
461       assertTrue("The log shouldn't have rolled yet", oldFilenum ==
462           DefaultWALProvider.extractFileNumFromWAL(log));
463 
464       // roll all datanodes in the pipeline
465       dfsCluster.restartDataNodes();
466       Thread.sleep(1000);
467       dfsCluster.waitActive();
468       LOG.info("Data Nodes restarted");
469       validateData(table, 1002);
470 
471       // this write should succeed, but trigger a log roll
472       writeData(table, 1003);
473       long newFilenum = DefaultWALProvider.extractFileNumFromWAL(log);
474 
475       assertTrue("Missing datanode should've triggered a log roll",
476           newFilenum > oldFilenum && newFilenum > curTime);
477       validateData(table, 1003);
478 
479       writeData(table, 1004);
480 
481       // roll all datanode again
482       dfsCluster.restartDataNodes();
483       Thread.sleep(1000);
484       dfsCluster.waitActive();
485       LOG.info("Data Nodes restarted");
486       validateData(table, 1004);
487 
488       // this write should succeed, but trigger a log roll
489       writeData(table, 1005);
490 
491       // force a log roll to read back and verify previously written logs
492       log.rollWriter(true);
493       assertTrue("preLogRolledCalled has size of " + preLogRolledCalled.size(),
494           preLogRolledCalled.size() >= 1);
495 
496       // read back the data written
497       Set<String> loggedRows = new HashSet<String>();
498       FSUtils fsUtils = FSUtils.getInstance(fs, TEST_UTIL.getConfiguration());
499       for (Path p : paths) {
500         LOG.debug("recovering lease for " + p);
501         fsUtils.recoverFileLease(((HFileSystem)fs).getBackingFs(), p,
502           TEST_UTIL.getConfiguration(), null);
503 
504         LOG.debug("Reading WAL "+FSUtils.getPath(p));
505         WAL.Reader reader = null;
506         try {
507           reader = WALFactory.createReader(fs, p, TEST_UTIL.getConfiguration());
508           WAL.Entry entry;
509           while ((entry = reader.next()) != null) {
510             LOG.debug("#"+entry.getKey().getLogSeqNum()+": "+entry.getEdit().getCells());
511             for (Cell cell : entry.getEdit().getCells()) {
512               loggedRows.add(Bytes.toStringBinary(cell.getRow()));
513             }
514           }
515         } catch (EOFException e) {
516           LOG.debug("EOF reading file "+FSUtils.getPath(p));
517         } finally {
518           if (reader != null) reader.close();
519         }
520       }
521 
522       // verify the written rows are there
523       assertTrue(loggedRows.contains("row1002"));
524       assertTrue(loggedRows.contains("row1003"));
525       assertTrue(loggedRows.contains("row1004"));
526       assertTrue(loggedRows.contains("row1005"));
527 
528       // flush all regions
529       for (Region r: server.getOnlineRegionsLocalContext()) {
530         r.flush(true);
531       }
532 
533       ResultScanner scanner = table.getScanner(new Scan());
534       try {
535         for (int i=2; i<=5; i++) {
536           Result r = scanner.next();
537           assertNotNull(r);
538           assertFalse(r.isEmpty());
539           assertEquals("row100"+i, Bytes.toString(r.getRow()));
540         }
541       } finally {
542         scanner.close();
543       }
544 
545       // verify that no region servers aborted
546       for (JVMClusterUtil.RegionServerThread rsThread:
547         TEST_UTIL.getHBaseCluster().getRegionServerThreads()) {
548         assertFalse(rsThread.getRegionServer().isAborted());
549       }
550     } finally {
551       if (t != null) t.close();
552     }
553   }
554 
555   /**
556    * Tests that logs are deleted when some region has a compaction
557    * record in WAL and no other records. See HBASE-8597.
558    */
559   @Test
560   public void testCompactionRecordDoesntBlockRolling() throws Exception {
561     Table table = null;
562     Table table2 = null;
563 
564     // When the hbase:meta table can be opened, the region servers are running
565     Table t = new HTable(TEST_UTIL.getConfiguration(), TableName.META_TABLE_NAME);
566     try {
567       table = createTestTable(getName());
568       table2 = createTestTable(getName() + "1");
569 
570       server = TEST_UTIL.getRSForFirstRegionInTable(table.getName());
571       final WAL log = server.getWAL(null);
572       Region region = server.getOnlineRegions(table2.getName()).get(0);
573       Store s = region.getStore(HConstants.CATALOG_FAMILY);
574 
575       //have to flush namespace to ensure it doesn't affect wall tests
576       admin.flush(TableName.NAMESPACE_TABLE_NAME);
577 
578       // Put some stuff into table2, to make sure we have some files to compact.
579       for (int i = 1; i <= 2; ++i) {
580         doPut(table2, i);
581         admin.flush(table2.getName());
582       }
583       doPut(table2, 3); // don't flush yet, or compaction might trigger before we roll WAL
584       assertEquals("Should have no WAL after initial writes", 0,
585           DefaultWALProvider.getNumRolledLogFiles(log));
586       assertEquals(2, s.getStorefilesCount());
587 
588       // Roll the log and compact table2, to have compaction record in the 2nd WAL.
589       log.rollWriter();
590       assertEquals("Should have WAL; one table is not flushed", 1,
591           DefaultWALProvider.getNumRolledLogFiles(log));
592       admin.flush(table2.getName());
593       region.compact(false);
594       // Wait for compaction in case if flush triggered it before us.
595       Assert.assertNotNull(s);
596       for (int waitTime = 3000; s.getStorefilesCount() > 1 && waitTime > 0; waitTime -= 200) {
597         Threads.sleepWithoutInterrupt(200);
598       }
599       assertEquals("Compaction didn't happen", 1, s.getStorefilesCount());
600 
601       // Write some value to the table so the WAL cannot be deleted until table is flushed.
602       doPut(table, 0); // Now 2nd WAL will have compaction record for table2 and put for table.
603       log.rollWriter(); // 1st WAL deleted, 2nd not deleted yet.
604       assertEquals("Should have WAL; one table is not flushed", 1,
605           DefaultWALProvider.getNumRolledLogFiles(log));
606 
607       // Flush table to make latest WAL obsolete; write another record, and roll again.
608       admin.flush(table.getName());
609       doPut(table, 1);
610       log.rollWriter(); // Now 2nd WAL is deleted and 3rd is added.
611       assertEquals("Should have 1 WALs at the end", 1,
612           DefaultWALProvider.getNumRolledLogFiles(log));
613     } finally {
614       if (t != null) t.close();
615       if (table != null) table.close();
616       if (table2 != null) table2.close();
617     }
618   }
619 
620   private void doPut(Table table, int i) throws IOException {
621     Put put = new Put(Bytes.toBytes("row" + String.format("%1$04d", i)));
622     put.add(HConstants.CATALOG_FAMILY, null, value);
623     table.put(put);
624   }
625 
626   private Table createTestTable(String tableName) throws IOException {
627     // Create the test table and open it
628     HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
629     desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
630     admin.createTable(desc);
631     return new HTable(TEST_UTIL.getConfiguration(), desc.getTableName());
632   }
633 }
634