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  package org.apache.hadoop.hbase.replication.regionserver;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertTrue;
23  
24  import java.net.URLEncoder;
25  import java.util.ArrayList;
26  import java.util.Collection;
27  import java.util.List;
28  import java.util.SortedMap;
29  import java.util.SortedSet;
30  import java.util.TreeSet;
31  import java.util.UUID;
32  import java.util.concurrent.CountDownLatch;
33  import java.util.concurrent.atomic.AtomicLong;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.conf.Configuration;
38  import org.apache.hadoop.fs.FileSystem;
39  import org.apache.hadoop.fs.Path;
40  import org.apache.hadoop.hbase.ChoreService;
41  import org.apache.hadoop.hbase.ClusterId;
42  import org.apache.hadoop.hbase.CoordinatedStateManager;
43  import org.apache.hadoop.hbase.HBaseConfiguration;
44  import org.apache.hadoop.hbase.HBaseTestingUtility;
45  import org.apache.hadoop.hbase.HColumnDescriptor;
46  import org.apache.hadoop.hbase.HConstants;
47  import org.apache.hadoop.hbase.HRegionInfo;
48  import org.apache.hadoop.hbase.HTableDescriptor;
49  import org.apache.hadoop.hbase.KeyValue;
50  import org.apache.hadoop.hbase.Server;
51  import org.apache.hadoop.hbase.ServerName;
52  import org.apache.hadoop.hbase.TableName;
53  import org.apache.hadoop.hbase.client.ClusterConnection;
54  import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
55  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
56  import org.apache.hadoop.hbase.replication.ReplicationFactory;
57  import org.apache.hadoop.hbase.replication.ReplicationPeers;
58  import org.apache.hadoop.hbase.replication.ReplicationQueueInfo;
59  import org.apache.hadoop.hbase.replication.ReplicationQueues;
60  import org.apache.hadoop.hbase.replication.ReplicationSourceDummy;
61  import org.apache.hadoop.hbase.replication.ReplicationStateZKBase;
62  import org.apache.hadoop.hbase.replication.regionserver.ReplicationSourceManager.NodeFailoverWorker;
63  import org.apache.hadoop.hbase.testclassification.MediumTests;
64  import org.apache.hadoop.hbase.util.Bytes;
65  import org.apache.hadoop.hbase.util.FSUtils;
66  import org.apache.hadoop.hbase.wal.WAL;
67  import org.apache.hadoop.hbase.wal.WALFactory;
68  import org.apache.hadoop.hbase.wal.WALKey;
69  import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
70  import org.apache.hadoop.hbase.zookeeper.ZKClusterId;
71  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
72  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
73  import org.junit.After;
74  import org.junit.AfterClass;
75  import org.junit.Before;
76  import org.junit.BeforeClass;
77  import org.junit.Test;
78  import org.junit.experimental.categories.Category;
79  
80  import com.google.common.collect.Sets;
81  
82  @Category(MediumTests.class)
83  public class TestReplicationSourceManager {
84  
85    private static final Log LOG =
86        LogFactory.getLog(TestReplicationSourceManager.class);
87  
88    private static Configuration conf;
89  
90    private static HBaseTestingUtility utility;
91  
92    private static Replication replication;
93  
94    private static ReplicationSourceManager manager;
95  
96    private static ZooKeeperWatcher zkw;
97  
98    private static HTableDescriptor htd;
99  
100   private static HRegionInfo hri;
101 
102   private static final byte[] r1 = Bytes.toBytes("r1");
103 
104   private static final byte[] r2 = Bytes.toBytes("r2");
105 
106   private static final byte[] f1 = Bytes.toBytes("f1");
107 
108   private static final TableName test =
109       TableName.valueOf("test");
110 
111   private static final String slaveId = "1";
112 
113   private static FileSystem fs;
114 
115   private static Path oldLogDir;
116 
117   private static Path logDir;
118 
119   private static CountDownLatch latch;
120 
121   private static List<String> files = new ArrayList<String>();
122 
123   @BeforeClass
124   public static void setUpBeforeClass() throws Exception {
125 
126     conf = HBaseConfiguration.create();
127     conf.set("replication.replicationsource.implementation",
128         ReplicationSourceDummy.class.getCanonicalName());
129     conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY,
130         HConstants.REPLICATION_ENABLE_DEFAULT);
131     conf.setLong("replication.sleep.before.failover", 2000);
132     conf.setInt("replication.source.maxretriesmultiplier", 10);
133     utility = new HBaseTestingUtility(conf);
134     utility.startMiniZKCluster();
135 
136     zkw = new ZooKeeperWatcher(conf, "test", null);
137     ZKUtil.createWithParents(zkw, "/hbase/replication");
138     ZKUtil.createWithParents(zkw, "/hbase/replication/peers/1");
139     ZKUtil.setData(zkw, "/hbase/replication/peers/1",
140         Bytes.toBytes(conf.get(HConstants.ZOOKEEPER_QUORUM) + ":"
141             + conf.get(HConstants.ZOOKEEPER_CLIENT_PORT) + ":/1"));
142     ZKUtil.createWithParents(zkw, "/hbase/replication/peers/1/peer-state");
143     ZKUtil.setData(zkw, "/hbase/replication/peers/1/peer-state",
144       ReplicationStateZKBase.ENABLED_ZNODE_BYTES);
145     ZKUtil.createWithParents(zkw, "/hbase/replication/state");
146     ZKUtil.setData(zkw, "/hbase/replication/state", ReplicationStateZKBase.ENABLED_ZNODE_BYTES);
147 
148     ZKClusterId.setClusterId(zkw, new ClusterId());
149     FSUtils.setRootDir(utility.getConfiguration(), utility.getDataTestDir());
150     fs = FileSystem.get(conf);
151     oldLogDir = new Path(utility.getDataTestDir(),
152         HConstants.HREGION_OLDLOGDIR_NAME);
153     logDir = new Path(utility.getDataTestDir(),
154         HConstants.HREGION_LOGDIR_NAME);
155     replication = new Replication(new DummyServer(), fs, logDir, oldLogDir);
156     manager = replication.getReplicationManager();
157 
158     manager.addSource(slaveId);
159 
160     htd = new HTableDescriptor(test);
161     HColumnDescriptor col = new HColumnDescriptor("f1");
162     col.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
163     htd.addFamily(col);
164     col = new HColumnDescriptor("f2");
165     col.setScope(HConstants.REPLICATION_SCOPE_LOCAL);
166     htd.addFamily(col);
167 
168     hri = new HRegionInfo(htd.getTableName(), r1, r2);
169   }
170 
171   @AfterClass
172   public static void tearDownAfterClass() throws Exception {
173     manager.join();
174     utility.shutdownMiniCluster();
175   }
176 
177   @Before
178   public void setUp() throws Exception {
179     fs.delete(logDir, true);
180     fs.delete(oldLogDir, true);
181   }
182 
183   @After
184   public void tearDown() throws Exception {
185     setUp();
186   }
187 
188   @Test
189   public void testLogRoll() throws Exception {
190     long seq = 0;
191     long baseline = 1000;
192     long time = baseline;
193     KeyValue kv = new KeyValue(r1, f1, r1);
194     WALEdit edit = new WALEdit();
195     edit.add(kv);
196 
197     List<WALActionsListener> listeners = new ArrayList<WALActionsListener>();
198     listeners.add(replication);
199     final WALFactory wals = new WALFactory(utility.getConfiguration(), listeners,
200         URLEncoder.encode("regionserver:60020", "UTF8"));
201     final WAL wal = wals.getWAL(hri.getEncodedNameAsBytes());
202     final AtomicLong sequenceId = new AtomicLong(1);
203     manager.init();
204     HTableDescriptor htd = new HTableDescriptor();
205     htd.addFamily(new HColumnDescriptor(f1));
206     // Testing normal log rolling every 20
207     for(long i = 1; i < 101; i++) {
208       if(i > 1 && i % 20 == 0) {
209         wal.rollWriter();
210       }
211       LOG.info(i);
212       final long txid = wal.append(htd, hri, new WALKey(hri.getEncodedNameAsBytes(), test,
213           System.currentTimeMillis()), edit, sequenceId, true ,null);
214       wal.sync(txid);
215     }
216 
217     // Simulate a rapid insert that's followed
218     // by a report that's still not totally complete (missing last one)
219     LOG.info(baseline + " and " + time);
220     baseline += 101;
221     time = baseline;
222     LOG.info(baseline + " and " + time);
223 
224     for (int i = 0; i < 3; i++) {
225       wal.append(htd, hri, new WALKey(hri.getEncodedNameAsBytes(), test,
226           System.currentTimeMillis()), edit, sequenceId, true, null);
227     }
228     wal.sync();
229 
230     assertEquals(6, manager.getWALs().get(slaveId).size());
231 
232     wal.rollWriter();
233 
234     manager.logPositionAndCleanOldLogs(manager.getSources().get(0).getCurrentPath(),
235         "1", 0, false, false);
236 
237     wal.append(htd, hri, new WALKey(hri.getEncodedNameAsBytes(), test,
238         System.currentTimeMillis()), edit, sequenceId, true, null);
239     wal.sync();
240 
241     assertEquals(1, manager.getWALs().size());
242 
243 
244     // TODO Need a case with only 2 WALs and we only want to delete the first one
245   }
246 
247   @Test
248   public void testClaimQueues() throws Exception {
249     LOG.debug("testNodeFailoverWorkerCopyQueuesFromRSUsingMulti");
250     conf.setBoolean(HConstants.ZOOKEEPER_USEMULTI, true);
251     final Server server = new DummyServer("hostname0.example.org");
252     ReplicationQueues rq =
253         ReplicationFactory.getReplicationQueues(server.getZooKeeper(), server.getConfiguration(),
254           server);
255     rq.init(server.getServerName().toString());
256     // populate some znodes in the peer znode
257     files.add("log1");
258     files.add("log2");
259     for (String file : files) {
260       rq.addLog("1", file);
261     }
262     // create 3 DummyServers
263     Server s1 = new DummyServer("dummyserver1.example.org");
264     Server s2 = new DummyServer("dummyserver2.example.org");
265     Server s3 = new DummyServer("dummyserver3.example.org");
266 
267     // create 3 DummyNodeFailoverWorkers
268     DummyNodeFailoverWorker w1 = new DummyNodeFailoverWorker(
269         server.getServerName().getServerName(), s1);
270     DummyNodeFailoverWorker w2 = new DummyNodeFailoverWorker(
271         server.getServerName().getServerName(), s2);
272     DummyNodeFailoverWorker w3 = new DummyNodeFailoverWorker(
273         server.getServerName().getServerName(), s3);
274 
275     latch = new CountDownLatch(3);
276     // start the threads
277     w1.start();
278     w2.start();
279     w3.start();
280     // make sure only one is successful
281     int populatedMap = 0;
282     // wait for result now... till all the workers are done.
283     latch.await();
284     populatedMap += w1.isLogZnodesMapPopulated() + w2.isLogZnodesMapPopulated()
285         + w3.isLogZnodesMapPopulated();
286     assertEquals(1, populatedMap);
287     server.abort("", null);
288   }
289 
290   @Test
291   public void testCleanupFailoverQueues() throws Exception {
292     final Server server = new DummyServer("hostname1.example.org");
293     ReplicationQueues rq =
294         ReplicationFactory.getReplicationQueues(server.getZooKeeper(), server.getConfiguration(),
295           server);
296     rq.init(server.getServerName().toString());
297     // populate some znodes in the peer znode
298     SortedSet<String> files = new TreeSet<String>();
299     files.add("log1");
300     files.add("log2");
301     for (String file : files) {
302       rq.addLog("1", file);
303     }
304     Server s1 = new DummyServer("dummyserver1.example.org");
305     ReplicationQueues rq1 =
306         ReplicationFactory.getReplicationQueues(s1.getZooKeeper(), s1.getConfiguration(), s1);
307     rq1.init(s1.getServerName().toString());
308     ReplicationPeers rp1 =
309         ReplicationFactory.getReplicationPeers(s1.getZooKeeper(), s1.getConfiguration(), s1);
310     rp1.init();
311     NodeFailoverWorker w1 =
312         manager.new NodeFailoverWorker(server.getServerName().getServerName(), rq1, rp1, new UUID(
313             new Long(1), new Long(2)));
314     w1.start();
315     w1.join(5000);
316     assertEquals(1, manager.getWalsByIdRecoveredQueues().size());
317     String id = "1-" + server.getServerName().getServerName();
318     assertEquals(files, manager.getWalsByIdRecoveredQueues().get(id));
319     manager.cleanOldLogs("log2", id, true);
320     // log1 should be deleted
321     assertEquals(Sets.newHashSet("log2"), manager.getWalsByIdRecoveredQueues().get(id));
322   }
323 
324   @Test
325   public void testNodeFailoverDeadServerParsing() throws Exception {
326     LOG.debug("testNodeFailoverDeadServerParsing");
327     conf.setBoolean(HConstants.ZOOKEEPER_USEMULTI, true);
328     final Server server = new DummyServer("ec2-54-234-230-108.compute-1.amazonaws.com");
329     ReplicationQueues repQueues =
330         ReplicationFactory.getReplicationQueues(server.getZooKeeper(), conf, server);
331     repQueues.init(server.getServerName().toString());
332     // populate some znodes in the peer znode
333     files.add("log1");
334     files.add("log2");
335     for (String file : files) {
336       repQueues.addLog("1", file);
337     }
338 
339     // create 3 DummyServers
340     Server s1 = new DummyServer("ip-10-8-101-114.ec2.internal");
341     Server s2 = new DummyServer("ec2-107-20-52-47.compute-1.amazonaws.com");
342     Server s3 = new DummyServer("ec2-23-20-187-167.compute-1.amazonaws.com");
343 
344     // simulate three servers fail sequentially
345     ReplicationQueues rq1 =
346         ReplicationFactory.getReplicationQueues(s1.getZooKeeper(), s1.getConfiguration(), s1);
347     rq1.init(s1.getServerName().toString());
348     SortedMap<String, SortedSet<String>> testMap =
349         rq1.claimQueues(server.getServerName().getServerName());
350     ReplicationQueues rq2 =
351         ReplicationFactory.getReplicationQueues(s2.getZooKeeper(), s2.getConfiguration(), s2);
352     rq2.init(s2.getServerName().toString());
353     testMap = rq2.claimQueues(s1.getServerName().getServerName());
354     ReplicationQueues rq3 =
355         ReplicationFactory.getReplicationQueues(s3.getZooKeeper(), s3.getConfiguration(), s3);
356     rq3.init(s3.getServerName().toString());
357     testMap = rq3.claimQueues(s2.getServerName().getServerName());
358 
359     ReplicationQueueInfo replicationQueueInfo = new ReplicationQueueInfo(testMap.firstKey());
360     List<String> result = replicationQueueInfo.getDeadRegionServers();
361 
362     // verify
363     assertTrue(result.contains(server.getServerName().getServerName()));
364     assertTrue(result.contains(s1.getServerName().getServerName()));
365     assertTrue(result.contains(s2.getServerName().getServerName()));
366 
367     server.abort("", null);
368   }
369 
370 
371   static class DummyNodeFailoverWorker extends Thread {
372     private SortedMap<String, SortedSet<String>> logZnodesMap;
373     Server server;
374     private String deadRsZnode;
375     ReplicationQueues rq;
376 
377     public DummyNodeFailoverWorker(String znode, Server s) throws Exception {
378       this.deadRsZnode = znode;
379       this.server = s;
380       this.rq =
381           ReplicationFactory.getReplicationQueues(server.getZooKeeper(), server.getConfiguration(),
382             server);
383       this.rq.init(this.server.getServerName().toString());
384     }
385 
386     @Override
387     public void run() {
388       try {
389         logZnodesMap = rq.claimQueues(deadRsZnode);
390         server.abort("Done with testing", null);
391       } catch (Exception e) {
392         LOG.error("Got exception while running NodeFailoverWorker", e);
393       } finally {
394         latch.countDown();
395       }
396     }
397 
398     /**
399      * @return 1 when the map is not empty.
400      */
401     private int isLogZnodesMapPopulated() {
402       Collection<SortedSet<String>> sets = logZnodesMap.values();
403       if (sets.size() > 1) {
404         throw new RuntimeException("unexpected size of logZnodesMap: " + sets.size());
405       }
406       if (sets.size() == 1) {
407         SortedSet<String> s = sets.iterator().next();
408         for (String file : files) {
409           // at least one file was missing
410           if (!s.contains(file)) {
411             return 0;
412           }
413         }
414         return 1; // we found all the files
415       }
416       return 0;
417     }
418   }
419 
420   static class DummyServer implements Server {
421     String hostname;
422 
423     DummyServer() {
424       hostname = "hostname.example.org";
425     }
426 
427     DummyServer(String hostname) {
428       this.hostname = hostname;
429     }
430 
431     @Override
432     public Configuration getConfiguration() {
433       return conf;
434     }
435 
436     @Override
437     public ZooKeeperWatcher getZooKeeper() {
438       return zkw;
439     }
440 
441     @Override
442     public CoordinatedStateManager getCoordinatedStateManager() {
443       return null;
444     }
445     @Override
446     public ClusterConnection getConnection() {
447       return null;
448     }
449 
450     @Override
451     public MetaTableLocator getMetaTableLocator() {
452       return null;
453     }
454 
455     @Override
456     public ServerName getServerName() {
457       return ServerName.valueOf(hostname, 1234, 1L);
458     }
459 
460     @Override
461     public void abort(String why, Throwable e) {
462       // To change body of implemented methods use File | Settings | File Templates.
463     }
464 
465     @Override
466     public boolean isAborted() {
467       return false;
468     }
469 
470     @Override
471     public void stop(String why) {
472       // To change body of implemented methods use File | Settings | File Templates.
473     }
474 
475     @Override
476     public boolean isStopped() {
477       return false; // To change body of implemented methods use File | Settings | File Templates.
478     }
479 
480     @Override
481     public ChoreService getChoreService() {
482       return null;
483     }
484   }
485 }