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.assertNull;
24  import static org.junit.Assert.assertTrue;
25  
26  import java.io.IOException;
27  import java.util.HashSet;
28  import java.util.Random;
29  import java.util.Set;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.apache.hadoop.conf.Configuration;
34  import org.apache.hadoop.fs.FileStatus;
35  import org.apache.hadoop.fs.FileSystem;
36  import org.apache.hadoop.fs.Path;
37  import org.apache.hadoop.hbase.HBaseTestingUtility;
38  import org.apache.hadoop.hbase.HColumnDescriptor;
39  import org.apache.hadoop.hbase.HConstants;
40  import org.apache.hadoop.hbase.HRegionInfo;
41  import org.apache.hadoop.hbase.HTableDescriptor;
42  import org.apache.hadoop.hbase.KeyValue;
43  import org.apache.hadoop.hbase.testclassification.MediumTests;
44  import org.apache.hadoop.hbase.ServerName;
45  import org.apache.hadoop.hbase.TableName;
46  import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
47  import org.apache.hadoop.hbase.testclassification.MediumTests;
48  import org.apache.hadoop.hbase.util.Bytes;
49  import org.apache.hadoop.hbase.util.FSUtils;
50  import org.junit.After;
51  import org.junit.AfterClass;
52  import org.junit.Before;
53  import org.junit.BeforeClass;
54  import org.junit.Rule;
55  import org.junit.Test;
56  import org.junit.experimental.categories.Category;
57  import org.junit.rules.TestName;
58  
59  // imports for things that haven't moved from regionserver.wal yet.
60  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
61  
62  @Category(MediumTests.class)
63  public class TestDefaultWALProvider {
64    private static final Log LOG = LogFactory.getLog(TestDefaultWALProvider.class);
65  
66    protected static Configuration conf;
67    protected static FileSystem fs;
68    protected static FileSystem walFs;
69    protected static Path walRootDir;
70    protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
71    protected MultiVersionConcurrencyControl mvcc;
72  
73    @Rule
74    public final TestName currentTest = new TestName();
75  
76    @Before
77    public void setUp() throws Exception {
78      mvcc = new MultiVersionConcurrencyControl();
79      FileStatus[] entries = fs.listStatus(new Path("/"));
80      for (FileStatus dir : entries) {
81        fs.delete(dir.getPath(), true);
82      }
83      walFs.delete(walRootDir, true);
84    }
85  
86    @After
87    public void tearDown() throws Exception {
88    }
89  
90    @BeforeClass
91    public static void setUpBeforeClass() throws Exception {
92      // Make block sizes small.
93      TEST_UTIL.getConfiguration().setInt("dfs.blocksize", 1024 * 1024);
94      // quicker heartbeat interval for faster DN death notification
95      TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000);
96      TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1);
97      TEST_UTIL.getConfiguration().setInt("dfs.client.socket-timeout", 5000);
98  
99      // faster failover with cluster.shutdown();fs.close() idiom
100     TEST_UTIL.getConfiguration()
101         .setInt("hbase.ipc.client.connect.max.retries", 1);
102     TEST_UTIL.getConfiguration().setInt(
103         "dfs.client.block.recovery.retries", 1);
104     TEST_UTIL.getConfiguration().setInt(
105       "hbase.ipc.client.connection.maxidletime", 500);
106     TEST_UTIL.startMiniDFSCluster(3);
107 
108     // Set up a working space for our tests.
109     walRootDir = TEST_UTIL.createWALRootDir();
110     conf = TEST_UTIL.getConfiguration();
111     fs = FSUtils.getRootDirFileSystem(conf);
112     walFs = FSUtils.getWALFileSystem(conf);
113   }
114 
115   @AfterClass
116   public static void tearDownAfterClass() throws Exception {
117     walFs.delete(walRootDir, true);
118     TEST_UTIL.shutdownMiniCluster();
119   }
120 
121   static String getName() {
122     return "TestDefaultWALProvider";
123   }
124 
125   @Test
126   public void testGetServerNameFromWALDirectoryName() throws IOException {
127     ServerName sn = ServerName.valueOf("hn", 450, 1398);
128     String hl = walRootDir + "/" +
129         DefaultWALProvider.getWALDirectoryName(sn.toString());
130 
131     // Must not throw exception
132     assertNull(DefaultWALProvider.getServerNameFromWALDirectoryName(conf, null));
133     assertNull(DefaultWALProvider.getServerNameFromWALDirectoryName(conf, walRootDir.toUri().toString()));
134     assertNull(DefaultWALProvider.getServerNameFromWALDirectoryName(conf, ""));
135     assertNull(DefaultWALProvider.getServerNameFromWALDirectoryName(conf, "                  "));
136     assertNull(DefaultWALProvider.getServerNameFromWALDirectoryName(conf, hl));
137     assertNull(DefaultWALProvider.getServerNameFromWALDirectoryName(conf, hl + "qdf"));
138     assertNull(DefaultWALProvider.getServerNameFromWALDirectoryName(conf, "sfqf" + hl + "qdf"));
139 
140     final String wals = "/WALs/";
141     ServerName parsed = DefaultWALProvider.getServerNameFromWALDirectoryName(conf,
142       walRootDir.toUri().toString() + wals + sn +
143       "/localhost%2C32984%2C1343316388997.1343316390417");
144     assertEquals("standard",  sn, parsed);
145 
146     parsed = DefaultWALProvider.getServerNameFromWALDirectoryName(conf, hl + "/qdf");
147     assertEquals("subdir", sn, parsed);
148 
149     parsed = DefaultWALProvider.getServerNameFromWALDirectoryName(conf,
150       walRootDir.toUri().toString() + wals + sn +
151       "-splitting/localhost%3A57020.1340474893931");
152     assertEquals("split", sn, parsed);
153   }
154 
155 
156   protected void addEdits(WAL log, HRegionInfo hri, HTableDescriptor htd,
157                         int times) 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, getWalKey(hri.getEncodedNameAsBytes(), htd.getTableName(), timestamp),
164         cols, true);
165     }
166     log.sync();
167   }
168 
169   /**
170    * used by TestDefaultWALProviderWithHLogKey
171    */
172   WALKey getWalKey(final byte[] info, final TableName tableName, final long timestamp) {
173     return new WALKey(info, tableName, timestamp, mvcc);
174   }
175 
176   /**
177    * helper method to simulate region flush for a WAL.
178    * @param wal
179    * @param regionEncodedName
180    */
181   protected void flushRegion(WAL wal, byte[] regionEncodedName, Set<byte[]> flushedFamilyNames) {
182     wal.startCacheFlush(regionEncodedName, flushedFamilyNames);
183     wal.completeCacheFlush(regionEncodedName);
184   }
185 
186   private static final byte[] UNSPECIFIED_REGION = new byte[]{};
187 
188   @Test
189   public void testLogCleaning() throws Exception {
190     LOG.info("testLogCleaning");
191     final HTableDescriptor htd =
192         new HTableDescriptor(TableName.valueOf("testLogCleaning")).addFamily(new HColumnDescriptor(
193             "row"));
194     final HTableDescriptor htd2 =
195         new HTableDescriptor(TableName.valueOf("testLogCleaning2"))
196             .addFamily(new HColumnDescriptor("row"));
197     final Configuration localConf = new Configuration(conf);
198     localConf.set(WALFactory.WAL_PROVIDER, DefaultWALProvider.class.getName());
199     final WALFactory wals = new WALFactory(localConf, null, currentTest.getMethodName());
200     try {
201       HRegionInfo hri = new HRegionInfo(htd.getTableName(),
202           HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
203       HRegionInfo hri2 = new HRegionInfo(htd2.getTableName(),
204           HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
205       // we want to mix edits from regions, so pick our own identifier.
206       final WAL log = wals.getWAL(UNSPECIFIED_REGION, null);
207 
208       // Add a single edit and make sure that rolling won't remove the file
209       // Before HBASE-3198 it used to delete it
210       addEdits(log, hri, htd, 1);
211       log.rollWriter();
212       assertEquals(1, DefaultWALProvider.getNumRolledLogFiles(log));
213 
214       // See if there's anything wrong with more than 1 edit
215       addEdits(log, hri, htd, 2);
216       log.rollWriter();
217       assertEquals(2, DefaultWALProvider.getNumRolledLogFiles(log));
218 
219       // Now mix edits from 2 regions, still no flushing
220       addEdits(log, hri, htd, 1);
221       addEdits(log, hri2, htd2, 1);
222       addEdits(log, hri, htd, 1);
223       addEdits(log, hri2, htd2, 1);
224       log.rollWriter();
225       assertEquals(3, DefaultWALProvider.getNumRolledLogFiles(log));
226 
227       // Flush the first region, we expect to see the first two files getting
228       // archived. We need to append something or writer won't be rolled.
229       addEdits(log, hri2, htd2, 1);
230       log.startCacheFlush(hri.getEncodedNameAsBytes(), htd.getFamiliesKeys());
231       log.completeCacheFlush(hri.getEncodedNameAsBytes());
232       log.rollWriter();
233       assertEquals(2, DefaultWALProvider.getNumRolledLogFiles(log));
234 
235       // Flush the second region, which removes all the remaining output files
236       // since the oldest was completely flushed and the two others only contain
237       // flush information
238       addEdits(log, hri2, htd2, 1);
239       log.startCacheFlush(hri2.getEncodedNameAsBytes(), htd2.getFamiliesKeys());
240       log.completeCacheFlush(hri2.getEncodedNameAsBytes());
241       log.rollWriter();
242       assertEquals(0, DefaultWALProvider.getNumRolledLogFiles(log));
243     } finally {
244       if (wals != null) {
245         wals.close();
246       }
247     }
248   }
249 
250   /**
251    * Tests wal archiving by adding data, doing flushing/rolling and checking we archive old logs
252    * and also don't archive "live logs" (that is, a log with un-flushed entries).
253    * <p>
254    * This is what it does:
255    * It creates two regions, and does a series of inserts along with log rolling.
256    * Whenever a WAL is rolled, HLogBase checks previous wals for archiving. A wal is eligible for
257    * archiving if for all the regions which have entries in that wal file, have flushed - past
258    * their maximum sequence id in that wal file.
259    * <p>
260    * @throws IOException
261    */
262   @Test
263   public void testWALArchiving() throws IOException {
264     LOG.debug("testWALArchiving");
265     HTableDescriptor table1 =
266         new HTableDescriptor(TableName.valueOf("t1")).addFamily(new HColumnDescriptor("row"));
267     HTableDescriptor table2 =
268         new HTableDescriptor(TableName.valueOf("t2")).addFamily(new HColumnDescriptor("row"));
269     final Configuration localConf = new Configuration(conf);
270     localConf.set(WALFactory.WAL_PROVIDER, DefaultWALProvider.class.getName());
271     final WALFactory wals = new WALFactory(localConf, null, currentTest.getMethodName());
272     try {
273       final WAL wal = wals.getWAL(UNSPECIFIED_REGION, null);
274       assertEquals(0, DefaultWALProvider.getNumRolledLogFiles(wal));
275       HRegionInfo hri1 =
276           new HRegionInfo(table1.getTableName(), HConstants.EMPTY_START_ROW,
277               HConstants.EMPTY_END_ROW);
278       HRegionInfo hri2 =
279           new HRegionInfo(table2.getTableName(), HConstants.EMPTY_START_ROW,
280               HConstants.EMPTY_END_ROW);
281       // ensure that we don't split the regions.
282       hri1.setSplit(false);
283       hri2.setSplit(false);
284       // variables to mock region sequenceIds.
285       // start with the testing logic: insert a waledit, and roll writer
286       addEdits(wal, hri1, table1, 1);
287       wal.rollWriter();
288       // assert that the wal is rolled
289       assertEquals(1, DefaultWALProvider.getNumRolledLogFiles(wal));
290       // add edits in the second wal file, and roll writer.
291       addEdits(wal, hri1, table1, 1);
292       wal.rollWriter();
293       // assert that the wal is rolled
294       assertEquals(2, DefaultWALProvider.getNumRolledLogFiles(wal));
295       // add a waledit to table1, and flush the region.
296       addEdits(wal, hri1, table1, 3);
297       flushRegion(wal, hri1.getEncodedNameAsBytes(), table1.getFamiliesKeys());
298       // roll log; all old logs should be archived.
299       wal.rollWriter();
300       assertEquals(0, DefaultWALProvider.getNumRolledLogFiles(wal));
301       // add an edit to table2, and roll writer
302       addEdits(wal, hri2, table2, 1);
303       wal.rollWriter();
304       assertEquals(1, DefaultWALProvider.getNumRolledLogFiles(wal));
305       // add edits for table1, and roll writer
306       addEdits(wal, hri1, table1, 2);
307       wal.rollWriter();
308       assertEquals(2, DefaultWALProvider.getNumRolledLogFiles(wal));
309       // add edits for table2, and flush hri1.
310       addEdits(wal, hri2, table2, 2);
311       flushRegion(wal, hri1.getEncodedNameAsBytes(), table2.getFamiliesKeys());
312       // the log : region-sequenceId map is
313       // log1: region2 (unflushed)
314       // log2: region1 (flushed)
315       // log3: region2 (unflushed)
316       // roll the writer; log2 should be archived.
317       wal.rollWriter();
318       assertEquals(2, DefaultWALProvider.getNumRolledLogFiles(wal));
319       // flush region2, and all logs should be archived.
320       addEdits(wal, hri2, table2, 2);
321       flushRegion(wal, hri2.getEncodedNameAsBytes(), table2.getFamiliesKeys());
322       wal.rollWriter();
323       assertEquals(0, DefaultWALProvider.getNumRolledLogFiles(wal));
324     } finally {
325       if (wals != null) {
326         wals.close();
327       }
328     }
329   }
330 
331   /**
332    * Write to a log file with three concurrent threads and verifying all data is written.
333    * @throws Exception
334    */
335   @Test
336   public void testConcurrentWrites() throws Exception {
337     // Run the WPE tool with three threads writing 3000 edits each concurrently.
338     // When done, verify that all edits were written.
339     int errCode = WALPerformanceEvaluation.
340       innerMain(new Configuration(TEST_UTIL.getConfiguration()),
341         new String [] {"-threads", "3", "-verify", "-noclosefs", "-iterations", "3000"});
342     assertEquals(0, errCode);
343   }
344 
345   /**
346    * Ensure that we can use Set.add to deduplicate WALs
347    */
348   @Test
349   public void setMembershipDedups() throws IOException {
350     final Configuration localConf = new Configuration(conf);
351     localConf.set(WALFactory.WAL_PROVIDER, DefaultWALProvider.class.getName());
352     final WALFactory wals = new WALFactory(localConf, null, currentTest.getMethodName());
353     try {
354       final Set<WAL> seen = new HashSet<WAL>(1);
355       final Random random = new Random();
356       assertTrue("first attempt to add WAL from default provider should work.",
357           seen.add(wals.getWAL(Bytes.toBytes(random.nextInt()), null)));
358       for (int i = 0; i < 1000; i++) {
359         assertFalse("default wal provider is only supposed to return a single wal, which should "
360             + "compare as .equals itself.",
361           seen.add(wals.getWAL(Bytes.toBytes(random.nextInt()), null)));
362       }
363     } finally {
364       wals.close();
365     }
366   }
367 }