use of com.datastax.oss.driver.api.core.metadata.EndPoint in project java-driver by datastax.
the class InsightsClientTest method mockDefaultDriverContext.
private DefaultDriverContext mockDefaultDriverContext() throws UnknownHostException {
DefaultDriverContext context = mock(DefaultDriverContext.class);
mockConnectionPools(context);
MetadataManager manager = mock(MetadataManager.class);
when(context.getMetadataManager()).thenReturn(manager);
Metadata metadata = mock(Metadata.class);
when(manager.getMetadata()).thenReturn(metadata);
Node node = mock(Node.class);
when(node.getExtras()).thenReturn(ImmutableMap.of(DseNodeProperties.DSE_VERSION, Objects.requireNonNull(Version.parse("6.0.5"))));
when(metadata.getNodes()).thenReturn(ImmutableMap.of(UUID.randomUUID(), node));
DriverExecutionProfile defaultExecutionProfile = mockDefaultExecutionProfile();
DriverExecutionProfile nonDefaultExecutionProfile = mockNonDefaultRequestTimeoutExecutionProfile();
Map<String, String> startupOptions = new HashMap<>();
startupOptions.put(StartupOptionsBuilder.CLIENT_ID_KEY, "client-id");
startupOptions.put(StartupOptionsBuilder.APPLICATION_VERSION_KEY, "1.0.0");
startupOptions.put(StartupOptionsBuilder.APPLICATION_NAME_KEY, "app-name");
startupOptions.put(StartupOptionsBuilder.DRIVER_VERSION_KEY, "2.x");
startupOptions.put(StartupOptionsBuilder.DRIVER_NAME_KEY, "DataStax Enterprise Java Driver");
when(context.getStartupOptions()).thenReturn(startupOptions);
when(context.getProtocolVersion()).thenReturn(DSE_V2);
DefaultNode contactPoint = mock(DefaultNode.class);
EndPoint contactEndPoint = mock(EndPoint.class);
when(contactEndPoint.resolve()).thenReturn(new InetSocketAddress("127.0.0.1", 9999));
when(contactPoint.getEndPoint()).thenReturn(contactEndPoint);
when(manager.getContactPoints()).thenReturn(ImmutableSet.of(contactPoint));
DriverConfig driverConfig = mock(DriverConfig.class);
when(context.getConfig()).thenReturn(driverConfig);
Map<String, DriverExecutionProfile> profiles = ImmutableMap.of("default", defaultExecutionProfile, "non-default", nonDefaultExecutionProfile);
Mockito.<Map<String, ? extends DriverExecutionProfile>>when(driverConfig.getProfiles()).thenReturn(profiles);
when(driverConfig.getDefaultProfile()).thenReturn(defaultExecutionProfile);
ControlConnection controlConnection = mock(ControlConnection.class);
DriverChannel channel = mock(DriverChannel.class);
EndPoint controlConnectionEndpoint = mock(EndPoint.class);
when(controlConnectionEndpoint.resolve()).thenReturn(new InetSocketAddress("127.0.0.1", 10));
when(channel.getEndPoint()).thenReturn(controlConnectionEndpoint);
when(channel.localAddress()).thenReturn(new InetSocketAddress("127.0.0.1", 10));
when(controlConnection.channel()).thenReturn(channel);
when(context.getControlConnection()).thenReturn(controlConnection);
return context;
}
use of com.datastax.oss.driver.api.core.metadata.EndPoint in project java-driver by datastax.
the class CloudConfigFactory method createCloudConfig.
/**
* Creates a {@link CloudConfig} with information fetched from the specified {@link InputStream}.
*
* <p>The stream must contain a valid secure connect bundle archive in ZIP format. Note that the
* stream will be closed after a call to that method and cannot be used anymore.
*
* @param cloudConfig the stream to read the Cloud configuration from; cannot be null.
* @throws IOException If the Cloud configuration cannot be read.
* @throws GeneralSecurityException If the Cloud SSL context cannot be created.
*/
@NonNull
public CloudConfig createCloudConfig(@NonNull InputStream cloudConfig) throws IOException, GeneralSecurityException {
Objects.requireNonNull(cloudConfig, "cloudConfig cannot be null");
JsonNode configJson = null;
ByteArrayOutputStream keyStoreOutputStream = null;
ByteArrayOutputStream trustStoreOutputStream = null;
ObjectMapper mapper = new ObjectMapper().configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
try (ZipInputStream zipInputStream = new ZipInputStream(cloudConfig)) {
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
String fileName = entry.getName();
switch(fileName) {
case "config.json":
configJson = mapper.readTree(zipInputStream);
break;
case "identity.jks":
keyStoreOutputStream = new ByteArrayOutputStream();
ByteStreams.copy(zipInputStream, keyStoreOutputStream);
break;
case "trustStore.jks":
trustStoreOutputStream = new ByteArrayOutputStream();
ByteStreams.copy(zipInputStream, trustStoreOutputStream);
break;
}
}
}
if (configJson == null) {
throw new IllegalStateException("Invalid bundle: missing file config.json");
}
if (keyStoreOutputStream == null) {
throw new IllegalStateException("Invalid bundle: missing file identity.jks");
}
if (trustStoreOutputStream == null) {
throw new IllegalStateException("Invalid bundle: missing file trustStore.jks");
}
char[] keyStorePassword = getKeyStorePassword(configJson);
char[] trustStorePassword = getTrustStorePassword(configJson);
ByteArrayInputStream keyStoreInputStream = new ByteArrayInputStream(keyStoreOutputStream.toByteArray());
ByteArrayInputStream trustStoreInputStream = new ByteArrayInputStream(trustStoreOutputStream.toByteArray());
SSLContext sslContext = createSslContext(keyStoreInputStream, keyStorePassword, trustStoreInputStream, trustStorePassword);
URL metadataServiceUrl = getMetadataServiceUrl(configJson);
JsonNode proxyMetadataJson;
try (BufferedReader proxyMetadata = fetchProxyMetadata(metadataServiceUrl, sslContext)) {
proxyMetadataJson = mapper.readTree(proxyMetadata);
}
InetSocketAddress sniProxyAddress = getSniProxyAddress(proxyMetadataJson);
List<EndPoint> endPoints = getEndPoints(proxyMetadataJson, sniProxyAddress);
String localDatacenter = getLocalDatacenter(proxyMetadataJson);
SniSslEngineFactory sslEngineFactory = new SniSslEngineFactory(sslContext);
validateIfBundleContainsUsernamePassword(configJson);
return new CloudConfig(sniProxyAddress, endPoints, localDatacenter, sslEngineFactory);
}
use of com.datastax.oss.driver.api.core.metadata.EndPoint in project java-driver by datastax.
the class NodeStateIT method should_remove_invalid_contact_point.
@Test
public void should_remove_invalid_contact_point() {
Iterator<EndPoint> contactPoints = simulacron.getContactPoints().iterator();
EndPoint endPoint1 = contactPoints.next();
EndPoint endPoint2 = contactPoints.next();
NodeStateListener localNodeStateListener = mock(NodeStateListener.class);
// Initialize the driver with 1 wrong address and 1 valid address
EndPoint wrongContactPoint = withUnusedPort(endPoint1);
DriverConfigLoader loader = SessionUtils.configLoaderBuilder().withDuration(DefaultDriverOption.RECONNECTION_BASE_DELAY, Duration.ofHours(1)).withDuration(DefaultDriverOption.RECONNECTION_MAX_DELAY, Duration.ofHours(1)).build();
try (CqlSession localSession = (CqlSession) SessionUtils.baseBuilder().addContactEndPoint(endPoint1).addContactEndPoint(wrongContactPoint).withNodeStateListener(localNodeStateListener).withConfigLoader(loader).build()) {
Metadata metadata = localSession.getMetadata();
assertThat(metadata.findNode(wrongContactPoint)).isEmpty();
Node localMetadataNode1 = metadata.findNode(endPoint1).orElseThrow(AssertionError::new);
Node localMetadataNode2 = metadata.findNode(endPoint2).orElseThrow(AssertionError::new);
// The order of the calls is not deterministic because contact points are shuffled, but it
// does not matter here since Mockito.verify does not enforce order.
verify(localNodeStateListener, timeout(500)).onRemove(nodeCaptor.capture());
assertThat(nodeCaptor.getValue().getEndPoint()).isEqualTo(wrongContactPoint);
verify(localNodeStateListener, timeout(500)).onUp(localMetadataNode1);
verify(localNodeStateListener, timeout(500)).onAdd(localMetadataNode2);
// Note: there might be an additional onDown for wrongContactPoint if it was hit first at
// init. This is hard to test since the node was removed later, so we simply don't call
// verifyNoMoreInteractions.
}
}
use of com.datastax.oss.driver.api.core.metadata.EndPoint in project java-driver by datastax.
the class ContactPoints method merge.
public static Set<EndPoint> merge(Set<EndPoint> programmaticContactPoints, List<String> configContactPoints, boolean resolve) {
Set<EndPoint> result = Sets.newHashSet(programmaticContactPoints);
for (String spec : configContactPoints) {
for (InetSocketAddress address : extract(spec, resolve)) {
DefaultEndPoint endPoint = new DefaultEndPoint(address);
boolean wasNew = result.add(endPoint);
if (!wasNew) {
LOG.warn("Duplicate contact point {}", address);
}
}
}
return ImmutableSet.copyOf(result);
}
use of com.datastax.oss.driver.api.core.metadata.EndPoint in project java-driver by datastax.
the class SessionBuilder method buildDefaultSessionAsync.
@NonNull
protected final CompletionStage<CqlSession> buildDefaultSessionAsync() {
try {
ProgrammaticArguments programmaticArguments = programmaticArgumentsBuilder.build();
DriverConfigLoader configLoader = this.configLoader != null ? this.configLoader : defaultConfigLoader(programmaticArguments.getClassLoader());
DriverExecutionProfile defaultConfig = configLoader.getInitialConfig().getDefaultProfile();
if (cloudConfigInputStream == null) {
String configUrlString = defaultConfig.getString(DefaultDriverOption.CLOUD_SECURE_CONNECT_BUNDLE, null);
if (configUrlString != null) {
cloudConfigInputStream = () -> getURL(configUrlString).openStream();
}
}
List<String> configContactPoints = defaultConfig.getStringList(DefaultDriverOption.CONTACT_POINTS, Collections.emptyList());
if (cloudConfigInputStream != null) {
if (!programmaticContactPoints.isEmpty() || !configContactPoints.isEmpty()) {
LOG.info("Both a secure connect bundle and contact points were provided. These are mutually exclusive. The contact points from the secure bundle will have priority.");
// clear the contact points provided in the setting file and via addContactPoints
configContactPoints = Collections.emptyList();
programmaticContactPoints = new HashSet<>();
}
if (programmaticSslFactory || defaultConfig.isDefined(DefaultDriverOption.SSL_ENGINE_FACTORY_CLASS)) {
LOG.info("Both a secure connect bundle and SSL options were provided. They are mutually exclusive. The SSL options from the secure bundle will have priority.");
}
CloudConfig cloudConfig = new CloudConfigFactory().createCloudConfig(cloudConfigInputStream.call());
addContactEndPoints(cloudConfig.getEndPoints());
boolean localDataCenterDefined = anyProfileHasDatacenterDefined(configLoader.getInitialConfig());
if (programmaticLocalDatacenter || localDataCenterDefined) {
LOG.info("Both a secure connect bundle and a local datacenter were provided. They are mutually exclusive. The local datacenter from the secure bundle will have priority.");
programmaticArgumentsBuilder.clearDatacenters();
}
withLocalDatacenter(cloudConfig.getLocalDatacenter());
withSslEngineFactory(cloudConfig.getSslEngineFactory());
withCloudProxyAddress(cloudConfig.getProxyAddress());
programmaticArguments = programmaticArgumentsBuilder.build();
}
boolean resolveAddresses = defaultConfig.getBoolean(DefaultDriverOption.RESOLVE_CONTACT_POINTS, true);
Set<EndPoint> contactPoints = ContactPoints.merge(programmaticContactPoints, configContactPoints, resolveAddresses);
if (keyspace == null && defaultConfig.isDefined(DefaultDriverOption.SESSION_KEYSPACE)) {
keyspace = CqlIdentifier.fromCql(defaultConfig.getString(DefaultDriverOption.SESSION_KEYSPACE));
}
return DefaultSession.init((InternalDriverContext) buildContext(configLoader, programmaticArguments), contactPoints, keyspace);
} catch (Throwable t) {
// failed future if anything goes wrong. So wrap any error from that synchronous part.
return CompletableFutures.failedFuture(t);
}
}
Aggregations