/** * Checks if Cassandra table absence error occur. * * @param e Exception to check. * @return {@code true} in case of table absence error. */ public static boolean isTableAbsenceError(Throwable e) { while (e != null) { if (e instanceof InvalidQueryException && (TABLE_EXIST_ERROR1.matcher(e.getMessage()).matches() || TABLE_EXIST_ERROR3.matcher(e.getMessage()).matches() || KEYSPACE_EXIST_ERROR1.matcher(e.getMessage()).matches() || KEYSPACE_EXIST_ERROR2.matcher(e.getMessage()).matches())) return true; if (e instanceof NoHostAvailableException && ((NoHostAvailableException) e).getErrors() != null) { NoHostAvailableException ex = (NoHostAvailableException)e; for (Map.Entry<InetSocketAddress, Throwable> entry : ex.getErrors().entrySet()) { Throwable error = entry.getValue(); if (error instanceof DriverException && (error.getMessage().contains(TABLE_EXIST_ERROR2) || KEYSPACE_EXIST_ERROR3.matcher(error.getMessage()).matches())) return true; } } e = e.getCause(); } return false; }
@Override public NoHostAvailableException copy() { return new NoHostAvailableException(getMessage(), this, errors); }
@Test(groups = "unit") public void should_build_formatted_message_with_stack_traces() { NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3)); String message = e.getCustomMessage(3, true, true); assertThat(message).startsWith("All host(s) tried for query failed (tried:\n"); assertThat(message).contains("/127.0.0.1:9042\nmock stack trace 1\n"); assertThat(message).contains("/127.0.0.3:9042\nmock stack trace 3\n"); assertThat(message).contains("/127.0.0.2:9042\nmock stack trace 2\n"); }
/** * Tests the NoHostAvailableException. by attempting to build a cluster using the IP address * "255.255.255.255" and test all available exception methods. */ @Test(groups = "short") public void noHostAvailableException() throws Exception { try { Cluster.builder().addContactPoints("255.255.255.255").build(); } catch (NoHostAvailableException e) { assertEquals(e.getErrors().size(), 1); assertTrue( e.getErrors() .values() .iterator() .next() .toString() .contains("[/255.255.255.255] Cannot connect")); NoHostAvailableException copy = (NoHostAvailableException) e.copy(); assertEquals(copy.getMessage(), e.getMessage()); assertEquals(copy.getErrors(), e.getErrors()); } }
logger.error(nae.getMessage()); throw nae;
private void reportNoMoreHosts(SpeculativeExecution execution) { runningExecutions.remove(execution); if (runningExecutions.isEmpty()) setFinalException( execution, null, new NoHostAvailableException( errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors)); }
private <T> T executeWithSession(SessionCallable<T> sessionCallable) { ReconnectionPolicy reconnectionPolicy = cluster.getConfiguration().getPolicies().getReconnectionPolicy(); ReconnectionSchedule schedule = reconnectionPolicy.newSchedule(); long deadline = System.currentTimeMillis() + noHostAvailableRetryTimeout.toMillis(); while (true) { try { return sessionCallable.executeWithSession(session.get()); } catch (NoHostAvailableException e) { long timeLeft = deadline - System.currentTimeMillis(); if (timeLeft <= 0) { throw e; } else { long delay = Math.min(schedule.nextDelayMs(), timeLeft); log.warn(e.getCustomMessage(10, true, true)); log.warn("Reconnecting in %dms", delay); try { Thread.sleep(delay); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", interrupted); } } } } }
public NoHostAvailableException(Map<InetSocketAddress, Throwable> errors) { super(makeMessage(errors, MAX_ERRORS_IN_DEFAULT_MESSAGE, false, false)); this.errors = errors; }
/** * Tests the NoHostAvailableException. by attempting to build a cluster using the IP address * "255.255.255.255" and test all available exception methods. */ @Test(groups = "short") public void noHostAvailableException() throws Exception { try { Cluster.builder().addContactPoints("255.255.255.255").build(); } catch (NoHostAvailableException e) { assertEquals(e.getErrors().size(), 1); assertTrue( e.getErrors() .values() .iterator() .next() .toString() .contains("[/255.255.255.255] Cannot connect")); NoHostAvailableException copy = (NoHostAvailableException) e.copy(); assertEquals(copy.getMessage(), e.getMessage()); assertEquals(copy.getErrors(), e.getErrors()); } }
@Override protected Connection tryReconnect() throws ConnectionException { if (isShutdown) throw new ConnectionException(null, "Control connection was shut down"); try { return reconnectInternal(queryPlan(), false); } catch (NoHostAvailableException e) { throw new ConnectionException(null, e.getMessage()); } catch (UnsupportedProtocolVersionException e) { // reconnectInternal only propagate those if we've not decided on the protocol version // yet, // which should only happen on the initial connection and thus in connect() but never // here. throw new AssertionError(); } }
iter.next(), new DriverException("Connection thread interrupted"), errors, iter); throw new NoHostAvailableException( errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors);
@OnScheduled public void onScheduled(ProcessContext context) { final boolean connectionProviderIsSet = context.getProperty(CONNECTION_PROVIDER_SERVICE).isSet(); if (connectionProviderIsSet) { CassandraSessionProviderService sessionProvider = context.getProperty(CONNECTION_PROVIDER_SERVICE).asControllerService(CassandraSessionProviderService.class); cluster.set(sessionProvider.getCluster()); cassandraSession.set(sessionProvider.getCassandraSession()); return; } try { connectToCassandra(context); } catch (NoHostAvailableException nhae) { getLogger().error("No host in the Cassandra cluster can be contacted successfully to execute this statement", nhae); getLogger().error(nhae.getCustomMessage(10, true, false)); throw new ProcessException(nhae); } catch (AuthenticationException ae) { getLogger().error("Invalid username/password combination", ae); throw new ProcessException(ae); } }
/** * Builds a custom message for this exception. * * @param maxErrors the maximum number of errors displayed (useful to limit the size of the * message for big clusters). Beyond this limit, host names are still displayed, but not the * associated errors. Set to {@code Integer.MAX_VALUE} to display all hosts. * @param formatted whether to format the output (line break between each host). * @param includeStackTraces whether to include the full stacktrace of each host error. Note that * this automatically implies {@code formatted}. * @return the message. */ public String getCustomMessage(int maxErrors, boolean formatted, boolean includeStackTraces) { if (includeStackTraces) formatted = true; return makeMessage(errors, maxErrors, formatted, includeStackTraces); }
@Test(groups = "short") public void should_fail_if_host_is_not_connected() { // given a statement with host explicitly set that for which we have no active pool. Host host4 = TestUtils.findHost(cluster, 4); Statement statement = new SimpleStatement("select * system.local").setHost(host4); try { // when statement is executed session.execute(statement); fail("Query should have failed"); } catch (NoHostAvailableException e) { // then the request should fail with a NHAE and no host was tried. assertThat(e.getErrors()).isEmpty(); } finally { verifyNoLbpInteractions(); } } }
@Test(groups = "unit") public void should_build_default_message_when_less_than_3_errors() { NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3)); String message = e.getMessage(); assertThat(message).startsWith("All host(s) tried for query failed"); assertThat(message) .contains( "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)"); assertThat(message) .contains( "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)"); assertThat(message) .contains( "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)"); }
/** * @return Result of healthy or unhealthy based on the cql statement */ @Override public Result check() { boolean res = false; String msg = ""; try { // this.session.execute( getBoundedStatemen() ); this.session.execute(SELECT_NOW_FROM_SYSTEM_LOCAL); res = true; } catch (NoHostAvailableException ex) { LOGGER.error("No hosts available", ex); msg = ex.getMessage(); } return res ? Result.healthy() : Result.unhealthy(msg); } }
@Test(groups = "unit") public void should_build_formatted_message_without_stack_traces() { NoHostAvailableException e = new NoHostAvailableException(buildMockErrors(3)); String message = e.getCustomMessage(3, true, false); assertThat(message).startsWith("All host(s) tried for query failed (tried:\n"); assertThat(message) .contains( "/127.0.0.1:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 1)\n"); assertThat(message) .contains( "/127.0.0.2:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 2)\n"); assertThat(message) .contains( "/127.0.0.3:9042 (com.datastax.driver.core.exceptions.NoHostAvailableExceptionTest$MockError: mock error 3)\n"); }
private void reportNoMoreHosts(SpeculativeExecution execution) { runningExecutions.remove(execution); if (runningExecutions.isEmpty()) setFinalException(execution, null, new NoHostAvailableException( errors == null ? Collections.<InetSocketAddress, Throwable>emptyMap() : errors)); }
getLogger().error(nhae.getCustomMessage(10, true, false)); flowFile = session.penalize(flowFile); session.transfer(flowFile, REL_RETRY);
public NoHostAvailableException(Map<InetSocketAddress, Throwable> errors) { super(makeMessage(errors, MAX_ERRORS_IN_DEFAULT_MESSAGE, false, false)); this.errors = errors; }