Search in sources :

Example 6 with Block

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

the class ServerDiscoveryAndMonitoringProseTests method testHeartbeatFrequency.

@Test
@SuppressWarnings("try")
public void testHeartbeatFrequency() throws InterruptedException {
    assumeFalse(isServerlessTest());
    CountDownLatch latch = new CountDownLatch(5);
    MongoClientSettings settings = getMongoClientSettingsBuilder().applyToServerSettings(new Block<ServerSettings.Builder>() {

        @Override
        public void apply(final ServerSettings.Builder builder) {
            builder.heartbeatFrequency(50, TimeUnit.MILLISECONDS);
            builder.addServerMonitorListener(new ServerMonitorListener() {

                @Override
                public void serverHeartbeatSucceeded(final ServerHeartbeatSucceededEvent event) {
                    latch.countDown();
                }
            });
        }
    }).build();
    try (MongoClient ignored = MongoClients.create(settings)) {
        assertTrue("Took longer than expected to reach expected number of hearbeats", latch.await(500, TimeUnit.MILLISECONDS));
    }
}
Also used : ServerSettings(com.mongodb.connection.ServerSettings) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Block(com.mongodb.Block) MongoClientSettings(com.mongodb.MongoClientSettings) CountDownLatch(java.util.concurrent.CountDownLatch) ServerHeartbeatSucceededEvent(com.mongodb.event.ServerHeartbeatSucceededEvent) ServerMonitorListener(com.mongodb.event.ServerMonitorListener) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 7 with Block

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

the class ServerDiscoveryAndMonitoringProseTests method testRTTUpdates.

@Test
public void testRTTUpdates() throws InterruptedException {
    assumeTrue(isStandalone());
    assumeTrue(serverVersionAtLeast(4, 4));
    List<ServerDescriptionChangedEvent> events = synchronizedList(new ArrayList<>());
    MongoClientSettings settings = getMongoClientSettingsBuilder().applicationName("streamingRttTest").applyToServerSettings(new Block<ServerSettings.Builder>() {

        @Override
        public void apply(final ServerSettings.Builder builder) {
            builder.heartbeatFrequency(50, TimeUnit.MILLISECONDS);
            builder.addServerListener(new ServerListener() {

                @Override
                public void serverDescriptionChanged(final ServerDescriptionChangedEvent event) {
                    events.add(event);
                }
            });
        }
    }).build();
    try (MongoClient client = MongoClients.create(settings)) {
        client.getDatabase("admin").runCommand(new Document("ping", 1));
        Thread.sleep(250);
        assertTrue(events.size() >= 1);
        events.forEach(event -> assertTrue(event.getNewDescription().getRoundTripTimeNanos() > 0));
        configureFailPoint(parse(format("{" + "configureFailPoint: \"failCommand\"," + "mode: {times: 1000}," + " data: {" + "   failCommands: [\"%s\", \"%s\"]," + "   blockConnection: true," + "   blockTimeMS: 100," + "   appName: \"streamingRttTest\"" + "  }" + "}", LEGACY_HELLO, HELLO)));
        long startTime = System.currentTimeMillis();
        while (true) {
            long rttMillis = NANOSECONDS.toMillis(client.getClusterDescription().getServerDescriptions().get(0).getRoundTripTimeNanos());
            if (rttMillis > 50) {
                break;
            }
            assertFalse(System.currentTimeMillis() - startTime > 1000);
            // noinspection BusyWait
            Thread.sleep(50);
        }
    } finally {
        disableFailPoint("failCommand");
    }
}
Also used : ServerDescriptionChangedEvent(com.mongodb.event.ServerDescriptionChangedEvent) ServerSettings(com.mongodb.connection.ServerSettings) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Block(com.mongodb.Block) MongoClientSettings(com.mongodb.MongoClientSettings) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) ServerListener(com.mongodb.event.ServerListener) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 8 with Block

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

the class InitialDnsSeedlistDiscoveryTest method shouldDiscoverSrvRecord.

@Test
public void shouldDiscoverSrvRecord() throws InterruptedException {
    assumeFalse(isServerlessTest());
    assumeFalse(isError);
    final CountDownLatch seedsLatch = new CountDownLatch(1);
    final CountDownLatch hostsLatch = new CountDownLatch(1);
    final ConnectionString connectionString = new ConnectionString(uri);
    final SslSettings sslSettings = getSslSettings(connectionString);
    assumeTrue("SSL settings don't match", getSslSettings().isEnabled() == sslSettings.isEnabled());
    MongoClientSettings settings = MongoClientSettings.builder().applyToClusterSettings(new Block<ClusterSettings.Builder>() {

        @Override
        public void apply(final ClusterSettings.Builder builder) {
            builder.applyConnectionString(connectionString).addClusterListener(new ClusterListener() {

                @Override
                public void clusterOpening(final ClusterOpeningEvent event) {
                }

                @Override
                public void clusterClosed(final ClusterClosedEvent event) {
                }

                @Override
                public void clusterDescriptionChanged(final ClusterDescriptionChangedEvent event) {
                    List<String> seedsList = event.getNewDescription().getServerDescriptions().stream().map(ServerDescription::getAddress).map(ServerAddress::toString).collect(Collectors.toList());
                    List<String> okHostsList = event.getNewDescription().getServerDescriptions().stream().filter(ServerDescription::isOk).map(ServerDescription::getAddress).map(ServerAddress::toString).collect(Collectors.toList());
                    hostsCheck(seedsList, seeds, numSeeds, seedsLatch);
                    hostsCheck(okHostsList, hosts, numHosts, hostsLatch);
                }
            });
        }

        private void hostsCheck(final List<String> actual, @Nullable final List<String> expected, @Nullable final Integer expectedSize, final CountDownLatch latch) {
            if (expected == null && expectedSize == null) {
                latch.countDown();
            } else if (expected != null && actual.size() == expected.size() && actual.containsAll(expected)) {
                latch.countDown();
            } else if (expectedSize != null && actual.size() == expectedSize) {
                latch.countDown();
            }
        }
    }).applyToSslSettings(new Block<SslSettings.Builder>() {

        @Override
        public void apply(final SslSettings.Builder builder) {
            builder.applySettings(sslSettings);
            builder.invalidHostNameAllowed(true);
        }
    }).build();
    try (MongoClient client = createMongoClient(settings)) {
        assertTrue(seedsLatch.await(ClusterFixture.TIMEOUT, TimeUnit.SECONDS));
        assertTrue(hostsLatch.await(ClusterFixture.TIMEOUT, TimeUnit.SECONDS));
        assertTrue(client.getDatabase("admin").runCommand(new Document("ping", 1)).containsKey("ok"));
    }
}
Also used : ClusterSettings(com.mongodb.connection.ClusterSettings) ServerDescription(com.mongodb.connection.ServerDescription) MongoClientSettings(com.mongodb.MongoClientSettings) ConnectionString(com.mongodb.ConnectionString) CountDownLatch(java.util.concurrent.CountDownLatch) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) ClusterFixture.getSslSettings(com.mongodb.ClusterFixture.getSslSettings) SslSettings(com.mongodb.connection.SslSettings) ClusterClosedEvent(com.mongodb.event.ClusterClosedEvent) ClusterDescriptionChangedEvent(com.mongodb.event.ClusterDescriptionChangedEvent) ClusterListener(com.mongodb.event.ClusterListener) Block(com.mongodb.Block) ConnectionString(com.mongodb.ConnectionString) ClusterOpeningEvent(com.mongodb.event.ClusterOpeningEvent) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 9 with Block

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

the class ReadConcernTest method setUp.

@Before
public void setUp() {
    assumeTrue(canRunTests());
    commandListener = new TestCommandListener();
    mongoClient = MongoClients.create(getMongoClientSettingsBuilder().addCommandListener(commandListener).applyToSocketSettings(new Block<SocketSettings.Builder>() {

        @Override
        public void apply(final SocketSettings.Builder builder) {
            builder.readTimeout(5, TimeUnit.SECONDS);
        }
    }).build());
}
Also used : TestCommandListener(com.mongodb.internal.connection.TestCommandListener) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Block(com.mongodb.Block) SocketSettings(com.mongodb.connection.SocketSettings) Before(org.junit.Before)

Example 10 with Block

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

the class AbstractUnifiedTest method setUp.

@Before
public void setUp() {
    assumeFalse(skipTest);
    assumeTrue("Skipping test: " + definition.getString("skipReason", new BsonString("")).getValue(), !definition.containsKey("skipReason"));
    assumeFalse("Skipping test of count", filename.equals("count.json"));
    collectionHelper = new CollectionHelper<Document>(new DocumentCodec(), new MongoNamespace(databaseName, collectionName));
    collectionHelper.killAllSessions();
    if (!isDataLakeTest()) {
        collectionHelper.create(collectionName, new CreateCollectionOptions(), WriteConcern.MAJORITY);
    }
    if (!data.isEmpty()) {
        List<BsonDocument> documents = new ArrayList<BsonDocument>();
        for (BsonValue document : data) {
            documents.add(document.asDocument());
        }
        collectionHelper.insertDocuments(documents, WriteConcern.MAJORITY);
    }
    if (definition.containsKey("failPoint")) {
        collectionHelper.runAdminCommand(definition.getDocument("failPoint"));
    }
    final BsonDocument clientOptions = definition.getDocument("clientOptions", new BsonDocument());
    connectionString = getConnectionString();
    useMultipleMongoses = definition.getBoolean("useMultipleMongoses", BsonBoolean.FALSE).getValue();
    if (useMultipleMongoses) {
        assumeTrue(isSharded());
        connectionString = getMultiMongosConnectionString();
        assumeTrue("The system property org.mongodb.test.transaction.uri is not set.", connectionString != null);
    }
    MongoClientSettings.Builder builder = getMongoClientSettingsBuilder().applyConnectionString(connectionString).addCommandListener(commandListener).applyToClusterSettings(clusterSettingsBuilder -> {
        if (clientOptions.containsKey("serverSelectionTimeoutMS")) {
            clusterSettingsBuilder.serverSelectionTimeout(clientOptions.getNumber("serverSelectionTimeoutMS").longValue(), MILLISECONDS);
        }
        if (clientOptions.containsKey("directConnection")) {
            setDirectConnection(clusterSettingsBuilder);
        }
    }).applyToSocketSettings(new Block<SocketSettings.Builder>() {

        @Override
        public void apply(final SocketSettings.Builder builder) {
            builder.readTimeout(clientOptions.getInt32("socketTimeoutMS", new BsonInt32(toIntExact(SECONDS.toMillis(5)))).getValue(), MILLISECONDS);
            if (clientOptions.containsKey("connectTimeoutMS")) {
                builder.connectTimeout(clientOptions.getNumber("connectTimeoutMS").intValue(), MILLISECONDS);
            }
        }
    }).writeConcern(getWriteConcern(clientOptions)).readConcern(getReadConcern(clientOptions)).readPreference(getReadPreference(clientOptions)).retryWrites(clientOptions.getBoolean("retryWrites", BsonBoolean.FALSE).getValue()).retryReads(false).applyToConnectionPoolSettings(poolSettingsBuilder -> {
        poolSettingsBuilder.addConnectionPoolListener(connectionPoolListener);
        if (clientOptions.containsKey("minPoolSize")) {
            poolSettingsBuilder.minSize(clientOptions.getInt32("minPoolSize").getValue());
        }
    }).applyToServerSettings(new Block<ServerSettings.Builder>() {

        @Override
        public void apply(final ServerSettings.Builder builder) {
            builder.heartbeatFrequency(50, MILLISECONDS);
            builder.minHeartbeatFrequency(MIN_HEARTBEAT_FREQUENCY_MS, MILLISECONDS);
            builder.addServerListener(serverListener);
        }
    });
    if (clientOptions.containsKey("heartbeatFrequencyMS")) {
        builder.applyToServerSettings(new Block<ServerSettings.Builder>() {

            @Override
            public void apply(final ServerSettings.Builder builder) {
                builder.heartbeatFrequency(clientOptions.getInt32("heartbeatFrequencyMS").intValue(), MILLISECONDS);
            }
        });
    }
    if (clientOptions.containsKey("appname")) {
        builder.applicationName(clientOptions.getString("appname").getValue());
    }
    if (clientOptions.containsKey("w")) {
        if (clientOptions.isString("w")) {
            builder.writeConcern(new WriteConcern(clientOptions.getString("w").getValue()));
        } else if (clientOptions.isNumber("w")) {
            builder.writeConcern(new WriteConcern(clientOptions.getNumber("w").intValue()));
        }
    }
    StreamFactoryFactory streamFactoryFactory = getStreamFactoryFactory();
    if (streamFactoryFactory != null) {
        builder.streamFactoryFactory(streamFactoryFactory);
    }
    mongoClient = createMongoClient(builder.build());
    database = mongoClient.getDatabase(databaseName);
    if (useMultipleMongoses) {
        // non-transactional distinct operation to avoid StaleDbVersion error
        runDistinctOnEachNode();
    }
    helper = new JsonPoweredCrudTestHelper(description, database, database.getCollection(collectionName, BsonDocument.class), null, mongoClient);
    sessionsMap = new HashMap<>();
    lsidMap = new HashMap<>();
    if (createSessions && serverVersionAtLeast(3, 6)) {
        ClientSession sessionZero = createSession("session0");
        ClientSession sessionOne = createSession("session1");
        sessionsMap.put("session0", sessionZero);
        sessionsMap.put("session1", sessionOne);
        lsidMap.put("session0", sessionZero.getServerSession().getIdentifier());
        lsidMap.put("session1", sessionOne.getServerSession().getIdentifier());
    }
}
Also used : Document(org.bson.Document) ServerDescription(com.mongodb.connection.ServerDescription) ClusterFixture.getConnectionString(com.mongodb.ClusterFixture.getConnectionString) BsonValue(org.bson.BsonValue) Collections.singletonList(java.util.Collections.singletonList) MongoWriteConcernException(com.mongodb.MongoWriteConcernException) StreamFactoryFactory(com.mongodb.connection.StreamFactoryFactory) Future(java.util.concurrent.Future) ClusterFixture.isSharded(com.mongodb.ClusterFixture.isSharded) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) SocketSettings(com.mongodb.connection.SocketSettings) BsonArray(org.bson.BsonArray) After(org.junit.After) Map(java.util.Map) ServerType(com.mongodb.connection.ServerType) ClusterFixture.getMultiMongosConnectionString(com.mongodb.ClusterFixture.getMultiMongosConnectionString) Assert.fail(org.junit.Assert.fail) ReadConcern(com.mongodb.ReadConcern) Parameterized(org.junit.runners.Parameterized) CommandMonitoringTestHelper.assertEventsEquality(com.mongodb.client.CommandMonitoringTestHelper.assertEventsEquality) CommandEvent(com.mongodb.event.CommandEvent) CollectionHelper(com.mongodb.client.test.CollectionHelper) MongoException(com.mongodb.MongoException) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) List(java.util.List) Block(com.mongodb.Block) Assert.assertFalse(org.junit.Assert.assertFalse) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) ReadPreference(com.mongodb.ReadPreference) CommandMonitoringTestHelper.getExpectedEvents(com.mongodb.client.CommandMonitoringTestHelper.getExpectedEvents) BsonBoolean(org.bson.BsonBoolean) Assume.assumeFalse(org.junit.Assume.assumeFalse) MongoCommandException(com.mongodb.MongoCommandException) ClusterSettings(com.mongodb.connection.ClusterSettings) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) BsonString(org.bson.BsonString) ServerSettings(com.mongodb.connection.ServerSettings) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) TransactionOptions(com.mongodb.TransactionOptions) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) DocumentCodec(org.bson.codecs.DocumentCodec) Fixture.getMongoClient(com.mongodb.client.Fixture.getMongoClient) Math.toIntExact(java.lang.Math.toIntExact) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ServerAddress(com.mongodb.ServerAddress) ClusterFixture.setDirectConnection(com.mongodb.ClusterFixture.setDirectConnection) MongoNamespace(com.mongodb.MongoNamespace) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) ClusterFixture.isDataLakeTest(com.mongodb.ClusterFixture.isDataLakeTest) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ConnectionString(com.mongodb.ConnectionString) Assert.assertNull(org.junit.Assert.assertNull) ClientSessionOptions(com.mongodb.ClientSessionOptions) ReadConcernLevel(com.mongodb.ReadConcernLevel) ClusterFixture.serverVersionAtLeast(com.mongodb.ClusterFixture.serverVersionAtLeast) Nullable(com.mongodb.lang.Nullable) BsonInt32(org.bson.BsonInt32) WriteConcern(com.mongodb.WriteConcern) CommandStartedEvent(com.mongodb.event.CommandStartedEvent) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) DocumentCodec(org.bson.codecs.DocumentCodec) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) ArrayList(java.util.ArrayList) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) SocketSettings(com.mongodb.connection.SocketSettings) BsonInt32(org.bson.BsonInt32) ServerSettings(com.mongodb.connection.ServerSettings) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) WriteConcern(com.mongodb.WriteConcern) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) Block(com.mongodb.Block) StreamFactoryFactory(com.mongodb.connection.StreamFactoryFactory) BsonValue(org.bson.BsonValue) Before(org.junit.Before)

Aggregations

Block (com.mongodb.Block)18 Document (org.bson.Document)13 MongoClientSettings (com.mongodb.MongoClientSettings)7 MongoCollection (com.mongodb.client.MongoCollection)7 MongoDatabase (com.mongodb.client.MongoDatabase)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 Fixture.getMongoClientSettingsBuilder (com.mongodb.client.Fixture.getMongoClientSettingsBuilder)5 List (java.util.List)5 BsonDocument (org.bson.BsonDocument)5 ServerSettings (com.mongodb.connection.ServerSettings)4 MongoConnection (fr.inria.spirals.repairnator.serializer.mongodb.MongoConnection)4 Map (java.util.Map)4 Test (org.junit.Test)4 ClusterFixture.isServerlessTest (com.mongodb.ClusterFixture.isServerlessTest)3 ConnectionString (com.mongodb.ConnectionString)3 MongoException (com.mongodb.MongoException)3 SocketSettings (com.mongodb.connection.SocketSettings)3 HashSet (java.util.HashSet)3 ObjectId (org.bson.types.ObjectId)3