/** * Get a Cassandra cluster using hosts and port. */ private Cluster getCluster(List<String> hosts, int port, String username, String password, String localDc, String consistencyLevel) { Cluster.Builder builder = Cluster.builder() .addContactPoints(hosts.toArray(new String[0])) .withPort(port); if (username != null) { builder.withAuthProvider(new PlainTextAuthProvider(username, password)); } if (localDc != null) { builder.withLoadBalancingPolicy( new TokenAwarePolicy(new DCAwareRoundRobinPolicy.Builder().withLocalDc(localDc).build())); } else { builder.withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); } if (consistencyLevel != null) { builder.withQueryOptions( new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf(consistencyLevel))); } return builder.build(); }
private static AuthProvider getClientAuthProvider(String factoryClassName, Configuration conf) { try { Class<?> c = Class.forName(factoryClassName); if (PlainTextAuthProvider.class.equals(c)) { String username = getStringSetting(USERNAME, conf).or(""); String password = getStringSetting(PASSWORD, conf).or(""); return (AuthProvider) c.getConstructor(String.class, String.class) .newInstance(username, password); } else { return (AuthProvider) c.newInstance(); } } catch (Exception e) { throw new RuntimeException("Failed to instantiate auth provider:" + factoryClassName, e); } }
private AuthProvider getAuthProvider() throws StageException { switch (conf.authProviderOption) { case NONE: return AuthProvider.NONE; case PLAINTEXT: return new PlainTextAuthProvider(conf.username.get(), conf.password.get()); case DSE_PLAINTEXT: return new DsePlainTextAuthProvider(conf.username.get(), conf.password.get()); case KERBEROS: AccessControlContext accessContext = AccessController.getContext(); Subject subject = Subject.getSubject(accessContext); return DseGSSAPIAuthProvider.builder().withSubject(subject).build(); default: throw new IllegalArgumentException("Unrecognized AuthProvider: " + conf.authProviderOption); } }
@Override protected AuthProvider getAuthProvider() { if (StringUtils.hasText(this.cassandraProperties.getUsername())) { return new PlainTextAuthProvider(this.cassandraProperties.getUsername(), this.cassandraProperties.getPassword()); } else { return null; } }
@Test public void shouldConnectUsingCassandraClient() throws SQLException { Cluster cluster = Cluster.builder().addContactPoint(CASSANDRA_HOST) .withAuthProvider(new PlainTextAuthProvider(username, password)).build(); Session session = cluster.connect(); session.close(); cluster.close(); }
public static void setUserNameAndPassword(Configuration conf, String username, String password) { if (StringUtils.isNotBlank(username)) { conf.set(INPUT_NATIVE_AUTH_PROVIDER, PlainTextAuthProvider.class.getName()); conf.set(USERNAME, username); conf.set(PASSWORD, password); } }
@Test public void testPlain() { final DatastaxAuthentication a = new DatastaxAuthentication.Plain(Optional.of("foo"), Optional.of("bar")); a.accept(builder); verify(builder).withAuthProvider(any(PlainTextAuthProvider.class)); }
private static Optional<AuthProvider> getDefaultAuthProvider(Configuration conf) { Optional<String> username = getStringSetting(USERNAME, conf); Optional<String> password = getStringSetting(PASSWORD, conf); if (username.isPresent() && password.isPresent()) { return Optional.of(new PlainTextAuthProvider(username.get(), password.get())); } else { return Optional.absent(); } }
private com.datastax.driver.core.Cluster.Builder newCqlDriverBuilder(ConnectionPoolConfiguration poolConfig, MetricRegistry metricRegistry) { performHostDiscovery(metricRegistry); String[] seeds = _seeds.split(","); List<String> contactPoints = Lists.newArrayListWithCapacity(seeds.length); // Each seed may be a host name or a host name and port (e.g.; "1.2.3.4" or "1.2.3.4:9160"). These need // to be converted into host names only. for (String seed : seeds) { HostAndPort hostAndPort = HostAndPort.fromString(seed); seed = hostAndPort.getHostText(); if (hostAndPort.hasPort()) { if (hostAndPort.getPort() == _thriftPort) { _log.debug("Seed {} found using RPC port; swapping for native port {}", seed, _cqlPort); } else if (hostAndPort.getPort() != _cqlPort) { throw new IllegalArgumentException(String.format( "Seed %s found with invalid port %s. The port must match either the RPC (thrift) port %s " + "or the native (CQL) port %s", seed, hostAndPort.getPort(), _thriftPort, _cqlPort)); } } contactPoints.add(seed); } PoolingOptions poolingOptions = new PoolingOptions(); if (poolConfig.getMaxConnectionsPerHost().or(getMaxConnectionsPerHost()).isPresent()) { poolingOptions.setMaxConnectionsPerHost(HostDistance.LOCAL, poolConfig.getMaxConnectionsPerHost().or(getMaxConnectionsPerHost()).get()); } if (poolConfig.getCoreConnectionsPerHost().or(getCoreConnectionsPerHost()).isPresent()) { poolingOptions.setCoreConnectionsPerHost(HostDistance.LOCAL, poolConfig.getCoreConnectionsPerHost().or(getCoreConnectionsPerHost()).get()); } SocketOptions socketOptions = new SocketOptions(); if (poolConfig.getConnectTimeout().or(getConnectTimeout()).isPresent()) { socketOptions.setConnectTimeoutMillis(poolConfig.getConnectTimeout().or(getConnectTimeout()).get()); } if (poolConfig.getSocketTimeout().or(getSocketTimeout()).isPresent()) { socketOptions.setReadTimeoutMillis(poolConfig.getSocketTimeout().or(getSocketTimeout()).get()); } AuthProvider authProvider = _authenticationCredentials != null ? new PlainTextAuthProvider(_authenticationCredentials.getUsername(), _authenticationCredentials.getPassword()) : AuthProvider.NONE; return com.datastax.driver.core.Cluster.builder() .addContactPoints(contactPoints.toArray(new String[contactPoints.size()])) .withPort(_cqlPort) .withPoolingOptions(poolingOptions) .withSocketOptions(socketOptions) .withRetryPolicy(Policies.defaultRetryPolicy()) .withAuthProvider(authProvider); }
@Test public void shouldUseAuthenticationSet() throws SQLException { assertThat(cluster.getConfiguration().getProtocolOptions().getAuthProvider()) .isInstanceOf(PlainTextAuthProvider.class); }
@Override public void accept(final Builder builder) { builder.withAuthProvider(new PlainTextAuthProvider(username, password)); }
@Override protected AuthProvider getAuthProvider() { return new PlainTextAuthProvider(cassandraConnectionFactory.getProperties().getUsername(), cassandraConnectionFactory.getProperties().getPassword()); }
@Override public AuthProvider build() { return new PlainTextAuthProvider(username, password); }
@Inject public CassandraCluster(final PersisterConfig config) { this.dbConfig = config.getCassandraDbConfiguration(); QueryOptions qo = new QueryOptions(); qo.setConsistencyLevel(ConsistencyLevel.valueOf(dbConfig.getConsistencyLevel())); qo.setDefaultIdempotence(true); String[] contactPoints = dbConfig.getContactPoints(); int retries = dbConfig.getMaxWriteRetries(); Builder builder = Cluster.builder().addContactPoints(contactPoints).withPort(dbConfig.getPort()); builder .withSocketOptions(new SocketOptions().setConnectTimeoutMillis(dbConfig.getConnectionTimeout()) .setReadTimeoutMillis(dbConfig.getReadTimeout())); builder.withQueryOptions(qo).withRetryPolicy(new MonascaRetryPolicy(retries, retries, retries)); lbPolicy = new TokenAwarePolicy( DCAwareRoundRobinPolicy.builder().withLocalDc(dbConfig.getLocalDataCenter()).build()); builder.withLoadBalancingPolicy(lbPolicy); String user = dbConfig.getUser(); if (user != null && !user.isEmpty()) { builder.withAuthProvider(new PlainTextAuthProvider(dbConfig.getUser(), dbConfig.getPassword())); } cluster = builder.build(); PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions(); poolingOptions.setConnectionsPerHost(HostDistance.LOCAL, dbConfig.getMaxConnections(), dbConfig.getMaxConnections()).setConnectionsPerHost(HostDistance.REMOTE, dbConfig.getMaxConnections(), dbConfig.getMaxConnections()); poolingOptions.setMaxRequestsPerConnection(HostDistance.LOCAL, dbConfig.getMaxRequests()) .setMaxRequestsPerConnection(HostDistance.REMOTE, dbConfig.getMaxRequests()); metricsSession = cluster.connect(dbConfig.getKeySpace()); measurementInsertStmt = metricsSession.prepare(MEASUREMENT_INSERT_CQL).setIdempotent(true); measurementUpdateStmt = metricsSession.prepare(MEASUREMENT_UPDATE_CQL).setIdempotent(true); metricInsertStmt = metricsSession.prepare(METRICS_INSERT_CQL).setIdempotent(true); metricUpdateStmt = metricsSession.prepare(METRICS_UPDATE_CQL).setIdempotent(true); dimensionStmt = metricsSession.prepare(DIMENSION_INSERT_CQL).setIdempotent(true); dimensionMetricStmt = metricsSession.prepare(DIMENSION_METRIC_INSERT_CQL).setIdempotent(true); metricDimensionStmt = metricsSession.prepare(METRIC_DIMENSION_INSERT_CQL).setIdempotent(true); retrieveMetricIdStmt = metricsSession.prepare(RETRIEVE_METRIC_ID_CQL).setIdempotent(true); retrieveMetricDimensionStmt = metricsSession.prepare(RETRIEVE_METRIC_DIMENSION_CQL) .setIdempotent(true); alarmsSession = cluster.connect(dbConfig.getKeySpace()); alarmHistoryInsertStmt = alarmsSession.prepare(INSERT_ALARM_STATE_HISTORY_SQL).setIdempotent(true); metricIdCache = CacheBuilder.newBuilder() .maximumSize(config.getCassandraDbConfiguration().getDefinitionMaxCacheSize()).build(); dimensionCache = CacheBuilder.newBuilder() .maximumSize(config.getCassandraDbConfiguration().getDefinitionMaxCacheSize()).build(); metricDimensionCache = CacheBuilder.newBuilder() .maximumSize(config.getCassandraDbConfiguration().getDefinitionMaxCacheSize()).build(); logger.info("loading cached definitions from db"); ExecutorService executor = Executors.newFixedThreadPool(250); //a majority of the ids are for metrics not actively receiving msgs anymore //loadMetricIdCache(executor); loadDimensionCache(); loadMetricDimensionCache(executor); executor.shutdown(); }
@Test public void shouldCreateClusterWithAuthentication() throws Exception { CassandraServiceInfo info = new CassandraServiceInfo("local", Collections.singletonList("127.0.0.1"), 9142, "walter", "white"); Cluster cluster = creator.create(info, null); Configuration configuration = cluster.getConfiguration(); assertThat(configuration.getProtocolOptions().getAuthProvider(), is(instanceOf(PlainTextAuthProvider.class))); }