Search in sources :

Example 56 with Timing

use of org.apache.curator.test.Timing in project xian by happyyangyuan.

the class TestPathChildrenCache method testBasicsOnTwoCachesWithSameExecutor.

@Test
public void testBasicsOnTwoCachesWithSameExecutor() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    client.start();
    try {
        client.create().forPath("/test");
        final BlockingQueue<PathChildrenCacheEvent.Type> events = new LinkedBlockingQueue<PathChildrenCacheEvent.Type>();
        final ExecutorService exec = Executors.newSingleThreadExecutor();
        PathChildrenCache cache = new PathChildrenCache(client, "/test", true, false, exec);
        cache.getListenable().addListener(new PathChildrenCacheListener() {

            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getData().getPath().equals("/test/one")) {
                    events.offer(event.getType());
                }
            }
        });
        cache.start();
        final BlockingQueue<PathChildrenCacheEvent.Type> events2 = new LinkedBlockingQueue<PathChildrenCacheEvent.Type>();
        PathChildrenCache cache2 = new PathChildrenCache(client, "/test", true, false, exec);
        cache2.getListenable().addListener(new PathChildrenCacheListener() {

            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getData().getPath().equals("/test/one")) {
                    events2.offer(event.getType());
                }
            }
        });
        cache2.start();
        client.create().forPath("/test/one", "hey there".getBytes());
        Assert.assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED);
        Assert.assertEquals(events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED);
        client.setData().forPath("/test/one", "sup!".getBytes());
        Assert.assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED);
        Assert.assertEquals(events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED);
        Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "sup!");
        Assert.assertEquals(new String(cache2.getCurrentData("/test/one").getData()), "sup!");
        client.delete().forPath("/test/one");
        Assert.assertEquals(events.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED);
        Assert.assertEquals(events2.poll(timing.forWaiting().seconds(), TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED);
        cache.close();
        cache2.close();
    } finally {
        client.close();
    }
}
Also used : RetryOneTime(org.apache.curator.retry.RetryOneTime) KeeperException(org.apache.zookeeper.KeeperException) CuratorFramework(org.apache.curator.framework.CuratorFramework) ExecuteCalledWatchingExecutorService(org.apache.curator.test.ExecuteCalledWatchingExecutorService) Timing(org.apache.curator.test.Timing) Test(org.testng.annotations.Test)

Example 57 with Timing

use of org.apache.curator.test.Timing in project xian by happyyangyuan.

the class TestPathChildrenCacheInCluster method testServerLoss.

@Test
public void testServerLoss() throws Exception {
    Timing timing = new Timing();
    CuratorFramework client = null;
    PathChildrenCache cache = null;
    TestingCluster cluster = new TestingCluster(3);
    try {
        cluster.start();
        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
        client.start();
        client.create().creatingParentsIfNeeded().forPath("/test");
        cache = new PathChildrenCache(client, "/test", false);
        cache.start();
        final CountDownLatch resetLatch = new CountDownLatch(1);
        final CountDownLatch reconnectLatch = new CountDownLatch(1);
        final AtomicReference<CountDownLatch> latch = new AtomicReference<CountDownLatch>(new CountDownLatch(3));
        cache.getListenable().addListener(new PathChildrenCacheListener() {

            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED) {
                    resetLatch.countDown();
                } else if (event.getType() == PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED) {
                    reconnectLatch.countDown();
                } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
                    latch.get().countDown();
                }
            }
        });
        client.create().forPath("/test/one");
        client.create().forPath("/test/two");
        client.create().forPath("/test/three");
        Assert.assertTrue(latch.get().await(10, TimeUnit.SECONDS));
        InstanceSpec connectionInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper());
        cluster.killServer(connectionInstance);
        Assert.assertTrue(timing.awaitLatch(reconnectLatch));
        Assert.assertEquals(cache.getCurrentData().size(), 3);
    } finally {
        CloseableUtils.closeQuietly(cache);
        CloseableUtils.closeQuietly(client);
        CloseableUtils.closeQuietly(cluster);
    }
}
Also used : RetryOneTime(org.apache.curator.retry.RetryOneTime) InstanceSpec(org.apache.curator.test.InstanceSpec) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) CuratorFramework(org.apache.curator.framework.CuratorFramework) TestingCluster(org.apache.curator.test.TestingCluster) Timing(org.apache.curator.test.Timing) Test(org.testng.annotations.Test)

Example 58 with Timing

use of org.apache.curator.test.Timing in project xian by happyyangyuan.

the class TestInterProcessMutexBase method testContainerCleanup.

@Test
public void testContainerCleanup() throws Exception {
    if (!ZKPaths.hasContainerSupport()) {
        System.out.println("ZooKeeper version does not support Containers. Skipping test");
        return;
    }
    server.close();
    System.setProperty("container.checkIntervalMs", "10");
    try {
        server = new TestingServer();
        final int THREAD_QTY = 10;
        ExecutorService service = null;
        final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(100, 3));
        try {
            client.start();
            List<Future<Object>> threads = Lists.newArrayList();
            service = Executors.newCachedThreadPool();
            for (int i = 0; i < THREAD_QTY; ++i) {
                Future<Object> t = service.submit(new Callable<Object>() {

                    @Override
                    public Object call() throws Exception {
                        InterProcessLock lock = makeLock(client);
                        lock.acquire();
                        try {
                            Thread.sleep(10);
                        } finally {
                            lock.release();
                        }
                        return null;
                    }
                });
                threads.add(t);
            }
            for (Future<Object> t : threads) {
                t.get();
            }
            new Timing().sleepABit();
            Assert.assertNull(client.checkExists().forPath(LOCK_BASE_PATH));
        } finally {
            if (service != null) {
                service.shutdownNow();
            }
            CloseableUtils.closeQuietly(client);
        }
    } finally {
        System.clearProperty("container.checkIntervalMs");
    }
}
Also used : TestingServer(org.apache.curator.test.TestingServer) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) CuratorFramework(org.apache.curator.framework.CuratorFramework) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) Timing(org.apache.curator.test.Timing) Test(org.testng.annotations.Test)

Example 59 with Timing

use of org.apache.curator.test.Timing in project xian by happyyangyuan.

the class TestInterProcessMutexBase method testWaitingProcessKilledServer.

@Test
public void testWaitingProcessKilledServer() throws Exception {
    final Timing timing = new Timing();
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3));
    try {
        client.start();
        final CountDownLatch latch = new CountDownLatch(1);
        ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        final AtomicBoolean isFirst = new AtomicBoolean(true);
        ExecutorCompletionService<Object> service = new ExecutorCompletionService<Object>(Executors.newFixedThreadPool(2));
        for (int i = 0; i < 2; ++i) {
            service.submit(new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    InterProcessLock lock = makeLock(client);
                    lock.acquire();
                    try {
                        if (isFirst.compareAndSet(true, false)) {
                            timing.sleepABit();
                            server.stop();
                            Assert.assertTrue(timing.awaitLatch(latch));
                            server.restart();
                        }
                    } finally {
                        try {
                            lock.release();
                        } catch (Exception e) {
                        // ignore
                        }
                    }
                    return null;
                }
            });
        }
        for (int i = 0; i < 2; ++i) {
            service.take().get(timing.forWaiting().milliseconds(), TimeUnit.MILLISECONDS);
        }
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) ExecutorCompletionService(java.util.concurrent.ExecutorCompletionService) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CuratorFramework(org.apache.curator.framework.CuratorFramework) 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 60 with Timing

use of org.apache.curator.test.Timing in project xian by happyyangyuan.

the class TestInterProcessSemaphore method testThreadedLeaseIncrease.

@Test
public void testThreadedLeaseIncrease() throws Exception {
    final Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
    try {
        client.start();
        final SharedCount count = new SharedCount(client, "/foo/count", 1);
        count.start();
        final InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", count);
        ExecutorService service = Executors.newCachedThreadPool();
        final CountDownLatch latch1 = new CountDownLatch(1);
        final CountDownLatch latch2 = new CountDownLatch(1);
        Future<Object> future1 = service.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                Lease lease = semaphore.acquire(timing.seconds(), TimeUnit.SECONDS);
                Assert.assertNotNull(lease);
                latch1.countDown();
                lease = semaphore.acquire(timing.forWaiting().seconds(), TimeUnit.SECONDS);
                Assert.assertNotNull(lease);
                latch2.countDown();
                return null;
            }
        });
        Future<Object> future2 = service.submit(new Callable<Object>() {

            @Override
            public Object call() throws Exception {
                Assert.assertTrue(latch1.await(timing.forWaiting().seconds(), TimeUnit.SECONDS));
                // make sure second acquire is waiting
                timing.sleepABit();
                Assert.assertTrue(count.trySetCount(2));
                // Make sure second acquire takes less than full waiting time:
                timing.sleepABit();
                Assert.assertTrue(latch2.await(0, TimeUnit.SECONDS));
                return null;
            }
        });
        future1.get();
        future2.get();
    } finally {
        CloseableUtils.closeQuietly(client);
    }
}
Also used : RetryOneTime(org.apache.curator.retry.RetryOneTime) SharedCount(org.apache.curator.framework.recipes.shared.SharedCount) CountDownLatch(java.util.concurrent.CountDownLatch) TimeoutException(java.util.concurrent.TimeoutException) KeeperException(org.apache.zookeeper.KeeperException) CuratorFramework(org.apache.curator.framework.CuratorFramework) ExecutorService(java.util.concurrent.ExecutorService) Timing(org.apache.curator.test.Timing) Test(org.testng.annotations.Test)

Aggregations

Timing (org.apache.curator.test.Timing)166 CuratorFramework (org.apache.curator.framework.CuratorFramework)147 Test (org.testng.annotations.Test)138 RetryOneTime (org.apache.curator.retry.RetryOneTime)129 CountDownLatch (java.util.concurrent.CountDownLatch)56 ConnectionState (org.apache.curator.framework.state.ConnectionState)39 ConnectionStateListener (org.apache.curator.framework.state.ConnectionStateListener)29 KeeperException (org.apache.zookeeper.KeeperException)28 ExecutorService (java.util.concurrent.ExecutorService)22 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)19 Semaphore (java.util.concurrent.Semaphore)18 ExponentialBackoffRetry (org.apache.curator.retry.ExponentialBackoffRetry)16 TestingServer (org.apache.curator.test.TestingServer)15 Stat (org.apache.zookeeper.data.Stat)12 TestingCluster (org.apache.curator.test.TestingCluster)11 AtomicReference (java.util.concurrent.atomic.AtomicReference)10 ExecutorCompletionService (java.util.concurrent.ExecutorCompletionService)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 InstanceSpec (org.apache.curator.test.InstanceSpec)9 Test (org.junit.Test)9