001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.replication.regionserver; 019 020import static org.apache.hadoop.hbase.wal.AbstractFSWALProvider.META_WAL_PROVIDER_ID; 021import static org.junit.jupiter.api.Assertions.assertEquals; 022import static org.junit.jupiter.api.Assertions.assertFalse; 023import static org.junit.jupiter.api.Assertions.assertNotNull; 024import static org.junit.jupiter.api.Assertions.assertNull; 025import static org.junit.jupiter.api.Assertions.assertTrue; 026import static org.mockito.Mockito.mock; 027import static org.mockito.Mockito.when; 028 029import java.io.IOException; 030import java.util.ArrayList; 031import java.util.OptionalLong; 032import java.util.UUID; 033import java.util.concurrent.ExecutorService; 034import java.util.concurrent.Executors; 035import java.util.concurrent.Future; 036import org.apache.hadoop.conf.Configuration; 037import org.apache.hadoop.fs.FileSystem; 038import org.apache.hadoop.fs.Path; 039import org.apache.hadoop.hbase.Cell; 040import org.apache.hadoop.hbase.CellBuilderType; 041import org.apache.hadoop.hbase.CompatibilitySingletonFactory; 042import org.apache.hadoop.hbase.ExtendedCellBuilderFactory; 043import org.apache.hadoop.hbase.HBaseConfiguration; 044import org.apache.hadoop.hbase.HBaseTestingUtil; 045import org.apache.hadoop.hbase.HConstants; 046import org.apache.hadoop.hbase.KeyValue; 047import org.apache.hadoop.hbase.Server; 048import org.apache.hadoop.hbase.ServerName; 049import org.apache.hadoop.hbase.SingleProcessHBaseCluster; 050import org.apache.hadoop.hbase.StartTestingClusterOption; 051import org.apache.hadoop.hbase.TableName; 052import org.apache.hadoop.hbase.Waiter; 053import org.apache.hadoop.hbase.client.Admin; 054import org.apache.hadoop.hbase.regionserver.HRegionServer; 055import org.apache.hadoop.hbase.regionserver.RegionServerServices; 056import org.apache.hadoop.hbase.replication.ReplicationEndpoint; 057import org.apache.hadoop.hbase.replication.ReplicationPeer; 058import org.apache.hadoop.hbase.replication.ReplicationPeerConfig; 059import org.apache.hadoop.hbase.replication.ReplicationQueueData; 060import org.apache.hadoop.hbase.replication.ReplicationQueueId; 061import org.apache.hadoop.hbase.replication.WALEntryFilter; 062import org.apache.hadoop.hbase.testclassification.MediumTests; 063import org.apache.hadoop.hbase.testclassification.ReplicationTests; 064import org.apache.hadoop.hbase.util.Bytes; 065import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 066import org.apache.hadoop.hbase.util.ManualEnvironmentEdge; 067import org.apache.hadoop.hbase.wal.WAL; 068import org.apache.hadoop.hbase.wal.WALEdit; 069import org.apache.hadoop.hbase.wal.WALEditInternalHelper; 070import org.apache.hadoop.hbase.wal.WALFactory; 071import org.apache.hadoop.hbase.wal.WALKeyImpl; 072import org.apache.hadoop.hbase.wal.WALProvider; 073import org.apache.hadoop.hbase.wal.WALStreamReader; 074import org.junit.jupiter.api.AfterAll; 075import org.junit.jupiter.api.BeforeAll; 076import org.junit.jupiter.api.Tag; 077import org.junit.jupiter.api.Test; 078import org.mockito.Mockito; 079import org.slf4j.Logger; 080import org.slf4j.LoggerFactory; 081 082import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableMap; 083 084@Tag(ReplicationTests.TAG) 085@Tag(MediumTests.TAG) 086public class TestReplicationSource { 087 088 private static final Logger LOG = LoggerFactory.getLogger(TestReplicationSource.class); 089 private final static HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil(); 090 private final static HBaseTestingUtil TEST_UTIL_PEER = new HBaseTestingUtil(); 091 private static FileSystem FS; 092 private static Path oldLogDir; 093 private static Path logDir; 094 private static Configuration conf = TEST_UTIL.getConfiguration(); 095 096 @BeforeAll 097 public static void setUpBeforeClass() throws Exception { 098 TEST_UTIL.startMiniDFSCluster(1); 099 FS = TEST_UTIL.getDFSCluster().getFileSystem(); 100 Path rootDir = TEST_UTIL.createRootDir(); 101 oldLogDir = new Path(rootDir, HConstants.HREGION_OLDLOGDIR_NAME); 102 if (FS.exists(oldLogDir)) { 103 FS.delete(oldLogDir, true); 104 } 105 logDir = new Path(rootDir, HConstants.HREGION_LOGDIR_NAME); 106 if (FS.exists(logDir)) { 107 FS.delete(logDir, true); 108 } 109 } 110 111 @AfterAll 112 public static void tearDownAfterClass() throws Exception { 113 try { 114 TEST_UTIL_PEER.shutdownMiniCluster(); 115 } finally { 116 TEST_UTIL.shutdownMiniCluster(); 117 } 118 } 119 120 /** 121 * Test the default ReplicationSource skips queuing hbase:meta WAL files. 122 */ 123 @Test 124 public void testDefaultSkipsMetaWAL() throws IOException { 125 ReplicationSource rs = new ReplicationSource(); 126 Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); 127 conf.setInt("replication.source.maxretriesmultiplier", 1); 128 ReplicationPeer mockPeer = Mockito.mock(ReplicationPeer.class); 129 Mockito.when(mockPeer.getConfiguration()).thenReturn(conf); 130 Mockito.when(mockPeer.getPeerBandwidth()).thenReturn(0L); 131 ReplicationPeerConfig peerConfig = Mockito.mock(ReplicationPeerConfig.class); 132 Mockito.when(peerConfig.getReplicationEndpointImpl()) 133 .thenReturn(DoNothingReplicationEndpoint.class.getName()); 134 Mockito.when(mockPeer.getPeerConfig()).thenReturn(peerConfig); 135 ReplicationSourceManager manager = Mockito.mock(ReplicationSourceManager.class); 136 Mockito.when(manager.getGlobalMetrics()) 137 .thenReturn(mock(MetricsReplicationGlobalSourceSource.class)); 138 139 RegionServerServices rss = 140 TEST_UTIL.createMockRegionServerService(ServerName.parseServerName("a.b.c,1,1")); 141 ReplicationQueueId queueId = new ReplicationQueueId(rss.getServerName(), "qid"); 142 rs.init(conf, null, manager, null, mockPeer, rss, 143 new ReplicationQueueData(queueId, ImmutableMap.of()), null, p -> OptionalLong.empty(), 144 new MetricsSource(queueId.toString())); 145 try { 146 rs.startup(); 147 assertTrue(rs.isSourceActive()); 148 assertEquals(0, rs.getSourceMetrics().getSizeOfLogQueue()); 149 rs.enqueueLog(new Path("a.1" + META_WAL_PROVIDER_ID)); 150 assertEquals(0, rs.getSourceMetrics().getSizeOfLogQueue()); 151 rs.enqueueLog(new Path("a.1")); 152 assertEquals(1, rs.getSourceMetrics().getSizeOfLogQueue()); 153 } finally { 154 rs.terminate("Done"); 155 rss.stop("Done"); 156 } 157 } 158 159 /** 160 * Test that we filter out meta edits, etc. 161 */ 162 @Test 163 public void testWALEntryFilter() throws IOException { 164 // To get the fully constructed default WALEntryFilter, need to create a ReplicationSource 165 // instance and init it. 166 ReplicationSource rs = new ReplicationSource(); 167 UUID uuid = UUID.randomUUID(); 168 Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); 169 ReplicationPeer mockPeer = Mockito.mock(ReplicationPeer.class); 170 Mockito.when(mockPeer.getConfiguration()).thenReturn(conf); 171 Mockito.when(mockPeer.getPeerBandwidth()).thenReturn(0L); 172 ReplicationPeerConfig peerConfig = Mockito.mock(ReplicationPeerConfig.class); 173 Mockito.when(peerConfig.getReplicationEndpointImpl()) 174 .thenReturn(DoNothingReplicationEndpoint.class.getName()); 175 Mockito.when(mockPeer.getPeerConfig()).thenReturn(peerConfig); 176 ReplicationSourceManager manager = Mockito.mock(ReplicationSourceManager.class); 177 RegionServerServices rss = 178 TEST_UTIL.createMockRegionServerService(ServerName.parseServerName("a.b.c,1,1")); 179 ReplicationQueueId queueId = new ReplicationQueueId(rss.getServerName(), "qid"); 180 rs.init(conf, null, manager, null, mockPeer, rss, 181 new ReplicationQueueData(queueId, ImmutableMap.of()), uuid, p -> OptionalLong.empty(), 182 new MetricsSource(queueId.toString())); 183 try { 184 rs.startup(); 185 TEST_UTIL.waitFor(30000, () -> rs.getWalEntryFilter() != null); 186 WALEntryFilter wef = rs.getWalEntryFilter(); 187 // Test non-system WAL edit. 188 WALEdit we = WALEditInternalHelper.addExtendedCell(new WALEdit(), 189 ExtendedCellBuilderFactory.create(CellBuilderType.DEEP_COPY) 190 .setRow(HConstants.EMPTY_START_ROW).setFamily(HConstants.CATALOG_FAMILY) 191 .setType(Cell.Type.Put).build()); 192 WAL.Entry e = new WAL.Entry( 193 new WALKeyImpl(HConstants.EMPTY_BYTE_ARRAY, TableName.valueOf("test"), -1, -1, uuid), we); 194 assertTrue(wef.filter(e) == e); 195 // Test system WAL edit. 196 e = new WAL.Entry( 197 new WALKeyImpl(HConstants.EMPTY_BYTE_ARRAY, TableName.META_TABLE_NAME, -1, -1, uuid), we); 198 assertNull(wef.filter(e)); 199 } finally { 200 rs.terminate("Done"); 201 rss.stop("Done"); 202 } 203 } 204 205 /** 206 * Sanity check that we can move logs around while we are reading from them. Should this test 207 * fail, ReplicationSource would have a hard time reading logs that are being archived. 208 */ 209 // This tests doesn't belong in here... it is not about ReplicationSource. 210 @Test 211 public void testLogMoving() throws Exception { 212 Path logPath = new Path(logDir, "log"); 213 if (!FS.exists(logDir)) { 214 FS.mkdirs(logDir); 215 } 216 if (!FS.exists(oldLogDir)) { 217 FS.mkdirs(oldLogDir); 218 } 219 WALProvider.Writer writer = 220 WALFactory.createWALWriter(FS, logPath, TEST_UTIL.getConfiguration()); 221 for (int i = 0; i < 3; i++) { 222 byte[] b = Bytes.toBytes(Integer.toString(i)); 223 KeyValue kv = new KeyValue(b, b, b); 224 WALEdit edit = new WALEdit(); 225 WALEditInternalHelper.addExtendedCell(edit, kv); 226 WALKeyImpl key = new WALKeyImpl(b, TableName.valueOf(b), 0, 0, HConstants.DEFAULT_CLUSTER_ID); 227 writer.append(new WAL.Entry(key, edit)); 228 writer.sync(false); 229 } 230 writer.close(); 231 232 WALStreamReader reader = 233 WALFactory.createStreamReader(FS, logPath, TEST_UTIL.getConfiguration()); 234 WAL.Entry entry = reader.next(); 235 assertNotNull(entry); 236 237 Path oldLogPath = new Path(oldLogDir, "log"); 238 FS.rename(logPath, oldLogPath); 239 240 entry = reader.next(); 241 assertNotNull(entry); 242 243 reader.next(); 244 entry = reader.next(); 245 246 assertNull(entry); 247 reader.close(); 248 } 249 250 /** 251 * Tests that {@link ReplicationSource#terminate(String)} will timeout properly Moved here from 252 * TestReplicationSource because doesn't need cluster. 253 */ 254 @Test 255 public void testTerminateTimeout() throws Exception { 256 ReplicationSource source = new ReplicationSource(); 257 ReplicationEndpoint replicationEndpoint = new DoNothingReplicationEndpoint(); 258 try { 259 replicationEndpoint.start(); 260 ReplicationPeer mockPeer = Mockito.mock(ReplicationPeer.class); 261 Mockito.when(mockPeer.getPeerBandwidth()).thenReturn(0L); 262 Configuration testConf = HBaseConfiguration.create(); 263 testConf.setInt("replication.source.maxretriesmultiplier", 1); 264 ReplicationSourceManager manager = Mockito.mock(ReplicationSourceManager.class); 265 ReplicationQueueId queueId = 266 new ReplicationQueueId(ServerName.valueOf("test,123,123"), "testPeer"); 267 source.init(testConf, null, manager, null, mockPeer, null, 268 new ReplicationQueueData(queueId, ImmutableMap.of()), null, p -> OptionalLong.empty(), 269 null); 270 ExecutorService executor = Executors.newSingleThreadExecutor(); 271 Future<?> future = executor.submit(() -> source.terminate("testing source termination")); 272 long sleepForRetries = testConf.getLong("replication.source.sleepforretries", 1000); 273 Waiter.waitFor(testConf, sleepForRetries * 2, (Waiter.Predicate<Exception>) future::isDone); 274 } finally { 275 replicationEndpoint.stop(); 276 } 277 } 278 279 @Test 280 public void testTerminateClearsBuffer() throws Exception { 281 ReplicationSource source = new ReplicationSource(); 282 ReplicationSourceManager mockManager = new ReplicationSourceManager(null, null, conf, null, 283 null, null, null, null, null, null, mock(MetricsReplicationGlobalSourceSource.class)); 284 ReplicationPeer mockPeer = mock(ReplicationPeer.class); 285 Mockito.when(mockPeer.getPeerBandwidth()).thenReturn(0L); 286 Configuration testConf = HBaseConfiguration.create(); 287 ReplicationQueueId queueId = 288 new ReplicationQueueId(ServerName.valueOf("test,123,123"), "testPeer"); 289 source.init(testConf, null, mockManager, null, mockPeer, Mockito.mock(Server.class), 290 new ReplicationQueueData(queueId, ImmutableMap.of()), null, p -> OptionalLong.empty(), 291 mock(MetricsSource.class)); 292 ReplicationSourceWALReader reader = 293 new ReplicationSourceWALReader(null, conf, null, 0, null, source, null); 294 ReplicationSourceShipper shipper = new ReplicationSourceShipper(conf, null, source, reader); 295 source.workerThreads.put("testPeer", shipper); 296 WALEntryBatch batch = new WALEntryBatch(10, logDir); 297 WAL.Entry mockEntry = mock(WAL.Entry.class); 298 WALEdit mockEdit = mock(WALEdit.class); 299 WALKeyImpl mockKey = mock(WALKeyImpl.class); 300 when(mockEntry.getEdit()).thenReturn(mockEdit); 301 when(mockEdit.isEmpty()).thenReturn(false); 302 when(mockEntry.getKey()).thenReturn(mockKey); 303 when(mockKey.estimatedSerializedSizeOf()).thenReturn(1000L); 304 when(mockEdit.heapSize()).thenReturn(10000L); 305 when(mockEdit.size()).thenReturn(0); 306 ArrayList<Cell> cells = new ArrayList<>(); 307 KeyValue kv = new KeyValue(Bytes.toBytes("0001"), Bytes.toBytes("f"), Bytes.toBytes("1"), 308 Bytes.toBytes("v1")); 309 cells.add(kv); 310 when(mockEdit.getCells()).thenReturn(cells); 311 reader.addEntryToBatch(batch, mockEntry); 312 reader.entryBatchQueue.put(batch); 313 source.terminate("test"); 314 assertEquals(0, source.getSourceManager().getTotalBufferUsed()); 315 } 316 317 /** 318 * Tests that recovered queues are preserved on a regionserver shutdown. See HBASE-18192 319 */ 320 @Test 321 public void testServerShutdownRecoveredQueue() throws Exception { 322 Configuration originalConf = new Configuration(conf); 323 try { 324 // Ensure single-threaded WAL 325 conf.set("hbase.wal.provider", "defaultProvider"); 326 conf.setInt("replication.sleep.before.failover", 2000); 327 // Introduces a delay in regionserver shutdown to give the race condition a chance to kick in. 328 conf.set(HConstants.REGION_SERVER_IMPL, ShutdownDelayRegionServer.class.getName()); 329 SingleProcessHBaseCluster cluster = TEST_UTIL.startMiniCluster( 330 StartTestingClusterOption.builder().numRegionServers(2).createRootDir(true).build()); 331 TEST_UTIL_PEER.startMiniCluster(1); 332 333 HRegionServer serverA = cluster.getRegionServer(0); 334 final ReplicationSourceManager managerA = 335 serverA.getReplicationSourceService().getReplicationManager(); 336 HRegionServer serverB = cluster.getRegionServer(1); 337 final ReplicationSourceManager managerB = 338 serverB.getReplicationSourceService().getReplicationManager(); 339 final Admin admin = TEST_UTIL.getAdmin(); 340 341 final String peerId = "TestPeer"; 342 admin.addReplicationPeer(peerId, ReplicationPeerConfig.newBuilder() 343 .setClusterKey(TEST_UTIL_PEER.getRpcConnnectionURI()).build()); 344 // Wait for replication sources to come up 345 Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() { 346 @Override 347 public boolean evaluate() { 348 return !(managerA.getSources().isEmpty() || managerB.getSources().isEmpty()); 349 } 350 }); 351 // Disabling peer makes sure there is at least one log to claim when the server dies 352 // The recovered queue will also stay there until the peer is disabled even if the 353 // WALs it contains have no data. 354 admin.disableReplicationPeer(peerId); 355 356 // Stopping serverA 357 // It's queues should be claimed by the only other alive server i.e. serverB 358 cluster.stopRegionServer(serverA.getServerName()); 359 Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() { 360 @Override 361 public boolean evaluate() throws Exception { 362 return managerB.getOldSources().size() == 1; 363 } 364 }); 365 366 final HRegionServer serverC = cluster.startRegionServer().getRegionServer(); 367 serverC.waitForServerOnline(); 368 Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() { 369 @Override 370 public boolean evaluate() throws Exception { 371 return serverC.getReplicationSourceService() != null; 372 } 373 }); 374 final ReplicationSourceManager managerC = 375 ((Replication) serverC.getReplicationSourceService()).getReplicationManager(); 376 // Sanity check 377 assertEquals(0, managerC.getOldSources().size()); 378 379 // Stopping serverB 380 // Now serverC should have two recovered queues: 381 // 1. The serverB's normal queue 382 // 2. serverA's recovered queue on serverB 383 cluster.stopRegionServer(serverB.getServerName()); 384 Waiter.waitFor(conf, 20000, 385 (Waiter.Predicate<Exception>) () -> managerC.getOldSources().size() == 2); 386 admin.enableReplicationPeer(peerId); 387 Waiter.waitFor(conf, 20000, 388 (Waiter.Predicate<Exception>) () -> managerC.getOldSources().size() == 0); 389 } finally { 390 for (String key : new String[] { "hbase.wal.provider", "replication.sleep.before.failover", 391 HConstants.REGION_SERVER_IMPL }) { 392 String value = originalConf.get(key); 393 if (value != null) { 394 conf.set(key, value); 395 } else { 396 conf.unset(key); 397 } 398 } 399 } 400 } 401 402 /** 403 * Regionserver implementation that adds a delay on the graceful shutdown. 404 */ 405 public static class ShutdownDelayRegionServer extends HRegionServer { 406 public ShutdownDelayRegionServer(Configuration conf) throws IOException { 407 super(conf); 408 } 409 410 @Override 411 protected void stopServiceThreads() { 412 // Add a delay before service threads are shutdown. 413 // This will keep the zookeeper connection alive for the duration of the delay. 414 LOG.info("Adding a delay to the regionserver shutdown"); 415 try { 416 Thread.sleep(2000); 417 } catch (InterruptedException ex) { 418 LOG.error("Interrupted while sleeping"); 419 } 420 super.stopServiceThreads(); 421 } 422 } 423 424 /** 425 * Deadend Endpoint. Does nothing. 426 */ 427 public static class DoNothingReplicationEndpoint extends HBaseInterClusterReplicationEndpoint { 428 private final UUID uuid = UUID.randomUUID(); 429 430 @Override 431 public void init(Context context) throws IOException { 432 this.ctx = context; 433 } 434 435 @Override 436 public WALEntryFilter getWALEntryfilter() { 437 return null; 438 } 439 440 @Override 441 public synchronized UUID getPeerUUID() { 442 return this.uuid; 443 } 444 445 @Override 446 protected void doStart() { 447 notifyStarted(); 448 } 449 450 @Override 451 protected void doStop() { 452 notifyStopped(); 453 } 454 455 @Override 456 public boolean canReplicateToSameCluster() { 457 return true; 458 } 459 } 460 461 /** 462 * Deadend Endpoint. Does nothing. 463 */ 464 public static class FlakyReplicationEndpoint extends DoNothingReplicationEndpoint { 465 466 static int count = 0; 467 468 @Override 469 public synchronized UUID getPeerUUID() { 470 if (count == 0) { 471 count++; 472 throw new RuntimeException(); 473 } else { 474 return super.getPeerUUID(); 475 } 476 } 477 478 } 479 480 /** 481 * Bad Endpoint with failing connection to peer on demand. 482 */ 483 public static class BadReplicationEndpoint extends DoNothingReplicationEndpoint { 484 static boolean failing = true; 485 486 @Override 487 public synchronized UUID getPeerUUID() { 488 return failing ? null : super.getPeerUUID(); 489 } 490 } 491 492 public static class FaultyReplicationEndpoint extends DoNothingReplicationEndpoint { 493 494 static int count = 0; 495 496 @Override 497 public synchronized UUID getPeerUUID() { 498 throw new RuntimeException(); 499 } 500 501 } 502 503 private RegionServerServices setupForAbortTests(ReplicationSource rs, Configuration conf, 504 String endpointName) throws IOException { 505 conf.setInt("replication.source.maxretriesmultiplier", 1); 506 ReplicationPeer mockPeer = Mockito.mock(ReplicationPeer.class); 507 Mockito.when(mockPeer.getConfiguration()).thenReturn(conf); 508 Mockito.when(mockPeer.getPeerBandwidth()).thenReturn(0L); 509 ReplicationPeerConfig peerConfig = Mockito.mock(ReplicationPeerConfig.class); 510 FaultyReplicationEndpoint.count = 0; 511 Mockito.when(peerConfig.getReplicationEndpointImpl()).thenReturn(endpointName); 512 Mockito.when(mockPeer.getPeerConfig()).thenReturn(peerConfig); 513 ReplicationSourceManager manager = Mockito.mock(ReplicationSourceManager.class); 514 Mockito.when(manager.getGlobalMetrics()) 515 .thenReturn(mock(MetricsReplicationGlobalSourceSource.class)); 516 RegionServerServices rss = 517 TEST_UTIL.createMockRegionServerService(ServerName.parseServerName("a.b.c,1,1")); 518 ReplicationQueueId queueId = new ReplicationQueueId(rss.getServerName(), "qid"); 519 rs.init(conf, null, manager, null, mockPeer, rss, 520 new ReplicationQueueData(queueId, ImmutableMap.of()), null, p -> OptionalLong.empty(), 521 new MetricsSource(queueId.toString())); 522 return rss; 523 } 524 525 /** 526 * Test ReplicationSource retries startup once an uncaught exception happens during initialization 527 * and <b>eplication.source.regionserver.abort</b> is set to false. 528 */ 529 @Test 530 public void testAbortFalseOnError() throws IOException { 531 Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); 532 conf.setBoolean("replication.source.regionserver.abort", false); 533 ReplicationSource rs = new ReplicationSource(); 534 RegionServerServices rss = 535 setupForAbortTests(rs, conf, FlakyReplicationEndpoint.class.getName()); 536 try { 537 rs.startup(); 538 assertTrue(rs.isSourceActive()); 539 assertEquals(0, rs.getSourceMetrics().getSizeOfLogQueue()); 540 rs.enqueueLog(new Path("a.1" + META_WAL_PROVIDER_ID)); 541 assertEquals(0, rs.getSourceMetrics().getSizeOfLogQueue()); 542 rs.enqueueLog(new Path("a.1")); 543 assertEquals(1, rs.getSourceMetrics().getSizeOfLogQueue()); 544 } finally { 545 rs.terminate("Done"); 546 rss.stop("Done"); 547 } 548 } 549 550 @Test 551 public void testReplicationSourceInitializingMetric() throws IOException { 552 Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); 553 conf.setBoolean("replication.source.regionserver.abort", false); 554 ReplicationSource rs = new ReplicationSource(); 555 RegionServerServices rss = setupForAbortTests(rs, conf, BadReplicationEndpoint.class.getName()); 556 try { 557 rs.startup(); 558 assertTrue(rs.isSourceActive()); 559 Waiter.waitFor(conf, 10000, () -> rs.getSourceMetrics().getSourceInitializing() == 1); 560 BadReplicationEndpoint.failing = false; 561 Waiter.waitFor(conf, 10000, () -> rs.getSourceMetrics().getSourceInitializing() == 0); 562 } finally { 563 rs.terminate("Done"); 564 rss.stop("Done"); 565 } 566 } 567 568 /** 569 * Test ReplicationSource keeps retrying startup indefinitely without blocking the main thread, 570 * when <b>replication.source.regionserver.abort</b> is set to false. 571 */ 572 @Test 573 public void testAbortFalseOnErrorDoesntBlockMainThread() throws IOException { 574 Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); 575 ReplicationSource rs = new ReplicationSource(); 576 RegionServerServices rss = 577 setupForAbortTests(rs, conf, FaultyReplicationEndpoint.class.getName()); 578 try { 579 rs.startup(); 580 assertTrue(true); 581 } finally { 582 rs.terminate("Done"); 583 rss.stop("Done"); 584 } 585 } 586 587 /** 588 * Test ReplicationSource retries startup once an uncaught exception happens during initialization 589 * and <b>replication.source.regionserver.abort</b> is set to true. 590 */ 591 @Test 592 public void testAbortTrueOnError() throws IOException { 593 Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); 594 ReplicationSource rs = new ReplicationSource(); 595 RegionServerServices rss = 596 setupForAbortTests(rs, conf, FlakyReplicationEndpoint.class.getName()); 597 try { 598 rs.startup(); 599 assertTrue(rs.isSourceActive()); 600 Waiter.waitFor(conf, 1000, () -> rss.isAborted()); 601 assertTrue(rss.isAborted()); 602 Waiter.waitFor(conf, 1000, () -> !rs.isSourceActive()); 603 assertFalse(rs.isSourceActive()); 604 } finally { 605 rs.terminate("Done"); 606 rss.stop("Done"); 607 } 608 } 609 610 /* 611 * Test age of oldest wal metric. 612 */ 613 @Test 614 public void testAgeOfOldestWal() throws Exception { 615 try { 616 ManualEnvironmentEdge manualEdge = new ManualEnvironmentEdge(); 617 EnvironmentEdgeManager.injectEdge(manualEdge); 618 619 String peerId = "1"; 620 MetricsSource metrics = new MetricsSource(peerId); 621 Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); 622 conf.setInt("replication.source.maxretriesmultiplier", 1); 623 ReplicationPeer mockPeer = Mockito.mock(ReplicationPeer.class); 624 Mockito.when(mockPeer.getConfiguration()).thenReturn(conf); 625 Mockito.when(mockPeer.getPeerBandwidth()).thenReturn(0L); 626 ReplicationPeerConfig peerConfig = Mockito.mock(ReplicationPeerConfig.class); 627 Mockito.when(peerConfig.getReplicationEndpointImpl()) 628 .thenReturn(DoNothingReplicationEndpoint.class.getName()); 629 Mockito.when(mockPeer.getPeerConfig()).thenReturn(peerConfig); 630 ReplicationSourceManager manager = Mockito.mock(ReplicationSourceManager.class); 631 Mockito.when(manager.getGlobalMetrics()) 632 .thenReturn(mock(MetricsReplicationGlobalSourceSource.class)); 633 RegionServerServices rss = 634 TEST_UTIL.createMockRegionServerService(ServerName.parseServerName("a.b.c,1,1")); 635 ReplicationQueueId queueId = new ReplicationQueueId(rss.getServerName(), peerId); 636 ReplicationSource source = new ReplicationSource(); 637 source.init(conf, null, manager, null, mockPeer, rss, 638 new ReplicationQueueData(queueId, ImmutableMap.of()), null, p -> OptionalLong.empty(), 639 metrics); 640 641 final Path log1 = new Path(logDir, "log-walgroup-a.8"); 642 manualEdge.setValue(10); 643 // Diff of current time (10) and log-walgroup-a.8 timestamp will be 2. 644 source.enqueueLog(log1); 645 MetricsReplicationSourceSource metricsSource1 = getSourceMetrics(peerId); 646 assertEquals(2, metricsSource1.getOldestWalAge()); 647 648 final Path log2 = new Path(logDir, "log-walgroup-b.4"); 649 // Diff of current time (10) and log-walgroup-b.4 will be 6 so oldestWalAge should be 6 650 source.enqueueLog(log2); 651 assertEquals(6, metricsSource1.getOldestWalAge()); 652 // Clear all metrics. 653 metrics.clear(); 654 } finally { 655 EnvironmentEdgeManager.reset(); 656 } 657 } 658 659 private MetricsReplicationSourceSource getSourceMetrics(String sourceId) { 660 MetricsReplicationSourceFactoryImpl factory = 661 (MetricsReplicationSourceFactoryImpl) CompatibilitySingletonFactory 662 .getInstance(MetricsReplicationSourceFactory.class); 663 return factory.getSource(sourceId); 664 } 665}