View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.replication;
20  
21  import java.io.IOException;
22  import java.util.ArrayList;
23  import java.util.Arrays;
24  import java.util.List;
25  import java.util.UUID;
26  import java.util.concurrent.atomic.AtomicBoolean;
27  import java.util.concurrent.atomic.AtomicInteger;
28  import java.util.concurrent.atomic.AtomicReference;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.hbase.Cell;
33  import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
34  import org.apache.hadoop.hbase.testclassification.MediumTests;
35  import org.apache.hadoop.hbase.HRegionInfo;
36  import org.apache.hadoop.hbase.Waiter;
37  import org.apache.hadoop.hbase.client.Connection;
38  import org.apache.hadoop.hbase.client.ConnectionFactory;
39  import org.apache.hadoop.hbase.client.Put;
40  import org.apache.hadoop.hbase.client.Table;
41  import org.apache.hadoop.hbase.wal.WAL.Entry;
42  import org.apache.hadoop.hbase.regionserver.HRegion;
43  import org.apache.hadoop.hbase.replication.regionserver.*;
44  import org.apache.hadoop.hbase.util.Bytes;
45  import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
46  import org.apache.hadoop.hbase.util.Threads;
47  import org.apache.hadoop.hbase.zookeeper.ZKConfig;
48  import org.apache.hadoop.metrics2.lib.DynamicMetricsRegistry;
49  import org.junit.AfterClass;
50  import org.junit.Assert;
51  import org.junit.Before;
52  import org.junit.BeforeClass;
53  import org.junit.Test;
54  import org.junit.experimental.categories.Category;
55  
56  import static org.mockito.Mockito.mock;
57  import static org.mockito.Mockito.verify;
58  import static org.mockito.Mockito.when;
59  
60  /**
61   * Tests ReplicationSource and ReplicationEndpoint interactions
62   */
63  @Category(MediumTests.class)
64  public class TestReplicationEndpoint extends TestReplicationBase {
65    private static final Log LOG = LogFactory.getLog(TestReplicationEndpoint.class);
66  
67    static int numRegionServers;
68  
69    @BeforeClass
70    public static void setUpBeforeClass() throws Exception {
71      TestReplicationBase.setUpBeforeClass();
72      admin.removePeer("2");
73      numRegionServers = utility1.getHBaseCluster().getRegionServerThreads().size();
74    }
75  
76    @AfterClass
77    public static void tearDownAfterClass() throws Exception {
78      TestReplicationBase.tearDownAfterClass();
79      // check stop is called
80      Assert.assertTrue(ReplicationEndpointForTest.stoppedCount.get() > 0);
81    }
82  
83    @Before
84    public void setup() throws Exception {
85      ReplicationEndpointForTest.contructedCount.set(0);
86      ReplicationEndpointForTest.startedCount.set(0);
87      ReplicationEndpointForTest.replicateCount.set(0);
88      ReplicationEndpointReturningFalse.replicated.set(false);
89      ReplicationEndpointForTest.lastEntries = null;
90      final List<RegionServerThread> rsThreads =
91          utility1.getMiniHBaseCluster().getRegionServerThreads();
92      for (RegionServerThread rs : rsThreads) {
93        utility1.getHBaseAdmin().rollWALWriter(rs.getRegionServer().getServerName());
94      }
95      // Wait for  all log roll to finish
96      utility1.waitFor(3000, new Waiter.ExplainingPredicate<Exception>() {
97        @Override
98        public boolean evaluate() throws Exception {
99          for (RegionServerThread rs : rsThreads) {
100           if (!rs.getRegionServer().walRollRequestFinished()) {
101             return false;
102           }
103         }
104         return true;
105       }
106 
107       @Override
108       public String explainFailure() throws Exception {
109         List<String> logRollInProgressRsList = new ArrayList<String>();
110         for (RegionServerThread rs : rsThreads) {
111           if (!rs.getRegionServer().walRollRequestFinished()) {
112             logRollInProgressRsList.add(rs.getRegionServer().toString());
113           }
114         }
115         return "Still waiting for log roll on regionservers: " + logRollInProgressRsList;
116       }
117     });
118   }
119 
120   @Test (timeout=120000)
121   public void testCustomReplicationEndpoint() throws Exception {
122     // test installing a custom replication endpoint other than the default one.
123     admin.addPeer("testCustomReplicationEndpoint",
124         new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
125             .setReplicationEndpointImpl(ReplicationEndpointForTest.class.getName()), null);
126 
127     // check whether the class has been constructed and started
128     Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
129       @Override
130       public boolean evaluate() throws Exception {
131         return ReplicationEndpointForTest.contructedCount.get() >= numRegionServers;
132       }
133     });
134 
135     Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
136       @Override
137       public boolean evaluate() throws Exception {
138         return ReplicationEndpointForTest.startedCount.get() >= numRegionServers;
139       }
140     });
141 
142     Assert.assertEquals(0, ReplicationEndpointForTest.replicateCount.get());
143 
144     // now replicate some data.
145     doPut(Bytes.toBytes("row42"));
146 
147     Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
148       @Override
149       public boolean evaluate() throws Exception {
150         return ReplicationEndpointForTest.replicateCount.get() >= 1;
151       }
152     });
153 
154     doAssert(Bytes.toBytes("row42"));
155 
156     admin.removePeer("testCustomReplicationEndpoint");
157   }
158 
159   @Test (timeout=120000)
160   public void testReplicationEndpointReturnsFalseOnReplicate() throws Exception {
161     Assert.assertEquals(0, ReplicationEndpointForTest.replicateCount.get());
162     Assert.assertTrue(!ReplicationEndpointReturningFalse.replicated.get());
163     int peerCount = admin.getPeersCount();
164     final String id = "testReplicationEndpointReturnsFalseOnReplicate";
165     admin.addPeer(id,
166       new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
167         .setReplicationEndpointImpl(ReplicationEndpointReturningFalse.class.getName()), null);
168     // This test is flakey and then there is so much stuff flying around in here its, hard to
169     // debug.  Peer needs to be up for the edit to make it across. This wait on
170     // peer count seems to be a hack that has us not progress till peer is up.
171     if (admin.getPeersCount() <= peerCount) {
172       LOG.info("Waiting on peercount to go up from " + peerCount);
173       Threads.sleep(100);
174     }
175     // now replicate some data
176     doPut(row);
177 
178     Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
179       @Override
180       public boolean evaluate() throws Exception {
181         // Looks like replication endpoint returns false unless we put more than 10 edits. We
182         // only send over one edit.
183         int count = ReplicationEndpointForTest.replicateCount.get();
184         LOG.info("count=" + count);
185         return ReplicationEndpointReturningFalse.replicated.get();
186       }
187     });
188     if (ReplicationEndpointReturningFalse.ex.get() != null) {
189       throw ReplicationEndpointReturningFalse.ex.get();
190     }
191 
192     admin.removePeer("testReplicationEndpointReturnsFalseOnReplicate");
193   }
194 
195   @Test (timeout=120000)
196   public void testInterClusterReplication() throws Exception {
197     final String id = "testInterClusterReplication";
198 
199     List<HRegion> regions = utility1.getHBaseCluster().getRegions(tableName);
200     int totEdits = 0;
201 
202     // Make sure edits are spread across regions because we do region based batching
203     // before shipping edits.
204     for(HRegion region: regions) {
205       HRegionInfo hri = region.getRegionInfo();
206       byte[] row = hri.getStartKey();
207       for (int i = 0; i < 100; i++) {
208         if (row.length > 0) {
209           Put put = new Put(row);
210           put.addColumn(famName, row, row);
211           region.put(put);
212           totEdits++;
213         }
214       }
215     }
216 
217     admin.addPeer(id,
218         new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf2))
219             .setReplicationEndpointImpl(InterClusterReplicationEndpointForTest.class.getName()),
220         null);
221 
222     final int numEdits = totEdits;
223     Waiter.waitFor(conf1, 30000, new Waiter.ExplainingPredicate<Exception>() {
224       @Override
225       public boolean evaluate() throws Exception {
226         return InterClusterReplicationEndpointForTest.replicateCount.get() == numEdits;
227       }
228       @Override
229       public String explainFailure() throws Exception {
230         String failure = "Failed to replicate all edits, expected = " + numEdits
231             + " replicated = " + InterClusterReplicationEndpointForTest.replicateCount.get();
232         return failure;
233       }
234     });
235 
236     admin.removePeer("testInterClusterReplication");
237     utility1.deleteTableData(tableName);
238   }
239 
240   @Test (timeout=120000)
241   public void testWALEntryFilterFromReplicationEndpoint() throws Exception {
242     ReplicationPeerConfig rpc =  new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
243             .setReplicationEndpointImpl(ReplicationEndpointWithWALEntryFilter.class.getName());
244     //test that we can create mutliple WALFilters reflectively
245     rpc.getConfiguration().put(ReplicationAdmin.REPLICATION_WALENTRYFILTER_CONFIG_KEY,
246         EverythingPassesWALEntryFilter.class.getName() + ","
247             + EverythingPassesWALEntryFilterSubclass.class.getName());
248     admin.addPeer("testWALEntryFilterFromReplicationEndpoint", rpc);
249     // now replicate some data.
250     try (Connection connection = ConnectionFactory.createConnection(conf1)) {
251       doPut(connection, Bytes.toBytes("row1"));
252       doPut(connection, row);
253       doPut(connection, Bytes.toBytes("row2"));
254     }
255 
256     Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
257       @Override
258       public boolean evaluate() throws Exception {
259         return ReplicationEndpointForTest.replicateCount.get() >= 1;
260       }
261     });
262 
263     Assert.assertNull(ReplicationEndpointWithWALEntryFilter.ex.get());
264     //make sure our reflectively created filter is in the filter chain
265     Assert.assertTrue(EverythingPassesWALEntryFilter.hasPassedAnEntry());
266     admin.removePeer("testWALEntryFilterFromReplicationEndpoint");
267   }
268 
269   @Test (timeout=120000, expected=ReplicationException.class)
270   public void testWALEntryFilterAddValidation() throws Exception {
271     ReplicationPeerConfig rpc =  new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
272             .setReplicationEndpointImpl(ReplicationEndpointWithWALEntryFilter.class.getName());
273     //test that we can create mutliple WALFilters reflectively
274         rpc.getConfiguration().put(ReplicationAdmin.REPLICATION_WALENTRYFILTER_CONFIG_KEY,
275                 "IAmNotARealWalEntryFilter");
276     admin.addPeer("testWALEntryFilterAddValidation", rpc);
277   }
278 
279       @Test (timeout=120000, expected=ReplicationException.class)
280   public void testWALEntryFilterUpdateValidation() throws Exception {
281     ReplicationPeerConfig rpc =  new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
282             .setReplicationEndpointImpl(ReplicationEndpointWithWALEntryFilter.class.getName());
283     //test that we can create mutliple WALFilters reflectively
284         rpc.getConfiguration().put(ReplicationAdmin.REPLICATION_WALENTRYFILTER_CONFIG_KEY,
285                 "IAmNotARealWalEntryFilter");
286     admin.updatePeerConfig("testWALEntryFilterUpdateValidation", rpc);
287   }
288 
289 
290   @Test
291   public void testMetricsSourceBaseSourcePassthrough(){
292     /*
293     The replication MetricsSource wraps a MetricsReplicationSourceSourceImpl
294     and a MetricsReplicationGlobalSourceSource, so that metrics get written to both namespaces.
295     Both of those classes wrap a MetricsReplicationSourceImpl that implements BaseSource, which
296     allows for custom JMX metrics.
297     This test checks to make sure the BaseSource decorator logic on MetricsSource actually calls down through
298     the two layers of wrapping to the actual BaseSource.
299     */
300     String id = "id";
301     DynamicMetricsRegistry mockRegistry = mock(DynamicMetricsRegistry.class);
302     MetricsReplicationSourceImpl singleRms = mock(MetricsReplicationSourceImpl.class);
303     when(singleRms.getMetricsRegistry()).thenReturn(mockRegistry);
304     MetricsReplicationSourceImpl globalRms = mock(MetricsReplicationSourceImpl.class);
305     when(globalRms.getMetricsRegistry()).thenReturn(mockRegistry);
306 
307     MetricsReplicationSourceSource singleSourceSource = new MetricsReplicationSourceSourceImpl(singleRms, id);
308     MetricsReplicationSourceSource globalSourceSource = new MetricsReplicationGlobalSourceSource(globalRms);
309     MetricsSource source = new MetricsSource(id, singleSourceSource, globalSourceSource);
310     String gaugeName = "gauge";
311     String singleGaugeName = "source.id." + gaugeName;
312     long delta = 1;
313     String counterName = "counter";
314     String singleCounterName = "source.id." + counterName;
315     long count = 2;
316     source.decGauge(gaugeName, delta);
317     source.getMetricsContext();
318     source.getMetricsDescription();
319     source.getMetricsJmxContext();
320     source.getMetricsName();
321     source.incCounters(counterName, count);
322     source.incGauge(gaugeName, delta);
323     source.init();
324     source.removeMetric(gaugeName);
325     source.setGauge(gaugeName, delta);
326     source.updateHistogram(counterName, count);
327 
328     verify(singleRms).decGauge(singleGaugeName, delta);
329     verify(globalRms).decGauge(gaugeName, delta);
330     verify(globalRms).getMetricsContext();
331     verify(globalRms).getMetricsJmxContext();
332     verify(globalRms).getMetricsName();
333     verify(singleRms).incCounters(singleCounterName, count);
334     verify(globalRms).incCounters(counterName, count);
335     verify(singleRms).incGauge(singleGaugeName, delta);
336     verify(globalRms).incGauge(gaugeName, delta);
337     verify(globalRms).init();
338     verify(singleRms).removeMetric(singleGaugeName);
339     verify(globalRms).removeMetric(gaugeName);
340     verify(singleRms).setGauge(singleGaugeName, delta);
341     verify(globalRms).setGauge(gaugeName, delta);
342     verify(singleRms).updateHistogram(singleCounterName, count);
343     verify(globalRms).updateHistogram(counterName, count);
344   }
345 
346   private void doPut(byte[] row) throws IOException {
347     try (Connection connection = ConnectionFactory.createConnection(conf1)) {
348       doPut(connection, row);
349     }
350   }
351 
352   private void doPut(final Connection connection, final byte [] row) throws IOException {
353     try (Table t = connection.getTable(tableName)) {
354       Put put = new Put(row);
355       put.add(famName, row, row);
356       t.put(put);
357     }
358   }
359 
360   private static void doAssert(byte[] row) throws Exception {
361     if (ReplicationEndpointForTest.lastEntries == null) {
362       return; // first call
363     }
364     Assert.assertEquals(1, ReplicationEndpointForTest.lastEntries.size());
365     List<Cell> cells = ReplicationEndpointForTest.lastEntries.get(0).getEdit().getCells();
366     Assert.assertEquals(1, cells.size());
367     Assert.assertTrue(Bytes.equals(cells.get(0).getRowArray(), cells.get(0).getRowOffset(),
368       cells.get(0).getRowLength(), row, 0, row.length));
369   }
370 
371   public static class ReplicationEndpointForTest extends BaseReplicationEndpoint {
372     static UUID uuid = UUID.randomUUID();
373     static AtomicInteger contructedCount = new AtomicInteger();
374     static AtomicInteger startedCount = new AtomicInteger();
375     static AtomicInteger stoppedCount = new AtomicInteger();
376     static AtomicInteger replicateCount = new AtomicInteger();
377     static volatile List<Entry> lastEntries = null;
378 
379     public ReplicationEndpointForTest() {
380       contructedCount.incrementAndGet();
381     }
382 
383     @Override
384     public UUID getPeerUUID() {
385       return uuid;
386     }
387 
388     @Override
389     public boolean replicate(ReplicateContext replicateContext) {
390       replicateCount.incrementAndGet();
391       lastEntries = new ArrayList<>(replicateContext.entries);
392       return true;
393     }
394 
395     @Override
396     protected void doStart() {
397       startedCount.incrementAndGet();
398       notifyStarted();
399     }
400 
401     @Override
402     protected void doStop() {
403       stoppedCount.incrementAndGet();
404       notifyStopped();
405     }
406   }
407 
408   public static class InterClusterReplicationEndpointForTest
409       extends HBaseInterClusterReplicationEndpoint {
410 
411     static AtomicInteger replicateCount = new AtomicInteger();
412     static boolean failedOnce;
413 
414     @Override
415     public boolean replicate(ReplicateContext replicateContext) {
416       boolean success = super.replicate(replicateContext);
417       if (success) {
418         replicateCount.addAndGet(replicateContext.entries.size());
419       }
420       return success;
421     }
422 
423     @Override
424     protected Replicator createReplicator(List<Entry> entries, int ordinal) {
425       // Fail only once, we don't want to slow down the test.
426       if (failedOnce) {
427         return new DummyReplicator(entries, ordinal);
428       } else {
429         failedOnce = true;
430         return new FailingDummyReplicator(entries, ordinal);
431       }
432     }
433 
434     protected class DummyReplicator extends Replicator {
435 
436       private int ordinal;
437 
438       public DummyReplicator(List<Entry> entries, int ordinal) {
439         super(entries, ordinal);
440         this.ordinal = ordinal;
441       }
442 
443       @Override
444       public Integer call() throws IOException {
445         return ordinal;
446       }
447     }
448 
449     protected class FailingDummyReplicator extends DummyReplicator {
450 
451       public FailingDummyReplicator(List<Entry> entries, int ordinal) {
452         super(entries, ordinal);
453       }
454 
455       @Override
456       public Integer call() throws IOException {
457         throw new IOException("Sample Exception: Failed to replicate.");
458       }
459     }
460   }
461 
462   public static class ReplicationEndpointReturningFalse extends ReplicationEndpointForTest {
463     static int COUNT = 10;
464     static AtomicReference<Exception> ex = new AtomicReference<Exception>(null);
465     static AtomicBoolean replicated = new AtomicBoolean(false);
466     @Override
467     public boolean replicate(ReplicateContext replicateContext) {
468       try {
469         // check row
470         doAssert(row);
471       } catch (Exception e) {
472         ex.set(e);
473       }
474 
475       super.replicate(replicateContext);
476       LOG.info("Replicated " + Bytes.toString(row) + ", count=" + replicateCount.get());
477 
478       replicated.set(replicateCount.get() > COUNT); // first 10 times, we return false
479       return replicated.get();
480     }
481   }
482 
483   // return a WALEntry filter which only accepts "row", but not other rows
484   public static class ReplicationEndpointWithWALEntryFilter extends ReplicationEndpointForTest {
485     static AtomicReference<Exception> ex = new AtomicReference<Exception>(null);
486 
487     @Override
488     public boolean replicate(ReplicateContext replicateContext) {
489       try {
490         super.replicate(replicateContext);
491         doAssert(row);
492       } catch (Exception e) {
493         ex.set(e);
494       }
495       return true;
496     }
497 
498     @Override
499     public WALEntryFilter getWALEntryfilter() {
500       return new ChainWALEntryFilter(super.getWALEntryfilter(), new WALEntryFilter() {
501         @Override
502         public Entry filter(Entry entry) {
503           ArrayList<Cell> cells = entry.getEdit().getCells();
504           int size = cells.size();
505           for (int i = size-1; i >= 0; i--) {
506             Cell cell = cells.get(i);
507             if (!Bytes.equals(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(),
508               row, 0, row.length)) {
509               cells.remove(i);
510             }
511           }
512           return entry;
513         }
514       });
515     }
516   }
517 
518   public static class EverythingPassesWALEntryFilter implements WALEntryFilter {
519     private static boolean passedEntry = false;
520     @Override
521     public Entry filter(Entry entry) {
522       passedEntry = true;
523       return entry;
524     }
525 
526     public static boolean hasPassedAnEntry(){
527         return passedEntry;
528     }
529   }
530 
531   public static class EverythingPassesWALEntryFilterSubclass extends EverythingPassesWALEntryFilter {
532 
533   }
534 }