Search in sources :

Example 16 with RetryNTimes

use of org.apache.curator.retry.RetryNTimes in project xian by happyyangyuan.

the class TestFrameworkEdges method testProtectedCreateNodeDeletion.

@Test
public void testProtectedCreateNodeDeletion() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), 1, new RetryNTimes(0, 0));
    try {
        client.start();
        for (int i = 0; i < 2; ++i) {
            CuratorFramework localClient = (i == 0) ? client : client.usingNamespace("nm");
            localClient.create().forPath("/parent");
            Assert.assertEquals(localClient.getChildren().forPath("/parent").size(), 0);
            CreateBuilderImpl createBuilder = (CreateBuilderImpl) localClient.create();
            createBuilder.failNextCreateForTesting = true;
            FindAndDeleteProtectedNodeInBackground.debugInsertError.set(true);
            try {
                createBuilder.withProtection().forPath("/parent/test");
                Assert.fail("failNextCreateForTesting should have caused a ConnectionLossException");
            } catch (KeeperException.ConnectionLossException e) {
            // ignore, correct
            }
            timing.sleepABit();
            List<String> children = localClient.getChildren().forPath("/parent");
            // protected mode should have deleted the node
            Assert.assertEquals(children.size(), 0, children.toString());
            localClient.delete().forPath("/parent");
        }
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) CuratorFramework(org.apache.curator.framework.CuratorFramework) KeeperException(org.apache.zookeeper.KeeperException) Test(org.testng.annotations.Test)

Example 17 with RetryNTimes

use of org.apache.curator.retry.RetryNTimes in project xian by happyyangyuan.

the class TestReadOnly method testConnectionStateNewClient.

@Test
public void testConnectionStateNewClient() throws Exception {
    Timing timing = new Timing();
    TestingCluster cluster = new TestingCluster(3);
    CuratorFramework client = null;
    try {
        cluster.start();
        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(100));
        client.start();
        client.checkExists().forPath("/");
        client.close();
        client = null;
        Iterator<InstanceSpec> iterator = cluster.getInstances().iterator();
        for (int i = 0; i < 2; ++i) {
            cluster.killServer(iterator.next());
        }
        client = CuratorFrameworkFactory.builder().connectString(cluster.getConnectString()).sessionTimeoutMs(timing.session()).connectionTimeoutMs(timing.connection()).retryPolicy(new RetryNTimes(3, timing.milliseconds())).canBeReadOnly(true).build();
        final BlockingQueue<ConnectionState> states = Queues.newLinkedBlockingQueue();
        client.getConnectionStateListenable().addListener(new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                states.add(newState);
            }
        });
        client.start();
        client.checkExists().forPath("/");
        ConnectionState state = states.poll(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS);
        Assert.assertEquals(state, ConnectionState.READ_ONLY);
    } finally {
        CloseableUtils.closeQuietly(client);
        CloseableUtils.closeQuietly(cluster);
    }
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) CuratorFramework(org.apache.curator.framework.CuratorFramework) TestingCluster(org.apache.curator.test.TestingCluster) RetryOneTime(org.apache.curator.retry.RetryOneTime) InstanceSpec(org.apache.curator.test.InstanceSpec) 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 18 with RetryNTimes

use of org.apache.curator.retry.RetryNTimes in project xian by happyyangyuan.

the class TestLeaderSelectorEdges method flappingTest.

/**
 * Create a LeaderSelector but close the connection right after the "lock" znode
 * has been created.
 *
 * @throws Exception
 */
@Test
public void flappingTest() throws Exception {
    final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryNTimes(1, 500)).sessionTimeoutMs(30000).build();
    final TestLeaderSelectorListener listener = new TestLeaderSelectorListener();
    LeaderSelector leaderSelector1 = new LeaderSelector(client, ChaosMonkeyCnxnFactory.CHAOS_ZNODE, listener);
    LeaderSelector leaderSelector2 = null;
    client.start();
    try {
        client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE);
        leaderSelector1.start();
        // At this point the ChaosMonkeyZookeeperServer must close the connection
        // right after the lock znode is created.
        Assert.assertTrue(listener.reconnected.await(10, TimeUnit.SECONDS), "Connection has not been lost");
        // Check that leader ship has failed
        Assert.assertEquals(listener.takeLeadership.getCount(), 1);
        // Wait FailedDelete
        Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2);
        // Check that there is no znode
        final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size();
        Assert.assertEquals(children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock");
        // Check that a new LeaderSelector can be started
        leaderSelector2 = new LeaderSelector(client, ChaosMonkeyCnxnFactory.CHAOS_ZNODE, listener);
        leaderSelector2.start();
        Assert.assertTrue(listener.takeLeadership.await(1, TimeUnit.SECONDS));
    } finally {
        try {
            leaderSelector1.close();
        } catch (IllegalStateException e) {
            Assert.fail(e.getMessage());
        }
        try {
            if (leaderSelector2 != null) {
                leaderSelector2.close();
            }
        } catch (IllegalStateException e) {
            Assert.fail(e.getMessage());
        }
        client.close();
    }
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) CuratorFramework(org.apache.curator.framework.CuratorFramework) Test(org.testng.annotations.Test)

Example 19 with RetryNTimes

use of org.apache.curator.retry.RetryNTimes in project xian by happyyangyuan.

the class TestLeaderSelectorEdges method createProtectedNodeInBackgroundTestNoRetry.

/**
 * Same test as above but without a retry policy
 */
@Test
public void createProtectedNodeInBackgroundTestNoRetry() throws Exception {
    final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString()).retryPolicy(new RetryNTimes(0, 0)).connectionTimeoutMs(100).sessionTimeoutMs(60000).build();
    final CountDownLatch latch = new CountDownLatch(1);
    client.start();
    try {
        client.create().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE);
        client.create().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).inBackground(new BackgroundCallback() {

            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                log.info("Receive event {}", event.toString());
                if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue()) {
                    latch.countDown();
                }
            }
        }).forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE_PREFIX + "foo-");
        Assert.assertTrue(latch.await(30, TimeUnit.SECONDS), "Callback has not been called");
        // Wait for the znode to be deleted
        Thread.sleep(ChaosMonkeyCnxnFactory.LOCKOUT_DURATION_MS * 2);
        // Check that there is no znode
        final int children = client.getChildren().forPath(ChaosMonkeyCnxnFactory.CHAOS_ZNODE).size();
        Assert.assertEquals(children, 0, "Still " + children + " znodes under " + ChaosMonkeyCnxnFactory.CHAOS_ZNODE + " lock");
    } finally {
        client.close();
    }
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) CuratorFramework(org.apache.curator.framework.CuratorFramework) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.testng.annotations.Test)

Example 20 with RetryNTimes

use of org.apache.curator.retry.RetryNTimes in project xian by happyyangyuan.

the class TestSharedCount method testDisconnectReconnectEventDoesNotFireValueWatcher.

@Test
public void testDisconnectReconnectEventDoesNotFireValueWatcher() throws Exception {
    final CountDownLatch gotSuspendEvent = new CountDownLatch(1);
    final CountDownLatch gotChangeEvent = new CountDownLatch(1);
    final CountDownLatch getReconnectEvent = new CountDownLatch(1);
    final AtomicInteger numChangeEvents = new AtomicInteger(0);
    CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryNTimes(10, 500));
    curatorFramework.start();
    curatorFramework.blockUntilConnected();
    SharedCount sharedCount = new SharedCount(curatorFramework, "/count", 10);
    sharedCount.addListener(new SharedCountListener() {

        @Override
        public void countHasChanged(SharedCountReader sharedCount, int newCount) throws Exception {
            numChangeEvents.incrementAndGet();
            gotChangeEvent.countDown();
        }

        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {
            if (newState == ConnectionState.SUSPENDED) {
                gotSuspendEvent.countDown();
            } else if (newState == ConnectionState.RECONNECTED) {
                getReconnectEvent.countDown();
            }
        }
    });
    sharedCount.start();
    try {
        sharedCount.setCount(11);
        Assert.assertTrue(gotChangeEvent.await(2, TimeUnit.SECONDS));
        server.stop();
        Assert.assertTrue(gotSuspendEvent.await(2, TimeUnit.SECONDS));
        server.restart();
        Assert.assertTrue(getReconnectEvent.await(2, TimeUnit.SECONDS));
        sharedCount.trySetCount(sharedCount.getVersionedValue(), 12);
        // flush background task queue
        final CountDownLatch flushDone = new CountDownLatch(1);
        curatorFramework.getData().inBackground(new BackgroundCallback() {

            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                flushDone.countDown();
            }
        }).forPath("/count");
        flushDone.await(5, TimeUnit.SECONDS);
        Assert.assertEquals(2, numChangeEvents.get());
    } finally {
        CloseableUtils.closeQuietly(sharedCount);
        CloseableUtils.closeQuietly(curatorFramework);
    }
}
Also used : RetryNTimes(org.apache.curator.retry.RetryNTimes) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch) CuratorFramework(org.apache.curator.framework.CuratorFramework) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConnectionState(org.apache.curator.framework.state.ConnectionState) Test(org.testng.annotations.Test)

Aggregations

RetryNTimes (org.apache.curator.retry.RetryNTimes)68 CuratorFramework (org.apache.curator.framework.CuratorFramework)51 Test (org.junit.Test)20 RetryPolicy (org.apache.curator.RetryPolicy)12 NIOServerCnxnFactory (org.apache.zookeeper.server.NIOServerCnxnFactory)12 Test (org.testng.annotations.Test)11 CuratorFrameworkFactory (org.apache.curator.framework.CuratorFrameworkFactory)10 CountDownLatch (java.util.concurrent.CountDownLatch)9 ZooKeeperGroup (io.fabric8.groups.internal.ZooKeeperGroup)8 IOException (java.io.IOException)6 ZooKeeperGroup (org.apache.camel.component.zookeepermaster.group.internal.ZooKeeperGroup)6 Before (org.junit.Before)6 ArrayList (java.util.ArrayList)5 TestingServer (org.apache.curator.test.TestingServer)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 ConnectionState (org.apache.curator.framework.state.ConnectionState)4 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 BackgroundCallback (org.apache.curator.framework.api.BackgroundCallback)3 CuratorEvent (org.apache.curator.framework.api.CuratorEvent)3