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.replication.regionserver;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertNotEquals;
24  import static org.junit.Assert.assertNotNull;
25  import static org.junit.Assert.assertNull;
26  import static org.junit.Assert.assertTrue;
27  import static org.junit.Assert.fail;
28  import static org.mockito.Mockito.mock;
29  import static org.mockito.Mockito.when;
30  
31  import java.io.IOException;
32  import java.util.ArrayList;
33  import java.util.Collections;
34  import java.util.HashMap;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.NavigableMap;
38  import java.util.NoSuchElementException;
39  import java.util.TreeMap;
40  import java.util.concurrent.PriorityBlockingQueue;
41  
42  import org.apache.hadoop.conf.Configuration;
43  import org.apache.hadoop.fs.FileSystem;
44  import org.apache.hadoop.fs.Path;
45  import org.apache.hadoop.hbase.Cell;
46  import org.apache.hadoop.hbase.CellUtil;
47  import org.apache.hadoop.hbase.HBaseTestingUtility;
48  import org.apache.hadoop.hbase.HConstants;
49  import org.apache.hadoop.hbase.HRegionInfo;
50  import org.apache.hadoop.hbase.HTableDescriptor;
51  import org.apache.hadoop.hbase.KeyValue;
52  import org.apache.hadoop.hbase.TableName;
53  import org.apache.hadoop.hbase.Waiter;
54  import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
55  import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
56  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
57  import org.apache.hadoop.hbase.replication.ChainWALEntryFilter;
58  import org.apache.hadoop.hbase.replication.ReplicationPeer;
59  import org.apache.hadoop.hbase.replication.ReplicationQueueInfo;
60  import org.apache.hadoop.hbase.replication.TableCfWALEntryFilter;
61  import org.apache.hadoop.hbase.replication.WALEntryFilter;
62  import org.apache.hadoop.hbase.replication.regionserver.ReplicationSourceWALReaderThread.WALEntryBatch;
63  import org.apache.hadoop.hbase.testclassification.LargeTests;
64  import org.apache.hadoop.hbase.testclassification.ReplicationTests;
65  import org.apache.hadoop.hbase.util.Bytes;
66  import org.apache.hadoop.hbase.wal.WAL;
67  import org.apache.hadoop.hbase.wal.WAL.Entry;
68  import org.apache.hadoop.hbase.wal.WALFactory;
69  import org.apache.hadoop.hbase.wal.WALKey;
70  import org.apache.hadoop.hdfs.MiniDFSCluster;
71  import org.junit.After;
72  import org.junit.AfterClass;
73  import org.junit.Before;
74  import org.junit.BeforeClass;
75  import org.junit.Rule;
76  import org.junit.Test;
77  import org.junit.experimental.categories.Category;
78  import org.junit.rules.TestName;
79  import org.junit.runner.RunWith;
80  import org.mockito.Mockito;
81  import org.mockito.runners.MockitoJUnitRunner;
82  
83  @RunWith(MockitoJUnitRunner.class)
84  @Category({ ReplicationTests.class, LargeTests.class })
85  public class TestWALEntryStream {
86  
87    private static HBaseTestingUtility TEST_UTIL;
88    private static Configuration conf;
89    private static FileSystem fs;
90    private static MiniDFSCluster cluster;
91    private static final TableName tableName = TableName.valueOf("tablename");
92    private static final byte[] family = Bytes.toBytes("column");
93    private static final byte[] qualifier = Bytes.toBytes("qualifier");
94    private static final HRegionInfo info =
95        new HRegionInfo(tableName, HConstants.EMPTY_START_ROW, HConstants.LAST_ROW, false);
96    private static final HTableDescriptor htd = new HTableDescriptor(tableName);
97    private static NavigableMap<byte[], Integer> scopes;
98  
99    private WAL log;
100   PriorityBlockingQueue<Path> walQueue;
101   private PathWatcher pathWatcher;
102 
103   @Rule
104   public TestName tn = new TestName();
105   private final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
106 
107   @BeforeClass
108   public static void setUpBeforeClass() throws Exception {
109     TEST_UTIL = new HBaseTestingUtility();
110     conf = TEST_UTIL.getConfiguration();
111     TEST_UTIL.startMiniDFSCluster(3);
112 
113     cluster = TEST_UTIL.getDFSCluster();
114     fs = cluster.getFileSystem();
115     scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);
116     for (byte[] fam : htd.getFamiliesKeys()) {
117       scopes.put(fam, 0);
118     }
119   }
120 
121   @AfterClass
122   public static void tearDownAfterClass() throws Exception {
123     TEST_UTIL.shutdownMiniCluster();
124   }
125 
126   @Before
127   public void setUp() throws Exception {
128     walQueue = new PriorityBlockingQueue<>();
129     List<WALActionsListener> listeners = new ArrayList<WALActionsListener>();
130     pathWatcher = new PathWatcher();
131     listeners.add(pathWatcher);
132     final WALFactory wals = new WALFactory(conf, listeners, tn.getMethodName());
133     log = wals.getWAL(info.getEncodedNameAsBytes(), info.getTable().getNamespace());
134   }
135 
136   @After
137   public void tearDown() throws Exception {
138     log.close();
139   }
140 
141   // Try out different combinations of row count and KeyValue count
142   @Test
143   public void testDifferentCounts() throws Exception {
144     int[] NB_ROWS = { 1500, 60000 };
145     int[] NB_KVS = { 1, 100 };
146     // whether compression is used
147     Boolean[] BOOL_VALS = { false, true };
148     // long lastPosition = 0;
149     for (int nbRows : NB_ROWS) {
150       for (int walEditKVs : NB_KVS) {
151         for (boolean isCompressionEnabled : BOOL_VALS) {
152           TEST_UTIL.getConfiguration().setBoolean(HConstants.ENABLE_WAL_COMPRESSION,
153             isCompressionEnabled);
154           mvcc.advanceTo(1);
155 
156           for (int i = 0; i < nbRows; i++) {
157             appendToLogPlus(walEditKVs);
158           }
159 
160           log.rollWriter();
161 
162           try (WALEntryStream entryStream =
163               new WALEntryStream(walQueue, fs, conf, new MetricsSource("1"))) {
164             int i = 0;
165             for (WAL.Entry e : entryStream) {
166               assertNotNull(e);
167               i++;
168             }
169             assertEquals(nbRows, i);
170 
171             // should've read all entries
172             assertFalse(entryStream.hasNext());
173           }
174           // reset everything for next loop
175           log.close();
176           setUp();
177         }
178       }
179     }
180   }
181 
182   /**
183    * Tests basic reading of log appends
184    */
185   @Test
186   public void testAppendsWithRolls() throws Exception {
187     appendToLog();
188 
189     long oldPos;
190     try (WALEntryStream entryStream =
191         new WALEntryStream(walQueue, fs, conf, new MetricsSource("1"))) {
192       // There's one edit in the log, read it. Reading past it needs to throw exception
193       assertTrue(entryStream.hasNext());
194       WAL.Entry entry = entryStream.next();
195       assertNotNull(entry);
196       assertFalse(entryStream.hasNext());
197       try {
198         entry = entryStream.next();
199         fail();
200       } catch (NoSuchElementException e) {
201         // expected
202       }
203       oldPos = entryStream.getPosition();
204     }
205 
206     appendToLog();
207 
208     try (WALEntryStream entryStream =
209         new WALEntryStream(walQueue, fs, conf, oldPos, new MetricsSource("1"))) {
210       // Read the newly added entry, make sure we made progress
211       WAL.Entry entry = entryStream.next();
212       assertNotEquals(oldPos, entryStream.getPosition());
213       assertNotNull(entry);
214       oldPos = entryStream.getPosition();
215     }
216 
217     // We rolled but we still should see the end of the first log and get that item
218     appendToLog();
219     log.rollWriter();
220     appendToLog();
221 
222     try (WALEntryStream entryStream =
223         new WALEntryStream(walQueue, fs, conf, oldPos, new MetricsSource("1"))) {
224       WAL.Entry entry = entryStream.next();
225       assertNotEquals(oldPos, entryStream.getPosition());
226       assertNotNull(entry);
227 
228       // next item should come from the new log
229       entry = entryStream.next();
230       assertNotEquals(oldPos, entryStream.getPosition());
231       assertNotNull(entry);
232 
233       // no more entries to read
234       assertFalse(entryStream.hasNext());
235       oldPos = entryStream.getPosition();
236     }
237   }
238 
239   /**
240    * Tests that if after a stream is opened, more entries come in and then the log is rolled, we
241    * don't mistakenly dequeue the current log thinking we're done with it
242    */
243   @Test
244   public void testLogrollWhileStreaming() throws Exception {
245     appendToLog("1");
246     appendToLog("2");// 2
247     try (WALEntryStream entryStream =
248         new WALEntryStream(walQueue, fs, conf, new MetricsSource("1"))) {
249       assertEquals("1", getRow(entryStream.next()));
250 
251       appendToLog("3"); // 3 - comes in after reader opened
252       log.rollWriter(); // log roll happening while we're reading
253       appendToLog("4"); // 4 - this append is in the rolled log
254 
255       assertEquals("2", getRow(entryStream.next()));
256       assertEquals(2, walQueue.size()); // we should not have dequeued yet since there's still an
257                                         // entry in first log
258       assertEquals("3", getRow(entryStream.next())); // if implemented improperly, this would be 4
259                                                      // and 3 would be skipped
260       assertEquals("4", getRow(entryStream.next())); // 4
261       assertEquals(1, walQueue.size()); // now we've dequeued and moved on to next log properly
262       assertFalse(entryStream.hasNext());
263     }
264   }
265 
266   /**
267    * Tests that if writes come in while we have a stream open, we shouldn't miss them
268    */
269   @Test
270   public void testNewEntriesWhileStreaming() throws Exception {
271     appendToLog("1");
272     try (WALEntryStream entryStream =
273         new WALEntryStream(walQueue, fs, conf, 0, new MetricsSource("1"))) {
274       entryStream.next(); // we've hit the end of the stream at this point
275 
276       // some new entries come in while we're streaming
277       appendToLog("2");
278       appendToLog("3");
279 
280       // don't see them
281       assertFalse(entryStream.hasNext());
282 
283       // But we do if we reset
284       entryStream.reset();
285       assertEquals("2", getRow(entryStream.next()));
286       assertEquals("3", getRow(entryStream.next()));
287       assertFalse(entryStream.hasNext());
288     }
289   }
290 
291   @Test
292   public void testResumeStreamingFromPosition() throws Exception {
293     long lastPosition = 0;
294     appendToLog("1");
295     try (WALEntryStream entryStream =
296         new WALEntryStream(walQueue, fs, conf, 0, new MetricsSource("1"))) {
297       entryStream.next(); // we've hit the end of the stream at this point
298       appendToLog("2");
299       appendToLog("3");
300       lastPosition = entryStream.getPosition();
301     }
302     // next stream should picks up where we left off
303     try (WALEntryStream entryStream =
304         new WALEntryStream(walQueue, fs, conf, lastPosition, new MetricsSource("1"))) {
305       assertEquals("2", getRow(entryStream.next()));
306       assertEquals("3", getRow(entryStream.next()));
307       assertFalse(entryStream.hasNext()); // done
308       assertEquals(1, walQueue.size());
309     }
310   }
311 
312   /**
313    * Tests that if we stop before hitting the end of a stream, we can continue where we left off
314    * using the last position
315    */
316   @Test
317   public void testPosition() throws Exception {
318     long lastPosition = 0;
319     appendEntriesToLog(3);
320     // read only one element
321     try (WALEntryStream entryStream =
322         new WALEntryStream(walQueue, fs, conf, lastPosition, new MetricsSource("1"))) {
323       entryStream.next();
324       lastPosition = entryStream.getPosition();
325     }
326     // there should still be two more entries from where we left off
327     try (WALEntryStream entryStream =
328         new WALEntryStream(walQueue, fs, conf, lastPosition, new MetricsSource("1"))) {
329       assertNotNull(entryStream.next());
330       assertNotNull(entryStream.next());
331       assertFalse(entryStream.hasNext());
332     }
333   }
334 
335 
336   @Test
337   public void testEmptyStream() throws Exception {
338     try (WALEntryStream entryStream =
339         new WALEntryStream(walQueue, fs, conf, 0, new MetricsSource("1"))) {
340       assertFalse(entryStream.hasNext());
341     }
342   }
343 
344   @Test
345   public void testReplicationSourceWALReaderThread() throws Exception {
346     appendEntriesToLog(3);
347     // get ending position
348     long position;
349     try (WALEntryStream entryStream =
350         new WALEntryStream(walQueue, fs, conf, new MetricsSource("1"))) {
351       entryStream.next();
352       entryStream.next();
353       entryStream.next();
354       position = entryStream.getPosition();
355     }
356 
357     // start up a batcher
358     ReplicationSourceManager mockSourceManager = Mockito.mock(ReplicationSourceManager.class);
359     ReplicationSourceWALReaderThread batcher = new ReplicationSourceWALReaderThread(mockSourceManager, getQueueInfo(),walQueue, 0,
360         fs, conf, getDummyFilter(), new MetricsSource("1"));
361     Path walPath = walQueue.peek();
362     batcher.start();
363     WALEntryBatch entryBatch = batcher.take();
364 
365     // should've batched up our entries
366     assertNotNull(entryBatch);
367     assertEquals(3, entryBatch.getWalEntries().size());
368     assertEquals(position, entryBatch.getLastWalPosition());
369     assertEquals(walPath, entryBatch.getLastWalPath());
370     assertEquals(3, entryBatch.getNbRowKeys());
371 
372     appendToLog("foo");
373     entryBatch = batcher.take();
374     assertEquals(1, entryBatch.getNbEntries());
375     assertEquals(getRow(entryBatch.getWalEntries().get(0)), "foo");
376   }
377 
378   @Test
379   public void testReplicationSourceWALReaderThreadRecoveredQueue() throws Exception {
380     appendEntriesToLog(3);
381     log.rollWriter();
382     appendEntriesToLog(2);
383 
384     long position;
385     try (WALEntryStream entryStream = new WALEntryStream(new PriorityBlockingQueue<>(walQueue),
386             fs, conf, new MetricsSource("1"))) {
387       entryStream.next();
388       entryStream.next();
389       entryStream.next();
390       entryStream.next();
391       entryStream.next();
392       position = entryStream.getPosition();
393     }
394 
395     ReplicationSourceManager mockSourceManager = mock(ReplicationSourceManager.class);
396     ReplicationSourceWALReaderThread reader =
397             new ReplicationSourceWALReaderThread(mockSourceManager, getRecoveredQueueInfo(),
398                     walQueue, 0, fs, conf, getDummyFilter(), new MetricsSource("1"));
399     Path walPath = walQueue.toArray(new Path[2])[1];
400     reader.start();
401     WALEntryBatch entryBatch = reader.take();
402 
403     assertNotNull(entryBatch);
404     assertEquals(5, entryBatch.getWalEntries().size());
405     assertEquals(position, entryBatch.getLastWalPosition());
406     assertEquals(walPath, entryBatch.getLastWalPath());
407     assertFalse(entryBatch.hasMoreEntries());
408   }
409 
410   @Test
411   public void testReplicationSourceWALReaderThreadWithFilter() throws Exception {
412     final byte[] notReplicatedCf = Bytes.toBytes("notReplicated");
413     final Map<TableName, List<String>> tableCfs = new HashMap<>();
414     tableCfs.put(tableName, Collections.singletonList(Bytes.toString(family)));
415     ReplicationPeer peer = mock(ReplicationPeer.class);
416     when(peer.getTableCFs()).thenReturn(tableCfs);
417     WALEntryFilter filter = new ChainWALEntryFilter(new TableCfWALEntryFilter(peer));
418 
419     // add filterable entries
420     appendToLogPlus(3, notReplicatedCf);
421     appendToLogPlus(3, notReplicatedCf);
422     appendToLogPlus(3, notReplicatedCf);
423 
424     // add non filterable entries
425     appendEntriesToLog(2);
426 
427     ReplicationSourceManager mockSourceManager = mock(ReplicationSourceManager.class);
428     final ReplicationSourceWALReaderThread reader =
429             new ReplicationSourceWALReaderThread(mockSourceManager, getQueueInfo(), walQueue,
430                     0, fs, conf, filter, new MetricsSource("1"));
431     reader.start();
432 
433     WALEntryBatch entryBatch = reader.take();
434 
435     assertNotNull(entryBatch);
436     assertFalse(entryBatch.isEmpty());
437     List<Entry> walEntries = entryBatch.getWalEntries();
438     assertEquals(2, walEntries.size());
439     for (Entry entry : walEntries) {
440       ArrayList<Cell> cells = entry.getEdit().getCells();
441       assertTrue(cells.size() == 1);
442       assertTrue(CellUtil.matchingFamily(cells.get(0), family));
443     }
444   }
445 
446   @Test
447   public void testReplicationSourceWALReaderThreadWithFilterWhenLogRolled() throws Exception {
448     final byte[] notReplicatedCf = Bytes.toBytes("notReplicated");
449     final Map<TableName, List<String>> tableCfs = new HashMap<>();
450     tableCfs.put(tableName, Collections.singletonList(Bytes.toString(family)));
451     ReplicationPeer peer = mock(ReplicationPeer.class);
452     when(peer.getTableCFs()).thenReturn(tableCfs);
453     WALEntryFilter filter = new ChainWALEntryFilter(new TableCfWALEntryFilter(peer));
454 
455     appendToLogPlus(3, notReplicatedCf);
456 
457     Path firstWAL = walQueue.peek();
458     final long eof = getPosition(firstWAL);
459 
460     ReplicationSourceManager mockSourceManager = mock(ReplicationSourceManager.class);
461     final ReplicationSourceWALReaderThread reader =
462             new ReplicationSourceWALReaderThread(mockSourceManager, getQueueInfo(), walQueue,
463                     0, fs, conf, filter, new MetricsSource("1"));
464     reader.start();
465 
466     // reader won't put any batch, even if EOF reached.
467     Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() {
468       @Override public boolean evaluate() {
469         return reader.getLastReadPosition() >= eof;
470       }
471     });
472     assertNull(reader.poll(0));
473 
474     log.rollWriter();
475 
476     // should get empty batch with current wal position, after wal rolled
477     WALEntryBatch entryBatch = reader.take();
478 
479     Path lastWAL= walQueue.peek();
480     long positionToBeLogged = getPosition(lastWAL);
481 
482     assertNotNull(entryBatch);
483     assertTrue(entryBatch.isEmpty());
484     assertEquals(1, walQueue.size());
485     assertNotEquals(firstWAL, entryBatch.getLastWalPath());
486     assertEquals(lastWAL, entryBatch.getLastWalPath());
487     assertEquals(positionToBeLogged, entryBatch.getLastWalPosition());
488   }
489 
490   private long getPosition(Path walPath) throws IOException {
491     WALEntryStream entryStream =
492             new WALEntryStream(new PriorityBlockingQueue<>(Collections.singletonList(walPath)),
493                     fs, conf, new MetricsSource("1"));
494     entryStream.hasNext();
495     return entryStream.getPosition();
496   }
497 
498   private String getRow(WAL.Entry entry) {
499     Cell cell = entry.getEdit().getCells().get(0);
500     return Bytes.toString(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
501   }
502 
503   private void appendToLog(String key) throws IOException {
504     final long txid = log.append(htd, info,
505       new WALKey(info.getEncodedNameAsBytes(), tableName, System.currentTimeMillis(), mvcc),
506       getWALEdit(key), true);
507     log.sync(txid);
508   }
509 
510   private void appendEntriesToLog(int count) throws IOException {
511     for (int i = 0; i < count; i++) {
512       appendToLog();
513     }
514   }
515 
516   private void appendToLog() throws IOException {
517     appendToLogPlus(1);
518   }
519 
520   private void appendToLogPlus(int count) throws IOException {
521     appendToLogPlus(count, family, qualifier);
522   }
523 
524   private void appendToLogPlus(int count, byte[] cf) throws IOException {
525     appendToLogPlus(count, cf, qualifier);
526   }
527 
528   private void appendToLogPlus(int count, byte[] cf, byte[] cq) throws IOException {
529     final long txid = log.append(htd, info,
530       new WALKey(info.getEncodedNameAsBytes(), tableName, System.currentTimeMillis(), mvcc),
531       getWALEdits(count, cf, cq), true);
532     log.sync(txid);
533   }
534 
535   private WALEdit getWALEdits(int count, byte[] cf, byte[] cq) {
536     WALEdit edit = new WALEdit();
537     for (int i = 0; i < count; i++) {
538       edit.add(new KeyValue(Bytes.toBytes(System.currentTimeMillis()), cf, cq,
539           System.currentTimeMillis(), cq));
540     }
541     return edit;
542   }
543 
544   private WALEdit getWALEdit(String row) {
545     WALEdit edit = new WALEdit();
546     edit.add(
547       new KeyValue(Bytes.toBytes(row), family, qualifier, System.currentTimeMillis(), qualifier));
548     return edit;
549   }
550 
551   private WALEntryFilter getDummyFilter() {
552     return new WALEntryFilter() {
553 
554       @Override
555       public Entry filter(Entry entry) {
556         return entry;
557       }
558     };
559   }
560 
561   private ReplicationQueueInfo getRecoveredQueueInfo() {
562     return getQueueInfo("1-1");
563   }
564 
565   private ReplicationQueueInfo getQueueInfo() {
566     return getQueueInfo("1");
567   }
568 
569   private ReplicationQueueInfo getQueueInfo(String znode) {
570     return new ReplicationQueueInfo(znode);
571   }
572 
573   class PathWatcher extends WALActionsListener.Base {
574 
575     Path currentPath;
576 
577     @Override
578     public void preLogRoll(Path oldPath, Path newPath) throws IOException {
579       walQueue.add(newPath);
580       currentPath = newPath;
581     }
582   }
583 }