Search in sources :

Example 1 with Scassandra

use of org.scassandra.Scassandra in project java-driver by datastax.

the class DefaultRetryPolicyIntegrationTest method should_rethrow_unavailable_in_no_host_available_exception.

@Test(groups = "short")
public void should_rethrow_unavailable_in_no_host_available_exception() {
    LoadBalancingPolicy firstHostOnlyPolicy = new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(), Collections.singletonList(host1.getSocketAddress()));
    Cluster whiteListedCluster = Cluster.builder().addContactPoints(scassandras.address(1).getAddress()).withPort(scassandras.getBinaryPort()).withRetryPolicy(retryPolicy).withLoadBalancingPolicy(firstHostOnlyPolicy).build();
    try {
        Session whiteListedSession = whiteListedCluster.connect();
        // Clear all activity as result of connect.
        for (Scassandra node : scassandras.nodes()) {
            node.activityClient().clearAllRecordedActivity();
        }
        simulateError(1, unavailable);
        try {
            query(whiteListedSession);
            fail("expected an NoHostAvailableException");
        } catch (NoHostAvailableException e) {
            // ok
            Throwable error = e.getErrors().get(host1.getSocketAddress());
            assertThat(error).isNotNull();
            assertThat(error).isInstanceOf(UnavailableException.class);
        }
        assertOnUnavailableWasCalled(1);
        // We expect a retry, but it was never sent because there were no more hosts.
        Metrics.Errors whiteListErrors = whiteListedCluster.getMetrics().getErrorMetrics();
        assertThat(whiteListErrors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
        assertQueried(1, 1);
        assertQueried(2, 0);
        assertQueried(3, 0);
    } finally {
        whiteListedCluster.close();
    }
}
Also used : Scassandra(org.scassandra.Scassandra) Test(org.testng.annotations.Test)

Example 2 with Scassandra

use of org.scassandra.Scassandra in project java-driver by datastax.

the class RequestHandlerTest method should_handle_race_between_response_and_cancellation.

@Test(groups = "long")
public void should_handle_race_between_response_and_cancellation() {
    final Scassandra scassandra = TestUtils.createScassandraServer();
    Cluster cluster = null;
    try {
        // Use a mock server that takes a constant time to reply
        scassandra.start();
        List<Map<String, ?>> rows = Collections.<Map<String, ?>>singletonList(ImmutableMap.of("key", 1));
        scassandra.primingClient().prime(PrimingRequest.queryBuilder().withQuery("mock query").withThen(then().withRows(rows).withFixedDelay(10L)).build());
        cluster = Cluster.builder().addContactPoint(TestUtils.ipOfNode(1)).withPort(scassandra.getBinaryPort()).withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1).setMaxConnectionsPerHost(HostDistance.LOCAL, 1).setHeartbeatIntervalSeconds(0)).build();
        Session session = cluster.connect();
        // To reproduce, we need to cancel the query exactly when the reply arrives.
        // Run a few queries to estimate how much that will take.
        int samples = 100;
        long start = System.currentTimeMillis();
        for (int i = 0; i < samples; i++) {
            session.execute("mock query");
        }
        long elapsed = System.currentTimeMillis() - start;
        long queryDuration = elapsed / samples;
        // Now run queries and cancel them after that estimated time
        for (int i = 0; i < 2000; i++) {
            ResultSetFuture future = session.executeAsync("mock query");
            try {
                future.getUninterruptibly(queryDuration, TimeUnit.MILLISECONDS);
            } catch (TimeoutException e) {
                future.cancel(true);
            }
        }
        Connection connection = getSingleConnection(session);
        assertThat(connection.inFlight.get()).isEqualTo(0);
    } finally {
        if (cluster != null)
            cluster.close();
        scassandra.stop();
    }
}
Also used : Scassandra(org.scassandra.Scassandra) ImmutableMap(com.google.common.collect.ImmutableMap) Map(java.util.Map) TimeoutException(java.util.concurrent.TimeoutException) Test(org.testng.annotations.Test)

Example 3 with Scassandra

use of org.scassandra.Scassandra in project java-driver by datastax.

the class ScassandraCluster method init.

public void init() {
    for (Map.Entry<Integer, List<Scassandra>> dc : dcNodeMap.entrySet()) {
        for (Scassandra node : dc.getValue()) {
            node.start();
            primeMetadata(node);
        }
    }
}
Also used : Scassandra(org.scassandra.Scassandra) List(java.util.List) Map(java.util.Map)

Example 4 with Scassandra

use of org.scassandra.Scassandra in project java-driver by datastax.

the class ScassandraCluster method start.

/**
 * Starts a node by id and then asserts that its {@link Host} is marked up
 * for the given {@link Cluster} instance within 10 seconds.
 *
 * @param cluster cluster to wait for up status on.
 * @param node    Node to start.
 */
public void start(Cluster cluster, int node) {
    logger.debug("Starting node {}.", node);
    Scassandra scassandra = node(node);
    scassandra.start();
    assertThat(cluster).host(node).comesUpWithin(10, TimeUnit.SECONDS);
}
Also used : Scassandra(org.scassandra.Scassandra)

Example 5 with Scassandra

use of org.scassandra.Scassandra in project java-driver by datastax.

the class ClusterInitTest method should_handle_failing_or_missing_contact_points.

/**
 * Test for JAVA-522: when the cluster and session initialize, if some contact points are behaving badly and
 * causing timeouts, we want to ensure that the driver does not wait multiple times on the same host.
 */
@Test(groups = "short")
public void should_handle_failing_or_missing_contact_points() throws UnknownHostException {
    Cluster cluster = null;
    Scassandra scassandra = null;
    List<FakeHost> failingHosts = Lists.newArrayList();
    try {
        // Simulate a cluster of 5 hosts.
        // - 1 is an actual Scassandra instance that will accept connections:
        scassandra = TestUtils.createScassandraServer();
        scassandra.start();
        int port = scassandra.getBinaryPort();
        // - the remaining 4 are fake servers that will throw connect timeouts:
        for (int i = 2; i <= 5; i++) {
            FakeHost failingHost = new FakeHost(TestUtils.ipOfNode(i), port, THROWING_CONNECT_TIMEOUTS);
            failingHosts.add(failingHost);
            failingHost.start();
        }
        // - we also have a "missing" contact point, i.e. there's no server listening at this address,
        // and the address is not listed in the live host's system.peers
        String missingHostAddress = TestUtils.ipOfNode(6);
        primePeerRows(scassandra, failingHosts);
        logger.info("Environment is set up, starting test");
        long start = System.nanoTime();
        // We want to count how many connections were attempted. For that, we rely on the fact that SocketOptions.getKeepAlive
        // is called in Connection.Factory.newBoostrap() each time we prepare to open a new connection.
        SocketOptions socketOptions = spy(new SocketOptions());
        // Set an "infinite" reconnection delay so that reconnection attempts don't pollute our observations
        ConstantReconnectionPolicy reconnectionPolicy = new ConstantReconnectionPolicy(3600 * 1000);
        // Force 1 connection per pool. Otherwise we can't distinguish a failed pool creation from multiple connection
        // attempts, because pools create their connections in parallel (so 1 pool failure equals multiple connection failures).
        PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(LOCAL, 1, 1);
        cluster = Cluster.builder().withPort(scassandra.getBinaryPort()).addContactPoints(ipOfNode(1), failingHosts.get(0).address, failingHosts.get(1).address, failingHosts.get(2).address, failingHosts.get(3).address, missingHostAddress).withSocketOptions(socketOptions).withReconnectionPolicy(reconnectionPolicy).withPoolingOptions(poolingOptions).build();
        cluster.connect();
        // For information only:
        long initTimeMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
        logger.info("Cluster and session initialized in {} ms", initTimeMs);
        // Expect :
        // - 2 connections for the live host (1 control connection + 1 pooled connection)
        // - 1 attempt per failing host (either a control connection attempt or a failed pool creation)
        // - 0 or 1 for the missing host. We can't know for sure because contact points are randomized. If it's tried
        // before the live host there will be a connection attempt, otherwise it will be removed directly because
        // it's not in the live host's system.peers.
        verify(socketOptions, atLeast(6)).getKeepAlive();
        verify(socketOptions, atMost(7)).getKeepAlive();
        assertThat(cluster).host(1).isNotNull().isUp();
        // called and submit a task that marks the host down.
        for (FakeHost failingHost : failingHosts) {
            assertThat(cluster).host(failingHost.address).goesDownWithin(10, TimeUnit.SECONDS);
            Host host = TestUtils.findHost(cluster, failingHost.address);
            // startPeriodicReconnectionAttempt, we add a slight delay here if the future isn't set yet.
            if (host != null && (host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone())) {
                logger.warn("Periodic Reconnection Attempt hasn't started yet for {}, waiting 1 second and then checking.", host);
                Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
            }
            assertThat(cluster).host(failingHost.address).isReconnectingFromDown();
        }
        assertThat(TestUtils.findHost(cluster, missingHostAddress)).isNull();
    } finally {
        if (cluster != null)
            cluster.close();
        for (FakeHost fakeHost : failingHosts) fakeHost.stop();
        if (scassandra != null)
            scassandra.stop();
    }
}
Also used : Scassandra(org.scassandra.Scassandra) ConstantReconnectionPolicy(com.datastax.driver.core.policies.ConstantReconnectionPolicy) Test(org.testng.annotations.Test)

Aggregations

Scassandra (org.scassandra.Scassandra)9 Map (java.util.Map)3 Test (org.testng.annotations.Test)3 ConstantReconnectionPolicy (com.datastax.driver.core.policies.ConstantReconnectionPolicy)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 List (java.util.List)1 TreeSet (java.util.TreeSet)1 TimeoutException (java.util.concurrent.TimeoutException)1 PrimingClient (org.scassandra.http.client.PrimingClient)1 BeforeMethod (org.testng.annotations.BeforeMethod)1