1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.regionserver.wal;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertNotEquals;
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.lang.reflect.Field;
29 import java.util.ArrayList;
30 import java.util.Comparator;
31 import java.util.List;
32 import java.util.Set;
33 import java.util.UUID;
34 import java.util.concurrent.CountDownLatch;
35 import java.util.concurrent.ExecutorService;
36 import java.util.concurrent.Executors;
37 import java.util.concurrent.atomic.AtomicBoolean;
38
39 import org.apache.commons.lang.mutable.MutableBoolean;
40 import org.apache.commons.logging.Log;
41 import org.apache.commons.logging.LogFactory;
42 import org.apache.hadoop.conf.Configuration;
43 import org.apache.hadoop.fs.FileStatus;
44 import org.apache.hadoop.fs.FileSystem;
45 import org.apache.hadoop.fs.Path;
46 import org.apache.hadoop.hbase.CellScanner;
47 import org.apache.hadoop.hbase.Coprocessor;
48 import org.apache.hadoop.hbase.HBaseConfiguration;
49 import org.apache.hadoop.hbase.HBaseTestingUtility;
50 import org.apache.hadoop.hbase.HColumnDescriptor;
51 import org.apache.hadoop.hbase.HConstants;
52 import org.apache.hadoop.hbase.HRegionInfo;
53 import org.apache.hadoop.hbase.HTableDescriptor;
54 import org.apache.hadoop.hbase.KeyValue;
55 import org.apache.hadoop.hbase.TableName;
56 import org.apache.hadoop.hbase.client.Get;
57 import org.apache.hadoop.hbase.client.Put;
58 import org.apache.hadoop.hbase.client.Result;
59 import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
60 import org.apache.hadoop.hbase.coprocessor.SampleRegionWALObserver;
61 import org.apache.hadoop.hbase.regionserver.HRegion;
62 import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
63 import org.apache.hadoop.hbase.regionserver.Region;
64 import org.apache.hadoop.hbase.testclassification.MediumTests;
65 import org.apache.hadoop.hbase.util.Bytes;
66 import org.apache.hadoop.hbase.util.EnvironmentEdge;
67 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
68 import org.apache.hadoop.hbase.util.FSUtils;
69 import org.apache.hadoop.hbase.util.Threads;
70 import org.apache.hadoop.hbase.wal.DefaultWALProvider;
71 import org.apache.hadoop.hbase.wal.WAL;
72 import org.apache.hadoop.hbase.wal.WALKey;
73 import org.junit.After;
74 import org.junit.AfterClass;
75 import org.junit.Before;
76 import org.junit.BeforeClass;
77 import org.junit.Rule;
78 import org.junit.Test;
79 import org.junit.experimental.categories.Category;
80 import org.junit.rules.TestName;
81
82
83
84
85 @Category(MediumTests.class)
86 public class TestFSHLog {
87 private static final Log LOG = LogFactory.getLog(TestFSHLog.class);
88
89 protected static Configuration conf;
90 protected static FileSystem fs;
91 protected static Path dir;
92 protected static Path rootDir;
93 protected static Path walRootDir;
94 protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
95
96 @Rule
97 public final TestName currentTest = new TestName();
98
99 @Before
100 public void setUp() throws Exception {
101 FileStatus[] entries = fs.listStatus(new Path("/"));
102 for (FileStatus dir : entries) {
103 fs.delete(dir.getPath(), true);
104 }
105 rootDir = TEST_UTIL.createRootDir();
106 walRootDir = TEST_UTIL.createWALRootDir();
107 dir = new Path(walRootDir, currentTest.getMethodName());
108 assertNotEquals(rootDir, walRootDir);
109 }
110
111 @After
112 public void tearDown() throws Exception {
113 }
114
115 @BeforeClass
116 public static void setUpBeforeClass() throws Exception {
117
118 TEST_UTIL.getConfiguration().setInt("dfs.blocksize", 1024 * 1024);
119
120 TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000);
121 TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1);
122 TEST_UTIL.getConfiguration().setInt("dfs.client.socket-timeout", 5000);
123
124
125 TEST_UTIL.getConfiguration()
126 .setInt("hbase.ipc.client.connect.max.retries", 1);
127 TEST_UTIL.getConfiguration().setInt(
128 "dfs.client.block.recovery.retries", 1);
129 TEST_UTIL.getConfiguration().setInt(
130 "hbase.ipc.client.connection.maxidletime", 500);
131 TEST_UTIL.getConfiguration().set(CoprocessorHost.WAL_COPROCESSOR_CONF_KEY,
132 SampleRegionWALObserver.class.getName());
133 TEST_UTIL.startMiniDFSCluster(3);
134
135 conf = TEST_UTIL.getConfiguration();
136 fs = TEST_UTIL.getDFSCluster().getFileSystem();
137 }
138
139 @AfterClass
140 public static void tearDownAfterClass() throws Exception {
141 fs.delete(rootDir, true);
142 fs.delete(walRootDir, true);
143 TEST_UTIL.shutdownMiniCluster();
144 }
145
146
147
148
149 @Test
150 public void testWALCoprocessorLoaded() throws Exception {
151
152 FSHLog log = null;
153 try {
154 log = new FSHLog(fs, walRootDir, dir.toString(),
155 HConstants.HREGION_OLDLOGDIR_NAME, conf, null, true, null, null);
156 WALCoprocessorHost host = log.getCoprocessorHost();
157 Coprocessor c = host.findCoprocessor(SampleRegionWALObserver.class.getName());
158 assertNotNull(c);
159 } finally {
160 if (log != null) {
161 log.close();
162 }
163 }
164 }
165
166 protected void addEdits(WAL log,
167 HRegionInfo hri,
168 HTableDescriptor htd,
169 int times,
170 MultiVersionConcurrencyControl mvcc)
171 throws IOException {
172 final byte[] row = Bytes.toBytes("row");
173 for (int i = 0; i < times; i++) {
174 long timestamp = System.currentTimeMillis();
175 WALEdit cols = new WALEdit();
176 cols.add(new KeyValue(row, row, row, timestamp, row));
177 WALKey key = new WALKey(hri.getEncodedNameAsBytes(), htd.getTableName(),
178 WALKey.NO_SEQUENCE_ID, timestamp, WALKey.EMPTY_UUIDS, HConstants.NO_NONCE,
179 HConstants.NO_NONCE, mvcc);
180 log.append(htd, hri, key, cols, true);
181 }
182 log.sync();
183 }
184
185
186
187
188
189
190 protected void flushRegion(WAL wal, byte[] regionEncodedName, Set<byte[]> flushedFamilyNames) {
191 wal.startCacheFlush(regionEncodedName, flushedFamilyNames);
192 wal.completeCacheFlush(regionEncodedName);
193 }
194
195
196
197
198
199
200 @Test
201 public void testWALComparator() throws Exception {
202 FSHLog wal1 = null;
203 FSHLog walMeta = null;
204 try {
205 wal1 = new FSHLog(fs, walRootDir, dir.toString(),
206 HConstants.HREGION_OLDLOGDIR_NAME, conf, null, true, null, null);
207 LOG.debug("Log obtained is: " + wal1);
208 Comparator<Path> comp = wal1.LOG_NAME_COMPARATOR;
209 Path p1 = wal1.computeFilename(11);
210 Path p2 = wal1.computeFilename(12);
211
212 assertTrue(comp.compare(p1, p1) == 0);
213
214 assertTrue(comp.compare(p1, p2) < 0);
215 walMeta = new FSHLog(fs, walRootDir, dir.toString(),
216 HConstants.HREGION_OLDLOGDIR_NAME, conf, null, true, null,
217 DefaultWALProvider.META_WAL_PROVIDER_ID);
218 Comparator<Path> compMeta = walMeta.LOG_NAME_COMPARATOR;
219
220 Path p1WithMeta = walMeta.computeFilename(11);
221 Path p2WithMeta = walMeta.computeFilename(12);
222 assertTrue(compMeta.compare(p1WithMeta, p1WithMeta) == 0);
223 assertTrue(compMeta.compare(p1WithMeta, p2WithMeta) < 0);
224
225 boolean ex = false;
226 try {
227 comp.compare(p1WithMeta, p2);
228 } catch (IllegalArgumentException e) {
229 ex = true;
230 }
231 assertTrue("Comparator doesn't complain while checking meta log files", ex);
232 boolean exMeta = false;
233 try {
234 compMeta.compare(p1WithMeta, p2);
235 } catch (IllegalArgumentException e) {
236 exMeta = true;
237 }
238 assertTrue("Meta comparator doesn't complain while checking log files", exMeta);
239 } finally {
240 if (wal1 != null) {
241 wal1.close();
242 }
243 if (walMeta != null) {
244 walMeta.close();
245 }
246 }
247 }
248
249
250
251
252
253
254
255
256
257
258 @Test
259 public void testFindMemStoresEligibleForFlush() throws Exception {
260 LOG.debug("testFindMemStoresEligibleForFlush");
261 Configuration conf1 = HBaseConfiguration.create(conf);
262 conf1.setInt("hbase.regionserver.maxlogs", 1);
263 FSHLog wal = new FSHLog(fs, walRootDir, dir.toString(),
264 HConstants.HREGION_OLDLOGDIR_NAME, conf1, null, true, null, null);
265 HTableDescriptor t1 =
266 new HTableDescriptor(TableName.valueOf("t1")).addFamily(new HColumnDescriptor("row"));
267 HTableDescriptor t2 =
268 new HTableDescriptor(TableName.valueOf("t2")).addFamily(new HColumnDescriptor("row"));
269 HRegionInfo hri1 =
270 new HRegionInfo(t1.getTableName(), HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
271 HRegionInfo hri2 =
272 new HRegionInfo(t2.getTableName(), HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
273
274 MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
275 try {
276 addEdits(wal, hri1, t1, 2, mvcc);
277 wal.rollWriter();
278
279 addEdits(wal, hri1, t1, 2, mvcc);
280 wal.rollWriter();
281
282 assertTrue(wal.getNumRolledLogFiles() == 2);
283
284
285
286 byte[][] regionsToFlush = wal.findRegionsToForceFlush();
287 assertEquals(1, regionsToFlush.length);
288 assertEquals(hri1.getEncodedNameAsBytes(), regionsToFlush[0]);
289
290 addEdits(wal, hri2, t2, 2, mvcc);
291
292 regionsToFlush = wal.findRegionsToForceFlush();
293 assertEquals(regionsToFlush.length, 1);
294 assertEquals(hri1.getEncodedNameAsBytes(), regionsToFlush[0]);
295
296
297 flushRegion(wal, hri1.getEncodedNameAsBytes(), t1.getFamiliesKeys());
298 wal.rollWriter();
299
300 assertEquals(1, wal.getNumRolledLogFiles());
301
302 flushRegion(wal, hri2.getEncodedNameAsBytes(), t2.getFamiliesKeys());
303 wal.rollWriter(true);
304
305 assertEquals(0, wal.getNumRolledLogFiles());
306
307 addEdits(wal, hri1, t1, 2, mvcc);
308 addEdits(wal, hri2, t2, 2, mvcc);
309 wal.rollWriter();
310
311 assertEquals(1, wal.getNumRolledLogFiles());
312 addEdits(wal, hri1, t1, 2, mvcc);
313 wal.rollWriter();
314
315
316 regionsToFlush = wal.findRegionsToForceFlush();
317 assertEquals(2, regionsToFlush.length);
318
319 flushRegion(wal, hri1.getEncodedNameAsBytes(), t1.getFamiliesKeys());
320 flushRegion(wal, hri2.getEncodedNameAsBytes(), t2.getFamiliesKeys());
321 wal.rollWriter(true);
322 assertEquals(0, wal.getNumRolledLogFiles());
323
324 addEdits(wal, hri1, t1, 2, mvcc);
325
326 wal.startCacheFlush(hri1.getEncodedNameAsBytes(), t1.getFamiliesKeys());
327 wal.rollWriter();
328 wal.completeCacheFlush(hri1.getEncodedNameAsBytes());
329 assertEquals(1, wal.getNumRolledLogFiles());
330 } finally {
331 if (wal != null) {
332 wal.close();
333 }
334 }
335 }
336
337 @Test(expected=IOException.class)
338 public void testFailedToCreateWALIfParentRenamed() throws IOException {
339 final String name = "testFailedToCreateWALIfParentRenamed";
340 FSHLog log = new FSHLog(fs, walRootDir, name, HConstants.HREGION_OLDLOGDIR_NAME,
341 conf, null, true, null, null);
342 long filenum = System.currentTimeMillis();
343 Path path = log.computeFilename(filenum);
344 log.createWriterInstance(path);
345 Path parent = path.getParent();
346 path = log.computeFilename(filenum + 1);
347 Path newPath = new Path(parent.getParent(), parent.getName() + "-splitting");
348 fs.rename(parent, newPath);
349 log.createWriterInstance(path);
350 fail("It should fail to create the new WAL");
351 }
352
353
354
355
356
357
358
359
360
361 @Test
362 public void testFlushSequenceIdIsGreaterThanAllEditsInHFile() throws IOException {
363 String testName = "testFlushSequenceIdIsGreaterThanAllEditsInHFile";
364 final TableName tableName = TableName.valueOf(testName);
365 final HRegionInfo hri = new HRegionInfo(tableName);
366 final byte[] rowName = tableName.getName();
367 final HTableDescriptor htd = new HTableDescriptor(tableName);
368 htd.addFamily(new HColumnDescriptor("f"));
369 HRegion r = HRegion.createHRegion(hri, rootDir,
370 TEST_UTIL.getConfiguration(), htd);
371 HRegion.closeHRegion(r);
372 final int countPerFamily = 10;
373 final MutableBoolean goslow = new MutableBoolean(false);
374
375 FSHLog wal = new FSHLog(FileSystem.get(conf), walRootDir,
376 testName, conf) {
377 @Override
378 void atHeadOfRingBufferEventHandlerAppend() {
379 if (goslow.isTrue()) {
380 Threads.sleep(100);
381 LOG.debug("Sleeping before appending 100ms");
382 }
383 super.atHeadOfRingBufferEventHandlerAppend();
384 }
385 };
386 HRegion region = HRegion.openHRegion(TEST_UTIL.getConfiguration(),
387 TEST_UTIL.getTestFileSystem(), rootDir, hri, htd, wal);
388 EnvironmentEdge ee = EnvironmentEdgeManager.getDelegate();
389 try {
390 List<Put> puts = null;
391 for (HColumnDescriptor hcd: htd.getFamilies()) {
392 puts =
393 TestWALReplay.addRegionEdits(rowName, hcd.getName(), countPerFamily, ee, region, "x");
394 }
395
396
397 final Get g = new Get(rowName);
398 Result result = region.get(g);
399 assertEquals(countPerFamily * htd.getFamilies().size(), result.size());
400
401
402 WALEdit edits = new WALEdit();
403 for (Put p: puts) {
404 CellScanner cs = p.cellScanner();
405 while (cs.advance()) {
406 edits.add(cs.current());
407 }
408 }
409
410 List<UUID> clusterIds = new ArrayList<UUID>();
411 clusterIds.add(UUID.randomUUID());
412
413 goslow.setValue(true);
414 for (int i = 0; i < countPerFamily; i++) {
415 final HRegionInfo info = region.getRegionInfo();
416 final WALKey logkey = new WALKey(info.getEncodedNameAsBytes(), tableName,
417 System.currentTimeMillis(), clusterIds, -1, -1, region.getMVCC());
418 wal.append(htd, info, logkey, edits, true);
419 }
420 region.flush(true);
421
422 long currentSequenceId = region.getSequenceId();
423
424 goslow.setValue(false);
425 synchronized (goslow) {
426 goslow.notifyAll();
427 }
428 assertTrue(currentSequenceId >= region.getSequenceId());
429 } finally {
430 region.close(true);
431 wal.close();
432 }
433 }
434
435 @Test
436 public void testSyncRunnerIndexOverflow() throws IOException, NoSuchFieldException,
437 SecurityException, IllegalArgumentException, IllegalAccessException {
438 final String name = "testSyncRunnerIndexOverflow";
439 FSHLog log =
440 new FSHLog(fs, walRootDir, name, HConstants.HREGION_OLDLOGDIR_NAME, conf,
441 null, true, null, null);
442 try {
443 Field ringBufferEventHandlerField = FSHLog.class.getDeclaredField("ringBufferEventHandler");
444 ringBufferEventHandlerField.setAccessible(true);
445 FSHLog.RingBufferEventHandler ringBufferEventHandler =
446 (FSHLog.RingBufferEventHandler) ringBufferEventHandlerField.get(log);
447 Field syncRunnerIndexField =
448 FSHLog.RingBufferEventHandler.class.getDeclaredField("syncRunnerIndex");
449 syncRunnerIndexField.setAccessible(true);
450 syncRunnerIndexField.set(ringBufferEventHandler, Integer.MAX_VALUE - 1);
451 HTableDescriptor htd =
452 new HTableDescriptor(TableName.valueOf("t1")).addFamily(new HColumnDescriptor("row"));
453 HRegionInfo hri =
454 new HRegionInfo(htd.getTableName(), HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
455 MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
456 for (int i = 0; i < 10; i++) {
457 addEdits(log, hri, htd, 1, mvcc);
458 }
459 } finally {
460 log.close();
461 }
462 }
463
464
465
466
467 @Test (timeout = 30000)
468 public void testUnflushedSeqIdTracking() throws IOException, InterruptedException {
469 final String name = "testSyncRunnerIndexOverflow";
470 final byte[] b = Bytes.toBytes("b");
471
472 final AtomicBoolean startHoldingForAppend = new AtomicBoolean(false);
473 final CountDownLatch holdAppend = new CountDownLatch(1);
474 final CountDownLatch flushFinished = new CountDownLatch(1);
475 final CountDownLatch putFinished = new CountDownLatch(1);
476
477 try (FSHLog log =
478 new FSHLog(fs, walRootDir, name, HConstants.HREGION_OLDLOGDIR_NAME, conf,
479 null, true, null, null)) {
480
481 log.registerWALActionsListener(new WALActionsListener.Base() {
482 @Override
483 public void visitLogEntryBeforeWrite(HTableDescriptor htd, WALKey logKey, WALEdit logEdit)
484 throws IOException {
485 if (startHoldingForAppend.get()) {
486 try {
487 holdAppend.await();
488 } catch (InterruptedException e) {
489 LOG.error(e);
490 }
491 }
492 }
493 });
494
495
496 HTableDescriptor htd =
497 new HTableDescriptor(TableName.valueOf("t1")).addFamily(new HColumnDescriptor(b));
498 HRegionInfo hri =
499 new HRegionInfo(htd.getTableName(), HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW);
500
501 final HRegion region = TEST_UTIL.createLocalHRegion(hri, htd, log);
502 ExecutorService exec = Executors.newFixedThreadPool(2);
503
504
505 region.put(new Put(b).addColumn(b, b,b));
506
507 startHoldingForAppend.set(true);
508 exec.submit(new Runnable() {
509 @Override
510 public void run() {
511 try {
512 region.put(new Put(b).addColumn(b, b,b));
513 putFinished.countDown();
514 } catch (IOException e) {
515 LOG.error(e);
516 }
517 }
518 });
519
520
521 Threads.sleep(3000);
522
523 exec.submit(new Runnable() {
524 @Override
525 public void run() {
526 try {
527 Region.FlushResult flushResult = region.flush(true);
528 LOG.info("Flush result:" + flushResult.getResult());
529 LOG.info("Flush succeeded:" + flushResult.isFlushSucceeded());
530 flushFinished.countDown();
531 } catch (IOException e) {
532 LOG.error(e);
533 }
534 }
535 });
536
537
538
539 Threads.sleep(3000);
540
541
542 holdAppend.countDown();
543 putFinished.await();
544 flushFinished.await();
545
546
547 assertEquals("Region did not flush?", 1, region.getStoreFileList(new byte[][]{b}).size());
548
549
550 long seqId = log.getEarliestMemstoreSeqNum(hri.getEncodedNameAsBytes());
551 assertEquals("Found seqId for the region which is already flushed",
552 HConstants.NO_SEQNUM, seqId);
553
554 region.close();
555 }
556 }
557 }