Search in sources :

Example 26 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project xian by happyyangyuan.

the class TestResetConnectionWithBackgroundFailure method testConnectionStateListener.

@Test
public void testConnectionStateListener() throws Exception {
    server.stop();
    LeaderSelector selector = null;
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        timing.sleepABit();
        LeaderSelectorListener listenerLeader = new LeaderSelectorListenerAdapter() {

            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                Thread.currentThread().join();
            }
        };
        selector = new LeaderSelector(client, "/leader", listenerLeader);
        selector.autoRequeue();
        selector.start();
        final BlockingQueue<ConnectionState> listenerSequence = Queues.newLinkedBlockingQueue();
        ConnectionStateListener listener1 = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                listenerSequence.add(newState);
            }
        };
        Timing forWaiting = timing.forWaiting();
        client.getConnectionStateListenable().addListener(listener1);
        log.debug("Starting ZK server");
        server.restart();
        Assert.assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED);
        log.debug("Stopping ZK server");
        server.stop();
        Assert.assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED);
        Assert.assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST);
        log.debug("Starting ZK server");
        server.restart();
        Assert.assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.RECONNECTED);
        log.debug("Stopping ZK server");
        server.close();
        Assert.assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED);
        Assert.assertEquals(listenerSequence.poll(forWaiting.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST);
    } finally {
        CloseableUtils.closeQuietly(selector);
        CloseableUtils.closeQuietly(client);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) RetryOneTime(org.apache.curator.retry.RetryOneTime) LeaderSelectorListener(org.apache.curator.framework.recipes.leader.LeaderSelectorListener) LeaderSelector(org.apache.curator.framework.recipes.leader.LeaderSelector) Timing(org.apache.curator.test.Timing) LeaderSelectorListenerAdapter(org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter) ConnectionState(org.apache.curator.framework.state.ConnectionState) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) Test(org.testng.annotations.Test)

Example 27 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project xian by happyyangyuan.

the class TestBlockUntilConnected method testBlockUntilConnectedCurrentlyConnected.

/**
 * Test the case where we're already connected
 */
@Test
public void testBlockUntilConnectedCurrentlyConnected() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
    try {
        final CountDownLatch connectedLatch = new CountDownLatch(1);
        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState.isConnected()) {
                    connectedLatch.countDown();
                }
            }
        });
        client.start();
        Assert.assertTrue(timing.awaitLatch(connectedLatch), "Timed out awaiting latch");
        Assert.assertTrue(client.blockUntilConnected(1, TimeUnit.SECONDS), "Not connected");
    } catch (InterruptedException e) {
        Assert.fail("Unexpected interruption");
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) RetryOneTime(org.apache.curator.retry.RetryOneTime) Timing(org.apache.curator.test.Timing) ConnectionState(org.apache.curator.framework.state.ConnectionState) CountDownLatch(java.util.concurrent.CountDownLatch) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) Test(org.testng.annotations.Test)

Example 28 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project xian by happyyangyuan.

the class TestBlockUntilConnected method testBlockUntilConnectedSessionExpired.

/**
 * Test that we got disconnected before calling blockUntilConnected and we reconnect we receive a session expired event.
 */
@Test
public void testBlockUntilConnectedSessionExpired() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).build();
    final CountDownLatch lostLatch = new CountDownLatch(1);
    client.getConnectionStateListenable().addListener(new ConnectionStateListener() {

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            if (newState == ConnectionState.LOST) {
                lostLatch.countDown();
            }
        }
    });
    final CountDownLatch expiredLatch = new CountDownLatch(1);
    client.getCuratorListenable().addListener(new CuratorListener() {

        @Override
        public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
            if (event.getType() == CuratorEventType.WATCHED && event.getWatchedEvent().getState() == Watcher.Event.KeeperState.Expired) {
                expiredLatch.countDown();
            }
        }
    });
    ConnectionStateAccessor.setDebugWaitOnExpiredForClient(client);
    try {
        client.start();
        // Block until we're connected
        Assert.assertTrue(client.blockUntilConnected(5, TimeUnit.SECONDS), "Failed to connect");
        final long sessionTimeoutMs = client.getZookeeperClient().getConnectionTimeoutMs();
        // Kill the server
        CloseableUtils.closeQuietly(server);
        // Wait until we hit the lost state
        Assert.assertTrue(timing.awaitLatch(lostLatch), "Failed to reach LOST state");
        Thread.sleep(sessionTimeoutMs);
        server = new TestingServer(server.getPort(), server.getTempDirectory());
        // Wait until we get expired event
        Assert.assertTrue(timing.awaitLatch(expiredLatch), "Failed to get Expired event");
        final boolean blockUntilConnected5Seconds = client.blockUntilConnected(5, TimeUnit.SECONDS);
        Assert.assertTrue(client.getZookeeperClient().isConnected(), "ConnectionState.isConnected returned false");
        Assert.assertTrue(blockUntilConnected5Seconds, "BlockUntilConnected returned false");
    } catch (Exception e) {
        Assert.fail("Unexpected exception " + e);
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : TestingServer(org.apache.curator.test.TestingServer) RetryOneTime(org.apache.curator.retry.RetryOneTime) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch) CuratorFramework(org.apache.curator.framework.CuratorFramework) CuratorListener(org.apache.curator.framework.api.CuratorListener) Timing(org.apache.curator.test.Timing) ConnectionState(org.apache.curator.framework.state.ConnectionState) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) Test(org.testng.annotations.Test)

Example 29 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project xian by happyyangyuan.

the class TestFailedDeleteManager method testWithNamespaceAndLostSessionAlt.

@Test
public void testWithNamespaceAndLostSessionAlt() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()).retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
    try {
        client.start();
        CuratorFramework namespaceClient = client.usingNamespace("foo");
        namespaceClient.create().forPath("/test-me");
        final CountDownLatch latch = new CountDownLatch(1);
        final Semaphore semaphore = new Semaphore(0);
        ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) {
                    semaphore.release();
                } else if (newState == ConnectionState.RECONNECTED) {
                    latch.countDown();
                }
            }
        };
        namespaceClient.getConnectionStateListenable().addListener(listener);
        server.stop();
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        try {
            namespaceClient.delete().guaranteed().forPath("/test-me");
            Assert.fail();
        } catch (KeeperException.ConnectionLossException e) {
        // expected
        }
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        timing.sleepABit();
        server.restart();
        Assert.assertTrue(timing.awaitLatch(latch));
        timing.sleepABit();
        Assert.assertNull(namespaceClient.checkExists().forPath("/test-me"));
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) Timing(org.apache.curator.test.Timing) Semaphore(java.util.concurrent.Semaphore) ConnectionState(org.apache.curator.framework.state.ConnectionState) CountDownLatch(java.util.concurrent.CountDownLatch) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) KeeperException(org.apache.zookeeper.KeeperException) Test(org.testng.annotations.Test)

Example 30 with ConnectionStateListener

use of org.apache.curator.framework.state.ConnectionStateListener in project xian by happyyangyuan.

the class TestFailedDeleteManager method testWithNamespaceAndLostSession.

@Test
public void testWithNamespaceAndLostSession() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()).retryPolicy(new ExponentialBackoffRetry(100, 3)).namespace("aisa").build();
    try {
        client.start();
        client.create().forPath("/test-me");
        final CountDownLatch latch = new CountDownLatch(1);
        final Semaphore semaphore = new Semaphore(0);
        ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if ((newState == ConnectionState.LOST) || (newState == ConnectionState.SUSPENDED)) {
                    semaphore.release();
                } else if (newState == ConnectionState.RECONNECTED) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        server.stop();
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        try {
            client.delete().guaranteed().forPath("/test-me");
            Assert.fail();
        } catch (KeeperException.ConnectionLossException e) {
        // expected
        }
        Assert.assertTrue(timing.acquireSemaphore(semaphore));
        timing.sleepABit();
        server.restart();
        Assert.assertTrue(timing.awaitLatch(latch));
        timing.sleepABit();
        Assert.assertNull(client.checkExists().forPath("/test-me"));
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) Timing(org.apache.curator.test.Timing) Semaphore(java.util.concurrent.Semaphore) ConnectionState(org.apache.curator.framework.state.ConnectionState) CountDownLatch(java.util.concurrent.CountDownLatch) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) KeeperException(org.apache.zookeeper.KeeperException) Test(org.testng.annotations.Test)

Aggregations

CuratorFramework (org.apache.curator.framework.CuratorFramework)37 ConnectionStateListener (org.apache.curator.framework.state.ConnectionStateListener)37 ConnectionState (org.apache.curator.framework.state.ConnectionState)36 Test (org.testng.annotations.Test)29 Timing (org.apache.curator.test.Timing)24 CountDownLatch (java.util.concurrent.CountDownLatch)23 RetryOneTime (org.apache.curator.retry.RetryOneTime)20 ExponentialBackoffRetry (org.apache.curator.retry.ExponentialBackoffRetry)9 KeeperException (org.apache.zookeeper.KeeperException)9 TestingCluster (org.apache.curator.test.TestingCluster)5 TestingServer (org.apache.curator.test.TestingServer)5 IOException (java.io.IOException)4 Semaphore (java.util.concurrent.Semaphore)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 InstanceSpec (org.apache.curator.test.InstanceSpec)4 ExecutorCompletionService (java.util.concurrent.ExecutorCompletionService)3 ExecutorService (java.util.concurrent.ExecutorService)3 RetryNTimes (org.apache.curator.retry.RetryNTimes)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2