Search in sources :

Example 26 with Watcher

use of org.apache.zookeeper.Watcher in project commons by twitter.

the class SingletonServiceTest method testNonLeaderDisconnect.

@Test
public void testNonLeaderDisconnect() throws Exception {
    CountDownLatch elected = new CountDownLatch(1);
    listener.onLeading(EasyMock.<LeaderControl>anyObject());
    expectLastCall().andAnswer(countDownAnswer(elected));
    listener.onDefeated(null);
    expectLastCall().anyTimes();
    control.replay();
    ZooKeeperClient zkClient = createZkClient();
    String path = "/fake/path";
    // Create a fake leading candidate node to ensure that the leader in this test is never
    // elected.
    ZooKeeperUtils.ensurePath(zkClient, ZooKeeperUtils.OPEN_ACL_UNSAFE, path);
    String leaderNode = zkClient.get().create(path + "/" + SingletonService.LEADER_ELECT_NODE_PREFIX, "fake_leader".getBytes(), ZooKeeperUtils.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
    serverSet = new ServerSetImpl(zkClient, path);
    candidate = SingletonService.createSingletonCandidate(zkClient, path, ZooKeeperUtils.OPEN_ACL_UNSAFE);
    DefeatOnDisconnectLeader leader = new DefeatOnDisconnectLeader(zkClient, listener);
    service = new SingletonService(serverSet, candidate);
    service.lead(InetSocketAddress.createUnresolved("foo", PORT_A), ImmutableMap.of("http-admin", InetSocketAddress.createUnresolved("foo", PORT_B)), leader);
    final CountDownLatch disconnected = new CountDownLatch(1);
    zkClient.register(new Watcher() {

        @Override
        public void process(WatchedEvent event) {
            if ((event.getType() == EventType.None) && (event.getState() == KeeperState.Disconnected)) {
                disconnected.countDown();
            }
        }
    });
    shutdownNetwork();
    disconnected.await();
    restartNetwork();
    zkClient.get().delete(leaderNode, ZooKeeperUtils.ANY_VERSION);
    // Upon deletion of the fake leader node, the candidate should become leader.
    elected.await();
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) DefeatOnDisconnectLeader(com.twitter.common.zookeeper.SingletonService.DefeatOnDisconnectLeader) Watcher(org.apache.zookeeper.Watcher) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test) BaseZooKeeperTest(com.twitter.common.zookeeper.testing.BaseZooKeeperTest)

Example 27 with Watcher

use of org.apache.zookeeper.Watcher in project pulsar by yahoo.

the class LeaderElectionService method elect.

/**
     * We try to get the data in the ELECTION_ROOT node. If the node is present (i.e. leader is present), we store it in
     * the currentLeader and keep a watch on the election node. If we lose the leader, then watch gets triggered and we
     * do the election again. If the node does not exist while getting the data, we get NoNodeException. This means,
     * there is no leader and we create the node at ELECTION_ROOT and write the leader broker's service URL in the node.
     * Once the leader is known, we call the listener method so that leader can take further actions.
     */
private void elect() {
    try {
        byte[] data = zkClient.getData(ELECTION_ROOT, new Watcher() {

            @Override
            public void process(WatchedEvent event) {
                log.warn("Type of the event is [{}] and path is [{}]", event.getType(), event.getPath());
                switch(event.getType()) {
                    case NodeDeleted:
                        log.warn("Election node {} is deleted, attempting re-election...", event.getPath());
                        if (event.getPath().equals(ELECTION_ROOT)) {
                            log.info("This should call elect again...");
                            executor.execute(new Runnable() {

                                @Override
                                public void run() {
                                    // If the node is deleted, attempt the re-election
                                    log.info("Broker [{}] is calling re-election from the thread", pulsar.getWebServiceAddress());
                                    elect();
                                }
                            });
                        }
                        break;
                    default:
                        log.warn("Got something wrong on watch: {}", event);
                        break;
                }
            }
        }, null);
        LeaderBroker leaderBroker = jsonMapper.readValue(data, LeaderBroker.class);
        currentLeader.set(leaderBroker);
        isLeader.set(false);
        leaderListener.brokerIsAFollowerNow();
        // If broker comes here it is a follower. Do nothing, wait for the watch to trigger
        log.info("Broker [{}] is the follower now. Waiting for the watch to trigger...", pulsar.getWebServiceAddress());
    } catch (NoNodeException nne) {
        // There's no leader yet... try to become the leader
        try {
            // Create the root node and add current broker's URL as its contents
            LeaderBroker leaderBroker = new LeaderBroker(pulsar.getWebServiceAddress());
            ZkUtils.createFullPathOptimistic(pulsar.getLocalZkCache().getZooKeeper(), ELECTION_ROOT, jsonMapper.writeValueAsBytes(leaderBroker), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            // Update the current leader and set the flag to true
            currentLeader.set(new LeaderBroker(leaderBroker.getServiceUrl()));
            isLeader.set(true);
            // Notify the listener that this broker is now the leader so that it can collect usage and start load
            // manager.
            log.info("Broker [{}] is the leader now, notifying the listener...", pulsar.getWebServiceAddress());
            leaderListener.brokerIsTheLeaderNow();
        } catch (NodeExistsException nee) {
            // Re-elect the new leader
            log.warn("Got exception [{}] while creating election node because it already exists. Attempting re-election...", nee.getMessage());
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    elect();
                }
            });
        } catch (Exception e) {
            // Kill the broker because this broker's session with zookeeper might be stale. Killing the broker will
            // make sure that we get the fresh zookeeper session.
            log.error("Got exception [{}] while creating the election node", e.getMessage());
            pulsar.getShutdownService().shutdown(-1);
        }
    } catch (Exception e) {
        // Kill the broker
        log.error("Could not get the content of [{}], got exception [{}]. Shutting down the broker...", ELECTION_ROOT, e);
        pulsar.getShutdownService().shutdown(-1);
    }
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) NoNodeException(org.apache.zookeeper.KeeperException.NoNodeException) NodeExistsException(org.apache.zookeeper.KeeperException.NodeExistsException) Watcher(org.apache.zookeeper.Watcher) NoNodeException(org.apache.zookeeper.KeeperException.NoNodeException) NodeExistsException(org.apache.zookeeper.KeeperException.NodeExistsException)

Example 28 with Watcher

use of org.apache.zookeeper.Watcher in project yyl_example by Relucent.

the class Test1 method main.

public static void main(String[] args) throws Exception {
    ZooKeeper zk = new ZooKeeper("localhost:2181", 1000, new Watcher() {

        // 监控所有被触发的事件
        public void process(WatchedEvent event) {
            System.out.println("已经触发了" + event.getType() + "事件!");
        }
    });
    // 创建一个目录节点
    zk.create("/testRootPath", "testRootData".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    // 创建一个子目录节点
    zk.create("/testRootPath/testChildPathOne", "testChildDataOne".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    System.out.println(new String(zk.getData("/testRootPath", false, null)));
    // 取出子目录节点列表
    System.out.println(zk.getChildren("/testRootPath", true));
    // 修改子目录节点数据
    zk.setData("/testRootPath/testChildPathOne", "modifyChildDataOne".getBytes(), -1);
    System.out.println("目录节点状态:[" + zk.exists("/testRootPath", true) + "]");
    // 创建另外一个子目录节点
    zk.create("/testRootPath/testChildPathTwo", "testChildDataTwo".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    System.out.println(new String(zk.getData("/testRootPath/testChildPathTwo", true, null)));
    // 删除子目录节点
    zk.delete("/testRootPath/testChildPathTwo", -1);
    zk.delete("/testRootPath/testChildPathOne", -1);
    // 删除父目录节点
    zk.delete("/testRootPath", -1);
    // 关闭连接
    zk.close();
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) ZooKeeper(org.apache.zookeeper.ZooKeeper) Watcher(org.apache.zookeeper.Watcher)

Example 29 with Watcher

use of org.apache.zookeeper.Watcher in project yyl_example by Relucent.

the class Test3 method main.

public static void main(String[] args) {
    ZooKeeper zk = null;
    try {
        zk = new ZooKeeper("localhost:2181", 1000, null);
        zk.exists("/test", new Watcher() {

            @Override
            public void process(WatchedEvent e) {
                System.out.println(e);
            }
        });
        Thread.sleep(60 * 1000);
    } catch (Exception e) {
        e.printStackTrace();
        try {
            if (zk != null) {
                zk.close();
            }
        } catch (Exception e1) {
        }
    }
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) ZooKeeper(org.apache.zookeeper.ZooKeeper) Watcher(org.apache.zookeeper.Watcher)

Example 30 with Watcher

use of org.apache.zookeeper.Watcher in project Dempsy by Dempsy.

the class TestZookeeperClusterImpl method testBadZooKeeperConnection.

@Test
public void testBadZooKeeperConnection() throws Throwable {
    int port = ZookeeperTestServer.findNextPort();
    ZookeeperTestServer server = new ZookeeperTestServer();
    Throwable receivedException = null;
    ZookeeperSession session = null;
    try {
        server.start();
        session = new ZookeeperSession("127.0.0.1:" + port, 5000) {

            @Override
            protected ZooKeeper makeZooKeeperClient(String connectString, int sessionTimeout) throws IOException {
                return new ZooKeeper(connectString, sessionTimeout, new ZkWatcher()) {

                    @Override
                    public List<String> getChildren(String path, Watcher watcher) throws KeeperException {
                        throw (appropriateException = new KeeperException(Code.DATAINCONSISTENCY) {

                            private static final long serialVersionUID = 1L;
                        });
                    }
                };
            }
        };
        try {
            session.getSubdirs(new ClusterId("test", "test").asPath(), null);
        } catch (Exception e) {
            receivedException = e.getCause();
        }
    } finally {
        server.shutdown();
        if (session != null)
            session.stop();
    }
    assertNotNull(appropriateException);
    assertTrue(receivedException == appropriateException);
}
Also used : ClusterId(com.nokia.dempsy.config.ClusterId) Watcher(org.apache.zookeeper.Watcher) IOException(java.io.IOException) ClusterInfoException(com.nokia.dempsy.cluster.ClusterInfoException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) ZooKeeper(org.apache.zookeeper.ZooKeeper) List(java.util.List) KeeperException(org.apache.zookeeper.KeeperException) Test(org.junit.Test)

Aggregations

Watcher (org.apache.zookeeper.Watcher)78 WatchedEvent (org.apache.zookeeper.WatchedEvent)62 KeeperException (org.apache.zookeeper.KeeperException)35 CountDownLatch (java.util.concurrent.CountDownLatch)25 ZooKeeper (org.apache.zookeeper.ZooKeeper)25 Stat (org.apache.zookeeper.data.Stat)21 Test (org.junit.Test)18 IOException (java.io.IOException)11 AsyncCallback (org.apache.zookeeper.AsyncCallback)10 List (java.util.List)8 Test (org.testng.annotations.Test)8 None (com.linkedin.common.util.None)7 HashSet (java.util.HashSet)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 Map (java.util.Map)5 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 Set (java.util.Set)4 TimeoutException (java.util.concurrent.TimeoutException)4 CountdownWatcher (org.apache.zookeeper.test.ClientBase.CountdownWatcher)4