Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion lib/mongo/monitoring/event/secure.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ module Secure
copydb
].freeze

# The hello / legacy hello command names, hoisted to a constant: the
# sensitivity check runs on every command event and an array literal
# would allocate on each call.
HELLO_COMMANDS = %w[hello ismaster isMaster].freeze

# Check whether the command is sensitive in terms of command monitoring
# spec. A command is detected as sensitive if it is in the
# list or if it is a hello/legacy hello command, and
Expand All @@ -53,7 +58,7 @@ def sensitive?(command_name:, document:)
# when speculativeAuthenticate is present, their commands AND replies
# MUST be redacted from the events.
# See https://github.com/mongodb/specifications/blob/master/source/command-logging-and-monitoring/command-logging-and-monitoring.md#security
%w[hello ismaster isMaster].include?(command_name.to_s) &&
HELLO_COMMANDS.include?(command_name.to_s) &&
!!document['speculativeAuthenticate']
end

Expand Down
285 changes: 179 additions & 106 deletions lib/mongo/tracing/open_telemetry/command_tracer.rb

Large diffs are not rendered by default.

118 changes: 85 additions & 33 deletions lib/mongo/tracing/open_telemetry/operation_tracer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ class OperationTracer
def initialize(otel_tracer, parent_tracer)
@otel_tracer = otel_tracer
@parent_tracer = parent_tracer
@operation_names = {}
@operation_names_mutex = Mutex.new
end

# Trace a MongoDB operation.
Expand All @@ -53,33 +55,66 @@ def initialize(otel_tracer, parent_tracer)
# @yield the block representing the operation to be traced.
#
# @return [ Object ] the result of the operation.
#
# rubocop:disable Lint/RescueException
def trace_operation(operation, operation_context, op_name: nil, &block)
span = create_operation_span(operation, operation_context, op_name)
execute_with_span(span, operation, &block)
# An invalid context has no trace identity: it cannot be propagated,
# continued, or correlated with anything downstream, so every
# operation on it, including finishing it, is waste. This is a state
# check on the span we were handed, not detection of whether the SDK
# is available — a custom API-only provider returning real spans
# sees the full path. Must not key on recording?: an
# unsampled-but-valid context still has to be made current for
# propagation. Skipping here also leaves the cursor context map
# untouched, consistent with tracing being effectively off.
return yield unless span.context.valid?

trace_with_span(span, operation, &block)
end

private

# Runs the operation with the span made current. A span that is not
# recording is still made current, so that the command spans created
# within it are nested under it, but gets no further attributes and
# no outcome: the SDK would discard them.
#
# @param span [ OpenTelemetry::Trace::Span ] a span with a valid context.
# @param operation [ Mongo::Operation ] the operation.
#
# @return [ Object ] the result of the operation.
#
# rubocop:disable Lint/RescueException
def trace_with_span(span, operation, &block)
recording = span.recording?
if recording && !operation.cursor_id.nil?
span.set_attribute('db.mongodb.cursor_id', operation.cursor_id)
end
execute_with_span(span, operation, recording, &block)
rescue Exception => e
handle_span_exception(span, e)
handle_span_exception(span, e) if recording
raise e
ensure
span&.finish
span.finish
end
# rubocop:enable Lint/RescueException

private

# Creates an OpenTelemetry span for the operation.
# Creates an OpenTelemetry span for the operation. The operation name,
# collection name and span name are each computed once and reused
# between the span name and the attributes.
#
# @param operation [ Mongo::Operation ] the operation.
# @param operation_context [ Mongo::Operation::Context ] the operation context.
# @param op_name [ String | nil ] optional operation name.
#
# @return [ OpenTelemetry::Trace::Span ] the created span.
def create_operation_span(operation, operation_context, op_name)
parent_context = parent_context_for(operation_context, operation.cursor_id)
parent_context = parent_context_for(operation_context)
name = operation_name(operation, op_name)
coll_name = collection_name(operation)
span_name = operation_span_name(name, operation.db_name, coll_name)
@otel_tracer.start_span(
operation_span_name(operation, op_name),
attributes: span_attributes(operation, op_name),
span_name,
attributes: span_attributes(operation, name, span_name, coll_name),
with_parent: parent_context,
kind: :client
)
Expand All @@ -89,14 +124,15 @@ def create_operation_span(operation, operation_context, op_name)
#
# @param span [ OpenTelemetry::Trace::Span ] the span.
# @param operation [ Mongo::Operation ] the operation.
# @param recording [ true | false ] whether the span is recording.
#
# @yield the block to execute.
#
# @return [ Object ] the result of the block.
def execute_with_span(span, operation)
def execute_with_span(span, operation, recording)
::OpenTelemetry::Trace.with_span(span) do |s, c|
yield.tap do |result|
process_cursor_context(result, operation.cursor_id, c, s)
process_cursor_context(result, operation.cursor_id, c, s, recording)
end
end
end
Expand All @@ -106,39 +142,54 @@ def execute_with_span(span, operation)
# @param span [ OpenTelemetry::Trace::Span ] the span.
# @param exception [ Exception ] the exception.
def handle_span_exception(span, exception)
return unless span

span.record_exception(exception)
span.status = ::OpenTelemetry::Trace::Status.error(
"Unhandled exception of type: #{exception.class}"
)
end

# Returns the operation name from the provided name or operation class.
# The class-derived name is memoized per class: it is invariant and
# deriving it (split + downcase) allocates on every call. The number
# of operation classes is small and fixed, so the cache is unbounded
# by design. Access is synchronized: unsynchronized Hash mutation is
# not safe on all Ruby runtimes (e.g. JRuby).
#
# @param operation [ Mongo::Operation ] the operation.
# @param op_name [ String | nil ] optional operation name.
#
# @return [ String ] the operation name in lowercase.
def operation_name(operation, op_name = nil)
op_name || operation.class.name.split('::').last.downcase
return op_name if op_name

klass = operation.class
@operation_names_mutex.synchronize do
@operation_names[klass] ||= klass.name.split('::').last.downcase
end
end

# Builds span attributes for the operation.
# Builds the attributes passed at span creation: the cheap set. The
# cursor id is deferred to trace_with_span (behind recording?) — on a
# non-recording span set_attribute discards, and the sampler has no
# use for it. db.operation.summary is outside the spec's recommended
# creation set, but here it is the span name, which is built anyway,
# and an attribute passed at creation is cheaper than one set later.
#
# @param operation [ Mongo::Operation ] the operation.
# @param op_name [ String | nil ] optional operation name.
# @param name [ String ] the operation name.
# @param span_name [ String ] the span name, reused as the summary.
# @param coll_name [ String | nil ] the collection name, computed once.
#
# @return [ Hash ] OpenTelemetry span attributes following MongoDB semantic conventions.
def span_attributes(operation, op_name)
{
def span_attributes(operation, name, span_name, coll_name)
attrs = {
'db.system.name' => 'mongodb',
'db.namespace' => operation.db_name.to_s,
'db.collection.name' => collection_name(operation),
'db.operation.name' => operation_name(operation, op_name),
'db.operation.summary' => operation_span_name(operation, op_name),
'db.mongodb.cursor_id' => operation.cursor_id,
}.compact
'db.operation.name' => name,
'db.operation.summary' => span_name
}
attrs['db.collection.name'] = coll_name unless coll_name.nil?
attrs
end

# Processes cursor context after operation execution.
Expand All @@ -150,7 +201,8 @@ def span_attributes(operation, op_name)
# @param cursor_id [ Integer | nil ] the cursor ID before the operation.
# @param context [ OpenTelemetry::Context ] the OpenTelemetry context.
# @param span [ OpenTelemetry::Trace::Span ] the current span.
def process_cursor_context(result, cursor_id, context, span)
# @param recording [ true | false ] whether the span is recording.
def process_cursor_context(result, cursor_id, context, span, recording)
return unless result.is_a?(Cursor)

if result.id.zero?
Expand All @@ -159,7 +211,7 @@ def process_cursor_context(result, cursor_id, context, span)
elsif result.id && cursor_id.nil?
# New cursor created, store its context.
cursor_context_map[result.id] = context
span.set_attribute('db.mongodb.cursor_id', result.id)
span.set_attribute('db.mongodb.cursor_id', result.id) if recording
end
end

Expand Down Expand Up @@ -209,16 +261,16 @@ def collection_key_for_operation(operation)

# Generates the span name for the operation.
#
# @param operation [ Mongo::Operation ] the operation.
# @param op_name [ String | nil ] optional operation name.
# @param name [ String ] the operation name.
# @param db_name [ String ] the database name.
# @param coll_name [ String | nil ] the collection name, if any.
#
# @return [ String ] span name in format "operation_name db.collection" or "operation_name db".
def operation_span_name(operation, op_name = nil)
coll_name = collection_name(operation)
def operation_span_name(name, db_name, coll_name)
if coll_name && !coll_name.empty?
"#{operation_name(operation, op_name)} #{operation.db_name}.#{coll_name}"
"#{name} #{db_name}.#{coll_name}"
else
"#{operation_name(operation, op_name)} #{operation.db_name}"
"#{name} #{db_name}"
end
end
end
Expand Down
44 changes: 21 additions & 23 deletions lib/mongo/tracing/open_telemetry/tracer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -146,34 +146,20 @@ def cursor_context_map
@cursor_context_map ||= {}
end

# Generates a unique key for cursor tracking in the context map.
#
# @param session [ Mongo::Session ] the session associated with the cursor.
# @param cursor_id [ Integer ] the cursor ID.
#
# @return [ String | nil ] unique key combining session ID and cursor ID, or nil if either is nil.
def cursor_map_key(session, cursor_id)
return if cursor_id.nil? || session.nil?

"#{session.session_id['id'].to_uuid}-#{cursor_id}"
end

# Determines the parent OpenTelemetry context for an operation.
#
# Returns the transaction context if the operation is part of a transaction,
# otherwise returns nil. Cursor-based context nesting is not currently implemented.
# Returns the transaction context if the operation is part of a
# transaction, otherwise returns nil. Cursor operations deliberately
# have no parent here: a caller-driven getMore must not be nested
# under the span of the operation that created the cursor.
#
# @param operation_context [ Mongo::Operation::Context ] the operation context.
# @param cursor_id [ Integer ] the cursor ID, if applicable.
#
# @return [ OpenTelemetry::Context | nil ] parent context or nil.
def parent_context_for(operation_context, cursor_id)
if (key = transaction_map_key(operation_context.session))
transaction_context_map[key]
elsif (_key = cursor_map_key(operation_context.session, cursor_id))
# We return nil here unless we decide how to nest cursor operations.
nil
end
def parent_context_for(operation_context)
return unless (key = transaction_map_key(operation_context.session))

transaction_context_map[key]
end

# Returns the transaction context map for tracking active transaction contexts.
Expand All @@ -200,14 +186,26 @@ def transaction_token_map
# Generates a unique key for transaction tracking.
#
# Returns nil for implicit sessions or sessions not in a transaction.
# The key is invariant for the life of a transaction but is needed on
# every operation span created inside it, and formatting it (a UUID
# plus interpolation) showed the same per-call cost the lsid cache
# removed from the command path. It is memoized on the session, keyed
# by the transaction number, so each transaction formats it once. A
# benign race may format it twice; the results are identical.
#
# @param session [ Mongo::Session ] the session.
#
# @return [ String | nil ] unique key combining session ID and transaction number, or nil.
def transaction_map_key(session)
return if session.nil? || session.implicit? || !session.in_transaction?

"#{session.session_id['id'].to_uuid}-#{session.txn_num}"
txn_num = session.txn_num
cached = session.instance_variable_get(:@otel_transaction_key)
return cached[1] if cached && cached[0] == txn_num

key = "#{session.session_id['id'].to_uuid}-#{txn_num}"
session.instance_variable_set(:@otel_transaction_key, [ txn_num, key ].freeze)
key
end

private
Expand Down
Loading
Loading