Refine search
@Override public Cluster get() { String host = configuration.getHostAddress(); int port = configuration.getPort(); LOGGER.info("Connecting to cassandra cluster with host:{}, port:{}", host, port); Cluster cluster = Cluster.builder() .addContactPoint(host) .withPort(port) .build(); Metadata metadata = cluster.getMetadata(); LOGGER.info("Connected to cluster: {}", metadata.getClusterName()); metadata.getAllHosts().forEach(h -> { LOGGER.info("Datacenter:{}, host:{}, rack: {}", h.getDatacenter(), h.getAddress(), h.getRack()); }); return cluster; } }
boolean supports(ProtocolVersion version) { return getCassandraVersion() == null || version.minCassandraVersion().compareTo(getCassandraVersion().nextStable()) <= 0; }
@Override public void onFailure(Throwable t) { if (t instanceof BusyPoolException) { logError(host.getSocketAddress(), t); } else { logger.error("Unexpected error while querying " + host.getAddress(), t); logError(host.getSocketAddress(), t); } findNextHostAndQuery(); } });
/** * {@inheritDoc} */ @Override public synchronized Session connect() throws NoHostAvailableException { if (isDisconnected()) { LOG.info("Connected to cluster: {}", cluster.getClusterName()); for (Host host : getAllHosts()) LOG.info("Datacenter: {}; Host: {}; Rack: {}", host.getDatacenter(), host.getAddress(), host.getRack()); LOG.info("Connect to cluster using keyspace %s", keyspace); session = cluster.connect(keyspace); } else { LOG.warn("{} - Already connected to cluster: {}", getExecutorName(), cluster.getClusterName()); } if (session.isClosed()) { LOG.warn("Session has been closed - create new one!"); this.session = cluster.newSession(); } return session; }
@Test(groups = "short") public void should_throw_proper_unavailable_exception() { simulateError(1, unavailable); try { query(); fail("expected an UnavailableException"); } catch (UnavailableException e) { assertThat(e.getMessage()) .isEqualTo( "Not enough replicas available for query at consistency LOCAL_ONE (1 required but only 0 alive)"); assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_ONE); assertThat(e.getAliveReplicas()).isEqualTo(0); assertThat(e.getRequiredReplicas()).isEqualTo(1); assertThat(e.getAddress()).isEqualTo(host1.getSocketAddress()); assertThat(e.getHost()).isEqualTo(host1.getAddress()); } }
@Test(groups = "short", dataProvider = "connectionErrors") public void should_rethrow_on_connection_error(CloseType closeType) { simulateError(1, Result.closed_connection, new ClosedConnectionConfig(closeType)); try { query(); Fail.fail("expected a TransportException"); } catch (TransportException e) { assertThat(e.getMessage()) .isEqualTo(String.format("[%s] Connection has been closed", host1.getSocketAddress())); } assertOnRequestErrorWasCalled(1, TransportException.class); assertThat(errors.getRetries().getCount()).isEqualTo(0); assertThat(errors.getConnectionErrors().getCount()).isEqualTo(1); assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0); assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(0); assertQueried(1, 1); assertQueried(2, 0); assertQueried(3, 0); } }
@Test(groups = "unit") public void should_ignore_DCs_in_black_list() { when(host1.getDatacenter()).thenReturn("dc1"); when(host2.getDatacenter()).thenReturn("dc2"); when(host3.getDatacenter()).thenReturn(null); HostFilterPolicy policy = HostFilterPolicy.fromDCBlackList(wrappedPolicy, Lists.newArrayList("dc2")); assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL); assertThat(policy.distance(host2)).isSameAs(HostDistance.IGNORED); assertThat(policy.distance(host3)).isSameAs(HostDistance.LOCAL); }
@Test(groups = "short") public void should_rethrow_unavailable_in_no_host_available_exception() { LoadBalancingPolicy firstHostOnlyPolicy = new WhiteListPolicy( Policies.defaultLoadBalancingPolicy(), Collections.singletonList(host1.getSocketAddress())); Cluster.builder() .addContactPoints(scassandras.address(1).getAddress()) .withPort(scassandras.getBinaryPort()) .withRetryPolicy(retryPolicy) .withLoadBalancingPolicy(firstHostOnlyPolicy) .build(); Session whiteListedSession = whiteListedCluster.connect(); fail("expected an NoHostAvailableException"); } catch (NoHostAvailableException e) { Throwable error = e.getErrors().get(host1.getSocketAddress()); assertThat(error).isNotNull(); assertThat(error).isInstanceOf(UnavailableException.class); Metrics.Errors whiteListErrors = whiteListedCluster.getMetrics().getErrorMetrics(); assertThat(whiteListErrors.getRetriesOnUnavailable().getCount()).isEqualTo(1); assertQueried(1, 1);
@Test(groups = "short") public void should_init_cluster_and_session_if_needed() throws Exception { // For this test we need an uninitialized cluster, so we can't reuse the one provided by the // parent class. Rebuild a new one with the same (unique) host. Host host = cluster().getMetadata().allHosts().iterator().next(); Cluster cluster2 = register( Cluster.builder() .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress())) .build()); try { Session session2 = cluster2.newSession(); // Neither cluster2 nor session2 are initialized at this point assertThat(cluster2.manager.metadata).isNull(); ResultSetFuture future = session2.executeAsync("select release_version from system.local"); Row row = Uninterruptibles.getUninterruptibly(future).one(); assertThat(row.getString(0)).isNotEmpty(); } finally { cluster2.close(); } }
@Test(groups = "short") public void should_connect_with_credentials() { PlainTextAuthProvider authProvider = spy(new PlainTextAuthProvider("cassandra", "cassandra")); Cluster cluster = Cluster.builder() .addContactPoints(getContactPoints()) .withPort(ccm().getBinaryPort()) .withAuthProvider(authProvider) .build(); cluster.connect(); verify(authProvider, atLeastOnce()) .newAuthenticator( findHost(cluster, 1).getSocketAddress(), "org.apache.cassandra.auth.PasswordAuthenticator"); assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()) .isEqualTo(0); }
@Test(groups = "short") @CCMConfig(createCcm = false) public void should_randomize_contact_points_when_determining_control_connection() { for (int i = 0; i < iterations; i++) { Cluster cluster = Cluster.builder() .addContactPoints(contactPoints) .withPort(scassandras.getBinaryPort()) .withNettyOptions(nonQuietClusterCloseOptions) .build(); cluster.init(); occurrencesByHost.add(cluster.manager.controlConnection.connectedHost().getAddress()); } finally { cluster.close();
@Test(groups = "short") public void should_log_ignored_request_error() throws InterruptedException { simulateError(1, server_error); retryDecision = ignore(); query(); String line = appender.waitAndGet(5000); assertThat(line.trim()) .isEqualTo( expectedMessage( IGNORING_REQUEST_ERROR, defaultCL, 0, new ServerError(host1.getSocketAddress(), "Server Error").toString())); }
public HostAssert isUp() { assertThat(actual.isUp()).isTrue(); return this; }
@Test(groups = "short") public void should_use_local_dc_from_contact_points_when_not_explicitly_specified() { Cluster cluster = builder() .addContactPoints(sCluster.address(1, 1).getAddress()) .withPort(sCluster.getBinaryPort()) .withLoadBalancingPolicy(policy) .build(); cluster.init(); assertThat(initHostsCaptor.getValue()).containsExactly(host1); assertThat(policy.localDc).isEqualTo(host1.getDatacenter()); cluster.close(); sCluster.stop();
@Test(groups = "short", dataProviderClass = DataProviders.class, dataProvider = "bool") @CCMConfig(createCcm = false) public void should_use_port_from_peers_v2_table(boolean sharedIP) { Cluster.builder() .addContactPointsWithPorts(sCluster.address(1)) .withNettyOptions(nonQuietClusterCloseOptions); builder.withPort(sCluster.getBinaryPort()); cluster.connect(); assertThat(cluster.getMetadata().getAllHosts()).hasSize(5); assertThat(host).hasNoListenSocketAddress(); uniqueAddresses.add(host.getAddress()); uniqueSocketAddresses.add(host.getSocketAddress());
@Test(groups = "short") @CCMConfig(createCcm = false) public void should_fetch_whole_peers_table_if_broadcast_address_changed() cluster.init(); Host host2 = cluster.getMetadata().getHost(node2RpcAddress); assertThat(host2).isNotNull(); InetSocketAddress node2OldBroadcastAddress = host2.getBroadcastSocketAddress(); InetSocketAddress node2NewBroadcastAddress = new InetSocketAddress(InetAddress.getByName("1.2.3.4"), scassandras.getBinaryPort()); assertThat(host2.getSocketAddress().getAddress()) .isEqualTo(node2OldBroadcastAddress.getAddress()); .put( "peer", node2NewBroadcastAddress.getAddress()) // new broadcast address for host 2 .put("rpc_address", host2.getAddress()) // rpc_broadcast_address remains unchanged .put("host_id", UUID.randomUUID()) .put("data_center", datacenter(1)) host2 = cluster.getMetadata().getHost(node2RpcAddress); assertThat(host2.getBroadcastSocketAddress().getAddress()) .isEqualTo(node2NewBroadcastAddress.getAddress()); assertThat(host2.getSocketAddress()).isEqualTo(node2RpcAddress);
@Test(groups = "short") public void should_parse_table_options() { VersionNumber version = TestUtils.findHost(cluster(), 1).getCassandraVersion(); TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable("with_options"); assertThat(table.getOptions().getBloomFilterFalsePositiveChance()).isEqualTo(0.01); assertThat(table.getOptions().getComment()).isEqualTo("My awesome table"); assertThat(table.getOptions().getCaching()).contains(entry("keys", "ALL")); assertThat(table.getOptions().getCaching()).contains(entry("rows_per_partition", "10")); assertThat(table.getOptions().getCompaction()) .contains(entry("class", "org.apache.cassandra.db.compaction.LeveledCompactionStrategy")); assertThat(table.getOptions().getCompaction()).contains(entry("sstable_size_in_mb", "15")); assertThat(table.getOptions().getCompression())
public HostAssert isInDatacenter(String datacenter) { assertThat(actual.getDatacenter()).isEqualTo(datacenter); return this; }
public ClusterAssert usesControlHost(int node) { String expectedAddress = TestUtils.ipOfNode(node); Host controlHost = actual.manager.controlConnection.connectedHost(); assertThat(controlHost.getAddress().getHostAddress()).isEqualTo(expectedAddress); return this; }
@Test(groups = "short") @CCMConfig(numberOfNodes = 2, clusterProvider = "updatablePolicy") public void refreshTest() throws Throwable { // Ugly Host[] hosts = new Host[2]; for (Host h : cluster().getMetadata().getAllHosts()) { if (h.getAddress().equals(ccm().addressOfNode(1).getAddress())) hosts[0] = h; else hosts[1] = h; } assertTrue( session().getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + session().getState().getConnectedHosts()); assertTrue( !session().getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + session().getState().getConnectedHosts()); policy.changeTheHost(hosts[1]); assertTrue( !session().getState().getConnectedHosts().contains(hosts[0]), "Connected hosts: " + session().getState().getConnectedHosts()); assertTrue( session().getState().getConnectedHosts().contains(hosts[1]), "Connected hosts: " + session().getState().getConnectedHosts()); }