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.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
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
94
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
109
110 @BeforeClass
111 public static void setUpBeforeClass() throws Exception {
112
113
114 System.setProperty("hbase.tests.use.shortcircuit.reads", "false");
115
116
117
118 TEST_UTIL.getConfiguration().setLong(HConstants.HREGION_MAX_FILESIZE, 768L * 1024L);
119
120
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
127 TEST_UTIL.getConfiguration().setInt("hbase.hregion.memstore.optionalflushcount", 2);
128
129
130 TEST_UTIL.getConfiguration().setInt(
131 HConstants.HREGION_MEMSTORE_FLUSH_SIZE, 8192);
132
133
134 TEST_UTIL.getConfiguration().setLong("hbase.client.pause", 10 * 1000);
135
136
137
138 TEST_UTIL.getConfiguration().setInt(HConstants.THREAD_WAKE_FREQUENCY, 2 * 1000);
139
140
141
142 TEST_UTIL.getConfiguration().setBoolean("dfs.support.append", true);
143
144
145 TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000);
146 TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1);
147
148
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
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
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++) {
181 doPut(table, i);
182 if (i % 32 == 0) {
183
184 try {
185 Thread.sleep(2000);
186 } catch (InterruptedException e) {
187
188 }
189 }
190 }
191 }
192
193
194
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
204 newLog.rollWriter(true);
205 } finally {
206 wals.close();
207 }
208 }
209
210
211
212
213
214
215 @Test
216 public void testLogRolling() throws Exception {
217 this.tableName = getName();
218
219 startAndWriteData();
220 final WAL log = server.getWAL(null);
221 LOG.info("after writing there are " + DefaultWALProvider.getNumRolledLogFiles(log) +
222 " log files");
223
224
225 for (Region r: server.getOnlineRegionsLocalContext()) {
226 r.flush(true);
227 }
228
229
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
245 try {
246 Thread.sleep(2000);
247 } catch (InterruptedException e) {
248
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
280 table.put(tmpPut);
281 try {
282 Thread.sleep(200);
283 } catch (InterruptedException e) {
284
285 }
286 remaining = timeout - (System.currentTimeMillis() - startTime);
287 }
288 }
289 }
290
291
292
293
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
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
327 assertTrue("Need append support for this test", FSUtils
328 .isAppendSupported(TEST_UTIL.getConfiguration()));
329
330
331
332
333
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
366
367 assertTrue(dfsCluster.stopDataNode(pipeline[0].getName()) != null);
368
369
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
380 writeData(table, 3);
381 assertTrue("The log should not roll again.",
382 DefaultWALProvider.extractFileNumFromWAL(log) == newFilenum);
383
384
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
396
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
408
409
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
419 Table t = new HTable(TEST_UTIL.getConfiguration(), TableName.META_TABLE_NAME);
420 try {
421 this.server = cluster.getRegionServer(0);
422
423
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
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
465 dfsCluster.restartDataNodes();
466 Thread.sleep(1000);
467 dfsCluster.waitActive();
468 LOG.info("Data Nodes restarted");
469 validateData(table, 1002);
470
471
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
482 dfsCluster.restartDataNodes();
483 Thread.sleep(1000);
484 dfsCluster.waitActive();
485 LOG.info("Data Nodes restarted");
486 validateData(table, 1004);
487
488
489 writeData(table, 1005);
490
491
492 log.rollWriter(true);
493 assertTrue("preLogRolledCalled has size of " + preLogRolledCalled.size(),
494 preLogRolledCalled.size() >= 1);
495
496
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
523 assertTrue(loggedRows.contains("row1002"));
524 assertTrue(loggedRows.contains("row1003"));
525 assertTrue(loggedRows.contains("row1004"));
526 assertTrue(loggedRows.contains("row1005"));
527
528
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
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
557
558
559 @Test
560 public void testCompactionRecordDoesntBlockRolling() throws Exception {
561 Table table = null;
562 Table table2 = null;
563
564
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
576 admin.flush(TableName.NAMESPACE_TABLE_NAME);
577
578
579 for (int i = 1; i <= 2; ++i) {
580 doPut(table2, i);
581 admin.flush(table2.getName());
582 }
583 doPut(table2, 3);
584 assertEquals("Should have no WAL after initial writes", 0,
585 DefaultWALProvider.getNumRolledLogFiles(log));
586 assertEquals(2, s.getStorefilesCount());
587
588
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
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
602 doPut(table, 0);
603 log.rollWriter();
604 assertEquals("Should have WAL; one table is not flushed", 1,
605 DefaultWALProvider.getNumRolledLogFiles(log));
606
607
608 admin.flush(table.getName());
609 doPut(table, 1);
610 log.rollWriter();
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
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