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..16bb5cccd87 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,7 @@ 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.session.SessionContext; import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; @@ -452,6 +453,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 +473,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 +487,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 +528,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 +574,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(); } } @@ -732,6 +738,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) -> { 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..db210fe73c0 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 @@ -18,6 +18,8 @@ import com.mongodb.internal.VisibleForTesting; import com.mongodb.MongoNamespace; +import com.mongodb.internal.diagnostics.logging.Logger; +import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.lang.Nullable; import com.mongodb.observability.micrometer.DefaultMongodbObservationConvention; import com.mongodb.observability.micrometer.MongodbObservation; @@ -57,10 +59,15 @@ public class MicrometerTracer implements Tracer { @VisibleForTesting(otherwise = PRIVATE) static final boolean MICROMETER_TRACING_ON_CLASSPATH = isMicrometerTracingOnClasspath(); + private static final Logger LOGGER = Loggers.getLogger("observability"); + private final ObservationRegistry observationRegistry; private final boolean allowCommandPayload; private final int textMaxLength; private final ObservationConvention convention; + /** + * Whether a scope failure has already been logged at WARN by this tracer; later ones are logged at DEBUG. + */ private static boolean isMicrometerTracingOnClasspath() { try { @@ -111,7 +118,7 @@ public Span nextSpan(final MongodbObservation observationType, final String name ((MongodbObservationContext) context).setRecording(false); } } - return new MicrometerSpan(started, namespace, textMaxLength); + return new MicrometerSpan(started, observationRegistry, namespace, textMaxLength); } @Override @@ -235,39 +242,105 @@ static String traceParent(final Observation observation) { /** * Represents a Micrometer-based span. + *

+ * Opening and closing its scope is guarded against application {@code ObservationHandler}s that throw; see {@link #openScope()}. + * One residual remains by design: Micrometer stops notifying handlers at the first {@code onScopeClosed} that throws, so a + * tracing handler registered before the throwing one may keep its own thread-local context on this span until an enclosing + * scope closes, although the registry's current scope is restored. + *

*/ - private static class MicrometerSpan implements Span { + static class MicrometerSpan implements Span { private final Observation observation; + private final ObservationRegistry registry; @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. * * @param observation The Micrometer {@link Observation}, or null if none exists. + * @param registry The registry holding the thread's current observation scope. * @param namespace The MongoDB namespace associated with the span. * @param queryTextLength The maximum length for query text truncation. */ - MicrometerSpan(final Observation observation, @Nullable final MongoNamespace namespace, final int queryTextLength) { + MicrometerSpan(final Observation observation, final ObservationRegistry registry, @Nullable final MongoNamespace namespace, + final int queryTextLength) { this.namespace = namespace; this.observation = observation; + this.registry = registry; this.queryTextLength = queryTextLength; } + /** + * Micrometer switches the registry's current scope before notifying handlers of {@code onScopeOpened}, and notifies + * {@code onScopeClosed} before restoring the previous scope, both without protection. An application + * {@code ObservationHandler} that throws would otherwise leave the thread stuck on this span and abort the driver's + * work around the scope (for example a connection check-in). As with listener failures, a {@link RuntimeException} + * is reported and swallowed; {@link Error}s propagate. + */ @Override - public void openScope() { - this.scope = observation.openScope(); + public SpanScope openScope() { + Observation.Scope previous = registry.getCurrentObservationScope(); + Observation.Scope scope; + try { + scope = observation.openScope(); + } catch (RuntimeException e) { + restoreAfterFailedOpen(previous); + reportScopeFailure("open", e); + return SpanScope.NO_OP; + } + return () -> closeScope(scope, previous); } - @Override - public void closeScope() { - if (scope != null) { + private void closeScope(final Observation.Scope scope, @Nullable final Observation.Scope previous) { + try { scope.close(); - scope = null; + } catch (RuntimeException e) { + // Micrometer notifies the handlers before restoring the previous scope, so force the restore. Micrometer also stops + // notifying at the first handler that throws, so a tracing handler registered before the thrower may keep its + // thread-local context on this span until an enclosing scope closes; that residual is accepted. + registry.setCurrentObservationScope(previous); + reportScopeFailure("close", e); + } + } + + private void restoreAfterFailedOpen(@Nullable final Observation.Scope previous) { + Observation.Scope leaked = registry.getCurrentObservationScope(); + try { + // closing the partially opened scope also lets handlers that did open (e.g. the tracing handler's thread-local) undo it. + // It also notifies handlers that never opened; when the same observation is already open in an enclosing scope, such + // a handler may undo the enclosing scope's tracing context for the rest of that scope. This is bounded: nothing stays + // stale once the enclosing scope closes. + if (leaked != null && leaked != previous && leaked.getCurrentObservation() == observation) { + leaked.close(); + } + } catch (RuntimeException closeFailure) { + // the thread-local is still forced back below and the open failure is reported by the caller + LOGGER.trace("Ignoring a failure while closing a partially opened span scope", closeFailure); + } finally { + registry.setCurrentObservationScope(previous); + } + } + + private void reportScopeFailure(final String what, final RuntimeException e) { + try { + // an event rather than an error: the database operation itself did not fail. The event name stays fixed (the tracing + // handler exports it as the span event name); the exception goes on the span as a high-cardinality key-value. + observation.event(Observation.Event.of("mongodb.span.scope." + what + ".failed")); + observation.highCardinalityKeyValue("mongodb.span.scope.failure", e.toString()); + } catch (RuntimeException eventFailure) { + // handlers are notified of events without protection too; the log line below still carries the failure + LOGGER.trace("Ignoring a failure while recording the span scope failure on the span", eventFailure); } + String traceParent = context().traceParent(); + String span = traceParent == null ? "" : traceParent; + String message = what.equals("open") + ? "Failed to open the span scope; work in it is not correlated with span " + span + + ". Recorded as an event on the span." + : "Failed to close the span scope; the thread's tracing context may remain on span " + span + + " until an enclosing scope closes. Recorded as an event on the span."; + LOGGER.warn(message, e); } @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/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/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/MicrometerSpanScopeGuardTest.java b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeGuardTest.java new file mode 100644 index 00000000000..0789dfb8ef5 --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/observability/micrometer/MicrometerSpanScopeGuardTest.java @@ -0,0 +1,210 @@ +/* + * 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; + +import com.mongodb.observability.micrometer.MongodbObservation; +import com.mongodb.observability.micrometer.MongodbObservationContext; +import io.micrometer.observation.Observation; +import io.micrometer.observation.ObservationHandler; +import io.micrometer.observation.ObservationRegistry; +import io.micrometer.tracing.handler.DefaultTracingObservationHandler; +import io.micrometer.tracing.test.simple.SimpleSpan; +import io.micrometer.tracing.test.simple.SimpleTracer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Verifies that {@link MicrometerTracer.MicrometerSpan#openScope()} isolates the thread's current observation and tracing + * span from an application {@link ObservationHandler} that throws from {@code onScopeOpened} or {@code onScopeClosed}. + * The throwing handler is registered after the tracing handler, so the tracing handler has already acted when it throws. + */ +class MicrometerSpanScopeGuardTest { + private final SimpleTracer simpleTracer = new SimpleTracer(); + private final ObservationRegistry registry = ObservationRegistry.create(); + private final ThrowingHandler throwingHandler = new ThrowingHandler(); + private final MicrometerTracer tracer = new MicrometerTracer(registry, false, 1000, null); + + @BeforeEach + void setUp() { + registry.observationConfig() + .observationHandler(new DefaultTracingObservationHandler(simpleTracer)) + .observationHandler(throwingHandler); + } + + @AfterEach + void tearDown() { + assertNull(registry.getCurrentObservation(), "a test left an observation current"); + assertNull(simpleTracer.currentSpan(), "a test left a tracing span current"); + } + + @Test + void openFailureRestoresThePreviousScopeAndReturnsNoOp() { + Observation outer = Observation.start("outer", registry); + try (Observation.Scope ignored = outer.openScope()) { + SimpleSpan outerTracingSpan = simpleTracer.currentSpan(); + assertNotNull(outerTracingSpan); + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + throwingHandler.onOpen = () -> new RuntimeException("thrown from onScopeOpened"); + + SpanScope scope = assertDoesNotThrow(span::openScope); + + assertSame(outer, registry.getCurrentObservation()); + assertSame(outerTracingSpan, simpleTracer.currentSpan()); + assertDoesNotThrow(scope::close); + assertSame(outer, registry.getCurrentObservation()); + assertSame(outerTracingSpan, simpleTracer.currentSpan()); + assertEquals(1, throwingHandler.events.size()); + assertEquals("mongodb.span.scope.open.failed", throwingHandler.events.get(0).getName()); + // the exception text must not become the exported event name; it is attached to the span as a key-value instead + assertEquals("mongodb.span.scope.open.failed", throwingHandler.events.get(0).getContextualName()); + MongodbObservationContext context = span.getMongodbObservationContext(); + assertNotNull(context); + assertTrue(context.getHighCardinalityKeyValues().stream().anyMatch(kv -> kv.getKey().equals("mongodb.span.scope.failure") + && kv.getValue().equals("java.lang.RuntimeException: thrown from onScopeOpened")), + "the span must carry the failure reason, got " + context.getHighCardinalityKeyValues()); + span.end(); + } finally { + outer.stop(); + } + } + + @Test + void closeFailureRestoresThePreviousScope() { + Observation outer = Observation.start("outer", registry); + try (Observation.Scope outerScope = outer.openScope()) { + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + throwingHandler.onClose = () -> new RuntimeException("thrown from onScopeClosed"); + + SpanScope scope = span.openScope(); + assertNotNull(registry.getCurrentObservation()); + assertTrue(registry.getCurrentObservation().getContext() instanceof MongodbObservationContext); + assertDoesNotThrow(scope::close); + + assertSame(outerScope, registry.getCurrentObservationScope()); + assertEquals(1, throwingHandler.events.size()); + assertEquals("mongodb.span.scope.close.failed", throwingHandler.events.get(0).getName()); + throwingHandler.onClose = null; + span.end(); + } finally { + outer.stop(); + } + } + + @Test + void runInScopeStillRunsTheActionWhenOpenFails() { + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + throwingHandler.onOpen = () -> new RuntimeException("thrown from onScopeOpened"); + AtomicInteger runs = new AtomicInteger(); + + Span.runInScope(span, runs::incrementAndGet); + + assertEquals(1, runs.get()); + assertNull(registry.getCurrentObservation()); + assertNull(simpleTracer.currentSpan()); + span.end(); + } + + @Test + void handlerRethrowingTheSameExceptionFromCleanupAndEventDoesNotEscape() { + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + RuntimeException preallocated = new RuntimeException("preallocated"); + throwingHandler.onOpen = () -> preallocated; + throwingHandler.onClose = () -> preallocated; + throwingHandler.onEventThrow = () -> preallocated; + + assertDoesNotThrow(() -> span.openScope().close()); + + assertEquals(0, preallocated.getSuppressed().length, "the guard must not mutate the handler's exception"); + assertNull(registry.getCurrentObservation()); + throwingHandler.onOpen = null; + throwingHandler.onClose = null; + throwingHandler.onEventThrow = null; + span.end(); + // the throwing handler is notified before the tracing handler on close, so the tracing handler never undid its scope: + // the documented residual. Reset the tracing thread-local for the teardown check. + simpleTracer.currentTraceContext().newScope(null).close(); + } + + @Test + void errorsFromHandlersPropagate() { + Span span = tracer.nextSpan(MongodbObservation.MONGODB_OPERATION, "insert", null, null); + throwingHandler.onOpen = () -> new AssertionError("thrown from onScopeOpened"); + try { + assertThrows(AssertionError.class, span::openScope); + } finally { + // the guard deliberately does not handle Errors, so undo the partially opened scope here + throwingHandler.onOpen = null; + Observation.Scope leaked = registry.getCurrentObservationScope(); + assertNotNull(leaked, "the Error escaped before Micrometer could restore the scope"); + leaked.close(); + span.end(); + } + } + + private static final class ThrowingHandler implements ObservationHandler { + private volatile Supplier onOpen; + private volatile Supplier onClose; + private volatile Supplier onEventThrow; + private final List events = new CopyOnWriteArrayList<>(); + + @Override + public boolean supportsContext(final Observation.Context context) { + return context instanceof MongodbObservationContext; + } + + @Override + public void onScopeOpened(final Observation.Context context) { + throwIfSet(onOpen); + } + + @Override + public void onScopeClosed(final Observation.Context context) { + throwIfSet(onClose); + } + + @Override + public void onEvent(final Observation.Event event, final Observation.Context context) { + events.add(event); + throwIfSet(onEventThrow); + } + + private static void throwIfSet(final Supplier supplier) { + if (supplier == null) { + return; + } + Throwable t = supplier.get(); + if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } + throw (Error) t; + } + } +} 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-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..a242e920faf 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractMicrometerProseTest.java @@ -16,20 +16,37 @@ package com.mongodb.client; +import com.mongodb.AuthenticationMechanism; import com.mongodb.MongoClientSettings; +import com.mongodb.MongoCredential; +import com.mongodb.MongoException; +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.observability.SpanTree; import com.mongodb.client.observability.SpanTree.SpanNode; +import com.mongodb.event.ConnectionCheckedInEvent; +import com.mongodb.event.ConnectionCheckedOutEvent; +import com.mongodb.event.ConnectionCreatedEvent; +import com.mongodb.internal.connection.TestConnectionPoolListener; +import com.mongodb.connection.ClusterConnectionMode; +import com.mongodb.connection.ClusterSettings; import com.mongodb.observability.micrometer.MicrometerObservabilitySettings; import io.micrometer.common.KeyValues; import io.micrometer.observation.Observation; import io.micrometer.observation.ObservationConvention; +import io.micrometer.observation.ObservationHandler; 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 +56,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; @@ -48,16 +66,31 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; 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.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 @@ -422,4 +455,382 @@ 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. + + /** + * Not a numbered spec prose test: an application {@link ObservationHandler} that throws from {@code onScopeOpened} + * while the "Connection checked in" message is emitted must not abort {@code PooledConnection.close()}. Micrometer + * switches the thread's current scope before notifying handlers and does not protect the notification, so without the + * driver's guard the check-in is skipped and the connection leaks. With a single-connection pool, a leak makes the + * second operation time out waiting for a connection. + */ + @DisplayName("A throwing observation handler at connection check-in does not leak the connection") + @Test + void testThrowingObservationHandlerAtConnectionCheckedInDoesNotLeakTheConnection() throws InterruptedException, TimeoutException { + String appName = "otel-log-throwing-handler-checkin"; + AtomicInteger thrown = new AtomicInteger(); + observationRegistry.observationConfig().observationHandler(new ObservationHandler() { + @Override + public boolean supportsContext(final Observation.Context context) { + // the check-in message is emitted in the scope of the operation span + return context instanceof MongodbObservationContext + && ((MongodbObservationContext) context).getObservationType() == MongodbObservation.MONGODB_OPERATION; + } + + @Override + public void onScopeOpened(final Observation.Context context) { + // the scope is opened from Span.runInScope <- PooledConnection.connectionCheckedIn, before the pool listener runs + for (StackTraceElement element : Thread.currentThread().getStackTrace()) { + if (element.getMethodName().equals("connectionCheckedIn")) { + thrown.incrementAndGet(); + throw new RuntimeException("thrown from onScopeOpened at connection check-in"); + } + } + } + }); + TestConnectionPoolListener poolListener = new TestConnectionPoolListener(asList("connectionCreatedEvent", + "connectionCheckedOutEvent", "connectionCheckedInEvent")); + MongoClientSettings settings = MongoClientSettings.builder(tracedSettings(appName)) + .applyToConnectionPoolSettings(b -> b + .maxSize(1) + .maxWaitTime(5, TimeUnit.SECONDS) + .addConnectionPoolListener(poolListener)) + .build(); + // the interceptor force-enables structured logging, so the check-in message (and its scope opening) is emitted + try (SpanRecordingInterceptor ignored = new SpanRecordingInterceptor(appName, inMemoryOtel.getTracer()); + MongoClient client = createMongoClient(settings)) { + MongoCollection collection = client.getDatabase(getDefaultDatabaseName()).getCollection("test"); + collection.insertOne(new Document("x", 1)); + collection.insertOne(new Document("x", 2)); + + poolListener.waitForEvent(ConnectionCheckedInEvent.class, 2, 5, TimeUnit.SECONDS); + assertTrue(thrown.get() >= 2, "the handler must have thrown at each check-in, threw " + thrown.get()); + assertEquals(2, poolListener.countEvents(ConnectionCheckedOutEvent.class), "each operation must check a connection out"); + assertEquals(2, poolListener.countEvents(ConnectionCheckedInEvent.class), "every connection must be checked back in"); + assertEquals(1, poolListener.countEvents(ConnectionCreatedEvent.class), "one connection must be created and reused"); + assertNoSpanIsCurrent(); + } + } + + /** + * 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/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" }