Search in sources :

Example 91 with TestingCluster

use of org.apache.curator.test.TestingCluster in project curator by apache.

the class TestInterProcessSemaphoreCluster method testCluster.

@Test
public void testCluster() throws Exception {
    final int QTY = 20;
    final int OPERATION_TIME_MS = 1000;
    final String PATH = "/foo/bar/lock";
    ExecutorService executorService = Executors.newFixedThreadPool(QTY);
    ExecutorCompletionService<Void> completionService = new ExecutorCompletionService<Void>(executorService);
    final Timing timing = new Timing();
    List<SemaphoreClient> semaphoreClients = Lists.newArrayList();
    TestingCluster cluster = createAndStartCluster(3);
    try {
        final AtomicInteger opCount = new AtomicInteger(0);
        for (int i = 0; i < QTY; ++i) {
            SemaphoreClient semaphoreClient = new SemaphoreClient(cluster.getConnectString(), PATH, new Callable<Void>() {

                @Override
                public Void call() throws Exception {
                    opCount.incrementAndGet();
                    Thread.sleep(OPERATION_TIME_MS);
                    return null;
                }
            });
            completionService.submit(semaphoreClient);
            semaphoreClients.add(semaphoreClient);
        }
        timing.forWaiting().sleepABit();
        assertNotNull(SemaphoreClient.getActiveClient());
        final CountDownLatch latch = new CountDownLatch(1);
        CuratorFramework client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new ExponentialBackoffRetry(100, 3));
        ConnectionStateListener listener = new ConnectionStateListener() {

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
                if (newState == ConnectionState.LOST) {
                    latch.countDown();
                }
            }
        };
        client.getConnectionStateListenable().addListener(listener);
        client.start();
        try {
            client.getZookeeperClient().blockUntilConnectedOrTimedOut();
            cluster.stop();
            latch.await();
        } finally {
            CloseableUtils.closeQuietly(client);
        }
        long startTicks = System.currentTimeMillis();
        for (; ; ) {
            int thisOpCount = opCount.get();
            Thread.sleep(2 * OPERATION_TIME_MS);
            if (thisOpCount == opCount.get()) {
                // checking that the op count isn't increasing
                break;
            }
            assertTrue((System.currentTimeMillis() - startTicks) < timing.forWaiting().milliseconds());
        }
        int thisOpCount = opCount.get();
        Iterator<InstanceSpec> iterator = cluster.getInstances().iterator();
        cluster = new TestingCluster(iterator.next(), iterator.next());
        cluster.start();
        timing.forWaiting().sleepABit();
        startTicks = System.currentTimeMillis();
        for (; ; ) {
            Thread.sleep(2 * OPERATION_TIME_MS);
            if (opCount.get() > thisOpCount) {
                // checking that semaphore has started working again
                break;
            }
            assertTrue((System.currentTimeMillis() - startTicks) < timing.forWaiting().milliseconds());
        }
    } finally {
        for (SemaphoreClient semaphoreClient : semaphoreClients) {
            CloseableUtils.closeQuietly(semaphoreClient);
        }
        CloseableUtils.closeQuietly(cluster);
        executorService.shutdownNow();
    }
}
Also used : InstanceSpec(org.apache.curator.test.InstanceSpec) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) ExecutorCompletionService(java.util.concurrent.ExecutorCompletionService) CountDownLatch(java.util.concurrent.CountDownLatch) IOException(java.io.IOException) 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.junit.jupiter.api.Test)

Example 92 with TestingCluster

use of org.apache.curator.test.TestingCluster in project curator by apache.

the class TestLeaderSelectorCluster method testRestart.

@Test
public void testRestart() throws Exception {
    final Timing timing = new Timing();
    CuratorFramework client = null;
    TestingCluster cluster = createAndStartCluster(3);
    try {
        client = CuratorFrameworkFactory.newClient(cluster.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
        client.start();
        final Semaphore semaphore = new Semaphore(0);
        LeaderSelectorListener listener = new LeaderSelectorListener() {

            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                List<String> names = client.getChildren().forPath("/leader");
                assertTrue(names.size() > 0);
                semaphore.release();
            }

            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {
            }
        };
        LeaderSelector selector = new LeaderSelector(client, "/leader", listener);
        selector.autoRequeue();
        selector.start();
        assertTrue(timing.acquireSemaphore(semaphore));
        InstanceSpec connectionInstance = cluster.findConnectionInstance(client.getZookeeperClient().getZooKeeper());
        cluster.killServer(connectionInstance);
        assertTrue(timing.multiple(4).acquireSemaphore(semaphore));
    } finally {
        CloseableUtils.closeQuietly(client);
        CloseableUtils.closeQuietly(cluster);
    }
}
Also used : 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) Semaphore(java.util.concurrent.Semaphore) ConnectionState(org.apache.curator.framework.state.ConnectionState) Test(org.junit.jupiter.api.Test)

Example 93 with TestingCluster

use of org.apache.curator.test.TestingCluster in project curator by apache.

the class TestFrameworkEdges method testProtectionWithKilledSession.

@Test
public void testProtectionWithKilledSession() throws Exception {
    // not needed
    server.stop();
    try (TestingCluster cluster = createAndStartCluster(3)) {
        InstanceSpec instanceSpec0 = cluster.getServers().get(0).getInstanceSpec();
        CountDownLatch serverStoppedLatch = new CountDownLatch(1);
        RetryPolicy retryPolicy = new RetryForever(100) {

            @Override
            public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) {
                if (serverStoppedLatch.getCount() > 0) {
                    try {
                        cluster.killServer(instanceSpec0);
                    } catch (Exception e) {
                    // ignore
                    }
                    serverStoppedLatch.countDown();
                }
                return super.allowRetry(retryCount, elapsedTimeMs, sleeper);
            }
        };
        try (CuratorFramework client = CuratorFrameworkFactory.newClient(instanceSpec0.getConnectString(), timing.session(), timing.connection(), retryPolicy)) {
            BlockingQueue<String> createdNode = new LinkedBlockingQueue<>();
            BackgroundCallback callback = (__, event) -> {
                if (event.getType() == CuratorEventType.CREATE) {
                    createdNode.offer(event.getPath());
                }
            };
            client.start();
            client.create().forPath("/test");
            ErrorListenerPathAndBytesable<String> builder = client.create().withProtection().withMode(CreateMode.EPHEMERAL).inBackground(callback);
            ((CreateBuilderImpl) builder).failNextCreateForTesting = true;
            builder.forPath("/test/hey");
            assertTrue(timing.awaitLatch(serverStoppedLatch));
            // wait for session to expire
            timing.forSessionSleep().sleep();
            cluster.restartServer(instanceSpec0);
            String path = timing.takeFromQueue(createdNode);
            List<String> children = client.getChildren().forPath("/test");
            assertEquals(Collections.singletonList(ZKPaths.getNodeFromPath(path)), children);
        }
    }
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) Stat(org.apache.zookeeper.data.Stat) ZKPaths(org.apache.curator.utils.ZKPaths) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) Timing2(org.apache.curator.test.compatibility.Timing2) BeforeAll(org.junit.jupiter.api.BeforeAll) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RetryForever(org.apache.curator.retry.RetryForever) Tag(org.junit.jupiter.api.Tag) CloseableUtils(org.apache.curator.utils.CloseableUtils) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) ConnectionStateListener(org.apache.curator.framework.state.ConnectionStateListener) BlockingQueue(java.util.concurrent.BlockingQueue) ErrorListenerPathAndBytesable(org.apache.curator.framework.api.ErrorListenerPathAndBytesable) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) Queues(com.google.common.collect.Queues) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) InstanceSpec(org.apache.curator.test.InstanceSpec) RetryPolicy(org.apache.curator.RetryPolicy) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) TestingCluster(org.apache.curator.test.TestingCluster) CuratorTestBase(org.apache.curator.test.compatibility.CuratorTestBase) RetryNTimes(org.apache.curator.retry.RetryNTimes) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) CuratorFrameworkFactory(org.apache.curator.framework.CuratorFrameworkFactory) CuratorListener(org.apache.curator.framework.api.CuratorListener) CreateBuilder(org.apache.curator.framework.api.CreateBuilder) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) BaseClassForTests(org.apache.curator.test.BaseClassForTests) RetryOneTime(org.apache.curator.retry.RetryOneTime) TestingServer(org.apache.curator.test.TestingServer) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) Watcher(org.apache.zookeeper.Watcher) Semaphore(java.util.concurrent.Semaphore) CuratorEventType(org.apache.curator.framework.api.CuratorEventType) ConnectionState(org.apache.curator.framework.state.ConnectionState) DisplayName(org.junit.jupiter.api.DisplayName) TimeUnit(java.util.concurrent.TimeUnit) RetrySleeper(org.apache.curator.RetrySleeper) Collections(java.util.Collections) InstanceSpec(org.apache.curator.test.InstanceSpec) RetrySleeper(org.apache.curator.RetrySleeper) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) KeeperException(org.apache.zookeeper.KeeperException) CuratorFramework(org.apache.curator.framework.CuratorFramework) TestingCluster(org.apache.curator.test.TestingCluster) RetryForever(org.apache.curator.retry.RetryForever) RetryPolicy(org.apache.curator.RetryPolicy) Test(org.junit.jupiter.api.Test)

Example 94 with TestingCluster

use of org.apache.curator.test.TestingCluster in project curator by apache.

the class TestReconfiguration method testAdd.

@Test
public void testAdd() throws Exception {
    try (CuratorFramework client = newClient()) {
        client.start();
        QuorumVerifier oldConfig = toQuorumVerifier(client.getConfig().forEnsemble());
        assertConfig(oldConfig, cluster.getInstances());
        CountDownLatch latch = setChangeWaiter(client);
        try (TestingCluster newCluster = new TestingCluster(TestingCluster.makeSpecs(1, false))) {
            newCluster.start();
            client.reconfig().joining(toReconfigSpec(newCluster.getInstances())).fromConfig(oldConfig.getVersion()).forEnsemble();
            assertTrue(timing.awaitLatch(latch));
            byte[] newConfigData = client.getConfig().forEnsemble();
            QuorumVerifier newConfig = toQuorumVerifier(newConfigData);
            List<InstanceSpec> newInstances = Lists.newArrayList(cluster.getInstances());
            newInstances.addAll(newCluster.getInstances());
            assertConfig(newConfig, newInstances);
            assertEquals(EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString());
        }
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) TestingCluster(org.apache.curator.test.TestingCluster) InstanceSpec(org.apache.curator.test.InstanceSpec) CountDownLatch(java.util.concurrent.CountDownLatch) QuorumVerifier(org.apache.zookeeper.server.quorum.flexible.QuorumVerifier) Test(org.junit.jupiter.api.Test)

Example 95 with TestingCluster

use of org.apache.curator.test.TestingCluster in project curator by apache.

the class TestReconfiguration method testNewMembers.

@Test
// it's what this test is inteded to do and it keeps failing - disable for now
@Disabled
public void testNewMembers() throws Exception {
    cluster.close();
    cluster = null;
    TestingCluster smallCluster = null;
    TestingCluster localCluster = new TestingCluster(5);
    try {
        List<TestingZooKeeperServer> servers = localCluster.getServers();
        List<InstanceSpec> smallClusterInstances = Lists.newArrayList();
        for (// only start 3 of the 5
        int i = 0; // only start 3 of the 5
        i < 3; // only start 3 of the 5
        ++i) {
            TestingZooKeeperServer server = servers.get(i);
            server.start();
            smallClusterInstances.add(server.getInstanceSpec());
        }
        smallCluster = new TestingCluster(smallClusterInstances);
        try (CuratorFramework client = newClient(smallCluster.getConnectString())) {
            client.start();
            QuorumVerifier oldConfig = toQuorumVerifier(client.getConfig().forEnsemble());
            assertEquals(oldConfig.getAllMembers().size(), 5);
            assertConfig(oldConfig, localCluster.getInstances());
            CountDownLatch latch = setChangeWaiter(client);
            client.reconfig().withNewMembers(toReconfigSpec(smallClusterInstances)).forEnsemble();
            assertTrue(timing.awaitLatch(latch));
            byte[] newConfigData = client.getConfig().forEnsemble();
            QuorumVerifier newConfig = toQuorumVerifier(newConfigData);
            assertEquals(newConfig.getAllMembers().size(), 3);
            assertConfig(newConfig, smallClusterInstances);
            assertEquals(EnsembleTracker.configToConnectionString(newConfig), ensembleProvider.getConnectionString());
        }
    } finally {
        CloseableUtils.closeQuietly(smallCluster);
        CloseableUtils.closeQuietly(localCluster);
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) TestingCluster(org.apache.curator.test.TestingCluster) InstanceSpec(org.apache.curator.test.InstanceSpec) TestingZooKeeperServer(org.apache.curator.test.TestingZooKeeperServer) CountDownLatch(java.util.concurrent.CountDownLatch) QuorumVerifier(org.apache.zookeeper.server.quorum.flexible.QuorumVerifier) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Aggregations

TestingCluster (org.apache.curator.test.TestingCluster)97 CuratorFramework (org.apache.curator.framework.CuratorFramework)48 InstanceSpec (org.apache.curator.test.InstanceSpec)41 ExponentialBackoffRetry (org.apache.curator.retry.ExponentialBackoffRetry)39 Before (org.junit.Before)30 Timing (org.apache.curator.test.Timing)21 Test (org.junit.jupiter.api.Test)21 CountDownLatch (java.util.concurrent.CountDownLatch)20 ConnectionState (org.apache.curator.framework.state.ConnectionState)16 RetryOneTime (org.apache.curator.retry.RetryOneTime)15 ConnectionStateListener (org.apache.curator.framework.state.ConnectionStateListener)12 HashMap (java.util.HashMap)10 PotentiallyGzippedCompressionProvider (org.apache.druid.curator.PotentiallyGzippedCompressionProvider)10 BeforeClass (org.junit.BeforeClass)10 Test (org.junit.Test)10 Test (org.testng.annotations.Test)10 ArrayList (java.util.ArrayList)9 TestBroker (org.apache.druid.indexing.kafka.test.TestBroker)8 ZkPathsConfig (org.apache.druid.server.initialization.ZkPathsConfig)8 GatewayConfig (org.apache.knox.gateway.config.GatewayConfig)8