Search in sources :

Example 1 with MongoConfigurationException

use of com.mongodb.MongoConfigurationException in project mongo-java-driver by mongodb.

the class DefaultDnsResolver method resolveHostFromSrvRecords.

/*
      The format of SRV record is
        priority weight port target.
      e.g.
        0 5 5060 example.com.

      The priority and weight are ignored, and we just concatenate the host (after removing the ending '.') and port with a
      ':' in between, as expected by ServerAddress.

      It's required that the srvHost has at least three parts (e.g. foo.bar.baz) and that all of the resolved hosts have a parent
      domain equal to the domain of the srvHost.
    */
@Override
public List<String> resolveHostFromSrvRecords(final String srvHost, final String srvServiceName) {
    String srvHostDomain = srvHost.substring(srvHost.indexOf('.') + 1);
    List<String> srvHostDomainParts = asList(srvHostDomain.split("\\."));
    List<String> hosts = new ArrayList<String>();
    InitialDirContext dirContext = createDnsDirContext();
    try {
        String resourceRecordName = "_" + srvServiceName + "._tcp." + srvHost;
        Attributes attributes = dirContext.getAttributes(resourceRecordName, new String[] { "SRV" });
        Attribute attribute = attributes.get("SRV");
        if (attribute == null) {
            throw new MongoConfigurationException(format("No SRV records available for %s", resourceRecordName));
        }
        NamingEnumeration<?> srvRecordEnumeration = attribute.getAll();
        while (srvRecordEnumeration.hasMore()) {
            String srvRecord = (String) srvRecordEnumeration.next();
            String[] split = srvRecord.split(" ");
            String resolvedHost = split[3].endsWith(".") ? split[3].substring(0, split[3].length() - 1) : split[3];
            String resolvedHostDomain = resolvedHost.substring(resolvedHost.indexOf('.') + 1);
            if (!sameParentDomain(srvHostDomainParts, resolvedHostDomain)) {
                throw new MongoConfigurationException(format("The SRV host name '%s'resolved to a host '%s 'that is not in a sub-domain of the SRV host.", srvHost, resolvedHost));
            }
            hosts.add(resolvedHost + ":" + split[2]);
        }
        if (hosts.isEmpty()) {
            throw new MongoConfigurationException("Unable to find any SRV records for host " + srvHost);
        }
    } catch (NamingException e) {
        throw new MongoConfigurationException("Unable to look up SRV record for host " + srvHost, e);
    } finally {
        try {
            dirContext.close();
        } catch (NamingException e) {
        // ignore
        }
    }
    return hosts;
}
Also used : MongoConfigurationException(com.mongodb.MongoConfigurationException) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) NamingException(javax.naming.NamingException) InitialDirContext(javax.naming.directory.InitialDirContext)

Example 2 with MongoConfigurationException

use of com.mongodb.MongoConfigurationException in project mongo-java-driver by mongodb.

the class SrvPollingProseTests method shouldIgnoreDnsRecordLookupFailure.

// 6. DNS record lookup timeout
// Unimplemented as DnsResolver doesn't throw a different exception for timeouts
// 7. DNS record lookup failure
@Test
public void shouldIgnoreDnsRecordLookupFailure() {
    initCluster(new MongoConfigurationException("Unable to look up SRV record for host " + srvHost, new NamingException()));
    assertEquals(setOf(initialHosts), clusterHostsSet());
}
Also used : MongoConfigurationException(com.mongodb.MongoConfigurationException) NamingException(javax.naming.NamingException) Test(org.junit.jupiter.api.Test)

Example 3 with MongoConfigurationException

use of com.mongodb.MongoConfigurationException in project mongo-java-driver by mongodb.

the class LoadBalancedClusterTest method shouldTimeoutSelectServerWhenThereIsSRVLookupException.

@Test
public void shouldTimeoutSelectServerWhenThereIsSRVLookupException() {
    // given
    String srvHostName = "foo.bar.com";
    ServerAddress resolvedServerAddress = new ServerAddress("host1");
    ClusterableServer expectedServer = mock(ClusterableServer.class);
    ClusterSettings clusterSettings = ClusterSettings.builder().serverSelectionTimeout(10, MILLISECONDS).mode(ClusterConnectionMode.LOAD_BALANCED).srvHost(srvHostName).build();
    ClusterableServerFactory serverFactory = mockServerFactory(resolvedServerAddress, expectedServer);
    DnsSrvRecordMonitorFactory dnsSrvRecordMonitorFactory = mock(DnsSrvRecordMonitorFactory.class);
    when(dnsSrvRecordMonitorFactory.create(eq(srvHostName), eq(clusterSettings.getSrvServiceName()), any())).thenAnswer(invocation -> new TestDnsSrvRecordMonitor(invocation.getArgument(2)).sleepTime(Duration.ofMillis(1)).exception(new MongoConfigurationException("Unable to resolve SRV record")));
    cluster = new LoadBalancedCluster(new ClusterId(), clusterSettings, serverFactory, dnsSrvRecordMonitorFactory);
    MongoTimeoutException exception = assertThrows(MongoTimeoutException.class, () -> cluster.selectServer(mock(ServerSelector.class)));
    assertEquals("Timed out after 10 ms while waiting to resolve SRV records for foo.bar.com. " + "Resolution exception was 'com.mongodb.MongoConfigurationException: Unable to resolve SRV record'", exception.getMessage());
}
Also used : MongoConfigurationException(com.mongodb.MongoConfigurationException) ClusterSettings(com.mongodb.connection.ClusterSettings) ClusterId(com.mongodb.connection.ClusterId) ServerAddress(com.mongodb.ServerAddress) MongoTimeoutException(com.mongodb.MongoTimeoutException) RepeatedTest(org.junit.jupiter.api.RepeatedTest) Test(org.junit.jupiter.api.Test)

Example 4 with MongoConfigurationException

use of com.mongodb.MongoConfigurationException in project mongo-java-driver by mongodb.

the class ServerSelectionSelectionTest method shouldPassAllOutcomes.

@Test
public void shouldPassAllOutcomes() {
    // skip this test because the driver prohibits maxStaleness or tagSets with mode of primary at a much lower level
    assumeTrue(!description.equals("max-staleness/ReplicaSetWithPrimary/MaxStalenessWithModePrimary.json"));
    ServerSelector serverSelector = null;
    List<ServerDescription> suitableServers = buildServerDescriptions(definition.getArray("suitable_servers", new BsonArray()));
    List<ServerDescription> selectedServers = null;
    try {
        serverSelector = getServerSelector();
        selectedServers = serverSelector.select(clusterDescription);
        if (error) {
            fail("Should have thrown exception");
        }
    } catch (MongoConfigurationException e) {
        if (!error) {
            fail("Should not have thrown exception: " + e);
        }
        return;
    }
    assertServers(selectedServers, suitableServers);
    ServerSelector latencyBasedServerSelector = new CompositeServerSelector(asList(serverSelector, new LatencyMinimizingServerSelector(15, TimeUnit.MILLISECONDS)));
    List<ServerDescription> inLatencyWindowServers = buildServerDescriptions(definition.getArray("in_latency_window"));
    List<ServerDescription> latencyBasedSelectedServers = latencyBasedServerSelector.select(clusterDescription);
    assertServers(latencyBasedSelectedServers, inLatencyWindowServers);
}
Also used : ServerSelector(com.mongodb.selector.ServerSelector) CompositeServerSelector(com.mongodb.selector.CompositeServerSelector) WritableServerSelector(com.mongodb.internal.selector.WritableServerSelector) LatencyMinimizingServerSelector(com.mongodb.internal.selector.LatencyMinimizingServerSelector) ReadPreferenceServerSelector(com.mongodb.internal.selector.ReadPreferenceServerSelector) MongoConfigurationException(com.mongodb.MongoConfigurationException) BsonArray(org.bson.BsonArray) LatencyMinimizingServerSelector(com.mongodb.internal.selector.LatencyMinimizingServerSelector) CompositeServerSelector(com.mongodb.selector.CompositeServerSelector) Test(org.junit.Test)

Example 5 with MongoConfigurationException

use of com.mongodb.MongoConfigurationException in project mongo-java-driver by mongodb.

the class SingleServerCluster method onChange.

@Override
public void onChange(final ServerDescriptionChangedEvent event) {
    withLock(() -> {
        ServerDescription newDescription = event.getNewDescription();
        if (newDescription.isOk()) {
            if (getSettings().getRequiredClusterType() != ClusterType.UNKNOWN && getSettings().getRequiredClusterType() != newDescription.getClusterType()) {
                newDescription = null;
            } else if (getSettings().getRequiredClusterType() == ClusterType.REPLICA_SET && getSettings().getRequiredReplicaSetName() != null) {
                if (!getSettings().getRequiredReplicaSetName().equals(newDescription.getSetName())) {
                    newDescription = ServerDescription.builder(newDescription).exception(new MongoConfigurationException(format("Replica set name '%s' does not match required replica set name of '%s'", newDescription.getSetName(), getSettings().getRequiredReplicaSetName()))).type(ServerType.UNKNOWN).setName(null).ok(false).build();
                    publishDescription(ClusterType.UNKNOWN, newDescription);
                    return;
                }
            }
        }
        publishDescription(newDescription);
    });
}
Also used : MongoConfigurationException(com.mongodb.MongoConfigurationException) ServerDescription(com.mongodb.connection.ServerDescription)

Aggregations

MongoConfigurationException (com.mongodb.MongoConfigurationException)7 NamingException (javax.naming.NamingException)3 Test (org.junit.jupiter.api.Test)3 MongoTimeoutException (com.mongodb.MongoTimeoutException)2 ServerAddress (com.mongodb.ServerAddress)2 ClusterId (com.mongodb.connection.ClusterId)2 ClusterSettings (com.mongodb.connection.ClusterSettings)2 ServerSelector (com.mongodb.selector.ServerSelector)2 Attribute (javax.naming.directory.Attribute)2 Attributes (javax.naming.directory.Attributes)2 InitialDirContext (javax.naming.directory.InitialDirContext)2 RepeatedTest (org.junit.jupiter.api.RepeatedTest)2 FutureResultCallback (com.mongodb.async.FutureResultCallback)1 ServerDescription (com.mongodb.connection.ServerDescription)1 LatencyMinimizingServerSelector (com.mongodb.internal.selector.LatencyMinimizingServerSelector)1 ReadPreferenceServerSelector (com.mongodb.internal.selector.ReadPreferenceServerSelector)1 WritableServerSelector (com.mongodb.internal.selector.WritableServerSelector)1 CompositeServerSelector (com.mongodb.selector.CompositeServerSelector)1 ArrayList (java.util.ArrayList)1 BsonArray (org.bson.BsonArray)1