Search in sources :

Example 16 with ConnectionStateListener

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

the class TestInterProcessSemaphoreCluster method testKilledServerWithEnsembleProvider.

@Test
public void testKilledServerWithEnsembleProvider() throws Exception {
    final int CLIENT_QTY = 10;
    final Timing timing = new Timing();
    final String PATH = "/foo/bar/lock";
    ExecutorService executorService = Executors.newFixedThreadPool(CLIENT_QTY);
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executorService);
    TestingCluster cluster = new TestingCluster(3);
    try {
        cluster.start();
        final AtomicReference<String> connectionString = new AtomicReference<String>(cluster.getConnectString());
        final EnsembleProvider provider = new EnsembleProvider() {

            @Override
            public void start() throws Exception {
            }

            @Override
            public String getConnectionString() {
                return connectionString.get();
            }

            @Override
            public void close() throws IOException {
            }
        };
        final Semaphore acquiredSemaphore = new Semaphore(0);
        final AtomicInteger acquireCount = new AtomicInteger(0);
        final CountDownLatch suspendedLatch = new CountDownLatch(CLIENT_QTY);
        for (int i = 0; i < CLIENT_QTY; ++i) {
            completionService.submit(new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    CuratorFramework client = CuratorFrameworkFactory.builder().ensembleProvider(provider).sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()).retryPolicy(new ExponentialBackoffRetry(100, 3)).build();
                    try {
                        final Semaphore suspendedSemaphore = new Semaphore(0);
                        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {

                            @Override
                            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                                if ((newState == ConnectionState.SUSPENDED) || (newState == ConnectionState.LOST)) {
                                    suspendedLatch.countDown();
                                    suspendedSemaphore.release();
                                }
                            }
                        });
                        client.start();
                        InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, PATH, 1);
                        while (!Thread.currentThread().isInterrupted()) {
                            Lease lease = null;
                            try {
                                lease = semaphore.acquire();
                                acquiredSemaphore.release();
                                acquireCount.incrementAndGet();
                                suspendedSemaphore.acquire();
                            } catch (Exception e) {
                            // just retry
                            } finally {
                                if (lease != null) {
                                    acquireCount.decrementAndGet();
                                    CloseableUtils.closeQuietly(lease);
                                }
                            }
                        }
                    } finally {
                        CloseableUtils.closeQuietly(client);
                    }
                    return null;
                }
            });
        }
        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        Assert.assertEquals(1, acquireCount.get());
        cluster.close();
        timing.awaitLatch(suspendedLatch);
        timing.forWaiting().sleepABit();
        Assert.assertEquals(0, acquireCount.get());
        cluster = new TestingCluster(3);
        cluster.start();
        connectionString.set(cluster.getConnectString());
        timing.forWaiting().sleepABit();
        Assert.assertTrue(timing.acquireSemaphore(acquiredSemaphore));
        timing.forWaiting().sleepABit();
        Assert.assertEquals(1, acquireCount.get());
    } finally {
        executorService.shutdown();
        executorService.awaitTermination(10, TimeUnit.SECONDS);
        executorService.shutdownNow();
        CloseableUtils.closeQuietly(cluster);
    }
}
Also used : ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) ExecutorCompletionService(java.util.concurrent.ExecutorCompletionService) AtomicReference(java.util.concurrent.atomic.AtomicReference) Semaphore(java.util.concurrent.Semaphore) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) EnsembleProvider(org.apache.curator.ensemble.EnsembleProvider) CuratorFramework(org.apache.curator.framework.CuratorFramework) TestingCluster(org.apache.curator.test.TestingCluster) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) 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 17 with ConnectionStateListener

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

the class TestPersistentEphemeralNode method testNoServerAtStart.

@Test
public void testNoServerAtStart() throws Exception {
    server.stop();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes());
        node.start();
        final CountDownLatch connectedLatch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.CONNECTED) {
                    connectedLatch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        timing.sleepABit();
        server.restart();
        Assert.assertTrue(timing.awaitLatch(connectedLatch));
        timing.sleepABit();
        Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS));
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) RetryOneTime(org.apache.curator.retry.RetryOneTime) 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 18 with ConnectionStateListener

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

the class TestPersistentEphemeralNode method testListenersReconnectedIsFast.

@Test
public void testListenersReconnectedIsFast() throws Exception {
    server.stop();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes());
        node.start();
        final CountDownLatch connectedLatch = new CountDownLatch(1);
        final CountDownLatch reconnectedLatch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.CONNECTED) {
                    connectedLatch.countDown();
                }
                if (newState == ConnectionState.RECONNECTED) {
                    reconnectedLatch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        timing.sleepABit();
        server.restart();
        Assert.assertTrue(timing.awaitLatch(connectedLatch));
        timing.sleepABit();
        Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS));
        server.stop();
        timing.sleepABit();
        server.restart();
        timing.sleepABit();
        Assert.assertTrue(timing.awaitLatch(reconnectedLatch));
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) RetryOneTime(org.apache.curator.retry.RetryOneTime) 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 19 with ConnectionStateListener

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

the class TestPersistentEphemeralNodeListener method testListenersReconnectedIsOK.

@Test
public void testListenersReconnectedIsOK() throws Exception {
    server.stop();
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        PersistentEphemeralNode node = new PersistentEphemeralNode(client, PersistentEphemeralNode.Mode.EPHEMERAL, "/abc/node", "hello".getBytes());
        node.start();
        final CountDownLatch connectedLatch = new CountDownLatch(1);
        final CountDownLatch reconnectedLatch = new CountDownLatch(1);
        final AtomicReference<ConnectionState> lastState = new AtomicReference<ConnectionState>();
        ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                lastState.set(newState);
                if (newState == ConnectionState.CONNECTED) {
                    connectedLatch.countDown();
                }
                if (newState == ConnectionState.RECONNECTED) {
                    reconnectedLatch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        timing.sleepABit();
        server.restart();
        Assert.assertTrue(timing.awaitLatch(connectedLatch));
        timing.sleepABit();
        Assert.assertTrue(node.waitForInitialCreate(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS));
        server.restart();
        timing.sleepABit();
        Assert.assertTrue(timing.awaitLatch(reconnectedLatch));
        timing.sleepABit();
        Assert.assertEquals(lastState.get(), ConnectionState.RECONNECTED);
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) RetryOneTime(org.apache.curator.retry.RetryOneTime) AtomicReference(java.util.concurrent.atomic.AtomicReference) 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 20 with ConnectionStateListener

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

the class CuratorFrameworkImpl method start.

@Override
public void start() {
    log.info("Starting");
    if (!state.compareAndSet(CuratorFrameworkState.LATENT, CuratorFrameworkState.STARTED)) {
        throw new IllegalStateException("Cannot be started more than once");
    }
    try {
        // ordering dependency - must be called before client.start()
        connectionStateManager.start();
        final ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (ConnectionState.CONNECTED == newState || ConnectionState.RECONNECTED == newState) {
                    logAsErrorConnectionErrors.set(true);
                }
            }
        };
        this.getConnectionStateListenable().addListener(listener);
        client.start();
        executorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
        executorService.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                backgroundOperationsLoop();
                return null;
            }
        });
    } catch (Exception e) {
        ThreadUtils.checkInterrupted(e);
        handleBackgroundOperationException(null, e);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) ConnectionState(org.apache.curator.framework.state.ConnectionState) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) KeeperException(org.apache.zookeeper.KeeperException) CuratorConnectionLossException(org.apache.curator.CuratorConnectionLossException)

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