Search in sources :

Example 1 with ServerId

use of com.mongodb.connection.ServerId 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 ServerId

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

the class DefaultClusterableServerFactory method create.

@Override
public ClusterableServer create(final Cluster cluster, final ServerAddress serverAddress) {
    ServerId serverId = new ServerId(cluster.getClusterId(), serverAddress);
    ClusterConnectionMode clusterMode = cluster.getSettings().getMode();
    SameObjectProvider<SdamServerDescriptionManager> sdamProvider = SameObjectProvider.uninitialized();
    ServerMonitor serverMonitor = new DefaultServerMonitor(serverId, serverSettings, cluster.getClock(), // no credentials, compressor list, or command listener for the server monitor factory
    new InternalStreamConnectionFactory(clusterMode, heartbeatStreamFactory, null, applicationName, mongoDriverInformation, emptyList(), null, serverApi), clusterMode, serverApi, sdamProvider);
    ConnectionPool connectionPool = new DefaultConnectionPool(serverId, new InternalStreamConnectionFactory(clusterMode, streamFactory, credential, applicationName, mongoDriverInformation, compressorList, commandListener, serverApi), connectionPoolSettings, internalConnectionPoolSettings, sdamProvider);
    ServerListener serverListener = singleServerListener(serverSettings);
    SdamServerDescriptionManager sdam = new DefaultSdamServerDescriptionManager(cluster, serverId, serverListener, serverMonitor, connectionPool, clusterMode);
    sdamProvider.initialize(sdam);
    serverMonitor.start();
    return new DefaultServer(serverId, clusterMode, connectionPool, new DefaultConnectionFactory(), serverMonitor, sdam, serverListener, commandListener, cluster.getClock(), true);
}
Also used : ClusterConnectionMode(com.mongodb.connection.ClusterConnectionMode) ServerId(com.mongodb.connection.ServerId) EventListenerHelper.singleServerListener(com.mongodb.internal.event.EventListenerHelper.singleServerListener) ServerListener(com.mongodb.event.ServerListener)

Example 3 with ServerId

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

the class LoadBalancedClusterableServerFactory method create.

@Override
public ClusterableServer create(final Cluster cluster, final ServerAddress serverAddress) {
    ConnectionPool connectionPool = new DefaultConnectionPool(new ServerId(cluster.getClusterId(), serverAddress), new InternalStreamConnectionFactory(ClusterConnectionMode.LOAD_BALANCED, streamFactory, credential, applicationName, mongoDriverInformation, compressorList, commandListener, serverApi), connectionPoolSettings, internalConnectionPoolSettings, EmptyProvider.instance());
    connectionPool.ready();
    return new LoadBalancedServer(new ServerId(cluster.getClusterId(), serverAddress), connectionPool, new DefaultConnectionFactory(), singleServerListener(serverSettings), cluster.getClock());
}
Also used : ServerId(com.mongodb.connection.ServerId)

Example 4 with ServerId

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

the class AbstractConnectionPoolTest method setUp.

@Before
public void setUp() {
    assumeFalse(skipTest);
    ConnectionPoolSettings.Builder settingsBuilder = ConnectionPoolSettings.builder();
    BsonDocument poolOptions = definition.getDocument("poolOptions", new BsonDocument());
    if (poolOptions.containsKey("maxPoolSize")) {
        settingsBuilder.maxSize(poolOptions.getNumber("maxPoolSize").intValue());
    }
    if (poolOptions.containsKey("minPoolSize")) {
        settingsBuilder.minSize(poolOptions.getNumber("minPoolSize").intValue());
    }
    if (poolOptions.containsKey("maxIdleTimeMS")) {
        settingsBuilder.maxConnectionIdleTime(poolOptions.getNumber("maxIdleTimeMS").intValue(), TimeUnit.MILLISECONDS);
    }
    if (poolOptions.containsKey("waitQueueTimeoutMS")) {
        settingsBuilder.maxWaitTime(poolOptions.getNumber("waitQueueTimeoutMS").intValue(), TimeUnit.MILLISECONDS);
    }
    if (poolOptions.containsKey("backgroundThreadIntervalMS")) {
        long intervalMillis = poolOptions.getNumber("backgroundThreadIntervalMS").longValue();
        assertFalse(intervalMillis == 0);
        if (intervalMillis < 0) {
            settingsBuilder.maintenanceInitialDelay(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
        } else {
            /* Using frequency/period instead of an interval as required by the specification is incorrect, for example,
                 * because it opens up a possibility to run the background thread non-stop if runs are as long as or longer than the period.
                 * Nevertheless, I am reusing what we already have in the driver instead of clogging up the implementation. */
            settingsBuilder.maintenanceFrequency(poolOptions.getNumber("backgroundThreadIntervalMS").longValue(), TimeUnit.MILLISECONDS);
        }
    }
    if (poolOptions.containsKey("maxConnecting")) {
        settingsBuilder.maxConnecting(poolOptions.getInt32("maxConnecting").intValue());
    }
    listener = new TestConnectionPoolListener();
    settingsBuilder.addConnectionPoolListener(listener);
    settings = settingsBuilder.build();
    InternalConnectionPoolSettings internalSettings = InternalConnectionPoolSettings.builder().prestartAsyncWorkManager(PRESTART_POOL_ASYNC_WORK_MANAGER_FILE_NAMES.contains(fileName)).build();
    Style style = Style.of(definition.getString("style").getValue());
    switch(style) {
        case UNIT:
            {
                ServerId serverId = new ServerId(new ClusterId(), new ServerAddress("host1"));
                pool = new DefaultConnectionPool(serverId, new TestInternalConnectionFactory(), settings, internalSettings, SameObjectProvider.initialized(mock(SdamServerDescriptionManager.class)));
                break;
            }
        case INTEGRATION:
            {
                ServerId serverId = new ServerId(new ClusterId(), ClusterFixture.getPrimary());
                ClusterConnectionMode connectionMode = ClusterConnectionMode.MULTIPLE;
                SameObjectProvider<SdamServerDescriptionManager> sdamProvider = SameObjectProvider.uninitialized();
                pool = new ConnectionIdAdjustingConnectionPool(new DefaultConnectionPool(serverId, new InternalStreamConnectionFactory(connectionMode, createStreamFactory(SocketSettings.builder().build(), ClusterFixture.getSslSettings()), ClusterFixture.getCredentialWithCache(), poolOptions.getString("appName", new BsonString(fileName + ": " + description)).getValue(), MongoDriverInformation.builder().build(), Collections.emptyList(), new TestCommandListener(), ClusterFixture.getServerApi()), settings, internalSettings, sdamProvider));
                sdamProvider.initialize(new DefaultSdamServerDescriptionManager(mockedCluster(), serverId, mock(ServerListener.class), mock(ServerMonitor.class), pool, connectionMode));
                setFailPoint();
                break;
            }
        default:
            {
                throw new AssertionError(format("Style %s is not implemented", style));
            }
    }
    if (internalSettings.isPrestartAsyncWorkManager()) {
        waitForPoolAsyncWorkManagerStart();
    }
}
Also used : ClusterId(com.mongodb.connection.ClusterId) ServerAddress(com.mongodb.ServerAddress) SameObjectProvider(com.mongodb.internal.inject.SameObjectProvider) ClusterConnectionMode(com.mongodb.connection.ClusterConnectionMode) ServerId(com.mongodb.connection.ServerId) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) ServerListener(com.mongodb.event.ServerListener) Before(org.junit.Before)

Example 5 with ServerId

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

the class AsynchronousClusterEventListenerTest method testEventsPublished.

@Test
public void testEventsPublished() throws InterruptedException {
    AllClusterEventListener targetListener = new AllClusterEventListener();
    ClusterId clusterId = new ClusterId();
    ServerId serverId = new ServerId(clusterId, new ServerAddress());
    ConnectionId connectionId = new ConnectionId(serverId);
    AsynchronousClusterEventListener listener = AsynchronousClusterEventListener.startNew(clusterId, targetListener, targetListener, targetListener);
    ClusterOpeningEvent clusterOpeningEvent = new ClusterOpeningEvent(clusterId);
    listener.clusterOpening(clusterOpeningEvent);
    assertEquals(clusterOpeningEvent, targetListener.take());
    ClusterDescriptionChangedEvent clusterDescriptionChangedEvent = new ClusterDescriptionChangedEvent(clusterId, new ClusterDescription(ClusterConnectionMode.SINGLE, ClusterType.STANDALONE, Collections.emptyList()), new ClusterDescription(ClusterConnectionMode.SINGLE, ClusterType.STANDALONE, Collections.emptyList()));
    listener.clusterDescriptionChanged(clusterDescriptionChangedEvent);
    assertEquals(clusterDescriptionChangedEvent, targetListener.take());
    ServerHeartbeatStartedEvent serverHeartbeatStartedEvent = new ServerHeartbeatStartedEvent(connectionId);
    listener.serverHearbeatStarted(serverHeartbeatStartedEvent);
    assertEquals(serverHeartbeatStartedEvent, targetListener.take());
    ServerHeartbeatSucceededEvent serverHeartbeatSucceededEvent = new ServerHeartbeatSucceededEvent(connectionId, new BsonDocument(), 1, true);
    listener.serverHeartbeatSucceeded(serverHeartbeatSucceededEvent);
    assertEquals(serverHeartbeatSucceededEvent, targetListener.take());
    ServerHeartbeatFailedEvent serverHeartbeatFailedEvent = new ServerHeartbeatFailedEvent(connectionId, 1, true, new IOException());
    listener.serverHeartbeatFailed(serverHeartbeatFailedEvent);
    assertEquals(serverHeartbeatFailedEvent, targetListener.take());
    ServerOpeningEvent serverOpeningEvent = new ServerOpeningEvent(serverId);
    listener.serverOpening(serverOpeningEvent);
    assertEquals(serverOpeningEvent, targetListener.take());
    ServerDescriptionChangedEvent serverDescriptionChangedEvent = new ServerDescriptionChangedEvent(serverId, ServerDescription.builder().address(new ServerAddress()).type(UNKNOWN).state(CONNECTING).build(), ServerDescription.builder().address(new ServerAddress()).type(STANDALONE).state(CONNECTED).build());
    listener.serverDescriptionChanged(serverDescriptionChangedEvent);
    assertEquals(serverDescriptionChangedEvent, targetListener.take());
    ServerClosedEvent serverClosedEvent = new ServerClosedEvent(serverId);
    listener.serverClosed(serverClosedEvent);
    assertEquals(serverClosedEvent, targetListener.take());
    ClusterClosedEvent clusterClosedEvent = new ClusterClosedEvent(clusterId);
    listener.clusterClosed(clusterClosedEvent);
    assertEquals(clusterClosedEvent, targetListener.take());
    // The thread should die after publishing the ClusterClosedEvent
    listener.getPublishingThread().join(5000);
}
Also used : ClusterId(com.mongodb.connection.ClusterId) ServerHeartbeatFailedEvent(com.mongodb.event.ServerHeartbeatFailedEvent) ServerAddress(com.mongodb.ServerAddress) ServerHeartbeatStartedEvent(com.mongodb.event.ServerHeartbeatStartedEvent) IOException(java.io.IOException) ServerHeartbeatSucceededEvent(com.mongodb.event.ServerHeartbeatSucceededEvent) ServerClosedEvent(com.mongodb.event.ServerClosedEvent) ServerDescriptionChangedEvent(com.mongodb.event.ServerDescriptionChangedEvent) ConnectionId(com.mongodb.connection.ConnectionId) ClusterClosedEvent(com.mongodb.event.ClusterClosedEvent) ServerId(com.mongodb.connection.ServerId) ClusterDescriptionChangedEvent(com.mongodb.event.ClusterDescriptionChangedEvent) BsonDocument(org.bson.BsonDocument) ServerOpeningEvent(com.mongodb.event.ServerOpeningEvent) ClusterDescription(com.mongodb.connection.ClusterDescription) ClusterOpeningEvent(com.mongodb.event.ClusterOpeningEvent) Test(org.junit.jupiter.api.Test)

Aggregations

ServerId (com.mongodb.connection.ServerId)13 ServerAddress (com.mongodb.ServerAddress)9 ClusterId (com.mongodb.connection.ClusterId)8 ConnectionDescription (com.mongodb.connection.ConnectionDescription)7 Before (org.junit.Before)6 ConnectionId (com.mongodb.connection.ConnectionId)4 ConnectionPoolSettings (com.mongodb.connection.ConnectionPoolSettings)3 ServerListener (com.mongodb.event.ServerListener)3 MongoConnectionPoolClearedException (com.mongodb.MongoConnectionPoolClearedException)2 MongoServerUnavailableException (com.mongodb.MongoServerUnavailableException)2 ClusterConnectionMode (com.mongodb.connection.ClusterConnectionMode)2 ClusterDescriptionChangedEvent (com.mongodb.event.ClusterDescriptionChangedEvent)2 ClusterOpeningEvent (com.mongodb.event.ClusterOpeningEvent)2 ConnectionCreatedEvent (com.mongodb.event.ConnectionCreatedEvent)2 BsonDocument (org.bson.BsonDocument)2 MongoCredential (com.mongodb.MongoCredential)1 MongoException (com.mongodb.MongoException)1 MongoInterruptedException (com.mongodb.MongoInterruptedException)1 MongoTimeoutException (com.mongodb.MongoTimeoutException)1 RequestContext (com.mongodb.RequestContext)1