Search in sources :

Example 1 with ConnectionPoolClearedEvent

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

the class ServerDiscoveryAndMonitoringProseTests method testConnectionPoolManagement.

/**
 * See
 * <a href="https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring-tests.rst#connection-pool-management">Connection Pool Management</a>.
 */
@Test
@Ignore
@SuppressWarnings("try")
public void testConnectionPoolManagement() throws InterruptedException {
    assumeTrue(serverVersionAtLeast(4, 3));
    assumeFalse(isServerlessTest());
    BlockingQueue<Object> events = new LinkedBlockingQueue<>();
    ServerMonitorListener serverMonitorListener = new ServerMonitorListener() {

        @Override
        public void serverHeartbeatSucceeded(final ServerHeartbeatSucceededEvent event) {
            put(events, event);
        }

        @Override
        public void serverHeartbeatFailed(final ServerHeartbeatFailedEvent event) {
            put(events, event);
        }
    };
    ConnectionPoolListener connectionPoolListener = new ConnectionPoolListener() {

        @Override
        public void connectionPoolReady(final ConnectionPoolReadyEvent event) {
            put(events, event);
        }

        @Override
        public void connectionPoolCleared(final ConnectionPoolClearedEvent event) {
            put(events, event);
        }
    };
    String appName = "SDAMPoolManagementTest";
    MongoClientSettings clientSettings = getMongoClientSettingsBuilder().applicationName(appName).applyToClusterSettings(ClusterFixture::setDirectConnection).applyToServerSettings(builder -> builder.heartbeatFrequency(100, TimeUnit.MILLISECONDS).addServerMonitorListener(serverMonitorListener)).applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(connectionPoolListener)).build();
    try (MongoClient unused = MongoClients.create(clientSettings)) {
        /* Note that ServerHeartbeatSucceededEvent type is sometimes allowed but never required.
             * This is because DefaultServerMonitor does not send such events in situations when a server check happens as part
             * of a connection handshake. */
        assertPoll(events, ServerHeartbeatSucceededEvent.class, singleton(ConnectionPoolReadyEvent.class));
        configureFailPoint(new BsonDocument().append("configureFailPoint", new BsonString("failCommand")).append("mode", new BsonDocument().append("times", new BsonInt32(2))).append("data", new BsonDocument().append("failCommands", new BsonArray(asList(new BsonString("isMaster"), new BsonString("hello")))).append("errorCode", new BsonInt32(1234)).append("appName", new BsonString(appName))));
        assertPoll(events, ServerHeartbeatSucceededEvent.class, new HashSet<>(asList(ServerHeartbeatFailedEvent.class, ConnectionPoolClearedEvent.class)));
        assertPoll(events, null, new HashSet<>(asList(ServerHeartbeatSucceededEvent.class, ConnectionPoolReadyEvent.class)));
    } finally {
        disableFailPoint("failCommand");
    }
}
Also used : Document(org.bson.Document) ServerListener(com.mongodb.event.ServerListener) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Collections.singleton(java.util.Collections.singleton) Arrays.asList(java.util.Arrays.asList) BsonArray(org.bson.BsonArray) ClusterFixture.isStandalone(com.mongodb.ClusterFixture.isStandalone) Assert.fail(org.junit.Assert.fail) ServerDescriptionChangedEvent(com.mongodb.event.ServerDescriptionChangedEvent) ServerHeartbeatSucceededEvent(com.mongodb.event.ServerHeartbeatSucceededEvent) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) BsonNull(org.bson.BsonNull) Collections.synchronizedList(java.util.Collections.synchronizedList) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) String.format(java.lang.String.format) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Block(com.mongodb.Block) Assert.assertFalse(org.junit.Assert.assertFalse) Optional(java.util.Optional) ClusterFixture.configureFailPoint(com.mongodb.ClusterFixture.configureFailPoint) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) Fixture.getDefaultDatabaseName(com.mongodb.client.Fixture.getDefaultDatabaseName) BsonDocument.parse(org.bson.BsonDocument.parse) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) Assume.assumeFalse(org.junit.Assume.assumeFalse) BsonString(org.bson.BsonString) ServerSettings(com.mongodb.connection.ServerSettings) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterFixture(com.mongodb.ClusterFixture) ServerHeartbeatFailedEvent(com.mongodb.event.ServerHeartbeatFailedEvent) Logger(com.mongodb.diagnostics.logging.Logger) MongoInterruptedException(com.mongodb.MongoInterruptedException) ConnectionPoolListener(com.mongodb.event.ConnectionPoolListener) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Timeout(com.mongodb.internal.Timeout) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ServerMonitorListener(com.mongodb.event.ServerMonitorListener) Ignore(org.junit.Ignore) Loggers(com.mongodb.diagnostics.logging.Loggers) ClusterFixture.serverVersionAtLeast(com.mongodb.ClusterFixture.serverVersionAtLeast) Nullable(com.mongodb.lang.Nullable) BsonInt32(org.bson.BsonInt32) ClusterFixture.disableFailPoint(com.mongodb.ClusterFixture.disableFailPoint) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) ServerHeartbeatFailedEvent(com.mongodb.event.ServerHeartbeatFailedEvent) BsonString(org.bson.BsonString) MongoClientSettings(com.mongodb.MongoClientSettings) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ServerHeartbeatSucceededEvent(com.mongodb.event.ServerHeartbeatSucceededEvent) ServerMonitorListener(com.mongodb.event.ServerMonitorListener) BsonInt32(org.bson.BsonInt32) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) BsonDocument(org.bson.BsonDocument) ConnectionPoolListener(com.mongodb.event.ConnectionPoolListener) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) Ignore(org.junit.Ignore) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 2 with ConnectionPoolClearedEvent

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

the class DefaultConnectionPool method invalidate.

public void invalidate(final ObjectId serviceId, final int generation) {
    assertTrue(isLoadBalanced());
    if (generation == InternalConnection.NOT_INITIALIZED_GENERATION) {
        return;
    }
    if (serviceStateManager.incrementGeneration(serviceId, generation)) {
        LOGGER.debug("Invalidating the connection pool for server id " + serviceId);
        connectionPoolListener.connectionPoolCleared(new ConnectionPoolClearedEvent(this.serverId, serviceId));
    }
}
Also used : ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent)

Example 3 with ConnectionPoolClearedEvent

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

the class AbstractConnectionPoolTest method shouldPassAllOutcomes.

@Test
public void shouldPassAllOutcomes() throws Exception {
    try {
        for (BsonValue cur : definition.getArray("operations")) {
            final BsonDocument operation = cur.asDocument();
            String name = operation.getString("name").getValue();
            if (name.equals("start")) {
                String target = operation.getString("target", new BsonString("")).getValue();
                executorServiceMap.put(target, Executors.newSingleThreadExecutor(r -> {
                    Thread result = Executors.defaultThreadFactory().newThread(r);
                    result.setName(target);
                    return result;
                }));
            } else if (name.equals("wait")) {
                Thread.sleep(operation.getNumber("ms").intValue());
            } else if (name.equals("waitForThread")) {
                String target = operation.getString("target", new BsonString("")).getValue();
                Exception exceptionFromFuture = futureMap.remove(target).get(5, TimeUnit.SECONDS);
                if (exceptionFromFuture != null) {
                    throw exceptionFromFuture;
                }
            } else if (name.equals("waitForEvent")) {
                Class<?> eventClass = getEventClass(operation.getString("event").getValue());
                assumeNotNull(eventClass);
                long timeoutMillis = operation.getNumber("timeout", new BsonInt64(TimeUnit.SECONDS.toMillis(5))).longValue();
                listener.waitForEvent(eventClass, operation.getNumber("count").intValue(), timeoutMillis, TimeUnit.MILLISECONDS);
            } else if (name.equals("clear")) {
                pool.invalidate(null);
            } else if (name.equals("ready")) {
                pool.ready();
            } else if (name.equals("close")) {
                pool.close();
            } else if (name.equals("checkOut") || name.equals("checkIn")) {
                Callable<Exception> callable = createCallable(operation);
                if (operation.containsKey("thread")) {
                    String threadTarget = operation.getString("thread").getValue();
                    ExecutorService executorService = executorServiceMap.get(threadTarget);
                    futureMap.put(threadTarget, executorService.submit(callable));
                } else {
                    callable.call();
                }
            } else {
                throw new UnsupportedOperationException("No support for " + name);
            }
        }
    } catch (Exception e) {
        if (!definition.containsKey("error")) {
            throw e;
        }
        BsonDocument errorDocument = definition.getDocument("error");
        String exceptionType = errorDocument.getString("type").getValue();
        if (exceptionType.equals("PoolClosedError")) {
            assertEquals(IllegalStateException.class, e.getClass());
        } else if (exceptionType.equals("WaitQueueTimeoutError")) {
            if (e.getClass() != MongoTimeoutException.class) {
                throw e;
            }
        } else {
            throw e;
        }
    }
    if (definition.containsKey("events")) {
        Iterator<Object> actualEventsIterator = getNonIgnoredActualEvents().iterator();
        BsonArray expectedEvents = definition.getArray("events");
        for (BsonValue cur : expectedEvents) {
            BsonDocument expectedEvent = cur.asDocument();
            String type = expectedEvent.getString("type").getValue();
            if (type.equals("ConnectionPoolCreated")) {
                ConnectionPoolCreatedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionPoolCreatedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
                assertEquals(settings, actualEvent.getSettings());
            } else if (type.equals("ConnectionPoolCleared")) {
                ConnectionPoolClearedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionPoolClearedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
            } else if (type.equals("ConnectionPoolReady")) {
                ConnectionPoolReadyEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionPoolReadyEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
            } else if (type.equals("ConnectionPoolClosed")) {
                ConnectionPoolClosedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionPoolClosedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
            } else if (type.equals("ConnectionCreated")) {
                ConnectionCreatedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCreatedEvent.class);
                assertConnectionIdMatch(expectedEvent, actualEvent.getConnectionId());
            } else if (type.equals("ConnectionReady")) {
                ConnectionReadyEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionReadyEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getConnectionId().getServerId().getAddress());
            } else if (type.equals("ConnectionClosed")) {
                ConnectionClosedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionClosedEvent.class);
                assertConnectionIdMatch(expectedEvent, actualEvent.getConnectionId());
                assertReasonMatch(expectedEvent, actualEvent);
            } else if (type.equals("ConnectionCheckOutStarted")) {
                ConnectionCheckOutStartedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCheckOutStartedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
            } else if (type.equals("ConnectionCheckOutFailed")) {
                ConnectionCheckOutFailedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCheckOutFailedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
                assertReasonMatch(expectedEvent, actualEvent);
            } else if (type.equals("ConnectionCheckedOut")) {
                ConnectionCheckedOutEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCheckedOutEvent.class);
                assertConnectionIdMatch(expectedEvent, actualEvent.getConnectionId());
            } else if (type.equals("ConnectionCheckedIn")) {
                ConnectionCheckedInEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCheckedInEvent.class);
                assertConnectionIdMatch(expectedEvent, actualEvent.getConnectionId());
            } else {
                throw new UnsupportedOperationException("Unsupported event type " + type);
            }
        }
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) JsonTestServerVersionChecker(com.mongodb.JsonTestServerVersionChecker) ConnectionPoolCreatedEvent(com.mongodb.event.ConnectionPoolCreatedEvent) BsonValue(org.bson.BsonValue) ClusterId(com.mongodb.connection.ClusterId) Future(java.util.concurrent.Future) ServerListener(com.mongodb.event.ServerListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SocketSettings(com.mongodb.connection.SocketSettings) BsonArray(org.bson.BsonArray) After(org.junit.After) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) Parameterized(org.junit.runners.Parameterized) StreamFactory(com.mongodb.connection.StreamFactory) Collection(java.util.Collection) Set(java.util.Set) Assertions.assertFalse(com.mongodb.assertions.Assertions.assertFalse) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) List(java.util.List) ConnectionClosedEvent(com.mongodb.event.ConnectionClosedEvent) Assume.assumeNotNull(org.junit.Assume.assumeNotNull) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) JsonPoweredTestHelper(util.JsonPoweredTestHelper) ConnectionCheckedInEvent(com.mongodb.event.ConnectionCheckedInEvent) Assume.assumeFalse(org.junit.Assume.assumeFalse) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) SameObjectProvider(com.mongodb.internal.inject.SameObjectProvider) BsonString(org.bson.BsonString) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterFixture(com.mongodb.ClusterFixture) ClusterConnectionMode(com.mongodb.connection.ClusterConnectionMode) BsonInt64(org.bson.BsonInt64) ConnectionCreatedEvent(com.mongodb.event.ConnectionCreatedEvent) MongoDriverInformation(com.mongodb.MongoDriverInformation) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ServerAddress(com.mongodb.ServerAddress) SslSettings(com.mongodb.connection.SslSettings) ConnectionReadyEvent(com.mongodb.event.ConnectionReadyEvent) MongoInterruptedException(com.mongodb.MongoInterruptedException) Iterator(java.util.Iterator) ServerId(com.mongodb.connection.ServerId) CommandReadOperation(com.mongodb.internal.operation.CommandReadOperation) Test(org.junit.Test) IOException(java.io.IOException) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) File(java.io.File) MongoTimeoutException(com.mongodb.MongoTimeoutException) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolClosedEvent(com.mongodb.event.ConnectionPoolClosedEvent) Mockito(org.mockito.Mockito) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent) ObjectId(org.bson.types.ObjectId) Nullable(com.mongodb.lang.Nullable) ConnectionId(com.mongodb.connection.ConnectionId) ConnectionCheckOutFailedEvent(com.mongodb.event.ConnectionCheckOutFailedEvent) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ConnectionClosedEvent(com.mongodb.event.ConnectionClosedEvent) ConnectionReadyEvent(com.mongodb.event.ConnectionReadyEvent) BsonString(org.bson.BsonString) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent) Callable(java.util.concurrent.Callable) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) ConnectionCreatedEvent(com.mongodb.event.ConnectionCreatedEvent) ConnectionCheckedInEvent(com.mongodb.event.ConnectionCheckedInEvent) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ConnectionCheckOutFailedEvent(com.mongodb.event.ConnectionCheckOutFailedEvent) URISyntaxException(java.net.URISyntaxException) MongoInterruptedException(com.mongodb.MongoInterruptedException) IOException(java.io.IOException) MongoTimeoutException(com.mongodb.MongoTimeoutException) BsonInt64(org.bson.BsonInt64) BsonDocument(org.bson.BsonDocument) ConnectionPoolCreatedEvent(com.mongodb.event.ConnectionPoolCreatedEvent) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) ExecutorService(java.util.concurrent.ExecutorService) ConnectionPoolClosedEvent(com.mongodb.event.ConnectionPoolClosedEvent) BsonValue(org.bson.BsonValue) Test(org.junit.Test)

Example 4 with ConnectionPoolClearedEvent

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

the class EventMatcher method assertConnectionPoolEventsEquality.

public void assertConnectionPoolEventsEquality(final String client, final BsonArray expectedEventDocuments, final List<Object> events) {
    context.push(ContextElement.ofConnectionPoolEvents(client, expectedEventDocuments, events));
    assertEquals(context.getMessage("Number of events must be the same"), expectedEventDocuments.size(), events.size());
    for (int i = 0; i < events.size(); i++) {
        Object actual = events.get(i);
        BsonDocument expectedEventDocument = expectedEventDocuments.get(i).asDocument();
        String eventType = expectedEventDocument.getFirstKey();
        context.push(ContextElement.ofConnectionPoolEvent(expectedEventDocument, actual, i));
        assertEquals(context.getMessage("Expected event type to match"), eventType, getEventType(actual.getClass()));
        if (actual.getClass().equals(ConnectionPoolClearedEvent.class)) {
            BsonDocument expected = expectedEventDocument.getDocument(eventType);
            ConnectionPoolClearedEvent connectionPoolClearedEvent = (ConnectionPoolClearedEvent) actual;
            if (expected.containsKey("hasServiceId")) {
                boolean hasServiceId = expected.getBoolean("hasServiceId").getValue();
                ObjectId serviceId = connectionPoolClearedEvent.getServiceId();
                if (hasServiceId) {
                    assertNotNull(context.getMessage("Expected serviceId"), serviceId);
                } else {
                    assertNull(context.getMessage("Expected no serviceId"), serviceId);
                }
            }
        } else if (actual.getClass().equals(ConnectionCheckOutFailedEvent.class)) {
            BsonDocument expected = expectedEventDocument.getDocument(eventType);
            ConnectionCheckOutFailedEvent actualEvent = (ConnectionCheckOutFailedEvent) actual;
            if (expected.containsKey("reason")) {
                assertEquals(context.getMessage("Expected reason to match"), expected.getString("reason").getValue(), getReasonString(actualEvent.getReason()));
            }
        } else if (actual.getClass().equals(ConnectionClosedEvent.class)) {
            BsonDocument expected = expectedEventDocument.getDocument(eventType);
            ConnectionClosedEvent actualEvent = (ConnectionClosedEvent) actual;
            if (expected.containsKey("reason")) {
                assertEquals(context.getMessage("Expected reason to match"), expected.getString("reason").getValue(), getReasonString(actualEvent.getReason()));
            }
        }
        context.pop();
    }
    context.pop();
}
Also used : ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) BsonDocument(org.bson.BsonDocument) ObjectId(org.bson.types.ObjectId) ConnectionClosedEvent(com.mongodb.event.ConnectionClosedEvent) ConnectionCheckOutFailedEvent(com.mongodb.event.ConnectionCheckOutFailedEvent)

Aggregations

ConnectionPoolClearedEvent (com.mongodb.event.ConnectionPoolClearedEvent)4 ClusterFixture (com.mongodb.ClusterFixture)2 MongoInterruptedException (com.mongodb.MongoInterruptedException)2 ConnectionCheckOutFailedEvent (com.mongodb.event.ConnectionCheckOutFailedEvent)2 ConnectionClosedEvent (com.mongodb.event.ConnectionClosedEvent)2 ConnectionPoolReadyEvent (com.mongodb.event.ConnectionPoolReadyEvent)2 ServerListener (com.mongodb.event.ServerListener)2 Nullable (com.mongodb.lang.Nullable)2 String.format (java.lang.String.format)2 ArrayList (java.util.ArrayList)2 BsonDocument (org.bson.BsonDocument)2 ObjectId (org.bson.types.ObjectId)2 Block (com.mongodb.Block)1 ClusterFixture.configureFailPoint (com.mongodb.ClusterFixture.configureFailPoint)1 ClusterFixture.disableFailPoint (com.mongodb.ClusterFixture.disableFailPoint)1 ClusterFixture.isServerlessTest (com.mongodb.ClusterFixture.isServerlessTest)1 ClusterFixture.isStandalone (com.mongodb.ClusterFixture.isStandalone)1 ClusterFixture.serverVersionAtLeast (com.mongodb.ClusterFixture.serverVersionAtLeast)1 JsonTestServerVersionChecker (com.mongodb.JsonTestServerVersionChecker)1 MongoClientSettings (com.mongodb.MongoClientSettings)1