diff --git a/driver-core/build.gradle.kts b/driver-core/build.gradle.kts index ff67aa67d56..5dfe4f17322 100644 --- a/driver-core/build.gradle.kts +++ b/driver-core/build.gradle.kts @@ -63,6 +63,7 @@ dependencies { testImplementation(libs.reflections) // Tracing testing + testImplementation(libs.micrometer.observation.test) testImplementation(platform(libs.micrometer.tracing.integration.test.bom)) testImplementation(libs.micrometer.tracing.integration.test) { exclude(group = "org.junit.jupiter") } diff --git a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java index e9dfccc3388..73b28beedb8 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -41,6 +41,7 @@ import com.mongodb.internal.logging.LogMessage; import com.mongodb.internal.logging.LogMessage.Entry; import com.mongodb.internal.logging.StructuredLogger; +import com.mongodb.internal.observability.micrometer.Span; import com.mongodb.internal.selector.AtMostTwoRandomServerSelector; import com.mongodb.internal.selector.LatencyMinimizingServerSelector; import com.mongodb.internal.selector.MinimumOperationCountServerSelector; @@ -555,25 +556,26 @@ static void logServerSelectionStarted( final ServerSelector serverSelector, final ClusterDescription clusterDescription) { if (STRUCTURED_LOGGER.isRequired(DEBUG, clusterId)) { - STRUCTURED_LOGGER.log(new LogMessage( + LogMessage logMessage = new LogMessage( SERVER_SELECTION, DEBUG, "Server selection started", clusterId, asList( new Entry(OPERATION, operationContext.getOperationName()), new Entry(OPERATION_ID, operationContext.getId()), new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), - "Server selection started for operation[ {}] with ID {}. Selector: {}, topology description: {}")); + "Server selection started for operation[ {}] with ID {}. Selector: {}, topology description: {}"); + Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } - private static void logServerSelectionWaiting( + static void logServerSelectionWaiting( final OperationContext operationContext, final ClusterId clusterId, final Timeout timeout, final ServerSelector serverSelector, final ClusterDescription clusterDescription) { if (STRUCTURED_LOGGER.isRequired(INFO, clusterId)) { - STRUCTURED_LOGGER.log(new LogMessage( + LogMessage logMessage = new LogMessage( SERVER_SELECTION, INFO, "Waiting for suitable server to become available", clusterId, asList( new Entry(OPERATION, operationContext.getOperationName()), @@ -585,11 +587,12 @@ private static void logServerSelectionWaiting( new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), "Waiting for server to become available for operation[ {}] with ID {}.[ Remaining time: {} ms.]" - + " Selector: {}, topology description: {}.")); + + " Selector: {}, topology description: {}."); + Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } - private static void logServerSelectionFailed( + static void logServerSelectionFailed( final OperationContext operationContext, final ClusterId clusterId, final MongoException failure, @@ -602,7 +605,7 @@ private static void logServerSelectionFailed( // The logging spec requires us to avoid such duplication of information. ? MongoTimeoutException.class.getName() + ": Timed out while waiting for a suitable server" : failure.toString(); - STRUCTURED_LOGGER.log(new LogMessage( + LogMessage logMessage = new LogMessage( SERVER_SELECTION, DEBUG, "Server selection failed", clusterId, asList( new Entry(OPERATION, operationContext.getOperationName()), @@ -610,7 +613,8 @@ private static void logServerSelectionFailed( new Entry(FAILURE, failureDescription), new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), - "Server selection failed for operation[ {}] with ID {}. Failure: {}. Selector: {}, topology description: {}")); + "Server selection failed for operation[ {}] with ID {}. Failure: {}. Selector: {}, topology description: {}"); + Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } @@ -621,7 +625,7 @@ static void logServerSelectionSucceeded( final ServerSelector serverSelector, final ClusterDescription clusterDescription) { if (STRUCTURED_LOGGER.isRequired(DEBUG, clusterId)) { - STRUCTURED_LOGGER.log(new LogMessage( + LogMessage logMessage = new LogMessage( SERVER_SELECTION, DEBUG, "Server selection succeeded", clusterId, asList( new Entry(OPERATION, operationContext.getOperationName()), @@ -631,7 +635,8 @@ static void logServerSelectionSucceeded( new Entry(SELECTOR, serverSelector.toString()), new Entry(TOPOLOGY_DESCRIPTION, clusterDescription.getShortDescription())), "Server selection succeeded for operation[ {}] with ID {}. Selected server: {}[:{}]." - + " Selector: {}, topology description: {}")); + + " Selector: {}, topology description: {}"); + Span.runInScope(operationContext.getTracingSpan(), () -> STRUCTURED_LOGGER.log(logMessage)); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java index a0a8bbe6e2d..3e40e3ae631 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java @@ -52,6 +52,7 @@ import com.mongodb.internal.inject.OptionalProvider; import com.mongodb.internal.logging.LogMessage; import com.mongodb.internal.logging.StructuredLogger; +import com.mongodb.internal.observability.micrometer.Span; import com.mongodb.internal.thread.DaemonThreadFactory; import com.mongodb.internal.time.StartTime; import com.mongodb.internal.time.Timeout; @@ -273,11 +274,12 @@ private Throwable checkOutFailed(final Throwable t, final OperationContext opera ClusterId clusterId = serverId.getClusterId(); if (requiresLogging(clusterId)) { String message = "Checkout failed for connection to {}:{}. Reason: {}.[ Error: {}.] Duration: {} ms"; - List entries = createBasicEntries(); + final List entries = createBasicEntries(); entries.add(new LogMessage.Entry(REASON_DESCRIPTION, EventReasonMessageResolver.getMessage(reason))); entries.add(new LogMessage.Entry(ERROR_DESCRIPTION, reason == Reason.CONNECTION_ERROR ? result.toString() : null)); entries.add(new LogMessage.Entry(DURATION_MS, checkoutDuration.toMillis())); - logMessage("Connection checkout failed", clusterId, message, entries); + Span.runInScope(operationContext.getTracingSpan(), + () -> logMessage("Connection checkout failed", clusterId, message, entries)); } connectionPoolListener.connectionCheckOutFailed( new ConnectionCheckOutFailedEvent(serverId, operationContext.getId(), reason, checkoutDuration.toNanos())); @@ -565,11 +567,12 @@ private void connectionCheckedOut( ConnectionId connectionId = getId(connection); ClusterId clusterId = serverId.getClusterId(); if (requiresLogging(clusterId)) { - List entries = createBasicEntries(); + final List entries = createBasicEntries(); entries.add(new LogMessage.Entry(DRIVER_CONNECTION_ID, connectionId.getLocalValue())); entries.add(new LogMessage.Entry(DURATION_MS, checkoutDuration.toMillis())); - logMessage("Connection checked out", clusterId, - "Connection checked out: address={}:{}, driver-generated ID={}, duration={} ms", entries); + Span.runInScope(operationContext.getTracingSpan(), + () -> logMessage("Connection checked out", clusterId, + "Connection checked out: address={}:{}, driver-generated ID={}, duration={} ms", entries)); } connectionPoolListener.connectionCheckedOut( @@ -585,7 +588,10 @@ private void connectionCheckedOut( */ private StartTime connectionCheckoutStarted(final OperationContext operationContext) { StartTime checkoutStart = StartTime.now(); - logEventMessage("Connection checkout started", "Checkout started for connection to {}:{}"); + if (requiresLogging(serverId.getClusterId())) { + Span.runInScope(operationContext.getTracingSpan(), + () -> logEventMessage("Connection checkout started", "Checkout started for connection to {}:{}")); + } connectionPoolListener.connectionCheckOutStarted(new ConnectionCheckOutStartedEvent(serverId, operationContext.getId())); return checkoutStart; @@ -615,6 +621,8 @@ private class PooledConnection implements InternalConnection { private final AtomicBoolean isClosed = new AtomicBoolean(); private Connection.PinningMode pinningMode; private long operationId; + @Nullable + private Span operationSpan; PooledConnection(final UsageTrackingInternalConnection wrapped) { this.wrapped = notNull("wrapped", wrapped); @@ -630,6 +638,7 @@ public int getGeneration() { */ public void checkedOutForOperation(final OperationContext operationContext) { this.operationId = operationContext.getId(); + this.operationSpan = operationContext.getTracingSpan(); } @Override @@ -677,9 +686,11 @@ public void close() { private void connectionCheckedIn() { ConnectionId connectionId = getId(wrapped); - logEventMessage("Connection checked in", - "Connection checked in: address={}:{}, driver-generated ID={}", - connectionId.getLocalValue()); + if (requiresLogging(serverId.getClusterId())) { + Span.runInScope(operationSpan, () -> logEventMessage("Connection checked in", + "Connection checked in: address={}:{}, driver-generated ID={}", + connectionId.getLocalValue())); + } connectionPoolListener.connectionCheckedIn(new ConnectionCheckedInEvent(connectionId, operationId)); } diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index bdeba4211a4..ff844e8d14a 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -51,6 +51,8 @@ import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.internal.logging.StructuredLogger; import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; +import com.mongodb.internal.observability.micrometer.TracingManager; import com.mongodb.internal.session.SessionContext; import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; @@ -93,6 +95,7 @@ import static com.mongodb.internal.connection.ProtocolHelper.createSpecialWriteConcernException; import static com.mongodb.internal.connection.ProtocolHelper.getClusterTime; import static com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException; +import static com.mongodb.internal.connection.ProtocolHelper.getCursorId; import static com.mongodb.internal.connection.ProtocolHelper.getMessageSettings; import static com.mongodb.internal.connection.ProtocolHelper.getOperationTime; import static com.mongodb.internal.connection.ProtocolHelper.getRecoveryToken; @@ -452,6 +455,7 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder final OperationContext operationContext) { CommandEventSender commandEventSender = new NoOpCommandEventSender(); Span tracingSpan = null; + SpanScope tracingScope = SpanScope.NO_OP; try (ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(this)) { tracingSpan = operationContext .getTracingManager() @@ -471,6 +475,13 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder if (isLoggingCommandNeeded || isTracingCommandPayloadNeeded) { commandDocument = message.getCommandDocument(bsonOutput); } + if (isTracingCommandPayloadNeeded) { + tracingSpan.setQueryText(commandDocument); + } + // Open the scope before the started event so command listeners and logs observe the command span. + if (tracingSpan != null) { + tracingScope = tracingSpan.openScope(); + } if (isLoggingCommandNeeded) { commandEventSender = new LoggingCommandEventSender( SECURITY_SENSITIVE_COMMANDS, SECURITY_SENSITIVE_HELLO_COMMANDS, description, commandListener, @@ -478,29 +489,26 @@ private T sendAndReceiveInternal(final CommandMessage message, final Decoder COMMAND_PROTOCOL_LOGGER, loggerSettings); commandEventSender.sendStartedEvent(); } - if (isTracingCommandPayloadNeeded) { - tracingSpan.setQueryText(commandDocument); - } - if (tracingSpan != null) { - tracingSpan.openScope(); - } sendCommandMessage(message, bsonOutput, operationContext); } catch (Throwable t) { - if (tracingSpan != null) { - tracingSpan.error(t); - tracingSpan.closeScope(); - tracingSpan.end(); + try { + commandEventSender.sendFailedEvent(t); + } finally { + if (tracingSpan != null) { + tracingSpan.error(t); + tracingScope.close(); + tracingSpan.end(); + } } - commandEventSender.sendFailedEvent(t); throw t; } if (message.isResponseExpected()) { - return receiveCommandMessageResponse(decoder, commandEventSender, operationContext, tracingSpan); + return receiveCommandMessageResponse(decoder, commandEventSender, operationContext, tracingSpan, tracingScope); } else { commandEventSender.sendSucceededEventForOneWayCommand(); if (tracingSpan != null) { - tracingSpan.closeScope(); + tracingScope.close(); tracingSpan.end(); } return null; @@ -522,7 +530,7 @@ public void send(final CommandMessage message, final Decoder decoder, fin @Override public T receive(final Decoder decoder, final OperationContext operationContext) { isTrue("Response is expected", hasMoreToCome); - return receiveCommandMessageResponse(decoder, new NoOpCommandEventSender(), operationContext, null); + return receiveCommandMessageResponse(decoder, new NoOpCommandEventSender(), operationContext, null, SpanScope.NO_OP); } @Override @@ -568,13 +576,13 @@ private void trySendMessage(final CommandMessage message, final ByteBufferBsonOu } private T receiveCommandMessageResponse(final Decoder decoder, final CommandEventSender commandEventSender, - final OperationContext operationContext, @Nullable final Span tracingSpan) { + final OperationContext operationContext, @Nullable final Span tracingSpan, final SpanScope tracingScope) { try { ResponseBuffers responseBuffers = receiveCommandResponseBuffers(commandEventSender, operationContext, tracingSpan); return processCommandResponse(decoder, responseBuffers, commandEventSender, operationContext, tracingSpan); } finally { if (tracingSpan != null) { - tracingSpan.closeScope(); + tracingScope.close(); tracingSpan.end(); } } @@ -613,6 +621,7 @@ private T processCommandResponse(final Decoder decoder, final ResponseBuf commandEventSender.sendSucceededEvent(responseBuffers); commandSuccessful = true; + recordCreatedCursorId(tracingSpan, operationContext, responseBuffers); T commandResult = getCommandResult(decoder, responseBuffers, responseTo, operationContext.getTimeoutContext()); hasMoreToCome = responseBuffers.getReplyHeader().hasMoreToCome(); @@ -630,6 +639,19 @@ private T processCommandResponse(final Decoder decoder, final ResponseBuf } } + /** + * A {@code getMore} span records the cursor id the driver sent, not the one returned, so only other commands are inspected. + */ + private static void recordCreatedCursorId(@Nullable final Span tracingSpan, final OperationContext operationContext, + final ResponseBuffers responseBuffers) { + if (tracingSpan != null) { + MongodbObservationContext ctx = tracingSpan.getMongodbObservationContext(); + if (ctx != null && !"getMore".equals(ctx.getCommandName())) { + TracingManager.setCreatedCursorId(tracingSpan, operationContext, getCursorId(responseBuffers)); + } + } + } + private void recordTracingError(@Nullable final Span tracingSpan, final Throwable t) { if (tracingSpan != null) { if (t instanceof MongoCommandException) { @@ -732,6 +754,9 @@ private void sendAndReceiveAsyncInternal(final CommandMessage message, final if (isTracingCommandPayloadNeeded) { tracingSpan.setQueryText(commandDocument); } + if (tracingSpan != null && isLoggingCommandNeeded) { + commandEventSender = new TracingScopedCommandEventSender(commandEventSender, tracingSpan); + } final Span commandSpan = tracingSpan; SingleResultCallback tracingCallback = commandSpan == null ? callback : (result, t) -> { @@ -755,7 +780,7 @@ private void sendAndReceiveAsyncInternal(final CommandMessage message, final Compressor localSendCompressor = sendCompressor; if (localSendCompressor == null || SECURITY_SENSITIVE_COMMANDS.contains(message.getCommandName())) { sendCommandMessageAsync(message.getId(), decoder, operationContext, tracingCallback, bsonOutput, commandEventSender, - message.isResponseExpected()); + message.isResponseExpected(), commandSpan); } else { List byteBuffers = bsonOutput.getByteBuffers(); try { @@ -767,7 +792,7 @@ private void sendAndReceiveAsyncInternal(final CommandMessage message, final bsonOutput.close(); } sendCommandMessageAsync(message.getId(), decoder, operationContext, tracingCallback, compressedBsonOutput, commandEventSender, - message.isResponseExpected()); + message.isResponseExpected(), commandSpan); } } catch (Throwable t) { bsonOutput.close(); @@ -782,7 +807,8 @@ private void sendAndReceiveAsyncInternal(final CommandMessage message, final private void sendCommandMessageAsync(final int messageId, final Decoder decoder, final OperationContext operationContext, final SingleResultCallback callback, final ByteBufferBsonOutput bsonOutput, - final CommandEventSender commandEventSender, final boolean responseExpected) { + final CommandEventSender commandEventSender, final boolean responseExpected, + @Nullable final Span tracingSpan) { boolean[] shouldReturn = {false}; Timeout.onExistsAndExpired(operationContext.getTimeoutContext().timeoutIncludingRoundTrip(), () -> { bsonOutput.close(); @@ -829,6 +855,7 @@ private void sendCommandMessageAsync(final int messageId, final Decoder d } commandEventSender.sendSucceededEvent(responseBuffers); commandSuccessful = true; + recordCreatedCursorId(tracingSpan, operationContext, responseBuffers); commandResult = getCommandResult(decoder, responseBuffers, messageId, operationContext.getTimeoutContext()); } catch (Throwable localThrowable) { diff --git a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java index cb8d0830dd1..f0d34a42377 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -31,6 +31,7 @@ import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.observability.micrometer.Span; import com.mongodb.internal.observability.micrometer.TracingManager; +import com.mongodb.internal.observability.micrometer.TransactionSpan; import com.mongodb.internal.operation.OperationHelper; import com.mongodb.internal.session.SessionContext; import com.mongodb.internal.thread.AsyncClientExecutor; @@ -66,6 +67,8 @@ public class OperationContext { private final AsyncClientExecutor clientExecutor; @Nullable private Span tracingSpan; + @Nullable + private TransactionSpan transactionSpan; @VisibleForTesting(otherwise = PRIVATE) public OperationContext(final RequestContext requestContext, final SessionContext sessionContext, final TimeoutContext timeoutContext, @@ -83,6 +86,7 @@ public OperationContext(final RequestContext requestContext, final SessionContex tracingManager, serverApi, operationName, + null, null); } @@ -97,6 +101,7 @@ public OperationContext(final RequestContext requestContext, final SessionContex tracingManager, serverApi, operationName, + null, null); } @@ -119,17 +124,17 @@ static OperationContext simpleOperationContext(final TimeoutSettings timeoutSett public OperationContext withSessionContext(final SessionContext sessionContext) { return new OperationContext(id, requestContext, sessionContext, timeoutContext, serverDeprioritization, clientExecutor, - tracingManager, serverApi, operationName, tracingSpan); + tracingManager, serverApi, operationName, tracingSpan, transactionSpan); } public OperationContext withTimeoutContext(final TimeoutContext timeoutContext) { return new OperationContext(id, requestContext, sessionContext, timeoutContext, serverDeprioritization, clientExecutor, - tracingManager, serverApi, operationName, tracingSpan); + tracingManager, serverApi, operationName, tracingSpan, transactionSpan); } public OperationContext withOperationName(final String operationName) { return new OperationContext(id, requestContext, sessionContext, timeoutContext, serverDeprioritization, clientExecutor, - tracingManager, serverApi, operationName, tracingSpan); + tracingManager, serverApi, operationName, tracingSpan, transactionSpan); } /** @@ -139,7 +144,7 @@ public OperationContext withOperationName(final String operationName) { public OperationContext withNewServerDeprioritization() { return new OperationContext(id, requestContext, sessionContext, timeoutContext, new ServerDeprioritization(serverDeprioritization.enableOverloadRetargeting), clientExecutor, - tracingManager, serverApi, operationName, tracingSpan); + tracingManager, serverApi, operationName, tracingSpan, transactionSpan); } public long getId() { @@ -185,6 +190,28 @@ public void setTracingSpan(final Span tracingSpan) { this.tracingSpan = tracingSpan; } + /** + * Returns a copy whose operation span is {@code tracingSpan}, for an operation the caller starts on a resource another + * operation created, such as a {@code getMore} on a cursor. + */ + public OperationContext withTracingSpan(@Nullable final Span tracingSpan) { + return new OperationContext(id, requestContext, sessionContext, timeoutContext, serverDeprioritization, clientExecutor, + tracingManager, serverApi, operationName, tracingSpan, transactionSpan); + } + + /** + * The transaction span the operation span was created under, or {@code null} if the operation is not part of a traced + * transaction. + */ + @Nullable + public TransactionSpan getTransactionSpan() { + return transactionSpan; + } + + public void setTransactionSpan(@Nullable final TransactionSpan transactionSpan) { + this.transactionSpan = transactionSpan; + } + private OperationContext(final long id, final RequestContext requestContext, final SessionContext sessionContext, @@ -194,7 +221,8 @@ private OperationContext(final long id, final TracingManager tracingManager, @Nullable final ServerApi serverApi, @Nullable final String operationName, - @Nullable final Span tracingSpan) { + @Nullable final Span tracingSpan, + @Nullable final TransactionSpan transactionSpan) { this.id = id; this.serverDeprioritization = serverDeprioritization; @@ -206,6 +234,7 @@ private OperationContext(final long id, this.serverApi = serverApi; this.operationName = operationName; this.tracingSpan = tracingSpan; + this.transactionSpan = transactionSpan; } /** diff --git a/driver-core/src/main/com/mongodb/internal/connection/ProtocolHelper.java b/driver-core/src/main/com/mongodb/internal/connection/ProtocolHelper.java index c6ad5f451a0..6cb64d3575c 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/ProtocolHelper.java +++ b/driver-core/src/main/com/mongodb/internal/connection/ProtocolHelper.java @@ -123,6 +123,14 @@ static BsonDocument getRecoveryToken(final ResponseBuffers responseBuffers) { return getFieldValueAsDocument(responseBuffers, "recoveryToken"); } + /** + * Returns the id of the cursor in the reply's {@code cursor} document, or {@code 0} if the reply has none. + */ + static long getCursorId(final ResponseBuffers responseBuffers) { + BsonValue cursorId = getNestedFieldValue(responseBuffers, "cursor", "id"); + return cursorId != null && cursorId.isInt64() ? cursorId.asInt64().getValue() : 0; + } + @SuppressWarnings("SameParameterValue") @Nullable private static BsonTimestamp getFieldValueAsTimestamp(final ResponseBuffers responseBuffers, final String fieldName) { diff --git a/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java b/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java new file mode 100644 index 00000000000..36e87fc81b4 --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/connection/TracingScopedCommandEventSender.java @@ -0,0 +1,64 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.connection; + +import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; + +/** + * A {@link CommandEventSender} for the asynchronous path that opens the command span's scope around each event, + * so command listeners and log appenders observe the command span on whichever thread emits the event. + * + *

This class is not part of the public API and may be removed or changed at any time

+ */ +final class TracingScopedCommandEventSender implements CommandEventSender { + private final CommandEventSender delegate; + private final Span span; + + TracingScopedCommandEventSender(final CommandEventSender delegate, final Span span) { + this.delegate = delegate; + this.span = span; + } + + @Override + public void sendStartedEvent() { + try (SpanScope ignored = span.openScope()) { + delegate.sendStartedEvent(); + } + } + + @Override + public void sendFailedEvent(final Throwable t) { + try (SpanScope ignored = span.openScope()) { + delegate.sendFailedEvent(t); + } + } + + @Override + public void sendSucceededEvent(final ResponseBuffers responseBuffers) { + try (SpanScope ignored = span.openScope()) { + delegate.sendSucceededEvent(responseBuffers); + } + } + + @Override + public void sendSucceededEventForOneWayCommand() { + try (SpanScope ignored = span.openScope()) { + delegate.sendSucceededEventForOneWayCommand(); + } + } +} diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java index 00338928f5b..c6d04286dbc 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/MicrometerTracer.java @@ -236,13 +236,11 @@ static String traceParent(final Observation observation) { /** * Represents a Micrometer-based span. */ - private static class MicrometerSpan implements Span { + static class MicrometerSpan implements Span { private final Observation observation; @Nullable private final MongoNamespace namespace; private final int queryTextLength; - @Nullable - private Observation.Scope scope; /** * Constructs a new {@link MicrometerSpan} instance with an associated Observation and MongoDB namespace. @@ -258,16 +256,9 @@ private static class MicrometerSpan implements Span { } @Override - public void openScope() { - this.scope = observation.openScope(); - } - - @Override - public void closeScope() { - if (scope != null) { - scope.close(); - scope = null; - } + public SpanScope openScope() { + Observation.Scope scope = observation.openScope(); + return scope::close; } @Override diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java index f0821f2375d..481b13cc1b2 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/Span.java @@ -47,11 +47,8 @@ public interface Span { */ Span EMPTY = new Span() { @Override - public void openScope() { - } - - @Override - public void closeScope() { + public SpanScope openScope() { + return SpanScope.NO_OP; } @Override @@ -89,17 +86,13 @@ public MongodbObservationContext getMongodbObservationContext() { }; /** - * Opens a scope for this span, making it the current observation on the thread. - * A successful {@code openScope()} must be followed by {@link #closeScope()}. - */ - void openScope(); - - /** - * Closes the scope previously opened by {@link #openScope()}, restoring the previous observation. - * Calling this without a prior {@code openScope()}, or more than once, is a no-op — error-handling - * paths may therefore call it unconditionally. + * Makes this span the current span on the calling thread until the returned scope is closed. Close it on the + * same thread, normally with try-with-resources. Scopes nest: closing the inner one restores the outer. + * Opening a scope after {@link #end()} is allowed. + * + * @return the scope, which must be closed on the calling thread */ - void closeScope(); + SpanScope openScope(); /** * Sets the query text on the observation context from the given command document. @@ -151,4 +144,22 @@ public MongodbObservationContext getMongodbObservationContext() { */ @Nullable MongoNamespace getNamespace(); + + /** + * Runs an action while the span's scope is open on the calling thread, so that anything that reads the current + * tracing context during the action (log appenders, MDC bridges, listeners) observes that span. The scope is + * closed even if the action throws. + * + * @param span the span to make current, or {@code null} to run the action without touching any scope + * @param action the action to run + */ + static void runInScope(@Nullable final Span span, final Runnable action) { + if (span == null) { + action.run(); + return; + } + try (SpanScope ignored = span.openScope()) { + action.run(); + } + } } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScope.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScope.java new file mode 100644 index 00000000000..662b02383ab --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/SpanScope.java @@ -0,0 +1,32 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.observability.micrometer; + +/** + * A handle to a scope opened by {@link Span#openScope()}; closing it restores the previously current span on the + * thread that opened it. + */ +public interface SpanScope extends AutoCloseable { + /** + * A scope that does nothing when closed. + */ + SpanScope NO_OP = () -> { + }; + + @Override + void close(); +} diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TracingManager.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TracingManager.java index d9500c8e5d8..fe20e0adf38 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TracingManager.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TracingManager.java @@ -34,6 +34,7 @@ import java.util.function.Predicate; import java.util.function.Supplier; +import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.observability.micrometer.MongodbObservation.MONGODB_COMMAND; import static com.mongodb.observability.micrometer.MongodbObservation.MONGODB_OPERATION; import static com.mongodb.observability.micrometer.MongodbObservation.MONGODB_TRANSACTION; @@ -278,6 +279,60 @@ public Span createOperationSpan(@Nullable final TransactionSpan transactionSpan, } operationContext.setTracingSpan(span); + operationContext.setTransactionSpan(transactionSpan); return span; } + + /** + * Creates the operation span for a {@code getMore} the caller drives on a cursor. + *

+ * The span is not nested under the operation span that created the cursor: it is parented on the transaction span the + * cursor was created under, if any, and otherwise on the current span of the application. It carries the id of the + * cursor the {@code getMore} operates on. + * + * @param cursorOperationContext the operation context of the cursor + * @param namespace the namespace of the cursor + * @param cursorId the id of the cursor the {@code getMore} is sent for + * @return the operation context to execute the {@code getMore} with, whose operation span is the created span + */ + public OperationContext createGetMoreOperationSpan(final OperationContext cursorOperationContext, final MongoNamespace namespace, + final long cursorId) { + if (!isEnabled()) { + return cursorOperationContext; + } + OperationContext operationContext = cursorOperationContext.withTracingSpan(null); + Span span = assertNotNull(createOperationSpan(cursorOperationContext.getTransactionSpan(), operationContext, "getMore", + namespace)); + MongodbObservationContext mongodbContext = span.getMongodbObservationContext(); + if (mongodbContext != null) { + mongodbContext.setCursorId(cursorId); + } + return operationContext; + } + + /** + * Records the id of the cursor a command created on its command span and on the operation span it is nested under. + * A cursor id of {@code 0} means no cursor remains open on the server, so it is not recorded. + * + * @param commandSpan the command span + * @param operationContext the operation context of the command + * @param cursorId the cursor id the server returned + */ + public static void setCreatedCursorId(final Span commandSpan, final OperationContext operationContext, final long cursorId) { + if (cursorId == 0) { + return; + } + setCursorId(commandSpan, cursorId); + Span operationSpan = operationContext.getTracingSpan(); + if (operationSpan != null) { + setCursorId(operationSpan, cursorId); + } + } + + private static void setCursorId(final Span span, final long cursorId) { + MongodbObservationContext mongodbContext = span.getMongodbObservationContext(); + if (mongodbContext != null) { + mongodbContext.setCursorId(cursorId); + } + } } diff --git a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java index 03a6301b02b..6b9de83c240 100644 --- a/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java +++ b/driver-core/src/main/com/mongodb/internal/observability/micrometer/TransactionSpan.java @@ -20,6 +20,9 @@ /** * State class for transaction tracing. + *

+ * Unlike operation and command spans, this span never opens a scope: operation spans started inside the + * transaction are parented on it through {@link #getContext()} instead, so it can be ended from any thread. * * @since 5.7 */ @@ -54,7 +57,6 @@ public void handleTransactionSpanError(final Throwable e) { } if (!isConvenientTransaction) { - span.closeScope(); span.end(); } } @@ -68,7 +70,6 @@ public void finalizeTransactionSpan(final String status) { span.event(status); // clear previous commit error if any if (!isConvenientTransaction) { - span.closeScope(); span.end(); } reportedError = null; // clear previous commit error if any @@ -84,7 +85,6 @@ public void spanFinalizing(final boolean cleanupTransactionContext) { if (reportedError != null) { span.error(reportedError); } - span.closeScope(); span.end(); reportedError = null; // Don't clean up transaction context if we're still retrying (we want the retries to fold under the original transaction span) @@ -112,12 +112,4 @@ public void setIsConvenientTransaction() { public TraceContext getContext() { return span.context(); } - - /** - * Opens a scope for the transaction span, making it the current observation on the thread. - * Must only be called from the sync driver where open and close happen on the same thread. - */ - public void openScope() { - span.openScope(); - } } diff --git a/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandCursor.java b/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandCursor.java index 6a4ef41a43e..c66b0810586 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandCursor.java @@ -35,6 +35,8 @@ import com.mongodb.internal.connection.AsyncConnection; import com.mongodb.internal.connection.Connection; import com.mongodb.internal.connection.OperationContext; +import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.TracingManager; import com.mongodb.internal.operation.AsyncOperationHelper.AsyncCallableConnectionWithCallback; import com.mongodb.internal.validator.NoOpFieldNameValidator; import com.mongodb.lang.Nullable; @@ -78,6 +80,11 @@ class AsyncCommandCursor implements AsyncCursor { private final boolean retryReads; @Nullable private final Integer maxAdaptiveRetriesSetting; + /** + * Whether the operation that creates this cursor iterates it to produce its own result, without exposing it to the caller. + * If so, its {@code getMore} commands nest under that operation's span instead of each getting an operation span. + */ + private final boolean iteratedByOperation; private int batchSize; private volatile CommandCursorResult commandCursorResult; @@ -90,6 +97,20 @@ class AsyncCommandCursor implements AsyncCursor { final AsyncConnection connection, final boolean retryReads, @Nullable final Integer maxAdaptiveRetriesSetting) { + this(commandCursorDocument, batchSize, decoder, comment, connectionSource, connection, retryReads, maxAdaptiveRetriesSetting, + false); + } + + AsyncCommandCursor( + final BsonDocument commandCursorDocument, + final int batchSize, + final Decoder decoder, + @Nullable final BsonValue comment, + final AsyncConnectionSource connectionSource, + final AsyncConnection connection, + final boolean retryReads, + @Nullable final Integer maxAdaptiveRetriesSetting, + final boolean iteratedByOperation) { ConnectionDescription connectionDescription = connection.getDescription(); this.commandCursorResult = toCommandCursorResult(connectionDescription.getServerAddress(), FIRST_BATCH, commandCursorDocument); this.namespace = commandCursorResult.getNamespace(); @@ -103,6 +124,7 @@ class AsyncCommandCursor implements AsyncCursor { resourceManager = new ResourceManager(namespace, connectionSource, connectionToPin, commandCursorResult.getServerCursor()); this.retryReads = retryReads; this.maxAdaptiveRetriesSetting = maxAdaptiveRetriesSetting; + this.iteratedByOperation = iteratedByOperation; } @Override @@ -191,7 +213,30 @@ private void getMoreLoop(final ServerCursor localServerCursor, }); } - private void getMore(final ServerCursor cursor, final OperationContext operationContext, final SingleResultCallback> callback) { + private void getMore(final ServerCursor cursor, final OperationContext cursorOperationContext, + final SingleResultCallback> callback) { + TracingManager tracingManager = cursorOperationContext.getTracingManager(); + if (!tracingManager.isEnabled() || iteratedByOperation) { + getMoreWithRetries(cursor, cursorOperationContext, callback); + return; + } + OperationContext operationContext = tracingManager.createGetMoreOperationSpan(cursorOperationContext, namespace, + cursor.getId()); + Span span = assertNotNull(operationContext.getTracingSpan()); + getMoreWithRetries(cursor, operationContext, (result, t) -> { + try { + if (t != null) { + span.error(t); + } + } finally { + span.end(); + callback.onResult(result, t); + } + }); + } + + private void getMoreWithRetries(final ServerCursor cursor, final OperationContext operationContext, + final SingleResultCallback> callback) { RetryControl retryControl = createSpecRetryControl( overloadForRead(retryReads, maxAdaptiveRetriesSetting), operationContext); AsyncCallbackSupplier> retryingCommandExecutor = decorateWithRetriesAsync(retryControl, operationContext, attemptCallback -> diff --git a/driver-core/src/main/com/mongodb/internal/operation/AsyncOperationHelper.java b/driver-core/src/main/com/mongodb/internal/operation/AsyncOperationHelper.java index bbce5a1010a..ccf53cfed9b 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AsyncOperationHelper.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AsyncOperationHelper.java @@ -392,8 +392,28 @@ static AsyncBatchCursor cursorDocumentToAsyncBatchCursor(final TimeoutMod final OperationContext operationContext, final boolean retryReads, @Nullable final Integer maxAdaptiveRetriesSetting) { + return cursorDocumentToAsyncBatchCursor(timeoutMode, cursorDocument, batchSize, decoder, comment, source, connection, + operationContext, retryReads, maxAdaptiveRetriesSetting, false); + } + + /** + * @param iteratedByOperation whether the operation creating the cursor iterates it to produce its own result, without + * exposing it to the caller + */ + static AsyncBatchCursor cursorDocumentToAsyncBatchCursor(final TimeoutMode timeoutMode, + final BsonDocument cursorDocument, + final int batchSize, + final Decoder decoder, + @Nullable final BsonValue comment, + final AsyncConnectionSource source, + final AsyncConnection connection, + final OperationContext operationContext, + final boolean retryReads, + @Nullable final Integer maxAdaptiveRetriesSetting, + final boolean iteratedByOperation) { return new AsyncCommandBatchCursor<>(timeoutMode, 0, operationContext, new AsyncCommandCursor<>( - cursorDocument, batchSize, decoder, comment, source, connection, retryReads, maxAdaptiveRetriesSetting + cursorDocument, batchSize, decoder, comment, source, connection, retryReads, maxAdaptiveRetriesSetting, + iteratedByOperation )); } diff --git a/driver-core/src/main/com/mongodb/internal/operation/ClientBulkWriteOperation.java b/driver-core/src/main/com/mongodb/internal/operation/ClientBulkWriteOperation.java index d60528d6e3e..702d490bd69 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ClientBulkWriteOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ClientBulkWriteOperation.java @@ -521,7 +521,8 @@ private List> exhaustBulkWriteCommandOkResponseCursor( connection, operationContext, retryReadsSetting, - maxAdaptiveRetriesSetting)) { + maxAdaptiveRetriesSetting, + true)) { return cursor.exhaust(); } @@ -544,7 +545,8 @@ private void exhaustBulkWriteCommandOkResponseCursorAsync( connection, operationContext, retryReadsSetting, - maxAdaptiveRetriesSetting); + maxAdaptiveRetriesSetting, + true); beginAsync().>>thenSupply(exhaustCallback -> { cursor.exhaust(exhaustCallback); diff --git a/driver-core/src/main/com/mongodb/internal/operation/CommandCursor.java b/driver-core/src/main/com/mongodb/internal/operation/CommandCursor.java index 75f4f3bbf8a..51db4a20293 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/CommandCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/CommandCursor.java @@ -32,6 +32,9 @@ import com.mongodb.internal.binding.ConnectionSource; import com.mongodb.internal.connection.Connection; import com.mongodb.internal.connection.OperationContext; +import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; +import com.mongodb.internal.observability.micrometer.TracingManager; import com.mongodb.internal.validator.NoOpFieldNameValidator; import com.mongodb.lang.Nullable; import org.bson.BsonDocument; @@ -72,6 +75,11 @@ class CommandCursor implements Cursor { private final boolean retryReads; @Nullable private final Integer maxAdaptiveRetriesSetting; + /** + * Whether the operation that creates this cursor iterates it to produce its own result, without exposing it to the caller. + * If so, its {@code getMore} commands nest under that operation's span instead of each getting an operation span. + */ + private final boolean iteratedByOperation; private int batchSize; private CommandCursorResult commandCursorResult; @@ -87,6 +95,20 @@ class CommandCursor implements Cursor { final Connection connection, final boolean retryReads, @Nullable final Integer maxAdaptiveRetriesSetting) { + this(commandCursorDocument, batchSize, decoder, comment, connectionSource, connection, retryReads, maxAdaptiveRetriesSetting, + false); + } + + CommandCursor( + final BsonDocument commandCursorDocument, + final int batchSize, + final Decoder decoder, + @Nullable final BsonValue comment, + final ConnectionSource connectionSource, + final Connection connection, + final boolean retryReads, + @Nullable final Integer maxAdaptiveRetriesSetting, + final boolean iteratedByOperation) { ConnectionDescription connectionDescription = connection.getDescription(); this.commandCursorResult = toCommandCursorResult(connectionDescription.getServerAddress(), FIRST_BATCH, commandCursorDocument); this.namespace = commandCursorResult.getNamespace(); @@ -100,6 +122,7 @@ class CommandCursor implements Cursor { resourceManager = new ResourceManager(namespace, connectionSource, connectionToPin, commandCursorResult.getServerCursor()); this.retryReads = retryReads; this.maxAdaptiveRetriesSetting = maxAdaptiveRetriesSetting; + this.iteratedByOperation = iteratedByOperation; } @Override @@ -230,8 +253,27 @@ public int getMaxWireVersion() { return maxWireVersion; } - private void getMore(final OperationContext operationContext) { + private void getMore(final OperationContext cursorOperationContext) { ServerCursor serverCursor = assertNotNull(resourceManager.getServerCursor()); + TracingManager tracingManager = cursorOperationContext.getTracingManager(); + if (!tracingManager.isEnabled() || iteratedByOperation) { + getMore(serverCursor, cursorOperationContext); + return; + } + OperationContext operationContext = tracingManager.createGetMoreOperationSpan(cursorOperationContext, namespace, + serverCursor.getId()); + Span span = assertNotNull(operationContext.getTracingSpan()); + try (SpanScope ignored = span.openScope()) { + getMore(serverCursor, operationContext); + } catch (RuntimeException e) { + span.error(e); + throw e; + } finally { + span.end(); + } + } + + private void getMore(final ServerCursor serverCursor, final OperationContext operationContext) { RetryControl retryControl = createSpecRetryControl( overloadForRead(retryReads, maxAdaptiveRetriesSetting), operationContext); Supplier retryingCommandExecutor = decorateWithRetries(retryControl, operationContext, () -> { diff --git a/driver-core/src/main/com/mongodb/internal/operation/SyncOperationHelper.java b/driver-core/src/main/com/mongodb/internal/operation/SyncOperationHelper.java index 08c5c1ce5ea..901cbfea44c 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/SyncOperationHelper.java +++ b/driver-core/src/main/com/mongodb/internal/operation/SyncOperationHelper.java @@ -388,8 +388,30 @@ static BatchCursor cursorDocumentToBatchCursor( final OperationContext operationContext, final boolean retryReads, @Nullable final Integer maxAdaptiveRetriesSetting) { + return cursorDocumentToBatchCursor(timeoutMode, cursorDocument, batchSize, decoder, comment, source, connection, + operationContext, retryReads, maxAdaptiveRetriesSetting, false); + } + + /** + * @param iteratedByOperation whether the operation creating the cursor iterates it to produce its own result, without + * exposing it to the caller + */ + static BatchCursor cursorDocumentToBatchCursor( + final TimeoutMode timeoutMode, + final BsonDocument cursorDocument, + final int batchSize, + final Decoder decoder, + @Nullable + final BsonValue comment, + final ConnectionSource source, + final Connection connection, + final OperationContext operationContext, + final boolean retryReads, + @Nullable final Integer maxAdaptiveRetriesSetting, + final boolean iteratedByOperation) { return new CommandBatchCursor<>(timeoutMode, 0, operationContext, new CommandCursor<>( - cursorDocument, batchSize, decoder, comment, source, connection, retryReads, maxAdaptiveRetriesSetting + cursorDocument, batchSize, decoder, comment, source, connection, retryReads, maxAdaptiveRetriesSetting, + iteratedByOperation )); } diff --git a/driver-core/src/main/com/mongodb/observability/micrometer/DefaultMongodbObservationConvention.java b/driver-core/src/main/com/mongodb/observability/micrometer/DefaultMongodbObservationConvention.java index a1e25dcbbfa..6fd78f5b3fb 100644 --- a/driver-core/src/main/com/mongodb/observability/micrometer/DefaultMongodbObservationConvention.java +++ b/driver-core/src/main/com/mongodb/observability/micrometer/DefaultMongodbObservationConvention.java @@ -73,6 +73,17 @@ public KeyValues getHighCardinalityKeyValues(final MongodbObservationContext con if (context.getObservationType() == MongodbObservation.MONGODB_COMMAND && context.isRecording()) { return getCommandHighCardinalityKeyValues(context); } + if (context.getObservationType() == MongodbObservation.MONGODB_OPERATION && context.isRecording()) { + return getOperationHighCardinalityKeyValues(context); + } + return KeyValues.empty(); + } + + private KeyValues getOperationHighCardinalityKeyValues(final MongodbObservationContext context) { + Long cursorId = context.getCursorId(); + if (cursorId != null) { + return KeyValues.of(MongodbObservation.HighCardinalityKeyNames.CURSOR_ID.withValue(String.valueOf(cursorId))); + } return KeyValues.empty(); } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java index e8d5c589e7c..8d2b43a755d 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTracingTest.java @@ -25,6 +25,7 @@ import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.connection.MessageSequences.EmptyMessageSequences; import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; import com.mongodb.internal.observability.micrometer.TraceContext; import com.mongodb.internal.observability.micrometer.TracingManager; import com.mongodb.internal.thread.AsyncClientExecutor; @@ -113,7 +114,7 @@ public ByteBuf read(final int numBytes, final OperationContext operationContext) /** * Verifies exactly-once span termination when the sync send fails: the widened {@code catch (Throwable)} - * must fire {@code error()}/{@code closeScope()}/{@code end()} once each, with no double-firing from the + * must fire {@code error()}/scope close/{@code end()} once each, with no double-firing from the * receive path (which is never reached). */ @Test @@ -338,13 +339,9 @@ private static final class RecordingSpan implements Span { private final AtomicInteger endCount = new AtomicInteger(); @Override - public void openScope() { + public SpanScope openScope() { openScopeCount.incrementAndGet(); - } - - @Override - public void closeScope() { - closeScopeCount.incrementAndGet(); + return closeScopeCount::incrementAndGet; } @Override diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTraceParentTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTraceParentTest.java index 8cb3a670d1e..ba52f047076 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTraceParentTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTraceParentTest.java @@ -136,7 +136,7 @@ protected Class loadClass(final String name, final boolean resolve) throws Cl Class spanInterface = Class.forName( "com.mongodb.internal.observability.micrometer.Span", true, isolatedLoader); - spanInterface.getMethod("openScope").invoke(span); + Object scope = spanInterface.getMethod("openScope").invoke(span); Object traceContext = assertDoesNotThrow(() -> spanInterface.getMethod("context").invoke(span), "obtaining the trace context must not throw when micrometer-tracing is absent"); @@ -149,7 +149,8 @@ protected Class loadClass(final String name, final boolean resolve) throws Cl assertNull(traceParent); - spanInterface.getMethod("closeScope").invoke(span); + Class.forName("com.mongodb.internal.observability.micrometer.SpanScope", true, isolatedLoader) + .getMethod("close").invoke(scope); spanInterface.getMethod("end").invoke(span); } } @@ -161,15 +162,13 @@ private static String traceParentFor(final String traceId, final String spanId, MicrometerTracer micrometerTracer = new MicrometerTracer(registry, false, 1000, null); Span span = micrometerTracer.nextSpan(MongodbObservation.MONGODB_COMMAND, "find", null, null); - span.openScope(); - try { + try (SpanScope ignored = span.openScope()) { SimpleTraceContext context = (SimpleTraceContext) tracer.lastSpan().context(); context.setTraceId(traceId); context.setSpanId(spanId); context.setSampled(sampled); return span.context().traceParent(); } finally { - span.closeScope(); span.end(); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTracerRecordingTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTracerRecordingTest.java index 9521b1f7dd2..6f3e533fe04 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTracerRecordingTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerTracerRecordingTest.java @@ -78,7 +78,7 @@ void droppedSpanStillPropagatesValidUnsampledTraceParent() { ObservationRegistry registry = registryWithSampler(Sampler.alwaysOff()); MicrometerTracer tracer = new MicrometerTracer(registry, false, 1000, null); Span span = tracer.nextSpan(MongodbObservation.MONGODB_COMMAND, "find", null, null); - span.openScope(); + SpanScope scope = span.openScope(); try { String traceParent = span.context().traceParent(); assertNotNull(traceParent, "an unsampled span still has a valid context to propagate"); @@ -87,7 +87,7 @@ void droppedSpanStillPropagatesValidUnsampledTraceParent() { assertTrue(traceParent.endsWith("-00"), "trace-flags must be 00 for an unsampled span"); assertFalse(traceParent.substring(3, 35).matches("0+"), "trace id must not be all zeroes"); } finally { - span.closeScope(); + scope.close(); span.end(); } } @@ -128,8 +128,7 @@ private static MongodbObservationContext runCommandSpan(final ObservationRegistr context.setServerAddress(new ServerAddress("localhost", 27017)); context.setConnectionId(new ConnectionId(new ServerId(new ClusterId(), new ServerAddress()), 3, 42L)); context.setQueryText("{find: 'coll'}"); - span.openScope(); - span.closeScope(); + span.openScope().close(); span.end(); return context; } diff --git a/driver-core/src/test/unit/com/mongodb/observability/micrometer/DefaultMongodbObservationConventionTest.java b/driver-core/src/test/unit/com/mongodb/observability/micrometer/DefaultMongodbObservationConventionTest.java index 6e86e0eeb33..8b369ed7d72 100644 --- a/driver-core/src/test/unit/com/mongodb/observability/micrometer/DefaultMongodbObservationConventionTest.java +++ b/driver-core/src/test/unit/com/mongodb/observability/micrometer/DefaultMongodbObservationConventionTest.java @@ -118,6 +118,22 @@ void commandHighCardinalityKeyValuesAreSkippedWhenSpanIsNotRecording() { assertEquals(8, toMap(convention.getLowCardinalityKeyValues(ctx)).size()); } + @Test + void operationHighCardinalityKeyValuesCarryTheCursorIdWhenRecording() { + MongodbObservationContext ctx = new MongodbObservationContext(); + ctx.setObservationType(MongodbObservation.MONGODB_OPERATION); + ctx.setCommandName("getMore"); + assertTrue(toMap(convention.getHighCardinalityKeyValues(ctx)).isEmpty()); + + ctx.setCursorId(7L); + Map kv = toMap(convention.getHighCardinalityKeyValues(ctx)); + assertEquals("7", kv.get("db.mongodb.cursor_id")); + assertEquals(1, kv.size()); + + ctx.setRecording(false); + assertTrue(toMap(convention.getHighCardinalityKeyValues(ctx)).isEmpty()); + } + @Test void recordingDefaultsToTrue() { assertTrue(new MongodbObservationContext().isRecording()); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/observability/MicrometerProseTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/observability/MicrometerProseTest.java index c58bb98f2cc..f45aeed1aa5 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/observability/MicrometerProseTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/observability/MicrometerProseTest.java @@ -18,6 +18,7 @@ import com.mongodb.MongoClientSettings; import com.mongodb.client.AbstractMicrometerProseTest; +import com.mongodb.client.ClientSession; import com.mongodb.client.MongoClient; import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; @@ -29,4 +30,12 @@ public class MicrometerProseTest extends AbstractMicrometerProseTest { protected MongoClient createMongoClient(final MongoClientSettings settings) { return new SyncMongoClient(settings); } + + @Override + protected void runInTransaction(final ClientSession session, final Runnable body) { + // the reactive driver has no withTransaction, so start and commit the transaction explicitly + session.startTransaction(); + body.run(); + session.commitTransaction(); + } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java index d2d6720edd9..482213b1593 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java @@ -201,7 +201,6 @@ private void startTransaction(final TransactionOptions transactionOptions, final if (tracingManager.isEnabled()) { transactionSpan = new TransactionSpan(tracingManager); - transactionSpan.openScope(); } clearTransactionContext(); setTimeoutContext(timeoutContext); diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java index 11579f86e40..90526704114 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java @@ -53,6 +53,7 @@ import com.mongodb.internal.connection.OperationContext; import com.mongodb.internal.connection.ReadConcernAwareNoOpSessionContext; import com.mongodb.internal.observability.micrometer.Span; +import com.mongodb.internal.observability.micrometer.SpanScope; import com.mongodb.internal.observability.micrometer.TracingManager; import com.mongodb.internal.operation.OperationHelper; import com.mongodb.internal.operation.Operations; @@ -441,9 +442,10 @@ public T execute(final ReadOperation operation, final ReadPreference r ReadBinding binding = getReadBinding(readPreference, actualClientSession, implicitSession); Span span = operationContext.getTracingManager().createOperationSpan( actualClientSession.getTransactionSpan(), operationContext, operation.getCommandName(), operation.getNamespace()); + SpanScope scope = SpanScope.NO_OP; try { if (span != null) { - span.openScope(); + scope = span.openScope(); } if (actualClientSession.hasActiveTransaction() && !binding.getReadPreference().equals(primary())) { throw new MongoClientException("Read preference in a transaction must be primary"); @@ -459,8 +461,8 @@ public T execute(final ReadOperation operation, final ReadPreference r throw e; } finally { binding.release(); + scope.close(); if (span != null) { - span.closeScope(); span.end(); } } @@ -479,9 +481,10 @@ public T execute(final WriteOperation operation, final ReadConcern readCo WriteBinding binding = getWriteBinding(actualClientSession, isImplicitSession(session)); Span span = operationContext.getTracingManager().createOperationSpan( actualClientSession.getTransactionSpan(), operationContext, operation.getCommandName(), operation.getNamespace()); + SpanScope scope = SpanScope.NO_OP; try { if (span != null) { - span.openScope(); + scope = span.openScope(); } return operation.execute(binding, operationContext); } catch (MongoException e) { @@ -494,8 +497,8 @@ public T execute(final WriteOperation operation, final ReadConcern readCo throw e; } finally { binding.release(); + scope.close(); if (span != null) { - span.closeScope(); span.end(); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java index 03842d5378c..467949199ad 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -16,13 +16,30 @@ package com.mongodb.client; +import com.mongodb.AuthenticationMechanism; import com.mongodb.MongoClientSettings; +import com.mongodb.MongoCredential; +import com.mongodb.MongoException; +import com.mongodb.MongoNamespace; +import com.mongodb.MongoTimeoutException; +import com.mongodb.ServerAddress; import com.mongodb.internal.EnvironmentProvider; +import com.mongodb.internal.logging.LogMessage; +import com.mongodb.internal.logging.LoggingInterceptor; +import com.mongodb.internal.logging.StructuredLogger; +import com.mongodb.lang.Nullable; import com.mongodb.observability.micrometer.MongodbObservationContext; import com.mongodb.observability.micrometer.MongodbObservation; import com.mongodb.observability.ObservabilitySettings; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.Updates; +import com.mongodb.client.model.bulk.ClientNamespacedWriteModel; import com.mongodb.client.observability.SpanTree; import com.mongodb.client.observability.SpanTree.SpanNode; +import com.mongodb.connection.ClusterConnectionMode; +import com.mongodb.connection.ClusterSettings; +import com.mongodb.event.CommandListener; +import com.mongodb.event.CommandStartedEvent; import com.mongodb.observability.micrometer.MicrometerObservabilitySettings; import io.micrometer.common.KeyValues; import io.micrometer.observation.Observation; @@ -30,6 +47,7 @@ import io.micrometer.observation.ObservationRegistry; import io.micrometer.tracing.exporter.FinishedSpan; import io.micrometer.tracing.test.reporter.inmemory.InMemoryOtelSetup; +import org.bson.BsonDocument; import org.bson.Document; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -39,6 +57,7 @@ import org.junit.jupiter.api.Test; import java.util.ArrayList; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -50,14 +69,30 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import static com.mongodb.ClusterFixture.getCredential; import static com.mongodb.ClusterFixture.getDefaultDatabaseName; +import static com.mongodb.ClusterFixture.getPrimary; +import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; +import static com.mongodb.ClusterFixture.isLoadBalanced; +import static com.mongodb.ClusterFixture.isSharded; +import static com.mongodb.ClusterFixture.serverVersionAtLeast; import static com.mongodb.client.Fixture.getMongoClientSettingsBuilder; +import static com.mongodb.client.model.bulk.ClientBulkWriteOptions.clientBulkWriteOptions; +import static com.mongodb.client.model.bulk.ClientUpdateOneOptions.clientUpdateOneOptions; +import static com.mongodb.observability.micrometer.MongodbObservation.HighCardinalityKeyNames.CURSOR_ID; import static com.mongodb.observability.micrometer.MongodbObservation.HighCardinalityKeyNames.QUERY_TEXT; import static com.mongodb.internal.observability.micrometer.TracingManager.ENV_OBSERVABILITY_ENABLED; import static com.mongodb.internal.observability.micrometer.TracingManager.ENV_OBSERVABILITY_QUERY_TEXT_MAX_LENGTH; +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Implementation of the prose tests @@ -217,6 +252,98 @@ void testControlCommandPayloadViaEnvironmentVariable() throws Exception { } } + @DisplayName("Test 3: getMore inside a withTransaction callback nests under the transaction span") + @Test + void testGetMoreInsideWithTransactionNestsUnderTransactionSpan() { + assumeTrue(isDiscoverableReplicaSet() || isSharded()); + assumeTrue(serverVersionAtLeast(4, 4)); + try (MongoClient client = createMongoClient(tracedSettings("otel-test3")); + ClientSession session = client.startSession()) { + MongoCollection collection = client.getDatabase(getDefaultDatabaseName()).getCollection("test"); + collection.drop(); + collection.insertMany(asList(new Document("_id", 1), new Document("_id", 2), new Document("_id", 3))); + + // three documents with a batchSize of 2 send exactly one getMore inside the transaction + runInTransaction(session, () -> collection.find(session).batchSize(2).into(new ArrayList<>())); + assertNoSpanIsCurrent(); + + List spans = inMemoryOtel.getFinishedSpans(); + FinishedSpan transaction = onlySpanNamed(spans, "transaction"); + FinishedSpan find = childSpan(spans, transaction, operationSpanName("find")); + FinishedSpan getMore = childSpan(spans, transaction, operationSpanName("getMore")); + // the getMore operation span is a sibling of the find operation span, not nested under it + assertTrue(childSpans(spans, find, operationSpanName("getMore")).isEmpty(), + "the getMore operation span must not be nested under the find operation span"); + childSpan(spans, getMore, "getMore"); + } + } + + @DisplayName("Test 4: getMore records the cursor id it sent, not the cursor id returned") + @Test + void testGetMoreRecordsTheCursorIdItSent() { + // the reactive cursor does not expose its server cursor, so the sent id is taken from the getMore command itself + List sentCursorIds = Collections.synchronizedList(new ArrayList<>()); + MongoClientSettings settings = MongoClientSettings.builder(tracedSettings("otel-test4")) + .addCommandListener(new CommandListener() { + @Override + public void commandStarted(final CommandStartedEvent event) { + if (event.getCommandName().equals("getMore")) { + sentCursorIds.add(event.getCommand().getInt64("getMore").getValue()); + } + } + }) + .build(); + try (MongoClient client = createMongoClient(settings)) { + MongoCollection collection = client.getDatabase(getDefaultDatabaseName()).getCollection("test"); + collection.drop(); + collection.insertMany(asList(new Document("_id", 1), new Document("_id", 2), new Document("_id", 3))); + + // the getMore drains the cursor, so the server's reply to it returns a cursor id of 0 + collection.find().batchSize(2).into(new ArrayList<>()); + assertNoSpanIsCurrent(); + + assertEquals(1, sentCursorIds.size(), "exactly one getMore expected, got " + sentCursorIds); + String sentCursorId = String.valueOf(sentCursorIds.get(0)); + List spans = inMemoryOtel.getFinishedSpans(); + FinishedSpan operation = onlySpanNamed(spans, operationSpanName("getMore")); + FinishedSpan command = childSpan(spans, operation, "getMore"); + assertEquals(sentCursorId, operation.getTags().get(CURSOR_ID.asString()), "cursor id of " + operation); + assertEquals(sentCursorId, command.getTags().get(CURSOR_ID.asString()), "cursor id of " + command); + } + } + + /** + * Verifies that a {@code getMore} the driver sends to iterate a cursor internally, to produce the result of one public API + * call, is nested under that call's operation span instead of getting an operation span of its own. + * + *

This test is not from the specification.

+ */ + @Test + void testGetMoreOfInternallyIteratedCursorNestsUnderTheOperationSpan() { + assumeTrue(serverVersionAtLeast(8, 0)); + try (MongoClient client = createMongoClient(tracedSettings("otel-internal-get-more"))) { + MongoDatabase database = client.getDatabase(getDefaultDatabaseName()); + database.getCollection("test").drop(); + int maxBsonObjectSize = database.runCommand(new Document("hello", 1)).getInteger("maxBsonObjectSize"); + MongoNamespace namespace = new MongoNamespace(getDefaultDatabaseName(), "test"); + // two verbose results of half the maximum document size each do not fit in the first batch, which requires a getMore + client.bulkWrite(asList( + ClientNamespacedWriteModel.updateOne(namespace, Filters.eq(String.join("", Collections.nCopies( + maxBsonObjectSize / 2, "a"))), Updates.set("x", 1), clientUpdateOneOptions().upsert(true)), + ClientNamespacedWriteModel.updateOne(namespace, Filters.eq(String.join("", Collections.nCopies( + maxBsonObjectSize / 2, "b"))), Updates.set("x", 1), clientUpdateOneOptions().upsert(true))), + clientBulkWriteOptions().verboseResults(true)); + assertNoSpanIsCurrent(); + + List spans = inMemoryOtel.getFinishedSpans(); + assertTrue(spans.stream().noneMatch(s -> s.getName().startsWith("getMore ")), + "no getMore operation span expected, got " + spans); + FinishedSpan operation = onlySpanNamed(spans, "bulkWrite admin"); + childSpan(spans, operation, "bulkWrite"); + childSpan(spans, operation, "getMore"); + } + } + /** * Verifies that concurrent operations produce isolated span trees with no cross-contamination. * Each operation should get its own trace ID, correct parent-child linkage, and collection-specific tags, @@ -422,4 +549,327 @@ public KeyValues getLowCardinalityKeyValues(final MongodbObservationContext cont "Custom convention should carry over 'db.system.name' on operation span."); } } + + @DisplayName("Test 10: Command log messages carry their own command span") + @Test + void testCommandLogMessagesCarryTheirOwnCommandSpan() { + assumeTrue(serverVersionAtLeast(4, 4)); + String appName = "otel-log-test10"; + BsonDocument failPoint = BsonDocument.parse("{ configureFailPoint: 'failCommand', mode: { times: 1 }," + + " data: { failCommands: ['find'], errorCode: 91, appName: '" + appName + "' } }"); + MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) + .retryReads(true) + // error 91 marks the server Unknown; without a fast heartbeat the retry waits ~10 s for rediscovery + .applyToServerSettings(b -> b.heartbeatFrequency(500, TimeUnit.MILLISECONDS)) + .build(); + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(settings); + FailPoint ignored = FailPoint.enable(failPoint, getPrimary())) { + client.getDatabase(getDefaultDatabaseName()).getCollection("test").find().first(); + assertNoSpanIsCurrent(); + + List spans = inMemoryOtel.getFinishedSpans(); + FinishedSpan operation = onlySpanNamed(spans, operationSpanName("find")); + // command spans finish in attempt order + List attempts = childSpans(spans, operation, "find"); + assertEquals(2, attempts.size(), "two find attempts expected under " + operation); + // exact equality to a command span also means that none of these messages carries the operation span + assertCarry(logs.messages("Command started"), attempts.get(0), attempts.get(1)); + assertCarry(logs.messages("Command failed"), attempts.get(0)); + assertCarry(logs.messages("Command succeeded"), attempts.get(1)); + } + } + + @DisplayName("Test 11 (steps 1-3): Operation-path log messages carry the operation span") + @Test + void testOperationPathLogMessagesCarryTheOperationSpan() { + assumeFalse(isLoadBalanced()); + String appName = "otel-log-test11"; + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(tracedSettings(appName))) { + client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1)); + assertNoSpanIsCurrent(); + + FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationSpanName("insert")); + assertEachCarries(logs, operation, "Server selection started", "Server selection succeeded", + "Connection checkout started", "Connection checked out", "Connection checked in"); + } + } + + @DisplayName("Test 11 (steps 4-6): Server selection failure log messages carry the operation span") + @Test + void testServerSelectionFailureLogMessagesCarryTheOperationSpan() { + // not on load balanced (per spec): a load-balanced client never waits for server selection, so the waiting message is never logged + assumeFalse(isLoadBalanced()); + String appName = "otel-log-test11-failing"; + // replace the fixture's cluster settings entirely (hosts and any srvHost) with a single unreachable host + MongoClientSettings failing = MongoClientSettings.builder(tracedSettings(appName)) + .applyToClusterSettings(b -> b.applySettings(ClusterSettings.builder() + .hosts(singletonList(new ServerAddress("localhost", 1))) + .mode(ClusterConnectionMode.SINGLE) + .serverSelectionTimeout(500, TimeUnit.MILLISECONDS) + .build())) + .build(); + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(failing)) { + assertThrows(MongoTimeoutException.class, + () -> client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1))); + assertNoSpanIsCurrent(); + + FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationSpanName("insert")); + assertEachCarries(logs, operation, "Waiting for suitable server to become available", "Server selection failed"); + } + } + + @DisplayName("Test 11 (steps 7-10): Connection checkout failure log messages carry the operation span") + @Test + void testConnectionCheckoutFailureLogMessagesCarryTheOperationSpan() { + // not on load balanced (per spec): the fail point is set on one mongos, but the load balancer may route the client to another + assumeFalse(isLoadBalanced()); + // only SCRAM (default) sends saslContinue as a standalone command + MongoCredential credential = getCredential(); + assumeTrue(credential != null); + assumeTrue(credential.getAuthenticationMechanism() == null + || credential.getAuthenticationMechanism() == AuthenticationMechanism.SCRAM_SHA_1 + || credential.getAuthenticationMechanism() == AuthenticationMechanism.SCRAM_SHA_256); + // the fail point is scoped by appName, which requires MongoDB 4.4 + assumeTrue(serverVersionAtLeast(4, 4)); + String appName = "otel-log-test11-checkout-failing"; + BsonDocument failPoint = BsonDocument.parse("{ configureFailPoint: 'failCommand', mode: { times: 1 }," + + " data: { failCommands: ['saslContinue'], closeConnection: true, appName: '" + appName + "' } }"); + MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) + .retryReads(false) + .applyToServerSettings(b -> b.heartbeatFrequency(10, TimeUnit.SECONDS)) + .build(); + try (FailPoint ignored = FailPoint.enable(failPoint, getPrimary()); + SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(settings)) { + assertThrows(MongoException.class, () -> client.getDatabase(getDefaultDatabaseName()).getCollection("test").find().first()); + assertNoSpanIsCurrent(); + + FinishedSpan operation = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationSpanName("find")); + assertEachCarries(logs, operation, "Connection checkout started", "Connection checkout failed"); + } + } + + @DisplayName("Test 12: Log messages inside a transaction") + @Test + void testLogMessagesInsideTransaction() { + assumeTrue(isDiscoverableReplicaSet() || isSharded()); + String appName = "otel-log-test12"; + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(tracedSettings(appName)); + ClientSession session = client.startSession()) { + MongoCollection collection = client.getDatabase(getDefaultDatabaseName()).getCollection("test"); + runInTransaction(session, () -> collection.insertOne(session, new Document("x", 1))); + assertNoSpanIsCurrent(); + + List spans = inMemoryOtel.getFinishedSpans(); + FinishedSpan transaction = onlySpanNamed(spans, "transaction"); + FinishedSpan insertOperation = childSpan(spans, transaction, operationSpanName("insert")); + FinishedSpan insertCommand = childSpan(spans, insertOperation, "insert"); + // admin commands have no collection in the operation span name + FinishedSpan commitOperation = childSpan(spans, transaction, "commitTransaction admin"); + FinishedSpan commitCommand = childSpan(spans, commitOperation, "commitTransaction"); + assertCarry(logs.messages("Command started"), insertCommand, commitCommand); + assertCarry(logs.messages("Command succeeded"), insertCommand, commitCommand); + + // server selection and connection checkout precede any command span, so they belong to the operation span of the + // insert or of the commit; neither is the transaction span + Set operationSpanIds = new HashSet<>(asList(insertOperation.getSpanId(), commitOperation.getSpanId())); + for (String messageId : asList("Server selection started", "Server selection succeeded", + "Connection checkout started", "Connection checked out", "Connection checked in")) { + List observed = logs.messages(messageId); + assertTrue(observed.stream().anyMatch(l -> insertOperation.getSpanId().equals(l.spanId)), + messageId + " must be emitted for the insert carrying its operation span, got " + observed); + for (ObservedLog l : observed) { + assertEquals(transaction.getTraceId(), l.traceId, messageId + " must carry the transaction's trace, got " + l); + assertTrue(operationSpanIds.contains(l.spanId), + messageId + " must carry an operation span of the transaction, got " + l); + } + } + + // the commit reuses the pooled connection the insert checked in, so its "Connection checked in" must carry the + // commit's operation span, not the span captured when the insert checked the connection out + assertTrue(logs.messages("Connection checked in").stream().anyMatch(l -> commitOperation.getSpanId().equals(l.spanId)), + "Connection checked in for the commit must carry the commit operation span"); + } + } + + @DisplayName("Test 13: Background log messages are not attributed to an operation") + @Test + void testBackgroundLogMessagesAreNotAttributedToAnOperation() throws InterruptedException { + // load-balanced clients start no monitoring connection, so they emit no heartbeat messages + assumeFalse(isLoadBalanced()); + String appName = "otel-log-test13"; + MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) + .applyToServerSettings(b -> b.heartbeatFrequency(100, TimeUnit.MILLISECONDS)) + .build(); + try (SpanRecordingInterceptor logs = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(settings)) { + client.getDatabase(getDefaultDatabaseName()).getCollection("test").insertOne(new Document("x", 1)); + assertNoSpanIsCurrent(); + int topologyMessagesBefore = logs.component(LogMessage.Component.TOPOLOGY).size(); + + // a fixed delay is not sufficient: without a heartbeat message after the operation there is nothing to check + assertTrue(awaitTopologyMessage(logs, topologyMessagesBefore, "Server heartbeat succeeded"), + "a \"Server heartbeat succeeded\" message must have been logged after the operation"); + + String operationTraceId = onlySpanNamed(inMemoryOtel.getFinishedSpans(), operationSpanName("insert")).getTraceId(); + List topology = logs.component(LogMessage.Component.TOPOLOGY); + for (ObservedLog l : topology.subList(topologyMessagesBefore, topology.size())) { + // trace id and span id come from the same current-span context, so this covers both spec clauses + assertNotEquals(operationTraceId, l.traceId, l.messageId + " must not carry the operation's trace"); + } + } + } + + // Tests 14 and 15 apply only to driver-managed log output and are not applicable to Java: the driver logs through SLF4J and + // has no driver-managed log destinations. The reactive subclass runs Tests 10 to 13 as the asynchronous API. + + /** + * Runs {@code body} in a transaction on {@code session}, as the spec's {@code withTransaction} step requires. + */ + protected void runInTransaction(final ClientSession session, final Runnable body) { + session.withTransaction(() -> { + body.run(); + return null; + }); + } + + private MongoClientSettings tracedSettings(final String applicationName) { + // tracing is enabled by default; clear any override left by another test + environmentOverride.set(ENV_OBSERVABILITY_ENABLED, null); + return getMongoClientSettingsBuilder() + .applicationName(applicationName) + .observabilitySettings(ObservabilitySettings.micrometerBuilder() + .observationRegistry(observationRegistry) + .build()) + .build(); + } + + private void assertNoSpanIsCurrent() { + assertNull(inMemoryOtel.getTracer().currentSpan(), "no span may be current after the operation"); + assertNull(observationRegistry.getCurrentObservation(), "no observation may be current after the operation"); + } + + private String operationSpanName(final String command) { + return command + " " + getDefaultDatabaseName() + ".test"; + } + + private static FinishedSpan onlySpanNamed(final List spans, final String name) { + List matching = spans.stream().filter(s -> s.getName().equals(name)).collect(Collectors.toList()); + assertEquals(1, matching.size(), "expected exactly one span named " + name + " but got " + matching); + return matching.get(0); + } + + private static List childSpans(final List spans, final FinishedSpan parent, final String name) { + return spans.stream() + .filter(s -> parent.getSpanId().equals(s.getParentId()) && s.getName().equals(name)) + .collect(Collectors.toList()); + } + + private static FinishedSpan childSpan(final List spans, final FinishedSpan parent, final String name) { + List matching = childSpans(spans, parent, name); + assertEquals(1, matching.size(), "expected exactly one span named " + name + " under " + parent + " but got " + matching); + return matching.get(0); + } + + /** Exactly these messages, in emission order, each carrying the trace id and span id of the matching span. */ + private static void assertCarry(final List observed, final FinishedSpan... expected) { + assertTrue(expected.length > 0, "assertCarry needs at least one expected span"); + assertEquals(expected.length, observed.size(), "expected one message per span of " + asList(expected) + " but got " + observed); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i].getTraceId(), observed.get(i).traceId, "trace id of message " + i + " in " + observed); + assertEquals(expected[i].getSpanId(), observed.get(i).spanId, "span id of message " + i + " in " + observed); + } + } + + /** Each message id is emitted at least once, and every emission carries {@code span}. */ + private static void assertEachCarries(final SpanRecordingInterceptor logs, final FinishedSpan span, final String... messageIds) { + for (String messageId : messageIds) { + List observed = logs.messages(messageId); + assertFalse(observed.isEmpty(), messageId + " must be emitted"); + for (ObservedLog l : observed) { + assertEquals(span.getTraceId(), l.traceId, messageId + " must carry the trace of " + span + ", got " + l); + assertEquals(span.getSpanId(), l.spanId, messageId + " must carry the span of " + span + ", got " + l); + } + } + } + + private static boolean awaitTopologyMessage(final SpanRecordingInterceptor logs, final int from, final String messageId) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (true) { + List topology = logs.component(LogMessage.Component.TOPOLOGY); + if (topology.subList(from, topology.size()).stream().anyMatch(l -> l.messageId.equals(messageId))) { + return true; + } + if (System.nanoTime() - deadline >= 0) { + return false; + } + Thread.sleep(50); + } + } + + /** Trace id and span id that were current on the thread when a log message was emitted. */ + private static final class ObservedLog { + private final String messageId; + private final LogMessage.Component component; + @Nullable + private final String traceId; + @Nullable + private final String spanId; + + ObservedLog(final LogMessage message, @Nullable final io.micrometer.tracing.Span current) { + this.messageId = message.getMessageId(); + this.component = message.getComponent(); + this.traceId = current == null ? null : current.context().traceId(); + this.spanId = current == null ? null : current.context().spanId(); + } + + @Override + public String toString() { + return messageId + "{traceId=" + traceId + ", spanId=" + spanId + "}"; + } + } + + /** + * Records, for each log message of the client with the given application name, the span current on the emitting thread. + * {@link StructuredLogger#log(LogMessage)} calls the interceptor on the emitting thread, so this observes exactly what an + * MDC bridge would. + */ + private static final class SpanRecordingInterceptor implements LoggingInterceptor, AutoCloseable { + private final String applicationName; + private final io.micrometer.tracing.Tracer tracer; + private final List logs = Collections.synchronizedList(new ArrayList<>()); + + SpanRecordingInterceptor(final String applicationName, final io.micrometer.tracing.Tracer tracer) { + this.applicationName = applicationName; + this.tracer = tracer; + StructuredLogger.addInterceptor(applicationName, this); + } + + @Override + public void intercept(final LogMessage message) { + logs.add(new ObservedLog(message, tracer.currentSpan())); + } + + List messages(final String messageId) { + synchronized (logs) { + return logs.stream().filter(l -> l.messageId.equals(messageId)).collect(Collectors.toList()); + } + } + + List component(final LogMessage.Component component) { + synchronized (logs) { + return logs.stream().filter(l -> l.component == component).collect(Collectors.toList()); + } + } + + @Override + public void close() { + StructuredLogger.removeInterceptor(applicationName); + } + } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/observability/SpanTree.java b/driver-sync/src/test/functional/com/mongodb/client/observability/SpanTree.java index f259c30ed8d..9388fdab9e4 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/observability/SpanTree.java +++ b/driver-sync/src/test/functional/com/mongodb/client/observability/SpanTree.java @@ -152,10 +152,7 @@ public static void assertValid(final SpanTree reportedSpans, final SpanTree expe final BiConsumer valueMatcher, final boolean ignoreExtraSpans) { if (ignoreExtraSpans) { - // remove from the reported spans all the nodes that are not expected - reportedSpans.roots.removeIf(node -> - expectedSpans.roots.stream().noneMatch(expectedNode -> expectedNode.getName().equalsIgnoreCase(node.getName())) - ); + removeUnexpectedSpans(reportedSpans.roots, expectedSpans.roots); } // check that we have the same root spans @@ -167,10 +164,19 @@ public static void assertValid(final SpanTree reportedSpans, final SpanTree expe } for (int i = 0; i < reportedSpans.roots.size(); i++) { - assertValid(reportedSpans.roots.get(i), expectedSpans.roots.get(i), valueMatcher); + assertValid(reportedSpans.roots.get(i), expectedSpans.roots.get(i), valueMatcher, ignoreExtraSpans); } } + /** + * Removes from the reported spans all the spans whose name matches none of the expected spans. + */ + private static void removeUnexpectedSpans(final List reportedSpans, final List expectedSpans) { + reportedSpans.removeIf(node -> + expectedSpans.stream().noneMatch(expectedNode -> expectedNode.getName().equalsIgnoreCase(node.getName())) + ); + } + /** * Asserts that a reported span node is valid against an expected span node. * This method checks that the reported span's name, tags, and children match the expected span. @@ -178,9 +184,11 @@ public static void assertValid(final SpanTree reportedSpans, final SpanTree expe * @param reportedNode the reported span node to validate * @param expectedNode the expected span node to validate against * @param valueMatcher a BiConsumer to match values of tags between reported and expected spans + * @param ignoreExtraSpans if true, allows the reported span to have child spans not present in the expected span. As the + * unified test format specifies, this applies at every level of the span tree. */ private static void assertValid(final SpanNode reportedNode, final SpanNode expectedNode, - final BiConsumer valueMatcher) { + final BiConsumer valueMatcher, final boolean ignoreExtraSpans) { // Check that the span names match if (!reportedNode.getName().equalsIgnoreCase(expectedNode.getName())) { fail("Reported span name " @@ -191,6 +199,10 @@ private static void assertValid(final SpanNode reportedNode, final SpanNode expe valueMatcher.accept(expectedNode.tags, reportedNode.tags); + if (ignoreExtraSpans) { + removeUnexpectedSpans(reportedNode.children, expectedNode.children); + } + // Spans should have the same number of children if (reportedNode.children.size() != expectedNode.children.size()) { fail("Reported span " + reportedNode.getName() @@ -200,7 +212,7 @@ private static void assertValid(final SpanNode reportedNode, final SpanNode expe // For every reported child span make sure it is valid against the expected child span for (int i = 0; i < reportedNode.children.size(); i++) { - assertValid(reportedNode.children.get(i), expectedNode.children.get(i), valueMatcher); + assertValid(reportedNode.children.get(i), expectedNode.children.get(i), valueMatcher, ignoreExtraSpans); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTest.java index 407719d9db3..3f521468c61 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTest.java @@ -111,7 +111,7 @@ public abstract class UnifiedTest { private static final Set PRESTART_POOL_ASYNC_WORK_MANAGER_FILE_DESCRIPTIONS = Collections.singleton( "wait queue timeout errors include details about checked out connections"); - private static final String MAX_SUPPORTED_SCHEMA_VERSION = "1.27"; + private static final String MAX_SUPPORTED_SCHEMA_VERSION = "1.29"; private static final List MAX_SUPPORTED_SCHEMA_VERSION_COMPONENTS = Arrays.stream(MAX_SUPPORTED_SCHEMA_VERSION.split("\\.")) .map(Integer::parseInt) .collect(Collectors.toList()); diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestModifications.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestModifications.java index 2de6e982aa2..d219c763d37 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestModifications.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestModifications.java @@ -79,6 +79,10 @@ public static void applyCustomizations(final TestDef def) { .file("client-side-encryption/tests/unified", "QE-Text-prefixPreview") .file("client-side-encryption/tests/unified", "QE-Text-suffixPreview") .file("client-side-encryption/tests/unified", "QE-Text-substringPreview"); + def.skipJira("https://jira.mongodb.org/browse/JAVA-6136 The unified test runner does not support the accessToken " + + "form of the Azure and GCP KMS providers (schema version 1.28)") + .file("client-side-encryption/tests/unified", "accessToken-azure") + .file("client-side-encryption/tests/unified", "accessToken-gcp"); // client-side-operation-timeout (CSOT) // The expected change stream timeout-refresh behaviour is unspecified on server 9.0+ (DRIVERS-3006), so the diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/ValueMatcher.java b/driver-sync/src/test/functional/com/mongodb/client/unified/ValueMatcher.java index ba887ff0fd5..bcc4b5b8a2e 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/ValueMatcher.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/ValueMatcher.java @@ -128,6 +128,12 @@ private void assertValuesMatch(final BsonValue initialExpected, @Nullable final value = value.asDocument().getNumber("$$lte"); assertTrue(actualValue.asNumber().longValue() <= value.asNumber().longValue()); return; + case "$$gte": + value = value.asDocument().getNumber("$$gte"); + assertNotNull(context.getMessage("Actual document must contain key " + key), actualValue); + assertTrue(context.getMessage("Expected actual value " + actualValue + " to be >= " + value), + actualValue.asNumber().doubleValue() >= value.asNumber().doubleValue()); + return; default: throw new UnsupportedOperationException("Unsupported special operator: " + value.asDocument().getFirstKey()); } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7ff2f38a879..73adf60f341 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -99,6 +99,7 @@ snappy-java = { module = "org.xerial.snappy:snappy-java", version.ref = "snappy" zstd-jni = { module = "com.github.luben:zstd-jni", version.ref = "zstd" } micrometer-observation-bom = { module = "io.micrometer:micrometer-bom", version.ref = "micrometer-observation-bom" } micrometer-observation = { module = "io.micrometer:micrometer-observation" } +micrometer-observation-test = { module = "io.micrometer:micrometer-observation-test" } graal-sdk = { module = "org.graalvm.sdk:graal-sdk", version.ref = "graal-sdk" } graal-sdk-nativeimage = { module = "org.graalvm.sdk:nativeimage", version.ref = "graal-sdk" }