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  package org.apache.hadoop.hbase.replication;
19  
20  import static org.junit.Assert.assertArrayEquals;
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertNotNull;
23  import static org.junit.Assert.fail;
24  
25  import com.google.protobuf.ServiceException;
26  
27  import java.io.Closeable;
28  import java.io.IOException;
29  import java.util.Arrays;
30  import java.util.List;
31  import java.util.Random;
32  import java.util.concurrent.CountDownLatch;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.fs.Path;
38  import org.apache.hadoop.hbase.Cell;
39  import org.apache.hadoop.hbase.ClusterStatus;
40  import org.apache.hadoop.hbase.HBaseConfiguration;
41  import org.apache.hadoop.hbase.HBaseTestingUtility;
42  import org.apache.hadoop.hbase.HColumnDescriptor;
43  import org.apache.hadoop.hbase.HConstants;
44  import org.apache.hadoop.hbase.HTableDescriptor;
45  import org.apache.hadoop.hbase.KeyValue;
46  import org.apache.hadoop.hbase.MiniHBaseCluster;
47  import org.apache.hadoop.hbase.ServerLoad;
48  import org.apache.hadoop.hbase.ServerName;
49  import org.apache.hadoop.hbase.TableName;
50  import org.apache.hadoop.hbase.Waiter;
51  import org.apache.hadoop.hbase.client.Admin;
52  import org.apache.hadoop.hbase.client.Delete;
53  import org.apache.hadoop.hbase.client.Durability;
54  import org.apache.hadoop.hbase.client.Get;
55  import org.apache.hadoop.hbase.client.HBaseAdmin;
56  import org.apache.hadoop.hbase.client.HTable;
57  import org.apache.hadoop.hbase.client.Put;
58  import org.apache.hadoop.hbase.client.Result;
59  import org.apache.hadoop.hbase.client.Table;
60  import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
61  import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
62  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
63  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
64  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
65  import org.apache.hadoop.hbase.regionserver.HRegion;
66  import org.apache.hadoop.hbase.regionserver.HRegionServer;
67  import org.apache.hadoop.hbase.regionserver.RSRpcServices;
68  import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
69  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
70  import org.apache.hadoop.hbase.testclassification.LargeTests;
71  import org.apache.hadoop.hbase.util.Bytes;
72  import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
73  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
74  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
75  import org.junit.After;
76  import org.junit.Before;
77  import org.junit.Test;
78  import org.junit.experimental.categories.Category;
79  
80  @Category(LargeTests.class)
81  public class TestMasterReplication {
82  
83    private static final Log LOG = LogFactory.getLog(TestReplicationBase.class);
84  
85    private Configuration baseConfiguration;
86  
87    private HBaseTestingUtility[] utilities;
88    private Configuration[] configurations;
89    private MiniZooKeeperCluster miniZK;
90  
91    private static final long SLEEP_TIME = 1000;
92    private static final int NB_RETRIES = 120;
93  
94    private static final TableName tableName = TableName.valueOf("test");
95    private static final byte[] famName = Bytes.toBytes("f");
96    private static final byte[] row = Bytes.toBytes("row");
97    private static final byte[] row1 = Bytes.toBytes("row1");
98    private static final byte[] row2 = Bytes.toBytes("row2");
99    private static final byte[] row3 = Bytes.toBytes("row3");
100   private static final byte[] row4 = Bytes.toBytes("row4");
101   private static final byte[] noRepfamName = Bytes.toBytes("norep");
102 
103   private static final byte[] count = Bytes.toBytes("count");
104   private static final byte[] put = Bytes.toBytes("put");
105   private static final byte[] delete = Bytes.toBytes("delete");
106 
107   private HTableDescriptor table;
108 
109   @Before
110   public void setUp() throws Exception {
111     baseConfiguration = HBaseConfiguration.create();
112     // smaller block size and capacity to trigger more operations
113     // and test them
114     baseConfiguration.setInt("hbase.regionserver.hlog.blocksize", 1024 * 20);
115     baseConfiguration.setInt("replication.source.size.capacity", 1024);
116     baseConfiguration.setLong("replication.source.sleepforretries", 100);
117     baseConfiguration.setInt("hbase.regionserver.maxlogs", 10);
118     baseConfiguration.setLong("hbase.master.logcleaner.ttl", 10);
119     baseConfiguration.setBoolean(HConstants.REPLICATION_ENABLE_KEY,
120         HConstants.REPLICATION_ENABLE_DEFAULT);
121     baseConfiguration.setBoolean("dfs.support.append", true);
122     baseConfiguration.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100);
123     baseConfiguration.setStrings(
124         CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,
125         CoprocessorCounter.class.getName());
126 
127     table = new HTableDescriptor(tableName);
128     HColumnDescriptor fam = new HColumnDescriptor(famName);
129     fam.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
130     table.addFamily(fam);
131     fam = new HColumnDescriptor(noRepfamName);
132     table.addFamily(fam);
133   }
134 
135   /**
136    * It tests the replication scenario involving 0 -> 1 -> 0. It does it by
137    * adding and deleting a row to a table in each cluster, checking if it's
138    * replicated. It also tests that the puts and deletes are not replicated back
139    * to the originating cluster.
140    */
141   @Test(timeout = 300000)
142   public void testCyclicReplication1() throws Exception {
143     LOG.info("testSimplePutDelete");
144     int numClusters = 2;
145     Table[] htables = null;
146     try {
147       startMiniClusters(numClusters);
148       createTableOnClusters(table);
149 
150       htables = getHTablesOnClusters(tableName);
151 
152       // Test the replication scenarios of 0 -> 1 -> 0
153       addPeer("1", 0, 1);
154       addPeer("1", 1, 0);
155 
156       int[] expectedCounts = new int[] { 2, 2 };
157 
158       // add rows to both clusters,
159       // make sure they are both replication
160       putAndWait(row, famName, htables[0], htables[1]);
161       putAndWait(row1, famName, htables[1], htables[0]);
162       validateCounts(htables, put, expectedCounts);
163 
164       deleteAndWait(row, htables[0], htables[1]);
165       deleteAndWait(row1, htables[1], htables[0]);
166       validateCounts(htables, delete, expectedCounts);
167     } finally {
168       close(htables);
169       shutDownMiniClusters();
170     }
171   }
172 
173   /**
174    * Tests the replication scenario 0 -> 0. By default
175    * {@link BaseReplicationEndpoint#canReplicateToSameCluster()} returns false, so the
176    * ReplicationSource should terminate, and no further logs should get enqueued
177    */
178   @Test(timeout = 300000)
179   public void testLoopedReplication() throws Exception {
180     LOG.info("testLoopedReplication");
181     startMiniClusters(1);
182     createTableOnClusters(table);
183     addPeer("1", 0, 0);
184     Thread.sleep(SLEEP_TIME);
185 
186     // wait for source to terminate
187     final ServerName rsName = utilities[0].getHBaseCluster().getRegionServer(0).getServerName();
188     Waiter.waitFor(baseConfiguration, 10000, new Waiter.Predicate<Exception>() {
189       @Override
190       public boolean evaluate() throws Exception {
191         ClusterStatus clusterStatus = utilities[0].getHBaseAdmin().getClusterStatus();
192         ServerLoad serverLoad = clusterStatus.getLoad(rsName);
193         List<ReplicationLoadSource> replicationLoadSourceList =
194             serverLoad.getReplicationLoadSourceList();
195         return replicationLoadSourceList.size() == 0;
196       }
197     });
198 
199     Table[] htables = getHTablesOnClusters(tableName);
200     putAndWait(row, famName, htables[0], htables[0]);
201     rollWALAndWait(utilities[0], table.getTableName(), row);
202     ZooKeeperWatcher zkw = utilities[0].getZooKeeperWatcher();
203     String queuesZnode =
204         ZKUtil.joinZNode(zkw.baseZNode, ZKUtil.joinZNode("replication", "rs"));
205     List<String> listChildrenNoWatch =
206         ZKUtil.listChildrenNoWatch(zkw, ZKUtil.joinZNode(queuesZnode, rsName.toString()));
207     assertEquals(0, listChildrenNoWatch.size());
208   }
209 
210 /**
211   * Tests the cyclic replication scenario of 0 -> 1 -> 2 -> 0 by adding and
212   * deleting rows to a table in each clusters and ensuring that the each of
213   * these clusters get the appropriate mutations. It also tests the grouping
214   * scenario where a cluster needs to replicate the edits originating from
215   * itself and also the edits that it received using replication from a
216   * different cluster. The scenario is explained in HBASE-9158
217    */
218   @Test(timeout = 300000)
219   public void testCyclicReplication2() throws Exception {
220     LOG.info("testCyclicReplication2");
221     int numClusters = 3;
222     Table[] htables = null;
223     try {
224       startMiniClusters(numClusters);
225       createTableOnClusters(table);
226 
227       // Test the replication scenario of 0 -> 1 -> 2 -> 0
228       addPeer("1", 0, 1);
229       addPeer("1", 1, 2);
230       addPeer("1", 2, 0);
231 
232       htables = getHTablesOnClusters(tableName);
233 
234       // put "row" and wait 'til it got around
235       putAndWait(row, famName, htables[0], htables[2]);
236       putAndWait(row1, famName, htables[1], htables[0]);
237       putAndWait(row2, famName, htables[2], htables[1]);
238 
239       deleteAndWait(row, htables[0], htables[2]);
240       deleteAndWait(row1, htables[1], htables[0]);
241       deleteAndWait(row2, htables[2], htables[1]);
242 
243       int[] expectedCounts = new int[] { 3, 3, 3 };
244       validateCounts(htables, put, expectedCounts);
245       validateCounts(htables, delete, expectedCounts);
246 
247       // Test HBASE-9158
248       disablePeer("1", 2);
249       // we now have an edit that was replicated into cluster originating from
250       // cluster 0
251       putAndWait(row3, famName, htables[0], htables[1]);
252       // now add a local edit to cluster 1
253       htables[1].put(new Put(row4).add(famName, row4, row4));
254       // re-enable replication from cluster 2 to cluster 0
255       enablePeer("1", 2);
256       // without HBASE-9158 the edit for row4 would have been marked with
257       // cluster 0's id
258       // and hence not replicated to cluster 0
259       wait(row4, htables[0], false);
260     } finally {
261       close(htables);
262       shutDownMiniClusters();
263     }
264   }
265 
266   /**
267    * Tests cyclic replication scenario of 0 -> 1 -> 2 -> 1.
268    */
269   @Test(timeout = 300000)
270   public void testCyclicReplication3() throws Exception {
271     LOG.info("testCyclicReplication2");
272     int numClusters = 3;
273     Table[] htables = null;
274     try {
275       startMiniClusters(numClusters);
276       createTableOnClusters(table);
277 
278       // Test the replication scenario of 0 -> 1 -> 2 -> 1
279       addPeer("1", 0, 1);
280       addPeer("1", 1, 2);
281       addPeer("1", 2, 1);
282 
283       htables = getHTablesOnClusters(tableName);
284 
285       // put "row" and wait 'til it got around
286       putAndWait(row, famName, htables[0], htables[2]);
287       putAndWait(row1, famName, htables[1], htables[2]);
288       putAndWait(row2, famName, htables[2], htables[1]);
289 
290       deleteAndWait(row, htables[0], htables[2]);
291       deleteAndWait(row1, htables[1], htables[2]);
292       deleteAndWait(row2, htables[2], htables[1]);
293 
294       int[] expectedCounts = new int[] { 1, 3, 3 };
295       validateCounts(htables, put, expectedCounts);
296       validateCounts(htables, delete, expectedCounts);
297     } finally {
298       close(htables);
299       shutDownMiniClusters();
300     }
301   }
302 
303   /*
304    * Test RSRpcServices#replicateWALEntry when replication is disabled. This is to simulate
305    * HBASE-14840
306    */
307   @Test(timeout = 180000, expected = ServiceException.class)
308   public void testReplicateWALEntryWhenReplicationIsDisabled() throws Exception {
309     LOG.info("testSimplePutDelete");
310     baseConfiguration.setBoolean(HConstants.REPLICATION_ENABLE_KEY, false);
311     Table[] htables = null;
312     try {
313       startMiniClusters(1);
314       createTableOnClusters(table);
315       htables = getHTablesOnClusters(tableName);
316 
317       HRegionServer rs = utilities[0].getRSForFirstRegionInTable(tableName);
318       RSRpcServices rsrpc = new RSRpcServices(rs);
319       rsrpc.replicateWALEntry(null, null);
320     } finally {
321       close(htables);
322       shutDownMiniClusters();
323     }
324   }
325 
326   @After
327   public void tearDown() throws IOException {
328     configurations = null;
329     utilities = null;
330   }
331 
332   @SuppressWarnings("resource")
333   private void startMiniClusters(int numClusters) throws Exception {
334     Random random = new Random();
335     utilities = new HBaseTestingUtility[numClusters];
336     configurations = new Configuration[numClusters];
337     for (int i = 0; i < numClusters; i++) {
338       Configuration conf = new Configuration(baseConfiguration);
339       conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/" + i + random.nextInt());
340       HBaseTestingUtility utility = new HBaseTestingUtility(conf);
341       if (i == 0) {
342         utility.startMiniZKCluster();
343         miniZK = utility.getZkCluster();
344       } else {
345         utility.setZkCluster(miniZK);
346       }
347       utility.startMiniCluster();
348       utilities[i] = utility;
349       configurations[i] = conf;
350       new ZooKeeperWatcher(conf, "cluster" + i, null, true);
351     }
352   }
353 
354   private void shutDownMiniClusters() throws Exception {
355     int numClusters = utilities.length;
356     for (int i = numClusters - 1; i >= 0; i--) {
357       if (utilities[i] != null) {
358         utilities[i].shutdownMiniCluster();
359       }
360     }
361     miniZK.shutdown();
362   }
363 
364   private void createTableOnClusters(HTableDescriptor table) throws Exception {
365     int numClusters = configurations.length;
366     for (int i = 0; i < numClusters; i++) {
367       Admin hbaseAdmin = null;
368       try {
369         hbaseAdmin = new HBaseAdmin(configurations[i]);
370         hbaseAdmin.createTable(table);
371       } finally {
372         close(hbaseAdmin);
373       }
374     }
375   }
376 
377   private void addPeer(String id, int masterClusterNumber,
378       int slaveClusterNumber) throws Exception {
379     ReplicationAdmin replicationAdmin = null;
380     try {
381       replicationAdmin = new ReplicationAdmin(
382           configurations[masterClusterNumber]);
383       replicationAdmin.addPeer(id,
384           utilities[slaveClusterNumber].getClusterKey());
385     } finally {
386       close(replicationAdmin);
387     }
388   }
389 
390   private void disablePeer(String id, int masterClusterNumber) throws Exception {
391     ReplicationAdmin replicationAdmin = null;
392     try {
393       replicationAdmin = new ReplicationAdmin(
394           configurations[masterClusterNumber]);
395       replicationAdmin.disablePeer(id);
396     } finally {
397       close(replicationAdmin);
398     }
399   }
400 
401   private void enablePeer(String id, int masterClusterNumber) throws Exception {
402     ReplicationAdmin replicationAdmin = null;
403     try {
404       replicationAdmin = new ReplicationAdmin(
405           configurations[masterClusterNumber]);
406       replicationAdmin.enablePeer(id);
407     } finally {
408       close(replicationAdmin);
409     }
410   }
411 
412   private void close(Closeable... closeables) {
413     try {
414       if (closeables != null) {
415         for (Closeable closeable : closeables) {
416           closeable.close();
417         }
418       }
419     } catch (Exception e) {
420       LOG.warn("Exception occured while closing the object:", e);
421     }
422   }
423 
424   @SuppressWarnings("resource")
425   private Table[] getHTablesOnClusters(TableName tableName) throws Exception {
426     int numClusters = utilities.length;
427     Table[] htables = new Table[numClusters];
428     for (int i = 0; i < numClusters; i++) {
429       Table htable = new HTable(configurations[i], tableName);
430       htable.setWriteBufferSize(1024);
431       htables[i] = htable;
432     }
433     return htables;
434   }
435 
436   private void validateCounts(Table[] htables, byte[] type,
437       int[] expectedCounts) throws IOException {
438     for (int i = 0; i < htables.length; i++) {
439       assertEquals(Bytes.toString(type) + " were replicated back ",
440           expectedCounts[i], getCount(htables[i], type));
441     }
442   }
443 
444   private int getCount(Table t, byte[] type) throws IOException {
445     Get test = new Get(row);
446     test.setAttribute("count", new byte[] {});
447     Result res = t.get(test);
448     return Bytes.toInt(res.getValue(count, type));
449   }
450 
451   private void deleteAndWait(byte[] row, Table source, Table target)
452       throws Exception {
453     Delete del = new Delete(row);
454     source.delete(del);
455     wait(row, target, true);
456   }
457 
458   private void putAndWait(byte[] row, byte[] fam, Table source, Table target)
459       throws Exception {
460     Put put = new Put(row);
461     put.add(fam, row, row);
462     source.put(put);
463     wait(row, target, false);
464   }
465 
466   private void wait(byte[] row, Table target, boolean isDeleted)
467       throws Exception {
468     Get get = new Get(row);
469     for (int i = 0; i < NB_RETRIES; i++) {
470       if (i == NB_RETRIES - 1) {
471         fail("Waited too much time for replication. Row:" + Bytes.toString(row)
472             + ". IsDeleteReplication:" + isDeleted);
473       }
474       Result res = target.get(get);
475       boolean sleep = isDeleted ? res.size() > 0 : res.size() == 0;
476       if (sleep) {
477         LOG.info("Waiting for more time for replication. Row:"
478             + Bytes.toString(row) + ". IsDeleteReplication:" + isDeleted);
479         Thread.sleep(SLEEP_TIME);
480       } else {
481         if (!isDeleted) {
482           assertArrayEquals(res.value(), row);
483         }
484         LOG.info("Obtained row:"
485             + Bytes.toString(row) + ". IsDeleteReplication:" + isDeleted);
486         break;
487       }
488     }
489   }
490 
491   private void rollWALAndWait(final HBaseTestingUtility utility, final TableName table,
492       final byte[] row) throws IOException {
493     final Admin admin = utility.getHBaseAdmin();
494     final MiniHBaseCluster cluster = utility.getMiniHBaseCluster();
495 
496     // find the region that corresponds to the given row.
497     HRegion region = null;
498     for (HRegion candidate : cluster.getRegions(table)) {
499       if (HRegion.rowIsInRange(candidate.getRegionInfo(), row)) {
500         region = candidate;
501         break;
502       }
503     }
504     assertNotNull("Couldn't find the region for row '" + Arrays.toString(row) + "'", region);
505 
506     final CountDownLatch latch = new CountDownLatch(1);
507 
508     // listen for successful log rolls
509     final WALActionsListener listener = new WALActionsListener.Base() {
510           @Override
511           public void postLogRoll(final Path oldPath, final Path newPath) throws IOException {
512             latch.countDown();
513           }
514         };
515     region.getWAL().registerWALActionsListener(listener);
516 
517     // request a roll
518     admin.rollWALWriter(cluster.getServerHoldingRegion(region.getTableDesc().getTableName(),
519       region.getRegionInfo().getRegionName()));
520 
521     // wait
522     try {
523       latch.await();
524     } catch (InterruptedException exception) {
525       LOG.warn("Interrupted while waiting for the wal of '" + region + "' to roll. If later " +
526           "replication tests fail, it's probably because we should still be waiting.");
527       Thread.currentThread().interrupt();
528     }
529     region.getWAL().unregisterWALActionsListener(listener);
530   }
531 
532   /**
533    * Use a coprocessor to count puts and deletes. as KVs would be replicated back with the same
534    * timestamp there is otherwise no way to count them.
535    */
536   public static class CoprocessorCounter extends BaseRegionObserver {
537     private int nCount = 0;
538     private int nDelete = 0;
539 
540     @Override
541     public void prePut(final ObserverContext<RegionCoprocessorEnvironment> e, final Put put,
542         final WALEdit edit, final Durability durability) throws IOException {
543       nCount++;
544     }
545 
546     @Override
547     public void postDelete(final ObserverContext<RegionCoprocessorEnvironment> c,
548         final Delete delete, final WALEdit edit, final Durability durability) throws IOException {
549       nDelete++;
550     }
551 
552     @Override
553     public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> c,
554         final Get get, final List<Cell> result) throws IOException {
555       if (get.getAttribute("count") != null) {
556         result.clear();
557         // order is important!
558         result.add(new KeyValue(count, count, delete, Bytes.toBytes(nDelete)));
559         result.add(new KeyValue(count, count, put, Bytes.toBytes(nCount)));
560         c.bypass();
561       }
562     }
563   }
564 
565 }