Search in sources :

Example 16 with EndPoint

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;
}
Also used : DriverChannel(com.datastax.oss.driver.internal.core.channel.DriverChannel) DriverExecutionProfile(com.datastax.oss.driver.api.core.config.DriverExecutionProfile) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) DefaultNode(com.datastax.oss.driver.internal.core.metadata.DefaultNode) SessionStateForNode(com.datastax.dse.driver.internal.core.insights.schema.SessionStateForNode) Node(com.datastax.oss.driver.api.core.metadata.Node) Metadata(com.datastax.oss.driver.api.core.metadata.Metadata) InsightMetadata(com.datastax.dse.driver.internal.core.insights.schema.InsightMetadata) EndPoint(com.datastax.oss.driver.api.core.metadata.EndPoint) MetadataManager(com.datastax.oss.driver.internal.core.metadata.MetadataManager) DefaultDriverContext(com.datastax.oss.driver.internal.core.context.DefaultDriverContext) ControlConnection(com.datastax.oss.driver.internal.core.control.ControlConnection) DefaultNode(com.datastax.oss.driver.internal.core.metadata.DefaultNode) DriverConfig(com.datastax.oss.driver.api.core.config.DriverConfig)

Example 17 with EndPoint

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);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ZipEntry(java.util.zip.ZipEntry) JsonNode(com.fasterxml.jackson.databind.JsonNode) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SSLContext(javax.net.ssl.SSLContext) SniEndPoint(com.datastax.oss.driver.internal.core.metadata.SniEndPoint) EndPoint(com.datastax.oss.driver.api.core.metadata.EndPoint) URL(java.net.URL) ZipInputStream(java.util.zip.ZipInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) SniSslEngineFactory(com.datastax.oss.driver.internal.core.ssl.SniSslEngineFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NonNull(edu.umd.cs.findbugs.annotations.NonNull)

Example 18 with EndPoint

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.
    }
}
Also used : NodeStateListener(com.datastax.oss.driver.api.core.metadata.NodeStateListener) DefaultNode(com.datastax.oss.driver.internal.core.metadata.DefaultNode) Node(com.datastax.oss.driver.api.core.metadata.Node) BoundNode(com.datastax.oss.simulacron.server.BoundNode) Metadata(com.datastax.oss.driver.api.core.metadata.Metadata) DriverConfigLoader(com.datastax.oss.driver.api.core.config.DriverConfigLoader) EndPoint(com.datastax.oss.driver.api.core.metadata.EndPoint) DefaultEndPoint(com.datastax.oss.driver.internal.core.metadata.DefaultEndPoint) CqlSession(com.datastax.oss.driver.api.core.CqlSession) Test(org.junit.Test)

Example 19 with EndPoint

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);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) DefaultEndPoint(com.datastax.oss.driver.internal.core.metadata.DefaultEndPoint) DefaultEndPoint(com.datastax.oss.driver.internal.core.metadata.DefaultEndPoint) EndPoint(com.datastax.oss.driver.api.core.metadata.EndPoint)

Example 20 with EndPoint

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);
    }
}
Also used : DriverExecutionProfile(com.datastax.oss.driver.api.core.config.DriverExecutionProfile) CloudConfig(com.datastax.oss.driver.internal.core.config.cloud.CloudConfig) DriverConfigLoader(com.datastax.oss.driver.api.core.config.DriverConfigLoader) DefaultDriverConfigLoader(com.datastax.oss.driver.internal.core.config.typesafe.DefaultDriverConfigLoader) CloudConfigFactory(com.datastax.oss.driver.internal.core.config.cloud.CloudConfigFactory) EndPoint(com.datastax.oss.driver.api.core.metadata.EndPoint) DefaultEndPoint(com.datastax.oss.driver.internal.core.metadata.DefaultEndPoint) NonNull(edu.umd.cs.findbugs.annotations.NonNull)

Aggregations

EndPoint (com.datastax.oss.driver.api.core.metadata.EndPoint)24 InetSocketAddress (java.net.InetSocketAddress)14 DefaultEndPoint (com.datastax.oss.driver.internal.core.metadata.DefaultEndPoint)11 Test (org.junit.Test)11 Node (com.datastax.oss.driver.api.core.metadata.Node)7 NonNull (edu.umd.cs.findbugs.annotations.NonNull)5 DriverChannel (com.datastax.oss.driver.internal.core.channel.DriverChannel)4 DefaultNode (com.datastax.oss.driver.internal.core.metadata.DefaultNode)4 CqlSession (com.datastax.oss.driver.api.core.CqlSession)3 DriverConfigLoader (com.datastax.oss.driver.api.core.config.DriverConfigLoader)3 DriverExecutionProfile (com.datastax.oss.driver.api.core.config.DriverExecutionProfile)3 Metadata (com.datastax.oss.driver.api.core.metadata.Metadata)3 ImmutableSet (com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet)3 SessionStateForNode (com.datastax.dse.driver.internal.core.insights.schema.SessionStateForNode)2 NodeStateListener (com.datastax.oss.driver.api.core.metadata.NodeStateListener)2 AdminResult (com.datastax.oss.driver.internal.core.adminrequest.AdminResult)2 AdminRow (com.datastax.oss.driver.internal.core.adminrequest.AdminRow)2 UnexpectedResponseException (com.datastax.oss.driver.internal.core.adminrequest.UnexpectedResponseException)2 ControlConnection (com.datastax.oss.driver.internal.core.control.ControlConnection)2 SniEndPoint (com.datastax.oss.driver.internal.core.metadata.SniEndPoint)2