requireNonNull(extraColumnMetadataCodec, "extraColumnMetadataCodec is null"); Cluster.Builder clusterBuilder = Cluster.builder() .withProtocolVersion(config.getProtocolVersion()); clusterBuilder.withPort(config.getNativeProtocolPort()); clusterBuilder.withReconnectionPolicy(new ExponentialReconnectionPolicy(500, 10000)); clusterBuilder.withRetryPolicy(config.getRetryPolicy().getPolicy()); clusterBuilder.withLoadBalancingPolicy(loadPolicy); socketOptions.setSoLinger(config.getClientSoLinger()); clusterBuilder.withSocketOptions(socketOptions); clusterBuilder.withCredentials(config.getUsername(), config.getPassword()); options.setFetchSize(config.getFetchSize()); options.setConsistencyLevel(config.getConsistencyLevel()); clusterBuilder.withQueryOptions(options); clusterBuilder.withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy( new ReopeningCluster(() -> { contactPoints.forEach(clusterBuilder::addContactPoint); return clusterBuilder.build(); }), config.getNoHostAvailableRetryTimeout());
/** * Add field use_raw_configuration_schema to endpointProfile that used to support devices using * SDK version 0.9.0 */ public void transform() { //mongo MongoClient client = new MongoClient(host); MongoDatabase database = client.getDatabase(dbName); MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile"); endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false))); //cassandra Cluster cluster = Cluster.builder().addContactPoint(host).build(); Session session = cluster.connect(dbName); session.execute("ALTER TABLE ep_profile ADD use_raw_schema boolean"); session.close(); cluster.close(); } }
cluster = Cluster.builder().withCredentials(username, password) .withPort(Integer.valueOf(port)).addContactPoints(hosts).build(); } else { cluster = Cluster.builder().withPort(Integer.valueOf(port)) .addContactPoints(hosts).build(); MAX_CONNECTIONS_PROPERTY); if (maxConnections != null) { cluster.getConfiguration().getPoolingOptions() .setMaxConnectionsPerHost(HostDistance.LOCAL, Integer.valueOf(maxConnections)); if (coreConnections != null) { cluster.getConfiguration().getPoolingOptions() .setCoreConnectionsPerHost(HostDistance.LOCAL, Integer.valueOf(coreConnections)); Metadata metadata = cluster.getMetadata(); logger.info("Connected to cluster: {}\n", metadata.getClusterName()); for (Host discoveredHost : metadata.getAllHosts()) { logger.info("Datacenter: {}; Host: {}; Rack: {}\n", discoveredHost.getDatacenter(), discoveredHost.getAddress(),
@Test(groups = "short") public void should_warn_if_contact_points_have_different_dcs_when_not_explicitly_specified() { DCAwareRoundRobinPolicy policy = spy(DCAwareRoundRobinPolicy.builder().build()); ScassandraCluster sCluster = ScassandraCluster.builder().withNodes(2, 2).build(); Cluster cluster = builder() .addContactPoints( sCluster.address(1, 1).getAddress(), sCluster.address(2, 1).getAddress()) .withPort(sCluster.getBinaryPort()) .withLoadBalancingPolicy(policy) .build(); cluster.init(); Mockito.verify(policy).init(any(Cluster.class), initHostsCaptor.capture()); assertThat(initHostsCaptor.getValue()).containsOnly(host1, host3); cluster.close(); sCluster.stop();
/** * Validates that when a Cluster is initialized that {@link * SpeculativeExecutionPolicy#init(Cluster)} is called and that when a Cluster is closed {@link * SpeculativeExecutionPolicy#close()} is called. * * @test_category queries:speculative_execution * @expected_result init and close are called on cluster init and close. * @jira_ticket JAVA-796 * @since 2.0.11, 2.1.7, 2.2.1 */ @Test(groups = "short") public void should_init_and_close_policy_on_cluster() { SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class); Cluster cluster = Cluster.builder() .addContactPoints(scassandras.address(2).getAddress()) .withPort(scassandras.getBinaryPort()) .withSpeculativeExecutionPolicy(mockPolicy) .build(); verify(mockPolicy, times(0)).init(cluster); verify(mockPolicy, times(0)).close(); try { cluster.init(); verify(mockPolicy, times(1)).init(cluster); } finally { cluster.close(); verify(mockPolicy, times(1)).close(); } }
@Test(groups = "short") public void session_should_detect_cluster_close() { ScassandraCluster scassandraCluster = ScassandraCluster.builder().withIpPrefix(TestUtils.IP_PREFIX).build(); Cluster cluster = Cluster.builder() .addContactPoints(scassandraCluster.address(1).getAddress()) .withPort(scassandraCluster.getBinaryPort()) .withNettyOptions(nonQuietClusterCloseOptions) .build(); Session session = cluster.connect(); cluster.close(); try { session.execute("SELECTS * FROM system.peers"); fail("Should have failed when session.execute was called on cluster that was closed"); } catch (DriverInternalError e) {
@Test(groups = "short") public void should_wait_on_connection_if_not_convicted_and_no_connections_available() throws Exception { Cluster cluster = this.createClusterBuilder() .withSocketOptions( new SocketOptions() .setConnectTimeoutMillis(readTimeout) .setReadTimeoutMillis(reconnectInterval)) .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) .build(); try { cluster.init(); assertThat(cluster).hasOpenControlConnection(); Connection.Factory factory = spy(cluster.manager.connectionFactory); cluster.manager.connectionFactory = factory; reset(factory); MockRequest request = MockRequest.send(pool, 1); verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class)); assertPoolSize(pool, 8); cluster.close();
@Test(groups = "short") public void should_use_same_default_timestamp_for_all_executions() { TimestampGenerator timestampGenerator = Mockito.spy(ServerSideTimestampGenerator.INSTANCE); Cluster cluster = Cluster.builder() .addContactPoints(scassandras.address(2).getAddress()) .withPort(scassandras.getBinaryPort()) .withLoadBalancingPolicy(loadBalancingPolicy) .withTimestampGenerator(timestampGenerator) .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(1, 2)) .withNettyOptions(nonQuietClusterCloseOptions) .build(); .build()); Session session = cluster.connect(); Metrics.Errors errors = cluster.getMetrics().getErrorMetrics(); session.execute(statement); Mockito.verify(timestampGenerator, times(1)).next();
@Test(groups = "short") @CCMConfig(createCcm = false) public void should_fetch_whole_peers_table_if_broadcast_address_changed() Cluster.builder() .addContactPoints(scassandras.address(1).getAddress()) .withPort(scassandras.getBinaryPort()) .withNettyOptions(nonQuietClusterCloseOptions) .build(); cluster.init(); Host host2 = cluster.getMetadata().getHost(node2RpcAddress); assertThat(host2).isNotNull(); new InetSocketAddress(InetAddress.getByName("1.2.3.4"), scassandras.getBinaryPort()); assertThat(host2.getSocketAddress().getAddress()) .isEqualTo(node2OldBroadcastAddress.getAddress()); host2 = cluster.getMetadata().getHost(node2RpcAddress);
@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 = "long") public void should_use_connection_from_reconnection_in_pool() { TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy()); SocketOptions socketOptions = spy(new SocketOptions()); Cluster cluster = register( Cluster.builder() .addContactPoints(getContactPoints().get(0)) .withPort(ccm().getBinaryPort()) .withReconnectionPolicy(new ConstantReconnectionPolicy(5000)) .withLoadBalancingPolicy(loadBalancingPolicy) .withSocketOptions(socketOptions) .withProtocolVersion(ccm().getProtocolVersion()) .build()); cluster.connect(); cluster.connect(); verify(socketOptions, times(1 + corePoolSize * 2)).getKeepAlive();
/** * Validates that a Cluster that was never able to successfully establish connection a session can * be closed properly. * * @test_category connection * @expected_result Cluster closes within 1 second. */ @Test(groups = "short") public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception { Cluster cluster = Cluster.builder() .addContactPointsWithPorts(new InetSocketAddress("127.0.0.1", 65534)) .withNettyOptions(nonQuietClusterCloseOptions) .build(); try { cluster.connect(); fail("Should not have been able to connect."); } catch (NoHostAvailableException e) { // Expected. CloseFuture closeFuture = cluster.closeAsync(); try { closeFuture.get(1, TimeUnit.SECONDS); } catch (TimeoutException e1) { fail("Close Future did not complete quickly."); } } finally { cluster.close(); } }
/** * Verifies that the cluster builder fails when beta flag is set and user attempts to pass a * version explicitly. * * @jira_ticket JAVA-1248 */ @Test(groups = "short") public void should_not_initialize_when_beta_flag_is_set_and_version_explicitly_required() throws Exception { try { Cluster.builder() .addContactPoints(getContactPoints()) .withPort(ccm().getBinaryPort()) .allowBetaProtocolVersion() .withProtocolVersion(V4) .build(); fail("Expected IllegalStateException"); } catch (IllegalStateException e) { assertThat(e.getMessage()) .isEqualTo("Can not set the version explicitly if `allowBetaProtocolVersion` was used."); } }
/** * Ensures that if the core connection pool is full that borrowConnection will create and use a * new connection. * * @jira_ticket JAVA-419 * @test_category connection:connection_pool * @since 2.0.10, 2.1.6 */ @Test(groups = "short") public void should_add_extra_connection_when_core_full() throws Exception { Cluster cluster = createClusterBuilder().build(); List<MockRequest> allRequests = newArrayList(); try { HostConnectionPool pool = createPool(cluster, 1, 2); Connection.Factory factory = spy(cluster.manager.connectionFactory); cluster.manager.connectionFactory = factory; Connection core = pool.connections.get(0); // Fill core connection + 1 List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool); assertBorrowedConnection(requests, core); allRequests.addAll(requests); allRequests.add(MockRequest.send(pool)); // Reaching the threshold should have triggered the creation of an extra one verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); assertPoolSize(pool, 2); } finally { MockRequest.completeAll(allRequests); cluster.close(); } }
/** * Verifies that the driver can connect to 3.10 with the following combination of options: Version * UNSET Flag UNSET Expected version: V4 * * @jira_ticket JAVA-1248 */ @Test(groups = "short") public void should_connect_after_renegotiation_when_no_version_explicitly_required_and_flag_not_set() throws Exception { // Note: when the driver's ProtocolVersion.NEWEST_SUPPORTED will be incremented to V6 or higher // the renegotiation will start downgrading the version from V6 to V4 instead of V5 to V4, // but the test should remain valid since it's executed against 3.10 exclusively Cluster cluster = Cluster.builder() .addContactPoints(getContactPoints()) .withPort(ccm().getBinaryPort()) .build(); cluster.connect(); assertThat(cluster.getConfiguration().getProtocolOptions().getProtocolVersion()).isEqualTo(V4); } }
@Test(groups = "short") public void should_countdown_inflight_requests_metrics() { sCluster .node(1) .primingClient() .prime(PrimingRequest.queryBuilder().withQuery("mock query").withThen(then()).build()); Cluster cluster = null; try { cluster = builder().build(); Session session = cluster.connect(); assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0); session.executeAsync("mock query").getUninterruptibly(); session.executeAsync("mock query").getUninterruptibly(); assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0); } finally { if (cluster != null) { cluster.close(); } } } }
@BeforeMethod(groups = "short") public void setup() { QueryOptions queryOptions = new QueryOptions(); queryOptions.setRefreshSchemaIntervalMillis(DEBOUNCE_TIME); queryOptions.setMaxPendingRefreshSchemaRequests(5); // Create a separate cluster that will receive the schema events on its control connection. cluster2 = register( Cluster.builder() .addContactPoints(getContactPoints()) .withPort(ccm().getBinaryPort()) .withQueryOptions(queryOptions) .build()); session2 = cluster2.connect(); // Create a spy of the Cluster's control connection and replace it with the spy. controlConnection = spy(cluster2.manager.controlConnection); cluster2.manager.controlConnection = controlConnection; // Create a mock of SchemaChangeListener to use for signalling events. listener = mock(SchemaChangeListener.class); cluster2.register(listener); reset(listener); reset(controlConnection); }
@Test(groups = "long") public void should_not_send_heartbeat_when_disabled() throws InterruptedException { Cluster cluster = Cluster.builder() .addContactPoints(hostAddress.getAddress()) .withPort(scassandra.getBinaryPort()) .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(0)) .build(); cluster.init(); assertThat(logs.get()).doesNotContain("sending heartbeat"); } finally { cluster.close();
@Test(groups = "long") @CCMConfig(numberOfNodes = 3) public void should_reestablish_if_control_node_decommissioned() throws InterruptedException { Cluster cluster = register( Cluster.builder() .addContactPoints(firstHost.getAddress()) .withPort(ccm().getBinaryPort()) .withQueryOptions(nonDebouncingQueryOptions()) .build()); cluster.init(); assertThat(controlHost).isEqualTo(firstHost.getAddress());
/** * Tests that, under protocol versions lesser than V4, it is NOT possible to execute a prepared * statement with unbound values. Note that we have to force protocol version to less than V4 * because higher protocol versions would allow such unbound values to be sent. * * @test_category prepared_statements:binding * @jira_ticket JAVA-777 * @since 2.2.0 */ @Test(groups = "short") public void should_not_allow_unbound_value_on_bound_statement_when_protocol_lesser_than_v4() { Cluster cluster = register( Cluster.builder() .addContactPoints(getContactPoints()) .withPort(ccm().getBinaryPort()) .withProtocolVersion(ccm().getProtocolVersion(ProtocolVersion.V3)) .build()); Session session = cluster.connect(); try { PreparedStatement ps = session.prepare("INSERT INTO " + keyspace + "." + SIMPLE_TABLE + " (k, i) VALUES (?, ?)"); BoundStatement bs = ps.bind("foo"); assertFalse(bs.isSet("i")); session.execute(bs); fail("Should not have executed statement with UNSET values in protocol V3"); } catch (IllegalStateException e) { assertThat(e.getMessage()).contains("Unset value at index 1"); } }