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  
20  package org.apache.hadoop.hbase.replication;
21  
22  import static org.apache.hadoop.hbase.replication.TestReplicationEndpoint.ReplicationEndpointForTest;
23  import static org.hamcrest.CoreMatchers.is;
24  import static org.hamcrest.MatcherAssert.assertThat;
25  import static org.junit.Assert.assertEquals;
26  import static org.junit.Assert.assertNotNull;
27  import static org.junit.Assert.assertNull;
28  import static org.junit.Assert.assertTrue;
29  import static org.mockito.Matchers.anyBoolean;
30  import static org.mockito.Matchers.anyString;
31  import static org.mockito.Mockito.mock;
32  import static org.mockito.Mockito.verify;
33  import static org.mockito.Mockito.when;
34  import static org.mockito.internal.verification.VerificationModeFactory.times;
35  
36  import java.io.IOException;
37  import java.util.Collections;
38  import java.util.List;
39  import java.util.Map;
40  import java.util.NavigableMap;
41  import java.util.TreeMap;
42  import java.util.UUID;
43  import java.util.concurrent.ExecutorService;
44  import java.util.concurrent.Executors;
45  import java.util.concurrent.Future;
46  
47  import org.apache.commons.logging.Log;
48  import org.apache.commons.logging.LogFactory;
49  import org.apache.hadoop.conf.Configuration;
50  import org.apache.hadoop.fs.FileSystem;
51  import org.apache.hadoop.fs.Path;
52  import org.apache.hadoop.hbase.CoordinatedStateManager;
53  import org.apache.hadoop.hbase.HBaseConfiguration;
54  import org.apache.hadoop.hbase.HBaseTestingUtility;
55  import org.apache.hadoop.hbase.HConstants;
56  import org.apache.hadoop.hbase.KeyValue;
57  import org.apache.hadoop.hbase.MiniHBaseCluster;
58  import org.apache.hadoop.hbase.Stoppable;
59  import org.apache.hadoop.hbase.TableName;
60  import org.apache.hadoop.hbase.Waiter;
61  import org.apache.hadoop.hbase.Waiter.Predicate;
62  import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
63  import org.apache.hadoop.hbase.regionserver.HRegionServer;
64  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
65  import org.apache.hadoop.hbase.replication.regionserver.HBaseInterClusterReplicationEndpoint;
66  import org.apache.hadoop.hbase.replication.regionserver.MetricsSource;
67  import org.apache.hadoop.hbase.replication.regionserver.Replication;
68  import org.apache.hadoop.hbase.replication.regionserver.ReplicationSource;
69  import org.apache.hadoop.hbase.replication.regionserver.ReplicationSourceManager;
70  import org.apache.hadoop.hbase.testclassification.MediumTests;
71  import org.apache.hadoop.hbase.util.Bytes;
72  import org.apache.hadoop.hbase.wal.WAL;
73  import org.apache.hadoop.hbase.wal.WALFactory;
74  import org.apache.hadoop.hbase.wal.WALKey;
75  import org.apache.hadoop.hbase.wal.WALProvider;
76  import org.junit.After;
77  import org.junit.AfterClass;
78  import org.junit.Before;
79  import org.junit.BeforeClass;
80  import org.junit.Test;
81  import org.junit.experimental.categories.Category;
82  import org.mockito.ArgumentCaptor;
83  import org.mockito.Mockito;
84  
85  @Category(MediumTests.class)
86  public class TestReplicationSource {
87  
88    private static final Log LOG =
89        LogFactory.getLog(TestReplicationSource.class);
90    private final static HBaseTestingUtility TEST_UTIL =
91        new HBaseTestingUtility();
92    private final static HBaseTestingUtility TEST_UTIL_PEER =
93        new HBaseTestingUtility();
94    private static FileSystem FS;
95    private static Path oldLogDir;
96    private static Path logDir;
97    private static Configuration conf = TEST_UTIL.getConfiguration();
98  
99    /**
100    * @throws java.lang.Exception
101    */
102   @BeforeClass
103   public static void setUpBeforeClass() throws Exception {
104     TEST_UTIL.startMiniDFSCluster(1);
105     FS = TEST_UTIL.getDFSCluster().getFileSystem();
106     Path rootDir = TEST_UTIL.createRootDir();
107     oldLogDir = new Path(rootDir, HConstants.HREGION_OLDLOGDIR_NAME);
108     if (FS.exists(oldLogDir)) FS.delete(oldLogDir, true);
109     logDir = new Path(rootDir, HConstants.HREGION_LOGDIR_NAME);
110     if (FS.exists(logDir)) FS.delete(logDir, true);
111   }
112 
113   @Before
114   public void setup() throws IOException {
115     if (!FS.exists(logDir)) {
116       FS.mkdirs(logDir);
117     }
118     if (!FS.exists(oldLogDir)) {
119       FS.mkdirs(oldLogDir);
120     }
121 
122     ReplicationEndpointForTest.contructedCount.set(0);
123     ReplicationEndpointForTest.startedCount.set(0);
124     ReplicationEndpointForTest.replicateCount.set(0);
125     ReplicationEndpointForTest.stoppedCount.set(0);
126     ReplicationEndpointForTest.lastEntries = null;
127   }
128 
129   @After
130   public void tearDown() throws IOException {
131     if (FS.exists(oldLogDir)) {
132       FS.delete(oldLogDir, true);
133     }
134     if (FS.exists(logDir)) {
135       FS.delete(logDir, true);
136     }
137   }
138 
139   @AfterClass
140   public static void tearDownAfterClass() throws Exception {
141     TEST_UTIL_PEER.shutdownMiniHBaseCluster();
142     TEST_UTIL.shutdownMiniHBaseCluster();
143     TEST_UTIL.shutdownMiniDFSCluster();
144   }
145 
146   /**
147    * Sanity check that we can move logs around while we are reading
148    * from them. Should this test fail, ReplicationSource would have a hard
149    * time reading logs that are being archived.
150    * @throws Exception
151    */
152   @Test
153   public void testLogMoving() throws Exception{
154     Path logPath = new Path(logDir, "log");
155     WALProvider.Writer writer = WALFactory.createWALWriter(FS, logPath,
156         TEST_UTIL.getConfiguration());
157     for(int i = 0; i < 3; i++) {
158       byte[] b = Bytes.toBytes(Integer.toString(i));
159       KeyValue kv = new KeyValue(b,b,b);
160       WALEdit edit = new WALEdit();
161       edit.add(kv);
162       WALKey key = new WALKey(b, TableName.valueOf(b), 0, 0,
163           HConstants.DEFAULT_CLUSTER_ID);
164       writer.append(new WAL.Entry(key, edit));
165       writer.sync();
166     }
167     writer.close();
168 
169     WAL.Reader reader = WALFactory.createReader(FS, logPath, TEST_UTIL.getConfiguration());
170     WAL.Entry entry = reader.next();
171     assertNotNull(entry);
172 
173     Path oldLogPath = new Path(oldLogDir, "log");
174     FS.rename(logPath, oldLogPath);
175 
176     entry = reader.next();
177     assertNotNull(entry);
178 
179     entry = reader.next();
180     entry = reader.next();
181 
182     assertNull(entry);
183     reader.close();
184   }
185 
186   /**
187    * Tests that {@link ReplicationSource#terminate(String)} will timeout properly
188    */
189   @Test
190   public void testTerminateTimeout() throws Exception {
191     final ReplicationSource source = new ReplicationSource();
192     ReplicationEndpoint replicationEndpoint = new HBaseInterClusterReplicationEndpoint() {
193       @Override
194       protected void doStart() {
195         notifyStarted();
196       }
197 
198       @Override
199       protected void doStop() {
200         // not calling notifyStopped() here causes the caller of stop() to get a Future that never
201         // completes
202       }
203     };
204     replicationEndpoint.start();
205     ReplicationPeers mockPeers = mock(ReplicationPeers.class);
206     Configuration testConf = HBaseConfiguration.create();
207     testConf.setInt("replication.source.maxretriesmultiplier", 1);
208     source.init(testConf, null, null, null, mockPeers, null, "testPeer", null, replicationEndpoint,
209       null);
210     ExecutorService executor = Executors.newSingleThreadExecutor();
211     final Future<?> future = executor.submit(new Runnable() {
212 
213       @Override
214       public void run() {
215         source.terminate("testing source termination");
216       }
217     });
218     long sleepForRetries = testConf.getLong("replication.source.sleepforretries", 1000);
219     Waiter.waitFor(testConf, sleepForRetries * 2, new Predicate<Exception>() {
220 
221       @Override
222       public boolean evaluate() throws Exception {
223         return future.isDone();
224       }
225 
226     });
227 
228   }
229 
230   private void appendEntries(WALProvider.Writer writer, int numEntries) throws IOException {
231     for (int i = 0; i < numEntries; i++) {
232       byte[] b = Bytes.toBytes(Integer.toString(i));
233       KeyValue kv = new KeyValue(b,b,b);
234       WALEdit edit = new WALEdit();
235       edit.add(kv);
236       WALKey key = new WALKey(b, TableName.valueOf(b), 0, 0,
237               HConstants.DEFAULT_CLUSTER_ID);
238       NavigableMap<byte[], Integer> scopes = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR);
239       scopes.put(b, HConstants.REPLICATION_SCOPE_GLOBAL);
240       key.setScopes(scopes);
241       writer.append(new WAL.Entry(key, edit));
242       writer.sync();
243     }
244     writer.close();
245   }
246 
247   private long getPosition(WALFactory wals, Path log2, int numEntries) throws IOException {
248     WAL.Reader reader = wals.createReader(FS, log2);
249     for (int i = 0; i < numEntries; i++) {
250       reader.next();
251     }
252     return reader.getPosition();
253   }
254 
255   private static final class Mocks {
256     private final ReplicationSourceManager manager = mock(ReplicationSourceManager.class);
257     private final ReplicationQueues queues = mock(ReplicationQueues.class);
258     private final ReplicationPeers peers = mock(ReplicationPeers.class);
259     private final MetricsSource metrics = mock(MetricsSource.class);
260     private final ReplicationPeer peer = mock(ReplicationPeer.class);
261     private final ReplicationEndpoint.Context context = mock(ReplicationEndpoint.Context.class);
262 
263     private Mocks() {
264       when(peers.getStatusOfPeer(anyString())).thenReturn(true);
265       when(context.getReplicationPeer()).thenReturn(peer);
266     }
267 
268     ReplicationSource createReplicationSourceWithMocks(ReplicationEndpoint endpoint)
269             throws IOException {
270       final ReplicationSource source = new ReplicationSource();
271       endpoint.init(context);
272       source.init(conf, FS, manager, queues, peers, mock(Stoppable.class),
273               "testPeerClusterZnode", UUID.randomUUID(), endpoint, metrics);
274       return source;
275     }
276   }
277 
278   @Test
279   public void testSetLogPositionForWALCurrentlyReadingWhenLogsRolled() throws Exception {
280     final int numWALEntries = 5;
281     conf.setInt("replication.source.nb.capacity", numWALEntries);
282 
283     Mocks mocks = new Mocks();
284     final ReplicationEndpointForTest endpoint = new ReplicationEndpointForTest() {
285       @Override
286       public WALEntryFilter getWALEntryfilter() {
287         return null;
288       }
289     };
290     WALFactory wals = new WALFactory(TEST_UTIL.getConfiguration(), null, "test");
291     final Path log1 = new Path(logDir, "log.1");
292     final Path log2 = new Path(logDir, "log.2");
293 
294     WALProvider.Writer writer1 = WALFactory.createWALWriter(FS, log1, TEST_UTIL.getConfiguration());
295     WALProvider.Writer writer2 = WALFactory.createWALWriter(FS, log2, TEST_UTIL.getConfiguration());
296 
297     appendEntries(writer1, 3);
298     appendEntries(writer2, 2);
299 
300     long pos = getPosition(wals, log2, 2);
301 
302     final ReplicationSource source = mocks.createReplicationSourceWithMocks(endpoint);
303     source.run();
304 
305     source.enqueueLog(log1);
306     // log rolled
307     source.enqueueLog(log2);
308 
309     Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() {
310       @Override public boolean evaluate() throws Exception {
311         return endpoint.replicateCount.get() > 0;
312       }
313     });
314 
315     ArgumentCaptor<Path> pathCaptor = ArgumentCaptor.forClass(Path.class);
316     ArgumentCaptor<Long> positionCaptor = ArgumentCaptor.forClass(Long.class);
317     verify(mocks.manager, times(1))
318         .logPositionAndCleanOldLogs(pathCaptor.capture(), anyString(), positionCaptor.capture(),
319               anyBoolean(), anyBoolean());
320     assertTrue(endpoint.lastEntries.size() == 5);
321     assertThat(pathCaptor.getValue(), is(log2));
322     assertThat(positionCaptor.getValue(), is(pos));
323   }
324 
325   @Test
326   public void testSetLogPositionAndRemoveOldWALsEvenIfEmptyWALsRolled() throws Exception {
327     Mocks mocks = new Mocks();
328 
329     final ReplicationEndpointForTest endpoint = new ReplicationEndpointForTest();
330     final ReplicationSource source = mocks.createReplicationSourceWithMocks(endpoint);
331     WALFactory wals = new WALFactory(TEST_UTIL.getConfiguration(), null, "test");
332 
333     final Path log1 = new Path(logDir, "log.1");
334     final Path log2 = new Path(logDir, "log.2");
335 
336     WALFactory.createWALWriter(FS, log1, TEST_UTIL.getConfiguration()).close();
337     WALFactory.createWALWriter(FS, log2, TEST_UTIL.getConfiguration()).close();
338     final long startPos = getPosition(wals, log2, 0);
339 
340     source.run();
341     source.enqueueLog(log1);
342     source.enqueueLog(log2);
343 
344     Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() {
345       @Override public boolean evaluate() throws Exception {
346         return log2.equals(source.getLastLoggedPath())
347                 && source.getLastLoggedPosition() >= startPos;
348       }
349     });
350 
351     ArgumentCaptor<Path> pathCaptor = ArgumentCaptor.forClass(Path.class);
352     ArgumentCaptor<Long> positionCaptor = ArgumentCaptor.forClass(Long.class);
353 
354     verify(mocks.manager, times(1))
355             .logPositionAndCleanOldLogs(pathCaptor.capture(), anyString(), positionCaptor.capture(),
356                     anyBoolean(), anyBoolean());
357     assertThat(pathCaptor.getValue(), is(log2));
358     assertThat(positionCaptor.getValue(), is(startPos));
359   }
360 
361   @Test
362   public void testSetLogPositionAndRemoveOldWALsEvenIfNoCfsReplicated() throws Exception {
363     Mocks mocks = new Mocks();
364     // set table cfs to filter all cells out
365     final TableName replicatedTable = TableName.valueOf("replicated_table");
366     final Map<TableName, List<String>> cfs =
367             Collections.singletonMap(replicatedTable, Collections.<String>emptyList());
368     when(mocks.peer.getTableCFs()).thenReturn(cfs);
369 
370     WALFactory wals = new WALFactory(TEST_UTIL.getConfiguration(), null, "test");
371     final Path log1 = new Path(logDir, "log.1");
372     final Path log2 = new Path(logDir, "log.2");
373 
374     WALProvider.Writer writer1 = WALFactory.createWALWriter(FS, log1, TEST_UTIL.getConfiguration());
375     WALProvider.Writer writer2 = WALFactory.createWALWriter(FS, log2, TEST_UTIL.getConfiguration());
376 
377     appendEntries(writer1, 3);
378     appendEntries(writer2, 2);
379     final long pos = getPosition(wals, log2, 2);
380 
381     final ReplicationEndpointForTest endpoint = new ReplicationEndpointForTest();
382     final ReplicationSource source = mocks.createReplicationSourceWithMocks(endpoint);
383     source.enqueueLog(log1);
384     source.enqueueLog(log2);
385     source.run();
386     Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() {
387       @Override public boolean evaluate() throws Exception {
388         // wait until reader read all cells
389         return log2.equals(source.getLastLoggedPath()) && source.getLastLoggedPosition() >= pos;
390       }
391     });
392 
393     ArgumentCaptor<Path> pathCaptor = ArgumentCaptor.forClass(Path.class);
394     ArgumentCaptor<Long> positionCaptor = ArgumentCaptor.forClass(Long.class);
395 
396     // all old wals should be removed by updating wal position, even if all cells are filtered out.
397     verify(mocks.manager, times(1))
398         .logPositionAndCleanOldLogs(pathCaptor.capture(), anyString(), positionCaptor.capture(),
399               anyBoolean(), anyBoolean());
400     assertThat(pathCaptor.getValue(), is(log2));
401     assertThat(positionCaptor.getValue(), is(pos));
402   }
403 
404   /**
405    * Tests that recovered queues are preserved on a regionserver shutdown.
406    * See HBASE-18192
407    */
408   @Test
409   public void testServerShutdownRecoveredQueue() throws Exception {
410     try {
411       // Ensure single-threaded WAL
412       conf.set("hbase.wal.provider", "defaultProvider");
413       conf.setInt("replication.sleep.before.failover", 2000);
414       // Introduces a delay in regionserver shutdown to give the race condition a chance to kick in.
415       conf.set(HConstants.REGION_SERVER_IMPL, ShutdownDelayRegionServer.class.getName());
416       MiniHBaseCluster cluster = TEST_UTIL.startMiniCluster(2);
417       TEST_UTIL_PEER.startMiniCluster(1);
418 
419       HRegionServer serverA = cluster.getRegionServer(0);
420       final ReplicationSourceManager managerA =
421           ((Replication) serverA.getReplicationSourceService()).getReplicationManager();
422       HRegionServer serverB = cluster.getRegionServer(1);
423       final ReplicationSourceManager managerB =
424           ((Replication) serverB.getReplicationSourceService()).getReplicationManager();
425       final ReplicationAdmin replicationAdmin = new ReplicationAdmin(TEST_UTIL.getConfiguration());
426 
427       final String peerId = "TestPeer";
428       replicationAdmin.addPeer(peerId,
429           new ReplicationPeerConfig().setClusterKey(TEST_UTIL_PEER.getClusterKey()), null);
430       // Wait for replication sources to come up
431       Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() {
432         @Override public boolean evaluate() throws Exception {
433           return !(managerA.getSources().isEmpty() || managerB.getSources().isEmpty());
434         }
435       });
436       // Disabling peer makes sure there is at least one log to claim when the server dies
437       // The recovered queue will also stay there until the peer is disabled even if the
438       // WALs it contains have no data.
439       replicationAdmin.disablePeer(peerId);
440 
441       // Stopping serverA
442       // It's queues should be claimed by the only other alive server i.e. serverB
443       cluster.stopRegionServer(serverA.getServerName());
444       Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() {
445         @Override public boolean evaluate() throws Exception {
446           return managerB.getOldSources().size() == 1;
447         }
448       });
449 
450       final HRegionServer serverC = cluster.startRegionServer().getRegionServer();
451       serverC.waitForServerOnline();
452       Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() {
453         @Override public boolean evaluate() throws Exception {
454           return serverC.getReplicationSourceService() != null;
455         }
456       });
457       final ReplicationSourceManager managerC =
458           ((Replication) serverC.getReplicationSourceService()).getReplicationManager();
459       // Sanity check
460       assertEquals(0, managerC.getOldSources().size());
461 
462       // Stopping serverB
463       // Now serverC should have two recovered queues:
464       // 1. The serverB's normal queue
465       // 2. serverA's recovered queue on serverB
466       cluster.stopRegionServer(serverB.getServerName());
467       Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() {
468         @Override public boolean evaluate() throws Exception {
469           return managerC.getOldSources().size() == 2;
470         }
471       });
472       replicationAdmin.enablePeer(peerId);
473       Waiter.waitFor(conf, 20000, new Waiter.Predicate<Exception>() {
474         @Override public boolean evaluate() throws Exception {
475           return managerC.getOldSources().size() == 0;
476         }
477       });
478     } finally {
479       conf.set(HConstants.REGION_SERVER_IMPL, HRegionServer.class.getName());
480     }
481   }
482 
483   /**
484    * Regionserver implementation that adds a delay on the graceful shutdown.
485    */
486   public static class ShutdownDelayRegionServer extends HRegionServer {
487     public ShutdownDelayRegionServer(Configuration conf) throws IOException, InterruptedException {
488       super(conf);
489     }
490 
491     public ShutdownDelayRegionServer(Configuration conf, CoordinatedStateManager csm)
492         throws IOException, InterruptedException {
493       super(conf, csm);
494     }
495 
496     @Override
497     protected void stopServiceThreads() {
498       // Add a delay before service threads are shutdown.
499       // This will keep the zookeeper connection alive for the duration of the delay.
500       LOG.info("Adding a delay to the regionserver shutdown");
501       try {
502         Thread.sleep(2000);
503       } catch (InterruptedException ex) {
504         LOG.error("Interrupted while sleeping");
505       }
506       super.stopServiceThreads();
507     }
508   }
509 
510 }
511