1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.replication;
20
21 import java.io.IOException;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.UUID;
27 import java.util.concurrent.atomic.AtomicBoolean;
28 import java.util.concurrent.atomic.AtomicInteger;
29 import java.util.concurrent.atomic.AtomicReference;
30
31 import org.apache.commons.logging.Log;
32 import org.apache.commons.logging.LogFactory;
33 import org.apache.hadoop.hbase.Cell;
34 import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
35 import org.apache.hadoop.hbase.testclassification.MediumTests;
36 import org.apache.hadoop.hbase.HRegionInfo;
37 import org.apache.hadoop.hbase.Waiter;
38 import org.apache.hadoop.hbase.client.Connection;
39 import org.apache.hadoop.hbase.client.ConnectionFactory;
40 import org.apache.hadoop.hbase.client.Put;
41 import org.apache.hadoop.hbase.client.Table;
42 import org.apache.hadoop.hbase.wal.WAL.Entry;
43 import org.apache.hadoop.hbase.regionserver.HRegion;
44 import org.apache.hadoop.hbase.replication.regionserver.*;
45 import org.apache.hadoop.hbase.util.Bytes;
46 import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
47 import org.apache.hadoop.hbase.util.Threads;
48 import org.apache.hadoop.hbase.zookeeper.ZKConfig;
49 import org.apache.hadoop.metrics2.lib.DynamicMetricsRegistry;
50 import org.junit.AfterClass;
51 import org.junit.Assert;
52 import org.junit.Before;
53 import org.junit.BeforeClass;
54 import org.junit.Test;
55 import org.junit.experimental.categories.Category;
56
57 import static org.mockito.Mockito.doNothing;
58 import static org.mockito.Mockito.mock;
59 import static org.mockito.Mockito.spy;
60 import static org.mockito.Mockito.verify;
61 import static org.mockito.Mockito.when;
62
63
64
65
66 @Category(MediumTests.class)
67 public class TestReplicationEndpoint extends TestReplicationBase {
68 private static final Log LOG = LogFactory.getLog(TestReplicationEndpoint.class);
69
70 static int numRegionServers;
71
72 @BeforeClass
73 public static void setUpBeforeClass() throws Exception {
74 TestReplicationBase.setUpBeforeClass();
75 admin.removePeer("2");
76 numRegionServers = utility1.getHBaseCluster().getRegionServerThreads().size();
77 }
78
79 @AfterClass
80 public static void tearDownAfterClass() throws Exception {
81 TestReplicationBase.tearDownAfterClass();
82
83 Assert.assertTrue(ReplicationEndpointForTest.stoppedCount.get() > 0);
84 }
85
86 @Before
87 public void setup() throws Exception {
88 ReplicationEndpointForTest.contructedCount.set(0);
89 ReplicationEndpointForTest.startedCount.set(0);
90 ReplicationEndpointForTest.replicateCount.set(0);
91 ReplicationEndpointReturningFalse.replicated.set(false);
92 ReplicationEndpointForTest.lastEntries = null;
93 final List<RegionServerThread> rsThreads =
94 utility1.getMiniHBaseCluster().getRegionServerThreads();
95 for (RegionServerThread rs : rsThreads) {
96 utility1.getHBaseAdmin().rollWALWriter(rs.getRegionServer().getServerName());
97 }
98
99 utility1.waitFor(3000, new Waiter.ExplainingPredicate<Exception>() {
100 @Override
101 public boolean evaluate() throws Exception {
102 for (RegionServerThread rs : rsThreads) {
103 if (!rs.getRegionServer().walRollRequestFinished()) {
104 return false;
105 }
106 }
107 return true;
108 }
109
110 @Override
111 public String explainFailure() throws Exception {
112 List<String> logRollInProgressRsList = new ArrayList<String>();
113 for (RegionServerThread rs : rsThreads) {
114 if (!rs.getRegionServer().walRollRequestFinished()) {
115 logRollInProgressRsList.add(rs.getRegionServer().toString());
116 }
117 }
118 return "Still waiting for log roll on regionservers: " + logRollInProgressRsList;
119 }
120 });
121 }
122
123 @Test (timeout=120000)
124 public void testCustomReplicationEndpoint() throws Exception {
125
126 admin.addPeer("testCustomReplicationEndpoint",
127 new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
128 .setReplicationEndpointImpl(ReplicationEndpointForTest.class.getName()), null);
129
130
131 Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
132 @Override
133 public boolean evaluate() throws Exception {
134 return ReplicationEndpointForTest.contructedCount.get() >= numRegionServers;
135 }
136 });
137
138 Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
139 @Override
140 public boolean evaluate() throws Exception {
141 return ReplicationEndpointForTest.startedCount.get() >= numRegionServers;
142 }
143 });
144
145 Assert.assertEquals(0, ReplicationEndpointForTest.replicateCount.get());
146
147
148 doPut(Bytes.toBytes("row42"));
149
150 Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
151 @Override
152 public boolean evaluate() throws Exception {
153 return ReplicationEndpointForTest.replicateCount.get() >= 1;
154 }
155 });
156
157 doAssert(Bytes.toBytes("row42"));
158
159 admin.removePeer("testCustomReplicationEndpoint");
160 }
161
162 @Test (timeout=120000)
163 public void testReplicationEndpointReturnsFalseOnReplicate() throws Exception {
164 Assert.assertEquals(0, ReplicationEndpointForTest.replicateCount.get());
165 Assert.assertTrue(!ReplicationEndpointReturningFalse.replicated.get());
166 int peerCount = admin.getPeersCount();
167 final String id = "testReplicationEndpointReturnsFalseOnReplicate";
168 admin.addPeer(id,
169 new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
170 .setReplicationEndpointImpl(ReplicationEndpointReturningFalse.class.getName()), null);
171
172
173
174 if (admin.getPeersCount() <= peerCount) {
175 LOG.info("Waiting on peercount to go up from " + peerCount);
176 Threads.sleep(100);
177 }
178
179 doPut(row);
180
181 Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
182 @Override
183 public boolean evaluate() throws Exception {
184
185
186 int count = ReplicationEndpointForTest.replicateCount.get();
187 LOG.info("count=" + count);
188 return ReplicationEndpointReturningFalse.replicated.get();
189 }
190 });
191 if (ReplicationEndpointReturningFalse.ex.get() != null) {
192 throw ReplicationEndpointReturningFalse.ex.get();
193 }
194
195 admin.removePeer("testReplicationEndpointReturnsFalseOnReplicate");
196 }
197
198 @Test (timeout=120000)
199 public void testInterClusterReplication() throws Exception {
200 final String id = "testInterClusterReplication";
201
202 List<HRegion> regions = utility1.getHBaseCluster().getRegions(tableName);
203 int totEdits = 0;
204
205
206
207 for(HRegion region: regions) {
208 HRegionInfo hri = region.getRegionInfo();
209 byte[] row = hri.getStartKey();
210 for (int i = 0; i < 100; i++) {
211 if (row.length > 0) {
212 Put put = new Put(row);
213 put.addColumn(famName, row, row);
214 region.put(put);
215 totEdits++;
216 }
217 }
218 }
219
220 admin.addPeer(id,
221 new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf2))
222 .setReplicationEndpointImpl(InterClusterReplicationEndpointForTest.class.getName()),
223 null);
224
225 final int numEdits = totEdits;
226 Waiter.waitFor(conf1, 30000, new Waiter.ExplainingPredicate<Exception>() {
227 @Override
228 public boolean evaluate() throws Exception {
229 return InterClusterReplicationEndpointForTest.replicateCount.get() == numEdits;
230 }
231 @Override
232 public String explainFailure() throws Exception {
233 String failure = "Failed to replicate all edits, expected = " + numEdits
234 + " replicated = " + InterClusterReplicationEndpointForTest.replicateCount.get();
235 return failure;
236 }
237 });
238
239 admin.removePeer("testInterClusterReplication");
240 utility1.deleteTableData(tableName);
241 }
242
243 @Test (timeout=120000)
244 public void testWALEntryFilterFromReplicationEndpoint() throws Exception {
245 ReplicationPeerConfig rpc = new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
246 .setReplicationEndpointImpl(ReplicationEndpointWithWALEntryFilter.class.getName());
247
248 rpc.getConfiguration().put(ReplicationAdmin.REPLICATION_WALENTRYFILTER_CONFIG_KEY,
249 EverythingPassesWALEntryFilter.class.getName() + ","
250 + EverythingPassesWALEntryFilterSubclass.class.getName());
251 admin.addPeer("testWALEntryFilterFromReplicationEndpoint", rpc);
252
253 try (Connection connection = ConnectionFactory.createConnection(conf1)) {
254 doPut(connection, Bytes.toBytes("row1"));
255 doPut(connection, row);
256 doPut(connection, Bytes.toBytes("row2"));
257 }
258
259 Waiter.waitFor(conf1, 60000, new Waiter.Predicate<Exception>() {
260 @Override
261 public boolean evaluate() throws Exception {
262 return ReplicationEndpointForTest.replicateCount.get() >= 1;
263 }
264 });
265
266 Assert.assertNull(ReplicationEndpointWithWALEntryFilter.ex.get());
267
268 Assert.assertTrue(EverythingPassesWALEntryFilter.hasPassedAnEntry());
269 admin.removePeer("testWALEntryFilterFromReplicationEndpoint");
270 }
271
272 @Test (timeout=120000, expected=ReplicationException.class)
273 public void testWALEntryFilterAddValidation() throws Exception {
274 ReplicationPeerConfig rpc = new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
275 .setReplicationEndpointImpl(ReplicationEndpointWithWALEntryFilter.class.getName());
276
277 rpc.getConfiguration().put(ReplicationAdmin.REPLICATION_WALENTRYFILTER_CONFIG_KEY,
278 "IAmNotARealWalEntryFilter");
279 admin.addPeer("testWALEntryFilterAddValidation", rpc);
280 }
281
282 @Test (timeout=120000, expected=ReplicationException.class)
283 public void testWALEntryFilterUpdateValidation() throws Exception {
284 ReplicationPeerConfig rpc = new ReplicationPeerConfig().setClusterKey(ZKConfig.getZooKeeperClusterKey(conf1))
285 .setReplicationEndpointImpl(ReplicationEndpointWithWALEntryFilter.class.getName());
286
287 rpc.getConfiguration().put(ReplicationAdmin.REPLICATION_WALENTRYFILTER_CONFIG_KEY,
288 "IAmNotARealWalEntryFilter");
289 admin.updatePeerConfig("testWALEntryFilterUpdateValidation", rpc);
290 }
291
292
293 @Test
294 public void testMetricsSourceBaseSourcePassthrough(){
295
296
297
298
299
300
301
302
303 String id = "id";
304 DynamicMetricsRegistry mockRegistry = mock(DynamicMetricsRegistry.class);
305 MetricsReplicationSourceImpl singleRms = mock(MetricsReplicationSourceImpl.class);
306 when(singleRms.getMetricsRegistry()).thenReturn(mockRegistry);
307 MetricsReplicationSourceImpl globalRms = mock(MetricsReplicationSourceImpl.class);
308 when(globalRms.getMetricsRegistry()).thenReturn(mockRegistry);
309
310 MetricsReplicationSourceSource singleSourceSource = new MetricsReplicationSourceSourceImpl(singleRms, id);
311 MetricsReplicationSourceSource globalSourceSource = new MetricsReplicationGlobalSourceSource(globalRms);
312 MetricsReplicationSourceSource spyglobalSourceSource = spy(globalSourceSource);
313 doNothing().when(spyglobalSourceSource).incrFailedRecoveryQueue();
314 Map<String, MetricsReplicationSourceSource> singleSourceSourceByTable = new HashMap<>();
315 MetricsSource source = new MetricsSource(id, singleSourceSource, spyglobalSourceSource,
316 singleSourceSourceByTable);
317 String gaugeName = "gauge";
318 String singleGaugeName = "source.id." + gaugeName;
319 long delta = 1;
320 String counterName = "counter";
321 String singleCounterName = "source.id." + counterName;
322 long count = 2;
323 source.decGauge(gaugeName, delta);
324 source.getMetricsContext();
325 source.getMetricsDescription();
326 source.getMetricsJmxContext();
327 source.getMetricsName();
328 source.incCounters(counterName, count);
329 source.incGauge(gaugeName, delta);
330 source.init();
331 source.removeMetric(gaugeName);
332 source.setGauge(gaugeName, delta);
333 source.updateHistogram(counterName, count);
334 source.incrFailedRecoveryQueue();
335
336 verify(singleRms).decGauge(singleGaugeName, delta);
337 verify(globalRms).decGauge(gaugeName, delta);
338 verify(globalRms).getMetricsContext();
339 verify(globalRms).getMetricsJmxContext();
340 verify(globalRms).getMetricsName();
341 verify(singleRms).incCounters(singleCounterName, count);
342 verify(globalRms).incCounters(counterName, count);
343 verify(singleRms).incGauge(singleGaugeName, delta);
344 verify(globalRms).incGauge(gaugeName, delta);
345 verify(globalRms).init();
346 verify(singleRms).removeMetric(singleGaugeName);
347 verify(globalRms).removeMetric(gaugeName);
348 verify(singleRms).setGauge(singleGaugeName, delta);
349 verify(globalRms).setGauge(gaugeName, delta);
350 verify(singleRms).updateHistogram(singleCounterName, count);
351 verify(globalRms).updateHistogram(counterName, count);
352 verify(spyglobalSourceSource).incrFailedRecoveryQueue();
353
354
355
356
357 boolean containsRandomNewTable = source.getSingleSourceSourceByTable()
358 .containsKey("RandomNewTable");
359 Assert.assertEquals(false, containsRandomNewTable);
360 source.setAgeOfLastShippedOpByTable(123L, "RandomNewTable");
361 containsRandomNewTable = source.getSingleSourceSourceByTable()
362 .containsKey("RandomNewTable");
363 Assert.assertEquals(true, containsRandomNewTable);
364 MetricsReplicationSourceSource msr = source.getSingleSourceSourceByTable()
365 .get("RandomNewTable");
366
367
368 Assert.assertTrue(msr.getLastShippedAge() > 0);
369 }
370
371 private void doPut(byte[] row) throws IOException {
372 try (Connection connection = ConnectionFactory.createConnection(conf1)) {
373 doPut(connection, row);
374 }
375 }
376
377 private void doPut(final Connection connection, final byte [] row) throws IOException {
378 try (Table t = connection.getTable(tableName)) {
379 Put put = new Put(row);
380 put.add(famName, row, row);
381 t.put(put);
382 }
383 }
384
385 private static void doAssert(byte[] row) throws Exception {
386 if (ReplicationEndpointForTest.lastEntries == null) {
387 return;
388 }
389 Assert.assertEquals(1, ReplicationEndpointForTest.lastEntries.size());
390 List<Cell> cells = ReplicationEndpointForTest.lastEntries.get(0).getEdit().getCells();
391 Assert.assertEquals(1, cells.size());
392 Assert.assertTrue(Bytes.equals(cells.get(0).getRowArray(), cells.get(0).getRowOffset(),
393 cells.get(0).getRowLength(), row, 0, row.length));
394 }
395
396 public static class ReplicationEndpointForTest extends BaseReplicationEndpoint {
397 static UUID uuid = UUID.randomUUID();
398 static AtomicInteger contructedCount = new AtomicInteger();
399 static AtomicInteger startedCount = new AtomicInteger();
400 static AtomicInteger stoppedCount = new AtomicInteger();
401 static AtomicInteger replicateCount = new AtomicInteger();
402 static volatile List<Entry> lastEntries = null;
403
404 public ReplicationEndpointForTest() {
405 contructedCount.incrementAndGet();
406 }
407
408 @Override
409 public UUID getPeerUUID() {
410 return uuid;
411 }
412
413 @Override
414 public boolean replicate(ReplicateContext replicateContext) {
415 replicateCount.incrementAndGet();
416 lastEntries = new ArrayList<>(replicateContext.entries);
417 return true;
418 }
419
420 @Override
421 protected void doStart() {
422 startedCount.incrementAndGet();
423 notifyStarted();
424 }
425
426 @Override
427 protected void doStop() {
428 stoppedCount.incrementAndGet();
429 notifyStopped();
430 }
431 }
432
433 public static class InterClusterReplicationEndpointForTest
434 extends HBaseInterClusterReplicationEndpoint {
435
436 static AtomicInteger replicateCount = new AtomicInteger();
437 static boolean failedOnce;
438
439 @Override
440 public boolean replicate(ReplicateContext replicateContext) {
441 boolean success = super.replicate(replicateContext);
442 if (success) {
443 replicateCount.addAndGet(replicateContext.entries.size());
444 }
445 return success;
446 }
447
448 @Override
449 protected Replicator createReplicator(List<Entry> entries, int ordinal) {
450
451 if (failedOnce) {
452 return new DummyReplicator(entries, ordinal);
453 } else {
454 failedOnce = true;
455 return new FailingDummyReplicator(entries, ordinal);
456 }
457 }
458
459 protected class DummyReplicator extends Replicator {
460
461 private int ordinal;
462
463 public DummyReplicator(List<Entry> entries, int ordinal) {
464 super(entries, ordinal);
465 this.ordinal = ordinal;
466 }
467
468 @Override
469 public Integer call() throws IOException {
470 return ordinal;
471 }
472 }
473
474 protected class FailingDummyReplicator extends DummyReplicator {
475
476 public FailingDummyReplicator(List<Entry> entries, int ordinal) {
477 super(entries, ordinal);
478 }
479
480 @Override
481 public Integer call() throws IOException {
482 throw new IOException("Sample Exception: Failed to replicate.");
483 }
484 }
485 }
486
487 public static class ReplicationEndpointReturningFalse extends ReplicationEndpointForTest {
488 static int COUNT = 10;
489 static AtomicReference<Exception> ex = new AtomicReference<Exception>(null);
490 static AtomicBoolean replicated = new AtomicBoolean(false);
491 @Override
492 public boolean replicate(ReplicateContext replicateContext) {
493 try {
494
495 doAssert(row);
496 } catch (Exception e) {
497 ex.set(e);
498 }
499
500 super.replicate(replicateContext);
501 LOG.info("Replicated " + Bytes.toString(row) + ", count=" + replicateCount.get());
502
503 replicated.set(replicateCount.get() > COUNT);
504 return replicated.get();
505 }
506 }
507
508
509 public static class ReplicationEndpointWithWALEntryFilter extends ReplicationEndpointForTest {
510 static AtomicReference<Exception> ex = new AtomicReference<Exception>(null);
511
512 @Override
513 public boolean replicate(ReplicateContext replicateContext) {
514 try {
515 super.replicate(replicateContext);
516 doAssert(row);
517 } catch (Exception e) {
518 ex.set(e);
519 }
520 return true;
521 }
522
523 @Override
524 public WALEntryFilter getWALEntryfilter() {
525 return new ChainWALEntryFilter(super.getWALEntryfilter(), new WALEntryFilter() {
526 @Override
527 public Entry filter(Entry entry) {
528 ArrayList<Cell> cells = entry.getEdit().getCells();
529 int size = cells.size();
530 for (int i = size-1; i >= 0; i--) {
531 Cell cell = cells.get(i);
532 if (!Bytes.equals(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(),
533 row, 0, row.length)) {
534 cells.remove(i);
535 }
536 }
537 return entry;
538 }
539 });
540 }
541 }
542
543 public static class EverythingPassesWALEntryFilter implements WALEntryFilter {
544 private static boolean passedEntry = false;
545 @Override
546 public Entry filter(Entry entry) {
547 passedEntry = true;
548 return entry;
549 }
550
551 public static boolean hasPassedAnEntry(){
552 return passedEntry;
553 }
554 }
555
556 public static class EverythingPassesWALEntryFilterSubclass extends EverythingPassesWALEntryFilter {
557
558 }
559 }