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;
019
020import static org.junit.Assert.assertArrayEquals;
021import static org.junit.Assert.assertEquals;
022import static org.junit.Assert.assertFalse;
023import static org.junit.Assert.assertNotNull;
024import static org.junit.Assert.assertTrue;
025import static org.junit.Assert.fail;
026
027import java.io.IOException;
028import java.util.Arrays;
029import java.util.concurrent.CountDownLatch;
030import org.apache.hadoop.conf.Configuration;
031import org.apache.hadoop.fs.Path;
032import org.apache.hadoop.hbase.*;
033import org.apache.hadoop.hbase.HBaseClassTestRule;
034import org.apache.hadoop.hbase.client.Admin;
035import org.apache.hadoop.hbase.client.Delete;
036import org.apache.hadoop.hbase.client.Get;
037import org.apache.hadoop.hbase.client.Put;
038import org.apache.hadoop.hbase.client.Result;
039import org.apache.hadoop.hbase.client.Table;
040import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
041import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
042import org.apache.hadoop.hbase.regionserver.HRegion;
043import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
044import org.apache.hadoop.hbase.testclassification.LargeTests;
045import org.apache.hadoop.hbase.testclassification.ReplicationTests;
046import org.apache.hadoop.hbase.util.Bytes;
047import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
048import org.apache.hadoop.hbase.zookeeper.ZKWatcher;
049import org.junit.BeforeClass;
050import org.junit.ClassRule;
051import org.junit.Test;
052import org.junit.experimental.categories.Category;
053import org.slf4j.Logger;
054import org.slf4j.LoggerFactory;
055
056@Category({ReplicationTests.class, LargeTests.class})
057public class TestMultiSlaveReplication {
058
059  @ClassRule
060  public static final HBaseClassTestRule CLASS_RULE =
061      HBaseClassTestRule.forClass(TestMultiSlaveReplication.class);
062
063  private static final Logger LOG = LoggerFactory.getLogger(TestReplicationBase.class);
064
065  private static Configuration conf1;
066  private static Configuration conf2;
067  private static Configuration conf3;
068
069  private static HBaseTestingUtility utility1;
070  private static HBaseTestingUtility utility2;
071  private static HBaseTestingUtility utility3;
072  private static final long SLEEP_TIME = 500;
073  private static final int NB_RETRIES = 100;
074
075  private static final TableName tableName = TableName.valueOf("test");
076  private static final byte[] famName = Bytes.toBytes("f");
077  private static final byte[] row = Bytes.toBytes("row");
078  private static final byte[] row1 = Bytes.toBytes("row1");
079  private static final byte[] row2 = Bytes.toBytes("row2");
080  private static final byte[] row3 = Bytes.toBytes("row3");
081  private static final byte[] noRepfamName = Bytes.toBytes("norep");
082
083  private static HTableDescriptor table;
084
085  @BeforeClass
086  public static void setUpBeforeClass() throws Exception {
087    conf1 = HBaseConfiguration.create();
088    conf1.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1");
089    // smaller block size and capacity to trigger more operations
090    // and test them
091    conf1.setInt("hbase.regionserver.hlog.blocksize", 1024*20);
092    conf1.setInt("replication.source.size.capacity", 1024);
093    conf1.setLong("replication.source.sleepforretries", 100);
094    conf1.setInt("hbase.regionserver.maxlogs", 10);
095    conf1.setLong("hbase.master.logcleaner.ttl", 10);
096    conf1.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100);
097    conf1.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,
098        "org.apache.hadoop.hbase.replication.TestMasterReplication$CoprocessorCounter");
099    conf1.setInt("hbase.master.cleaner.interval", 5 * 1000);
100
101    utility1 = new HBaseTestingUtility(conf1);
102    utility1.startMiniZKCluster();
103    MiniZooKeeperCluster miniZK = utility1.getZkCluster();
104    utility1.setZkCluster(miniZK);
105    new ZKWatcher(conf1, "cluster1", null, true);
106
107    conf2 = new Configuration(conf1);
108    conf2.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/2");
109
110    conf3 = new Configuration(conf1);
111    conf3.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/3");
112
113    utility2 = new HBaseTestingUtility(conf2);
114    utility2.setZkCluster(miniZK);
115    new ZKWatcher(conf2, "cluster2", null, true);
116
117    utility3 = new HBaseTestingUtility(conf3);
118    utility3.setZkCluster(miniZK);
119    new ZKWatcher(conf3, "cluster3", null, true);
120
121    table = new HTableDescriptor(tableName);
122    HColumnDescriptor fam = new HColumnDescriptor(famName);
123    fam.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
124    table.addFamily(fam);
125    fam = new HColumnDescriptor(noRepfamName);
126    table.addFamily(fam);
127  }
128
129  @Test
130  public void testMultiSlaveReplication() throws Exception {
131    LOG.info("testCyclicReplication");
132    MiniHBaseCluster master = utility1.startMiniCluster();
133    utility2.startMiniCluster();
134    utility3.startMiniCluster();
135    ReplicationAdmin admin1 = new ReplicationAdmin(conf1);
136
137    utility1.getAdmin().createTable(table);
138    utility2.getAdmin().createTable(table);
139    utility3.getAdmin().createTable(table);
140    Table htable1 = utility1.getConnection().getTable(tableName);
141    Table htable2 = utility2.getConnection().getTable(tableName);
142    Table htable3 = utility3.getConnection().getTable(tableName);
143
144    ReplicationPeerConfig rpc = new ReplicationPeerConfig();
145    rpc.setClusterKey(utility2.getClusterKey());
146    admin1.addPeer("1", rpc, null);
147
148    // put "row" and wait 'til it got around, then delete
149    putAndWait(row, famName, htable1, htable2);
150    deleteAndWait(row, htable1, htable2);
151    // check it wasn't replication to cluster 3
152    checkRow(row,0,htable3);
153
154    putAndWait(row2, famName, htable1, htable2);
155
156    // now roll the region server's logs
157    rollWALAndWait(utility1, htable1.getName(), row2);
158
159    // after the log was rolled put a new row
160    putAndWait(row3, famName, htable1, htable2);
161
162    rpc = new ReplicationPeerConfig();
163    rpc.setClusterKey(utility3.getClusterKey());
164    admin1.addPeer("2", rpc, null);
165
166    // put a row, check it was replicated to all clusters
167    putAndWait(row1, famName, htable1, htable2, htable3);
168    // delete and verify
169    deleteAndWait(row1, htable1, htable2, htable3);
170
171    // make sure row2 did not get replicated after
172    // cluster 3 was added
173    checkRow(row2,0,htable3);
174
175    // row3 will get replicated, because it was in the
176    // latest log
177    checkRow(row3,1,htable3);
178
179    Put p = new Put(row);
180    p.addColumn(famName, row, row);
181    htable1.put(p);
182    // now roll the logs again
183    rollWALAndWait(utility1, htable1.getName(), row);
184
185    // cleanup "row2", also conveniently use this to wait replication
186    // to finish
187    deleteAndWait(row2, htable1, htable2, htable3);
188    // Even if the log was rolled in the middle of the replication
189    // "row" is still replication.
190    checkRow(row, 1, htable2);
191    // Replication thread of cluster 2 may be sleeping, and since row2 is not there in it,
192    // we should wait before checking.
193    checkWithWait(row, 1, htable3);
194
195    // cleanup the rest
196    deleteAndWait(row, htable1, htable2, htable3);
197    deleteAndWait(row3, htable1, htable2, htable3);
198
199    utility3.shutdownMiniCluster();
200    utility2.shutdownMiniCluster();
201    utility1.shutdownMiniCluster();
202  }
203
204  private void rollWALAndWait(final HBaseTestingUtility utility, final TableName table,
205      final byte[] row) throws IOException {
206    final Admin admin = utility.getAdmin();
207    final MiniHBaseCluster cluster = utility.getMiniHBaseCluster();
208
209    // find the region that corresponds to the given row.
210    HRegion region = null;
211    for (HRegion candidate : cluster.getRegions(table)) {
212      if (HRegion.rowIsInRange(candidate.getRegionInfo(), row)) {
213        region = candidate;
214        break;
215      }
216    }
217    assertNotNull("Couldn't find the region for row '" + Arrays.toString(row) + "'", region);
218
219    final CountDownLatch latch = new CountDownLatch(1);
220
221    // listen for successful log rolls
222    final WALActionsListener listener = new WALActionsListener() {
223          @Override
224          public void postLogRoll(final Path oldPath, final Path newPath) throws IOException {
225            latch.countDown();
226          }
227        };
228    region.getWAL().registerWALActionsListener(listener);
229
230    // request a roll
231    admin.rollWALWriter(cluster.getServerHoldingRegion(region.getTableDescriptor().getTableName(),
232      region.getRegionInfo().getRegionName()));
233
234    // wait
235    try {
236      latch.await();
237    } catch (InterruptedException exception) {
238      LOG.warn("Interrupted while waiting for the wal of '" + region + "' to roll. If later " +
239          "replication tests fail, it's probably because we should still be waiting.");
240      Thread.currentThread().interrupt();
241    }
242    region.getWAL().unregisterWALActionsListener(listener);
243  }
244
245
246  private void checkWithWait(byte[] row, int count, Table table) throws Exception {
247    Get get = new Get(row);
248    for (int i = 0; i < NB_RETRIES; i++) {
249      if (i == NB_RETRIES - 1) {
250        fail("Waited too much time while getting the row.");
251      }
252      boolean rowReplicated = false;
253      Result res = table.get(get);
254      if (res.size() >= 1) {
255        LOG.info("Row is replicated");
256        rowReplicated = true;
257        assertEquals("Table '" + table + "' did not have the expected number of  results.",
258            count, res.size());
259        break;
260      }
261      if (rowReplicated) {
262        break;
263      } else {
264        Thread.sleep(SLEEP_TIME);
265      }
266    }
267  }
268
269  private void checkRow(byte[] row, int count, Table... tables) throws IOException {
270    Get get = new Get(row);
271    for (Table table : tables) {
272      Result res = table.get(get);
273      assertEquals("Table '" + table + "' did not have the expected number of results.",
274          count, res.size());
275    }
276  }
277
278  private void deleteAndWait(byte[] row, Table source, Table... targets)
279  throws Exception {
280    Delete del = new Delete(row);
281    source.delete(del);
282
283    Get get = new Get(row);
284    for (int i = 0; i < NB_RETRIES; i++) {
285      if (i==NB_RETRIES-1) {
286        fail("Waited too much time for del replication");
287      }
288      boolean removedFromAll = true;
289      for (Table target : targets) {
290        Result res = target.get(get);
291        if (res.size() >= 1) {
292          LOG.info("Row not deleted");
293          removedFromAll = false;
294          break;
295        }
296      }
297      if (removedFromAll) {
298        break;
299      } else {
300        Thread.sleep(SLEEP_TIME);
301      }
302    }
303  }
304
305  private void putAndWait(byte[] row, byte[] fam, Table source, Table... targets)
306  throws Exception {
307    Put put = new Put(row);
308    put.addColumn(fam, row, row);
309    source.put(put);
310
311    Get get = new Get(row);
312    for (int i = 0; i < NB_RETRIES; i++) {
313      if (i==NB_RETRIES-1) {
314        fail("Waited too much time for put replication");
315      }
316      boolean replicatedToAll = true;
317      for (Table target : targets) {
318        Result res = target.get(get);
319        if (res.isEmpty()) {
320          LOG.info("Row not available");
321          replicatedToAll = false;
322          break;
323        } else {
324          assertArrayEquals(res.value(), row);
325        }
326      }
327      if (replicatedToAll) {
328        break;
329      } else {
330        Thread.sleep(SLEEP_TIME);
331      }
332    }
333  }
334
335}
336