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  import static org.junit.Assert.fail;
26  
27  import java.io.IOException;
28  import java.util.ArrayList;
29  import java.util.Comparator;
30  import java.util.HashMap;
31  import java.util.List;
32  import java.util.Map;
33  import java.util.Set;
34  import java.util.UUID;
35  import java.util.concurrent.atomic.AtomicLong;
36  
37  import org.apache.commons.lang.mutable.MutableBoolean;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.apache.hadoop.conf.Configuration;
41  import org.apache.hadoop.fs.FileStatus;
42  import org.apache.hadoop.fs.FileSystem;
43  import org.apache.hadoop.fs.Path;
44  import org.apache.hadoop.hbase.CellScanner;
45  import org.apache.hadoop.hbase.Coprocessor;
46  import org.apache.hadoop.hbase.HBaseConfiguration;
47  import org.apache.hadoop.hbase.HBaseTestingUtility;
48  import org.apache.hadoop.hbase.HColumnDescriptor;
49  import org.apache.hadoop.hbase.HConstants;
50  import org.apache.hadoop.hbase.HRegionInfo;
51  import org.apache.hadoop.hbase.HTableDescriptor;
52  import org.apache.hadoop.hbase.KeyValue;
53  import org.apache.hadoop.hbase.testclassification.MediumTests;
54  import org.apache.hadoop.hbase.TableName;
55  import org.apache.hadoop.hbase.client.Get;
56  import org.apache.hadoop.hbase.client.Put;
57  import org.apache.hadoop.hbase.client.Result;
58  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
59  import org.apache.hadoop.hbase.coprocessor.SampleRegionWALObserver;
60  import org.apache.hadoop.hbase.regionserver.HRegion;
61  import org.apache.hadoop.hbase.util.Bytes;
62  import org.apache.hadoop.hbase.util.EnvironmentEdge;
63  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
64  import org.apache.hadoop.hbase.util.FSUtils;
65  import org.apache.hadoop.hbase.util.Threads;
66  import org.apache.hadoop.hbase.wal.DefaultWALProvider;
67  import org.apache.hadoop.hbase.wal.WAL;
68  import org.apache.hadoop.hbase.wal.WALKey;
69  import org.junit.After;
70  import org.junit.AfterClass;
71  import org.junit.Before;
72  import org.junit.BeforeClass;
73  import org.junit.Rule;
74  import org.junit.Test;
75  import org.junit.experimental.categories.Category;
76  import org.junit.rules.TestName;
77  
78  /**
79   * Provides FSHLog test cases.
80   */
81  @Category(MediumTests.class)
82  public class TestFSHLog {
83    protected static final Log LOG = LogFactory.getLog(TestFSHLog.class);
84  
85    protected static Configuration conf;
86    protected static FileSystem fs;
87    protected static Path dir;
88    protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
89  
90    @Rule
91    public final TestName currentTest = new TestName();
92  
93    @Before
94    public void setUp() throws Exception {
95      FileStatus[] entries = fs.listStatus(new Path("/"));
96      for (FileStatus dir : entries) {
97        fs.delete(dir.getPath(), true);
98      }
99      final Path hbaseDir = TEST_UTIL.createRootDir();
100     dir = new Path(hbaseDir, currentTest.getMethodName());
101   }
102 
103   @After
104   public void tearDown() throws Exception {
105   }
106 
107   @BeforeClass
108   public static void setUpBeforeClass() throws Exception {
109     // Make block sizes small.
110     TEST_UTIL.getConfiguration().setInt("dfs.blocksize", 1024 * 1024);
111     // quicker heartbeat interval for faster DN death notification
112     TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000);
113     TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1);
114     TEST_UTIL.getConfiguration().setInt("dfs.client.socket-timeout", 5000);
115 
116     // faster failover with cluster.shutdown();fs.close() idiom
117     TEST_UTIL.getConfiguration()
118         .setInt("hbase.ipc.client.connect.max.retries", 1);
119     TEST_UTIL.getConfiguration().setInt(
120         "dfs.client.block.recovery.retries", 1);
121     TEST_UTIL.getConfiguration().setInt(
122       "hbase.ipc.client.connection.maxidletime", 500);
123     TEST_UTIL.getConfiguration().set(CoprocessorHost.WAL_COPROCESSOR_CONF_KEY,
124         SampleRegionWALObserver.class.getName());
125     TEST_UTIL.startMiniDFSCluster(3);
126 
127     conf = TEST_UTIL.getConfiguration();
128     fs = TEST_UTIL.getDFSCluster().getFileSystem();
129   }
130 
131   @AfterClass
132   public static void tearDownAfterClass() throws Exception {
133     TEST_UTIL.shutdownMiniCluster();
134   }
135 
136   /**
137    * A loaded WAL coprocessor won't break existing WAL test cases.
138    */
139   @Test
140   public void testWALCoprocessorLoaded() throws Exception {
141     // test to see whether the coprocessor is loaded or not.
142     FSHLog log = null;
143     try {
144       log = new FSHLog(fs, FSUtils.getRootDir(conf), dir.toString(),
145           HConstants.HREGION_OLDLOGDIR_NAME, conf, null, true, null, null);
146       WALCoprocessorHost host = log.getCoprocessorHost();
147       Coprocessor c = host.findCoprocessor(SampleRegionWALObserver.class.getName());
148       assertNotNull(c);
149     } finally {
150       if (log != null) {
151         log.close();
152       }
153     }
154   }
155 
156   protected void addEdits(WAL log, HRegionInfo hri, HTableDescriptor htd, int times,
157       AtomicLong sequenceId) throws IOException {
158     final byte[] row = Bytes.toBytes("row");
159     for (int i = 0; i < times; i++) {
160       long timestamp = System.currentTimeMillis();
161       WALEdit cols = new WALEdit();
162       cols.add(new KeyValue(row, row, row, timestamp, row));
163       log.append(htd, hri, new WALKey(hri.getEncodedNameAsBytes(), htd.getTableName(), timestamp),
164         cols, sequenceId, true, null);
165     }
166     log.sync();
167   }
168 
169   /**
170    * helper method to simulate region flush for a WAL.
171    * @param wal
172    * @param regionEncodedName
173    */
174   protected void flushRegion(WAL wal, byte[] regionEncodedName, Set<byte[]> flushedFamilyNames) {
175     wal.startCacheFlush(regionEncodedName, flushedFamilyNames);
176     wal.completeCacheFlush(regionEncodedName);
177   }
178 
179   /**
180    * tests the log comparator. Ensure that we are not mixing meta logs with non-meta logs (throws
181    * exception if we do). Comparison is based on the timestamp present in the wal name.
182    * @throws Exception
183    */
184   @Test 
185   public void testWALComparator() throws Exception {
186     FSHLog wal1 = null;
187     FSHLog walMeta = null;
188     try {
189       wal1 = new FSHLog(fs, FSUtils.getRootDir(conf), dir.toString(),
190           HConstants.HREGION_OLDLOGDIR_NAME, conf, null, true, null, null);
191       LOG.debug("Log obtained is: " + wal1);
192       Comparator<Path> comp = wal1.LOG_NAME_COMPARATOR;
193       Path p1 = wal1.computeFilename(11);
194       Path p2 = wal1.computeFilename(12);
195       // comparing with itself returns 0
196       assertTrue(comp.compare(p1, p1) == 0);
197       // comparing with different filenum.
198       assertTrue(comp.compare(p1, p2) < 0);
199       walMeta = new FSHLog(fs, FSUtils.getRootDir(conf), dir.toString(),
200           HConstants.HREGION_OLDLOGDIR_NAME, conf, null, true, null,
201           DefaultWALProvider.META_WAL_PROVIDER_ID);
202       Comparator<Path> compMeta = walMeta.LOG_NAME_COMPARATOR;
203 
204       Path p1WithMeta = walMeta.computeFilename(11);
205       Path p2WithMeta = walMeta.computeFilename(12);
206       assertTrue(compMeta.compare(p1WithMeta, p1WithMeta) == 0);
207       assertTrue(compMeta.compare(p1WithMeta, p2WithMeta) < 0);
208       // mixing meta and non-meta logs gives error
209       boolean ex = false;
210       try {
211         comp.compare(p1WithMeta, p2);
212       } catch (IllegalArgumentException e) {
213         ex = true;
214       }
215       assertTrue("Comparator doesn't complain while checking meta log files", ex);
216       boolean exMeta = false;
217       try {
218         compMeta.compare(p1WithMeta, p2);
219       } catch (IllegalArgumentException e) {
220         exMeta = true;
221       }
222       assertTrue("Meta comparator doesn't complain while checking log files", exMeta);
223     } finally {
224       if (wal1 != null) {
225         wal1.close();
226       }
227       if (walMeta != null) {
228         walMeta.close();
229       }
230     }
231   }
232 
233   /**
234    * On rolling a wal after reaching the threshold, {@link WAL#rollWriter()} returns the
235    * list of regions which should be flushed in order to archive the oldest wal file.
236    * <p>
237    * This method tests this behavior by inserting edits and rolling the wal enough times to reach
238    * the max number of logs threshold. It checks whether we get the "right regions" for flush on
239    * rolling the wal.
240    * @throws Exception
241    */
242   @Test 
243   public void testFindMemStoresEligibleForFlush() throws Exception {
244     LOG.debug("testFindMemStoresEligibleForFlush");
245     Configuration conf1 = HBaseConfiguration.create(conf);
246     conf1.setInt("hbase.regionserver.maxlogs", 1);
247     FSHLog wal = new FSHLog(fs, FSUtils.getRootDir(conf1), dir.toString(),
248         HConstants.HREGION_OLDLOGDIR_NAME, conf1, null, true, null, null);
249     HTableDescriptor t1 =
250         new HTableDescriptor(TableName.valueOf("t1")).addFamily(new HColumnDescriptor("row"));
251     HTableDescriptor t2 =
252         new HTableDescriptor(TableName.valueOf("t2")).addFamily(new HColumnDescriptor("row"));
253     HRegionInfo hri1 =
254         new HRegionInfo(t1.getTableName(), HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
255     HRegionInfo hri2 =
256         new HRegionInfo(t2.getTableName(), HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
257     // variables to mock region sequenceIds
258     final AtomicLong sequenceId1 = new AtomicLong(1);
259     final AtomicLong sequenceId2 = new AtomicLong(1);
260     // add edits and roll the wal
261     try {
262       addEdits(wal, hri1, t1, 2, sequenceId1);
263       wal.rollWriter();
264       // add some more edits and roll the wal. This would reach the log number threshold
265       addEdits(wal, hri1, t1, 2, sequenceId1);
266       wal.rollWriter();
267       // with above rollWriter call, the max logs limit is reached.
268       assertTrue(wal.getNumRolledLogFiles() == 2);
269 
270       // get the regions to flush; since there is only one region in the oldest wal, it should
271       // return only one region.
272       byte[][] regionsToFlush = wal.findRegionsToForceFlush();
273       assertEquals(1, regionsToFlush.length);
274       assertEquals(hri1.getEncodedNameAsBytes(), regionsToFlush[0]);
275       // insert edits in second region
276       addEdits(wal, hri2, t2, 2, sequenceId2);
277       // get the regions to flush, it should still read region1.
278       regionsToFlush = wal.findRegionsToForceFlush();
279       assertEquals(regionsToFlush.length, 1);
280       assertEquals(hri1.getEncodedNameAsBytes(), regionsToFlush[0]);
281       // flush region 1, and roll the wal file. Only last wal which has entries for region1 should
282       // remain.
283       flushRegion(wal, hri1.getEncodedNameAsBytes(), t1.getFamiliesKeys());
284       wal.rollWriter();
285       // only one wal should remain now (that is for the second region).
286       assertEquals(1, wal.getNumRolledLogFiles());
287       // flush the second region
288       flushRegion(wal, hri2.getEncodedNameAsBytes(), t2.getFamiliesKeys());
289       wal.rollWriter(true);
290       // no wal should remain now.
291       assertEquals(0, wal.getNumRolledLogFiles());
292       // add edits both to region 1 and region 2, and roll.
293       addEdits(wal, hri1, t1, 2, sequenceId1);
294       addEdits(wal, hri2, t2, 2, sequenceId2);
295       wal.rollWriter();
296       // add edits and roll the writer, to reach the max logs limit.
297       assertEquals(1, wal.getNumRolledLogFiles());
298       addEdits(wal, hri1, t1, 2, sequenceId1);
299       wal.rollWriter();
300       // it should return two regions to flush, as the oldest wal file has entries
301       // for both regions.
302       regionsToFlush = wal.findRegionsToForceFlush();
303       assertEquals(2, regionsToFlush.length);
304       // flush both regions
305       flushRegion(wal, hri1.getEncodedNameAsBytes(), t1.getFamiliesKeys());
306       flushRegion(wal, hri2.getEncodedNameAsBytes(), t2.getFamiliesKeys());
307       wal.rollWriter(true);
308       assertEquals(0, wal.getNumRolledLogFiles());
309       // Add an edit to region1, and roll the wal.
310       addEdits(wal, hri1, t1, 2, sequenceId1);
311       // tests partial flush: roll on a partial flush, and ensure that wal is not archived.
312       wal.startCacheFlush(hri1.getEncodedNameAsBytes(), t1.getFamiliesKeys());
313       wal.rollWriter();
314       wal.completeCacheFlush(hri1.getEncodedNameAsBytes());
315       assertEquals(1, wal.getNumRolledLogFiles());
316     } finally {
317       if (wal != null) {
318         wal.close();
319       }
320     }
321   }
322 
323   /**
324    * Simulates WAL append ops for a region and tests
325    * {@link FSHLog#areAllRegionsFlushed(Map, Map, Map)} API.
326    * It compares the region sequenceIds with oldestFlushing and oldestUnFlushed entries.
327    * If a region's entries are larger than min of (oldestFlushing, oldestUnFlushed), then the
328    * region should be flushed before archiving this WAL.
329   */
330   @Test
331   public void testAllRegionsFlushed() {
332     LOG.debug("testAllRegionsFlushed");
333     Map<byte[], Long> oldestFlushingSeqNo = new HashMap<byte[], Long>();
334     Map<byte[], Long> oldestUnFlushedSeqNo = new HashMap<byte[], Long>();
335     Map<byte[], Long> seqNo = new HashMap<byte[], Long>();
336     // create a table
337     TableName t1 = TableName.valueOf("t1");
338     // create a region
339     HRegionInfo hri1 = new HRegionInfo(t1, HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
340     // variables to mock region sequenceIds
341     final AtomicLong sequenceId1 = new AtomicLong(1);
342     // test empty map
343     assertTrue(FSHLog.areAllRegionsFlushed(seqNo, oldestFlushingSeqNo, oldestUnFlushedSeqNo));
344     // add entries in the region
345     seqNo.put(hri1.getEncodedNameAsBytes(), sequenceId1.incrementAndGet());
346     oldestUnFlushedSeqNo.put(hri1.getEncodedNameAsBytes(), sequenceId1.get());
347     // should say region1 is not flushed.
348     assertFalse(FSHLog.areAllRegionsFlushed(seqNo, oldestFlushingSeqNo, oldestUnFlushedSeqNo));
349     // test with entries in oldestFlushing map.
350     oldestUnFlushedSeqNo.clear();
351     oldestFlushingSeqNo.put(hri1.getEncodedNameAsBytes(), sequenceId1.get());
352     assertFalse(FSHLog.areAllRegionsFlushed(seqNo, oldestFlushingSeqNo, oldestUnFlushedSeqNo));
353     // simulate region flush, i.e., clear oldestFlushing and oldestUnflushed maps
354     oldestFlushingSeqNo.clear();
355     oldestUnFlushedSeqNo.clear();
356     assertTrue(FSHLog.areAllRegionsFlushed(seqNo, oldestFlushingSeqNo, oldestUnFlushedSeqNo));
357     // insert some large values for region1
358     oldestUnFlushedSeqNo.put(hri1.getEncodedNameAsBytes(), 1000l);
359     seqNo.put(hri1.getEncodedNameAsBytes(), 1500l);
360     assertFalse(FSHLog.areAllRegionsFlushed(seqNo, oldestFlushingSeqNo, oldestUnFlushedSeqNo));
361 
362     // tests when oldestUnFlushed/oldestFlushing contains larger value.
363     // It means region is flushed.
364     oldestFlushingSeqNo.put(hri1.getEncodedNameAsBytes(), 1200l);
365     oldestUnFlushedSeqNo.clear();
366     seqNo.put(hri1.getEncodedNameAsBytes(), 1199l);
367     assertTrue(FSHLog.areAllRegionsFlushed(seqNo, oldestFlushingSeqNo, oldestUnFlushedSeqNo));
368   }
369 
370   @Test(expected=IOException.class)
371   public void testFailedToCreateWALIfParentRenamed() throws IOException {
372     final String name = "testFailedToCreateWALIfParentRenamed";
373     FSHLog log = new FSHLog(fs, FSUtils.getRootDir(conf), name, HConstants.HREGION_OLDLOGDIR_NAME,
374         conf, null, true, null, null);
375     long filenum = System.currentTimeMillis();
376     Path path = log.computeFilename(filenum);
377     log.createWriterInstance(path);
378     Path parent = path.getParent();
379     path = log.computeFilename(filenum + 1);
380     Path newPath = new Path(parent.getParent(), parent.getName() + "-splitting");
381     fs.rename(parent, newPath);
382     log.createWriterInstance(path);
383     fail("It should fail to create the new WAL");
384   }
385 
386   /**
387    * Test flush for sure has a sequence id that is beyond the last edit appended.  We do this
388    * by slowing appends in the background ring buffer thread while in foreground we call
389    * flush.  The addition of the sync over HRegion in flush should fix an issue where flush was
390    * returning before all of its appends had made it out to the WAL (HBASE-11109).
391    * @throws IOException
392    * @see HBASE-11109
393    */
394   @Test
395   public void testFlushSequenceIdIsGreaterThanAllEditsInHFile() throws IOException {
396     String testName = "testFlushSequenceIdIsGreaterThanAllEditsInHFile";
397     final TableName tableName = TableName.valueOf(testName);
398     final HRegionInfo hri = new HRegionInfo(tableName);
399     final byte[] rowName = tableName.getName();
400     final HTableDescriptor htd = new HTableDescriptor(tableName);
401     htd.addFamily(new HColumnDescriptor("f"));
402     HRegion r = HRegion.createHRegion(hri, TEST_UTIL.getDefaultRootDirPath(),
403       TEST_UTIL.getConfiguration(), htd);
404     HRegion.closeHRegion(r);
405     final int countPerFamily = 10;
406     final MutableBoolean goslow = new MutableBoolean(false);
407     // subclass and doctor a method.
408     FSHLog wal = new FSHLog(FileSystem.get(conf), TEST_UTIL.getDefaultRootDirPath(),
409         testName, conf) {
410       @Override
411       void atHeadOfRingBufferEventHandlerAppend() {
412         if (goslow.isTrue()) {
413           Threads.sleep(100);
414           LOG.debug("Sleeping before appending 100ms");
415         }
416         super.atHeadOfRingBufferEventHandlerAppend();
417       }
418     };
419     HRegion region = HRegion.openHRegion(TEST_UTIL.getConfiguration(),
420       TEST_UTIL.getTestFileSystem(), TEST_UTIL.getDefaultRootDirPath(), hri, htd, wal);
421     EnvironmentEdge ee = EnvironmentEdgeManager.getDelegate();
422     try {
423       List<Put> puts = null;
424       for (HColumnDescriptor hcd: htd.getFamilies()) {
425         puts =
426           TestWALReplay.addRegionEdits(rowName, hcd.getName(), countPerFamily, ee, region, "x");
427       }
428 
429       // Now assert edits made it in.
430       final Get g = new Get(rowName);
431       Result result = region.get(g);
432       assertEquals(countPerFamily * htd.getFamilies().size(), result.size());
433 
434       // Construct a WALEdit and add it a few times to the WAL.
435       WALEdit edits = new WALEdit();
436       for (Put p: puts) {
437         CellScanner cs = p.cellScanner();
438         while (cs.advance()) {
439           edits.add(cs.current());
440         }
441       }
442       // Add any old cluster id.
443       List<UUID> clusterIds = new ArrayList<UUID>();
444       clusterIds.add(UUID.randomUUID());
445       // Now make appends run slow.
446       goslow.setValue(true);
447       for (int i = 0; i < countPerFamily; i++) {
448         final HRegionInfo info = region.getRegionInfo();
449         final WALKey logkey = new WALKey(info.getEncodedNameAsBytes(), tableName,
450             System.currentTimeMillis(), clusterIds, -1, -1);
451         wal.append(htd, info, logkey, edits, region.getSequenceId(), true, null);
452       }
453       region.flush(true);
454       // FlushResult.flushSequenceId is not visible here so go get the current sequence id.
455       long currentSequenceId = region.getSequenceId().get();
456       // Now release the appends
457       goslow.setValue(false);
458       synchronized (goslow) {
459         goslow.notifyAll();
460       }
461       assertTrue(currentSequenceId >= region.getSequenceId().get());
462     } finally {
463       region.close(true);
464       wal.close();
465     }
466   }
467 
468 }