Search in sources :

Example 1 with UnavailableException

use of com.datastax.oss.driver.api.core.servererrors.UnavailableException in project java-driver by datastax.

the class ReactiveRetryIT method should_retry_at_application_level.

@Test
public void should_retry_at_application_level() {
    // Given
    CqlSession session = spy(SESSION_RULE.session());
    BoundCluster cluster = SIMULACRON_RULE.cluster();
    cluster.node(0).prime(when(QUERY_STRING).then(unavailable(ConsistencyLevel.ONE, 1, 0)));
    cluster.node(1).prime(when(QUERY_STRING).then(unavailable(ConsistencyLevel.ONE, 1, 0)));
    cluster.node(2).prime(when(QUERY_STRING).then(rows().row("col1", "Yay!")));
    // When
    ReactiveRow row = Flowable.defer(() -> session.executeReactive(QUERY_STRING)).retry((retry, error) -> {
        assertThat(error).isInstanceOf(UnavailableException.class);
        UnavailableException ue = (UnavailableException) error;
        Node coordinator = ue.getCoordinator();
        if (retry == 1) {
            assertCoordinator(0, coordinator);
            return true;
        } else if (retry == 2) {
            assertCoordinator(1, coordinator);
            return true;
        } else {
            fail("Unexpected retry attempt");
            return false;
        }
    }).blockingLast();
    // Then
    assertThat(row.getString(0)).isEqualTo("Yay!");
    verify(session, times(3)).executeReactive(QUERY_STRING);
    assertUnavailableMetric(0, 1L);
    assertUnavailableMetric(1, 1L);
    assertUnavailableMetric(2, 0L);
}
Also used : Metrics(com.datastax.oss.driver.api.core.metrics.Metrics) BoundCluster(com.datastax.oss.simulacron.server.BoundCluster) DefaultNodeMetric(com.datastax.oss.driver.api.core.metrics.DefaultNodeMetric) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) LoadBalancingPolicy(com.datastax.oss.driver.api.core.loadbalancing.LoadBalancingPolicy) PrimeDsl.when(com.datastax.oss.simulacron.common.stubbing.PrimeDsl.when) NodeDistance(com.datastax.oss.driver.api.core.loadbalancing.NodeDistance) SimulacronRule(com.datastax.oss.driver.api.testinfra.simulacron.SimulacronRule) NonNull(edu.umd.cs.findbugs.annotations.NonNull) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) ClassRule(org.junit.ClassRule) DriverContext(com.datastax.oss.driver.api.core.context.DriverContext) SessionUtils(com.datastax.oss.driver.api.testinfra.session.SessionUtils) Metric(com.codahale.metrics.Metric) UUID(java.util.UUID) Category(org.junit.experimental.categories.Category) List(java.util.List) VerificationModeFactory.times(org.mockito.internal.verification.VerificationModeFactory.times) Optional(java.util.Optional) Queue(java.util.Queue) ReactiveRow(com.datastax.dse.driver.api.core.cql.reactive.ReactiveRow) Node(com.datastax.oss.driver.api.core.metadata.Node) ClusterSpec(com.datastax.oss.simulacron.common.cluster.ClusterSpec) Iterables(com.google.common.collect.Iterables) TestRule(org.junit.rules.TestRule) Mockito.spy(org.mockito.Mockito.spy) ParallelizableTests(com.datastax.oss.driver.categories.ParallelizableTests) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) NoRetryPolicy(com.datastax.oss.driver.core.retry.PerProfileRetryPolicyIT.NoRetryPolicy) DefaultDriverOption(com.datastax.oss.driver.api.core.config.DefaultDriverOption) Flowable(io.reactivex.Flowable) CqlSession(com.datastax.oss.driver.api.core.CqlSession) Before(org.junit.Before) Session(com.datastax.oss.driver.api.core.session.Session) Iterator(java.util.Iterator) Test(org.junit.Test) UnavailableException(com.datastax.oss.driver.api.core.servererrors.UnavailableException) Request(com.datastax.oss.driver.api.core.session.Request) PrimeDsl.rows(com.datastax.oss.simulacron.common.stubbing.PrimeDsl.rows) Mockito.verify(org.mockito.Mockito.verify) SessionRule(com.datastax.oss.driver.api.testinfra.session.SessionRule) RuleChain(org.junit.rules.RuleChain) PrimeDsl.unavailable(com.datastax.oss.simulacron.common.stubbing.PrimeDsl.unavailable) ConsistencyLevel(com.datastax.oss.simulacron.common.codec.ConsistencyLevel) Nullable(edu.umd.cs.findbugs.annotations.Nullable) NodeComparator(com.datastax.oss.driver.api.testinfra.loadbalancing.NodeComparator) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) Node(com.datastax.oss.driver.api.core.metadata.Node) UnavailableException(com.datastax.oss.driver.api.core.servererrors.UnavailableException) ReactiveRow(com.datastax.dse.driver.api.core.cql.reactive.ReactiveRow) BoundCluster(com.datastax.oss.simulacron.server.BoundCluster) CqlSession(com.datastax.oss.driver.api.core.CqlSession) Test(org.junit.Test)

Example 2 with UnavailableException

use of com.datastax.oss.driver.api.core.servererrors.UnavailableException in project java-driver by datastax.

the class AllNodesFailedExceptionTest method should_create_instance_from_map_of_first_errors.

@SuppressWarnings("deprecation")
@Test
public void should_create_instance_from_map_of_first_errors() {
    // given
    UnavailableException e1 = new UnavailableException(node1, QUORUM, 2, 1);
    ReadTimeoutException e2 = new ReadTimeoutException(node2, QUORUM, 2, 1, false);
    Map<Node, Throwable> errors = ImmutableMap.of(node1, e1, node2, e2);
    // when
    AllNodesFailedException e = AllNodesFailedException.fromErrors(errors);
    // then
    assertThat(e).hasMessage("All 2 node(s) tried for the query failed " + "(showing first 2 nodes, use getAllErrors() for more): " + "node1: [%s], node2: [%s]", e1, e2);
    assertThat(e.getAllErrors()).hasEntrySatisfying(node1, list -> assertThat(list).containsExactly(e1));
    assertThat(e.getAllErrors()).hasEntrySatisfying(node2, list -> assertThat(list).containsExactly(e2));
    assertThat(e.getErrors()).containsEntry(node1, e1);
    assertThat(e.getErrors()).containsEntry(node2, e2);
    assertThat(e).hasSuppressedException(e1).hasSuppressedException(e2);
}
Also used : ReadTimeoutException(com.datastax.oss.driver.api.core.servererrors.ReadTimeoutException) Node(com.datastax.oss.driver.api.core.metadata.Node) UnavailableException(com.datastax.oss.driver.api.core.servererrors.UnavailableException) Test(org.junit.Test)

Example 3 with UnavailableException

use of com.datastax.oss.driver.api.core.servererrors.UnavailableException in project java-driver by datastax.

the class ReactiveResultSetSubscriptionTest method should_report_error_on_intermediary_page.

@Test
public void should_report_error_on_intermediary_page() {
    CompletableFuture<AsyncResultSet> future1 = new CompletableFuture<>();
    CompletableFuture<AsyncResultSet> future2 = new CompletableFuture<>();
    MockAsyncResultSet page1 = new MockAsyncResultSet(3, future2);
    TestSubscriber<ReactiveRow> mainSubscriber = new TestSubscriber<>();
    TestSubscriber<ColumnDefinitions> colDefsSubscriber = new TestSubscriber<>();
    TestSubscriber<ExecutionInfo> execInfosSubscriber = new TestSubscriber<>();
    TestSubscriber<Boolean> wasAppliedSubscriber = new TestSubscriber<>();
    ReactiveResultSetSubscription<AsyncResultSet> subscription = new ReactiveResultSetSubscription<>(mainSubscriber, colDefsSubscriber, execInfosSubscriber, wasAppliedSubscriber);
    mainSubscriber.onSubscribe(subscription);
    subscription.start(() -> future1);
    future1.complete(page1);
    future2.completeExceptionally(new UnavailableException(null, null, 0, 0));
    mainSubscriber.awaitTermination();
    assertThat(mainSubscriber.getElements()).extracting("row").isEqualTo(page1.currentPage());
    assertThat(mainSubscriber.getError()).isNotNull().isInstanceOf(UnavailableException.class);
    // colDefsSubscriber completed normally when page1 arrived
    assertThat(colDefsSubscriber.getError()).isNull();
    assertThat(colDefsSubscriber.getElements()).hasSize(1).containsExactly(page1.getColumnDefinitions());
    // execInfosSubscriber completed with error, but should have emitted 1 item for page1
    assertThat(execInfosSubscriber.getElements()).hasSize(1).containsExactly(page1.getExecutionInfo());
    assertThat(execInfosSubscriber.getError()).isNotNull().isInstanceOf(UnavailableException.class);
    // colDefsSubscriber completed normally when page1 arrived
    assertThat(wasAppliedSubscriber.getElements()).hasSize(1).containsExactly(true);
    assertThat(wasAppliedSubscriber.getError()).isNull();
}
Also used : ColumnDefinitions(com.datastax.oss.driver.api.core.cql.ColumnDefinitions) AsyncResultSet(com.datastax.oss.driver.api.core.cql.AsyncResultSet) UnavailableException(com.datastax.oss.driver.api.core.servererrors.UnavailableException) ExecutionInfo(com.datastax.oss.driver.api.core.cql.ExecutionInfo) ReactiveRow(com.datastax.dse.driver.api.core.cql.reactive.ReactiveRow) CompletableFuture(java.util.concurrent.CompletableFuture) Test(org.junit.Test)

Example 4 with UnavailableException

use of com.datastax.oss.driver.api.core.servererrors.UnavailableException in project java-driver by datastax.

the class ReactiveResultSetSubscriptionTest method should_report_error_on_first_page.

@Test
public void should_report_error_on_first_page() {
    CompletableFuture<AsyncResultSet> future1 = new CompletableFuture<>();
    TestSubscriber<ReactiveRow> mainSubscriber = new TestSubscriber<>();
    TestSubscriber<ColumnDefinitions> colDefsSubscriber = new TestSubscriber<>();
    TestSubscriber<ExecutionInfo> execInfosSubscriber = new TestSubscriber<>();
    TestSubscriber<Boolean> wasAppliedSubscriber = new TestSubscriber<>();
    ReactiveResultSetSubscription<AsyncResultSet> subscription = new ReactiveResultSetSubscription<>(mainSubscriber, colDefsSubscriber, execInfosSubscriber, wasAppliedSubscriber);
    mainSubscriber.onSubscribe(subscription);
    subscription.start(() -> future1);
    future1.completeExceptionally(new UnavailableException(null, null, 0, 0));
    mainSubscriber.awaitTermination();
    assertThat(mainSubscriber.getError()).isNotNull().isInstanceOf(UnavailableException.class);
    assertThat(colDefsSubscriber.getError()).isNotNull().isInstanceOf(UnavailableException.class);
    assertThat(execInfosSubscriber.getError()).isNotNull().isInstanceOf(UnavailableException.class);
    assertThat(wasAppliedSubscriber.getError()).isNotNull().isInstanceOf(UnavailableException.class);
}
Also used : ColumnDefinitions(com.datastax.oss.driver.api.core.cql.ColumnDefinitions) AsyncResultSet(com.datastax.oss.driver.api.core.cql.AsyncResultSet) UnavailableException(com.datastax.oss.driver.api.core.servererrors.UnavailableException) ExecutionInfo(com.datastax.oss.driver.api.core.cql.ExecutionInfo) ReactiveRow(com.datastax.dse.driver.api.core.cql.reactive.ReactiveRow) CompletableFuture(java.util.concurrent.CompletableFuture) Test(org.junit.Test)

Example 5 with UnavailableException

use of com.datastax.oss.driver.api.core.servererrors.UnavailableException in project java-driver by datastax.

the class DowngradingRetry method read.

/**
 * Queries data, retrying if necessary with a downgraded CL.
 *
 * @param cl the consistency level to apply.
 * @param retryCount the current retry count.
 * @throws DriverException if the current consistency level cannot be downgraded.
 */
private ResultSet read(ConsistencyLevel cl, int retryCount) {
    System.out.printf("Reading at %s (retry count: %d)%n", cl, retryCount);
    Statement stmt = SimpleStatement.newInstance("SELECT sensor_id, date, timestamp, value " + "FROM downgrading.sensor_data " + "WHERE " + "sensor_id = 756716f7-2e54-4715-9f00-91dcbea6cf50 AND " + "date = '2018-02-26' AND " + "timestamp > '2018-02-26+01:00'").setConsistencyLevel(cl);
    try {
        ResultSet rows = session.execute(stmt);
        System.out.println("Read succeeded at " + cl);
        return rows;
    } catch (DriverException e) {
        if (retryCount == maxRetries) {
            throw e;
        }
        e = unwrapAllNodesFailedException(e);
        System.out.println("Read failed: " + e);
        if (e instanceof UnavailableException) {
            // Downgrade to the number of replicas reported alive and retry.
            int aliveReplicas = ((UnavailableException) e).getAlive();
            ConsistencyLevel downgraded = downgrade(cl, aliveReplicas, e);
            return read(downgraded, retryCount + 1);
        } else if (e instanceof ReadTimeoutException) {
            ReadTimeoutException readTimeout = (ReadTimeoutException) e;
            int received = readTimeout.getReceived();
            int required = readTimeout.getBlockFor();
            // equal to the number of received acknowledgements.
            if (received < required) {
                ConsistencyLevel downgraded = downgrade(cl, received, e);
                return read(downgraded, retryCount + 1);
            }
            // and get the data back.
            if (!readTimeout.wasDataPresent()) {
                return read(cl, retryCount + 1);
            }
            // Otherwise, abort since the read timeout is unlikely to be solved by a retry.
            throw e;
        } else {
            // and hope to talk to a healthier coordinator.
            return read(cl, retryCount + 1);
        }
    }
}
Also used : DefaultConsistencyLevel(com.datastax.oss.driver.api.core.DefaultConsistencyLevel) ConsistencyLevel(com.datastax.oss.driver.api.core.ConsistencyLevel) BatchStatement(com.datastax.oss.driver.api.core.cql.BatchStatement) SimpleStatement(com.datastax.oss.driver.api.core.cql.SimpleStatement) Statement(com.datastax.oss.driver.api.core.cql.Statement) ReadTimeoutException(com.datastax.oss.driver.api.core.servererrors.ReadTimeoutException) ResultSet(com.datastax.oss.driver.api.core.cql.ResultSet) UnavailableException(com.datastax.oss.driver.api.core.servererrors.UnavailableException) DriverException(com.datastax.oss.driver.api.core.DriverException)

Aggregations

UnavailableException (com.datastax.oss.driver.api.core.servererrors.UnavailableException)8 Test (org.junit.Test)6 ReactiveRow (com.datastax.dse.driver.api.core.cql.reactive.ReactiveRow)3 ExecutionInfo (com.datastax.oss.driver.api.core.cql.ExecutionInfo)3 Node (com.datastax.oss.driver.api.core.metadata.Node)3 ReadTimeoutException (com.datastax.oss.driver.api.core.servererrors.ReadTimeoutException)3 ConsistencyLevel (com.datastax.oss.driver.api.core.ConsistencyLevel)2 DefaultConsistencyLevel (com.datastax.oss.driver.api.core.DefaultConsistencyLevel)2 DriverException (com.datastax.oss.driver.api.core.DriverException)2 AsyncResultSet (com.datastax.oss.driver.api.core.cql.AsyncResultSet)2 BatchStatement (com.datastax.oss.driver.api.core.cql.BatchStatement)2 ColumnDefinitions (com.datastax.oss.driver.api.core.cql.ColumnDefinitions)2 SimpleStatement (com.datastax.oss.driver.api.core.cql.SimpleStatement)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 Metric (com.codahale.metrics.Metric)1 CqlSession (com.datastax.oss.driver.api.core.CqlSession)1 DefaultDriverOption (com.datastax.oss.driver.api.core.config.DefaultDriverOption)1 DriverContext (com.datastax.oss.driver.api.core.context.DriverContext)1 ResultSet (com.datastax.oss.driver.api.core.cql.ResultSet)1 Statement (com.datastax.oss.driver.api.core.cql.Statement)1