1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.regionserver;
21
22 import static org.junit.Assert.assertFalse;
23 import static org.junit.Assert.assertTrue;
24
25 import java.util.concurrent.Semaphore;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29 import org.apache.hadoop.hbase.HBaseTestingUtility;
30 import org.apache.hadoop.hbase.HServerAddress;
31 import org.apache.hadoop.hbase.MasterAddressTracker;
32 import org.apache.hadoop.hbase.zookeeper.ZKUtil;
33 import org.apache.hadoop.hbase.zookeeper.ZooKeeperListener;
34 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
35 import org.junit.AfterClass;
36 import org.junit.BeforeClass;
37 import org.junit.Test;
38
39 public class TestMasterAddressManager {
40 private static final Log LOG = LogFactory.getLog(TestMasterAddressManager.class);
41
42 private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
43
44 @BeforeClass
45 public static void setUpBeforeClass() throws Exception {
46 TEST_UTIL.startMiniZKCluster();
47 }
48
49 @AfterClass
50 public static void tearDownAfterClass() throws Exception {
51 TEST_UTIL.shutdownMiniZKCluster();
52 }
53
54
55
56
57
58 @Test
59 public void testMasterAddressManagerFromZK() throws Exception {
60
61 ZooKeeperWatcher zk = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(),
62 "testMasterAddressManagerFromZK", null);
63 ZKUtil.createAndFailSilent(zk, zk.baseZNode);
64
65
66 MasterAddressTracker addressManager = new MasterAddressTracker(zk, null);
67 addressManager.start();
68 assertFalse(addressManager.hasMaster());
69 zk.registerListener(addressManager);
70
71
72 NodeCreationListener listener = new NodeCreationListener(zk, zk.masterAddressZNode);
73 zk.registerListener(listener);
74
75
76 String host = "localhost";
77 int port = 1234;
78 HServerAddress dummyAddress = new HServerAddress(host, port);
79 LOG.info("Creating master node");
80 ZKUtil.setAddressAndWatch(zk, zk.masterAddressZNode, dummyAddress);
81
82
83 LOG.info("Waiting for master address manager to be notified");
84 listener.waitForCreation();
85 LOG.info("Master node created");
86 assertTrue(addressManager.hasMaster());
87 HServerAddress pulledAddress = addressManager.getMasterAddress();
88 assertTrue(pulledAddress.equals(dummyAddress));
89
90 }
91
92 public static class NodeCreationListener extends ZooKeeperListener {
93 private static final Log LOG = LogFactory.getLog(NodeCreationListener.class);
94
95 private Semaphore lock;
96 private String node;
97
98 public NodeCreationListener(ZooKeeperWatcher watcher, String node) {
99 super(watcher);
100 lock = new Semaphore(0);
101 this.node = node;
102 }
103
104 @Override
105 public void nodeCreated(String path) {
106 if(path.equals(node)) {
107 LOG.debug("nodeCreated(" + path + ")");
108 lock.release();
109 }
110 }
111
112 public void waitForCreation() throws InterruptedException {
113 lock.acquire();
114 }
115 }
116 }