Search in sources :

Example 1 with ConnectionCheckOutStartedEvent

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

the class DefaultConnectionPool method getAsync.

@Override
public void getAsync(final SingleResultCallback<InternalConnection> callback) {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace(format("Asynchronously getting a connection from the pool for server %s", serverId));
    }
    connectionPoolListener.connectionCheckOutStarted(new ConnectionCheckOutStartedEvent(serverId));
    Timeout timeout = Timeout.startNow(settings.getMaxWaitTime(NANOSECONDS));
    SingleResultCallback<InternalConnection> eventSendingCallback = (result, failure) -> {
        SingleResultCallback<InternalConnection> errHandlingCallback = errorHandlingCallback(callback, LOGGER);
        if (failure == null) {
            connectionPoolListener.connectionCheckedOut(new ConnectionCheckedOutEvent(getId(result)));
            errHandlingCallback.onResult(result, null);
        } else {
            errHandlingCallback.onResult(null, checkOutFailed(failure));
        }
    };
    try {
        stateAndGeneration.throwIfClosedOrPaused();
    } catch (RuntimeException e) {
        eventSendingCallback.onResult(null, e);
        return;
    }
    asyncWorkManager.enqueue(new Task(timeout, t -> {
        if (t != null) {
            eventSendingCallback.onResult(null, t);
        } else {
            PooledConnection connection;
            try {
                connection = getPooledConnection(timeout);
            } catch (RuntimeException e) {
                eventSendingCallback.onResult(null, e);
                return;
            }
            if (connection.opened()) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(format("Pooled connection %s to server %s is already open", getId(connection), serverId));
                }
                eventSendingCallback.onResult(connection, null);
            } else {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(format("Pooled connection %s to server %s is not yet open", getId(connection), serverId));
                }
                openConcurrencyLimiter.openAsyncWithConcurrencyLimit(connection, timeout, eventSendingCallback);
            }
        }
    }));
}
Also used : SdamIssue(com.mongodb.internal.connection.SdamServerDescriptionManager.SdamIssue) ServerDescription(com.mongodb.connection.ServerDescription) ConcurrentPool.lockUnfair(com.mongodb.internal.connection.ConcurrentPool.lockUnfair) ConnectionPoolCreatedEvent(com.mongodb.event.ConnectionPoolCreatedEvent) ConnectionDescription(com.mongodb.connection.ConnectionDescription) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentPool.sizeToString(com.mongodb.internal.connection.ConcurrentPool.sizeToString) MongoServerUnavailableException(com.mongodb.MongoServerUnavailableException) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Prune(com.mongodb.internal.connection.ConcurrentPool.Prune) MongoException(com.mongodb.MongoException) Predicate(java.util.function.Predicate) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) BlockingQueue(java.util.concurrent.BlockingQueue) Assertions.assertFalse(com.mongodb.assertions.Assertions.assertFalse) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) Decoder(org.bson.codecs.Decoder) PRIVATE(com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE) List(java.util.List) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) NonNull(com.mongodb.lang.NonNull) Assertions.fail(com.mongodb.assertions.Assertions.fail) Optional(java.util.Optional) ThreadSafe(com.mongodb.annotations.ThreadSafe) Reason(com.mongodb.event.ConnectionCheckOutFailedEvent.Reason) Queue(java.util.Queue) ConnectionClosedEvent(com.mongodb.event.ConnectionClosedEvent) NotThreadSafe(com.mongodb.annotations.NotThreadSafe) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) LongAdder(java.util.concurrent.atomic.LongAdder) ConnectionCheckedInEvent(com.mongodb.event.ConnectionCheckedInEvent) Assertions.assertNotNull(com.mongodb.assertions.Assertions.assertNotNull) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) ErrorHandlingResultCallback.errorHandlingCallback(com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Deque(java.util.Deque) ConcurrentPool.lockInterruptibly(com.mongodb.internal.connection.ConcurrentPool.lockInterruptibly) Supplier(java.util.function.Supplier) INFINITE_SIZE(com.mongodb.internal.connection.ConcurrentPool.INFINITE_SIZE) Assertions.isTrue(com.mongodb.assertions.Assertions.isTrue) MongoConnectionPoolClearedException(com.mongodb.MongoConnectionPoolClearedException) VisibleForTesting(com.mongodb.internal.VisibleForTesting) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) SessionContext(com.mongodb.internal.session.SessionContext) ConnectionCreatedEvent(com.mongodb.event.ConnectionCreatedEvent) LinkedList(java.util.LinkedList) Logger(com.mongodb.diagnostics.logging.Logger) ExecutorService(java.util.concurrent.ExecutorService) ConnectionReadyEvent(com.mongodb.event.ConnectionReadyEvent) ByteBuf(org.bson.ByteBuf) MongoInterruptedException(com.mongodb.MongoInterruptedException) ConnectionPoolListener(com.mongodb.event.ConnectionPoolListener) ReentrantLock(java.util.concurrent.locks.ReentrantLock) EventListenerHelper.getConnectionPoolListener(com.mongodb.internal.event.EventListenerHelper.getConnectionPoolListener) ServerId(com.mongodb.connection.ServerId) RequestContext(com.mongodb.RequestContext) Timeout(com.mongodb.internal.Timeout) MongoTimeoutException(com.mongodb.MongoTimeoutException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ConnectionPoolClosedEvent(com.mongodb.event.ConnectionPoolClosedEvent) OptionalProvider(com.mongodb.internal.inject.OptionalProvider) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) Condition(java.util.concurrent.locks.Condition) Lock(java.util.concurrent.locks.Lock) Assertions.assertNull(com.mongodb.assertions.Assertions.assertNull) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent) Assertions.assertTrue(com.mongodb.assertions.Assertions.assertTrue) Loggers(com.mongodb.diagnostics.logging.Loggers) DaemonThreadFactory(com.mongodb.internal.thread.DaemonThreadFactory) ObjectId(org.bson.types.ObjectId) Nullable(com.mongodb.lang.Nullable) ConnectionId(com.mongodb.connection.ConnectionId) ConnectionCheckOutFailedEvent(com.mongodb.event.ConnectionCheckOutFailedEvent) StampedLock(java.util.concurrent.locks.StampedLock) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) Timeout(com.mongodb.internal.Timeout) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent)

Example 2 with ConnectionCheckOutStartedEvent

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

the class DefaultConnectionPool method get.

@Override
public InternalConnection get(final long timeoutValue, final TimeUnit timeUnit) {
    connectionPoolListener.connectionCheckOutStarted(new ConnectionCheckOutStartedEvent(serverId));
    Timeout timeout = Timeout.startNow(timeoutValue, timeUnit);
    try {
        stateAndGeneration.throwIfClosedOrPaused();
        PooledConnection connection = getPooledConnection(timeout);
        if (!connection.opened()) {
            connection = openConcurrencyLimiter.openOrGetAvailable(connection, timeout);
        }
        connectionPoolListener.connectionCheckedOut(new ConnectionCheckedOutEvent(getId(connection)));
        return connection;
    } catch (RuntimeException e) {
        throw (RuntimeException) checkOutFailed(e);
    }
}
Also used : ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) Timeout(com.mongodb.internal.Timeout) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent)

Example 3 with ConnectionCheckOutStartedEvent

use of com.mongodb.event.ConnectionCheckOutStartedEvent 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)

Aggregations

ConnectionCheckOutStartedEvent (com.mongodb.event.ConnectionCheckOutStartedEvent)3 ConnectionCheckedOutEvent (com.mongodb.event.ConnectionCheckedOutEvent)3 MongoInterruptedException (com.mongodb.MongoInterruptedException)2 MongoTimeoutException (com.mongodb.MongoTimeoutException)2 Assertions.assertFalse (com.mongodb.assertions.Assertions.assertFalse)2 ConnectionId (com.mongodb.connection.ConnectionId)2 ConnectionPoolSettings (com.mongodb.connection.ConnectionPoolSettings)2 ServerId (com.mongodb.connection.ServerId)2 ConnectionCheckOutFailedEvent (com.mongodb.event.ConnectionCheckOutFailedEvent)2 ConnectionCheckedInEvent (com.mongodb.event.ConnectionCheckedInEvent)2 ConnectionClosedEvent (com.mongodb.event.ConnectionClosedEvent)2 ConnectionCreatedEvent (com.mongodb.event.ConnectionCreatedEvent)2 ConnectionPoolClearedEvent (com.mongodb.event.ConnectionPoolClearedEvent)2 ConnectionPoolClosedEvent (com.mongodb.event.ConnectionPoolClosedEvent)2 ConnectionPoolCreatedEvent (com.mongodb.event.ConnectionPoolCreatedEvent)2 ConnectionPoolReadyEvent (com.mongodb.event.ConnectionPoolReadyEvent)2 ConnectionReadyEvent (com.mongodb.event.ConnectionReadyEvent)2 Timeout (com.mongodb.internal.Timeout)2 SingleResultCallback (com.mongodb.internal.async.SingleResultCallback)2 ClusterFixture (com.mongodb.ClusterFixture)1