Class: Datadog::DI::Instrumenter Private
- Inherits:
-
Object
- Object
- Datadog::DI::Instrumenter
- Defined in:
- lib/datadog/di/instrumenter.rb
Overview
This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.
Arranges to invoke a callback when a particular Ruby method or line of code is executed.
Method instrumentation is accomplished via module prepending. Unlike the alias_method_chain pattern, module prepending permits removing instrumentation with no virtually performance side-effects (the target class retains an empty included module, but no additional code is executed as part of target method).
Method hooking works with explicitly defined methods and "virtual" methods defined via method_missing.
Line instrumentation is normally accomplished with a targeted line trace point. This requires MRI and at least Ruby 2.6. For testing purposes, it is also possible to use untargeted trace points, but they have a huge performance penalty and should generally not be used in production.
Targeted line trace points require tracking of loaded code; see the CodeTracker class for more details.
Instrumentation state (i.e., the module or trace point used for instrumentation) is stored in the Probe instance. Thus, Instrumenter mutates attributes of Probes it is asked to install or remove. A previous version of the code attempted to maintain the instrumentation state within Instrumenter but this was very messy and hard to guarantee correctness of. With the state stored in Probes, it is straightforward to determine if a Probe has been successfully instrumented, and thus requires cleanup, and to properly clean it up.
Note that the upstream code is responsible for generally storing Probes.
This is normally accomplished by ProbeManager. ProbeManager stores all
known probes, instrumented or not, and is responsible for calling
unhook of Instrumenter to clean up instrumentation when a user
deletes a probe in UI or when DI is shut down.
Given the need to store state, and also that there are several Probe attributes that affect how instrumentation is set up and that must be consulted very early in the callback invocation (e.g., to perform rate limiting correctly), Instrumenter takes Probe instances as arguments rather than e.g. file + line number or class + method name. As a result, Instrumenter is rather coupled to DI the product and is not trivially usable as a general-purpose Ruby instrumentation tool (however, Probe instances can be replaced by OpenStruct instances providing the same interface with not much effort).
Instrumenter (this class) is responsible for building snapshots. This is because to capture values on method entry, those values need to be duplicated or serialized into immutable values to prevent their modification by the instrumented method. Therefore this class must do at least some serialization/snapshot building and to keep the code well-encapsulated, all serialization/snapshot building should thus be initiated from this class rather than downstream code.
As a consequence of Instrumenter building snapshots, it should not expose TracePoint objects to any downstream code.
Defined Under Namespace
Classes: Location
Constant Summary collapse
- GLOBAL_SNAPSHOT_RATE_LIMIT =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
Maximum number of capturing-probe snapshots admitted per second across the whole process.
20- GLOBAL_LOG_RATE_LIMIT =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
Maximum number of non-capturing probe emissions admitted per second across the whole process.
5000
Instance Attribute Summary collapse
- #code_tracker ⇒ Object private
-
#global_log_rate_limiter ⇒ Datadog::Core::TokenBucket
readonly
private
Process-wide log rate limiter.
-
#global_snapshot_rate_limiter ⇒ Datadog::Core::TokenBucket
readonly
private
Process-wide snapshot rate limiter.
- #logger ⇒ Object readonly private
- #serializer ⇒ Object readonly private
- #settings ⇒ Object readonly private
- #telemetry ⇒ Object readonly private
Class Method Summary collapse
Instance Method Summary collapse
- #capture_expression_evaluator ⇒ Object private
- #hook(probe, responder) ⇒ Object private
-
#hook_line(probe, responder) ⇒ Object
private
Instruments a particluar line in a source file.
-
#hook_method(probe, responder) ⇒ Object
private
Method probes can only target instance methods.
-
#initialize(settings, serializer, logger, code_tracker: nil, telemetry: nil) ⇒ Instrumenter
constructor
private
A new instance of Instrumenter.
- #kwargs_from_splat(args) ⇒ Object private
-
#probe_global_rate_limiter(probe) ⇒ Datadog::Core::TokenBucket
private
Returns the process-wide rate limiter for the probe.
-
#run_method_probe(args, kwargs, target_block, target_self, probe, responder, loc, method_name) { ... } ⇒ Object
private
Body of the method probe wrapper.
- #unhook(probe) ⇒ Object private
- #unhook_line(probe) ⇒ Object private
- #unhook_method(probe) ⇒ Object private
Constructor Details
#initialize(settings, serializer, logger, code_tracker: nil, telemetry: nil) ⇒ Instrumenter
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns a new instance of Instrumenter.
81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/datadog/di/instrumenter.rb', line 81 def initialize(settings, serializer, logger, code_tracker: nil, telemetry: nil) @settings = settings @serializer = serializer @logger = logger @telemetry = telemetry @code_tracker = code_tracker @global_snapshot_rate_limiter = Datadog::Core::TokenBucket.new(GLOBAL_SNAPSHOT_RATE_LIMIT) @global_log_rate_limiter = Datadog::Core::TokenBucket.new(GLOBAL_LOG_RATE_LIMIT) @lock = Mutex.new end |
Instance Attribute Details
#code_tracker ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
97 98 99 |
# File 'lib/datadog/di/instrumenter.rb', line 97 def code_tracker @code_tracker end |
#global_log_rate_limiter ⇒ Datadog::Core::TokenBucket (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Process-wide log rate limiter.
110 111 112 |
# File 'lib/datadog/di/instrumenter.rb', line 110 def global_log_rate_limiter @global_log_rate_limiter end |
#global_snapshot_rate_limiter ⇒ Datadog::Core::TokenBucket (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Process-wide snapshot rate limiter.
107 108 109 |
# File 'lib/datadog/di/instrumenter.rb', line 107 def global_snapshot_rate_limiter @global_snapshot_rate_limiter end |
#logger ⇒ Object (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
95 96 97 |
# File 'lib/datadog/di/instrumenter.rb', line 95 def logger @logger end |
#serializer ⇒ Object (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
94 95 96 |
# File 'lib/datadog/di/instrumenter.rb', line 94 def serializer @serializer end |
#settings ⇒ Object (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
93 94 95 |
# File 'lib/datadog/di/instrumenter.rb', line 93 def settings @settings end |
#telemetry ⇒ Object (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
96 97 98 |
# File 'lib/datadog/di/instrumenter.rb', line 96 def telemetry @telemetry end |
Class Method Details
.get_local_variables(trace_point) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
452 453 454 455 456 457 458 459 460 461 462 463 464 465 |
# File 'lib/datadog/di/instrumenter.rb', line 452 def get_local_variables(trace_point) # binding appears to be constructed on access, therefore # 1) we should attempt to cache it and # 2) we should not call +binding+ until we actually need variable values. binding = trace_point.binding # steep hack - should never happen return {} unless binding binding.local_variables.each_with_object({}) do |name, map| value = binding.local_variable_get(name) map[name] = value end end |
Instance Method Details
#capture_expression_evaluator ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
112 113 114 115 116 |
# File 'lib/datadog/di/instrumenter.rb', line 112 def capture_expression_evaluator @capture_expression_evaluator ||= CaptureExpressionEvaluator.new( settings: settings, serializer: serializer, logger: logger, telemetry: telemetry, ) end |
#hook(probe, responder) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
429 430 431 432 433 434 435 436 437 438 |
# File 'lib/datadog/di/instrumenter.rb', line 429 def hook(probe, responder) if probe.method? hook_method(probe, responder) elsif probe.line? hook_line(probe, responder) else # TODO add test coverage for this path logger.debug { "di: unknown probe type to hook: #{probe}" } end end |
#hook_line(probe, responder) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Instruments a particluar line in a source file. Note that this method only works for physical files, not for eval'd code, unless the eval'd code is associated with a file name and client invokes this method with the correct file name for the eval'd code.
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 |
# File 'lib/datadog/di/instrumenter.rb', line 301 def hook_line(probe, responder) lock.synchronize do if probe.instrumentation_trace_point # Already instrumented, warn? return end end line_no = probe.line_no! # Memoize the value to ensure this method always uses the same # value for the setting. # Normally none of the settings should change, but in the test suite # we use mock objects and the methods may be mocked with # individual invocations, yielding different return values on # different calls to the same method. permit_untargeted_trace_points = settings.dynamic_instrumentation.internal.untargeted_trace_points iseq = nil if code_tracker # Steep: Complex type narrowing (before calling hook_line, # we check that probe.line? is true which itself checks that probe.file is not nil) # Annotation do not work here as `file` is a method on probe, not a local variable. ret = if code_tracker.respond_to?(:iseq_for_line) code_tracker.iseq_for_line(probe.file, line_no) # steep:ignore ArgumentTypeMismatch else code_tracker.iseqs_for_path_suffix(probe.file) # steep:ignore ArgumentTypeMismatch end unless ret if permit_untargeted_trace_points # Continue withoout targeting the trace point. # This is going to cause a serious performance penalty for # the entire file containing the line to be instrumented. else # Do not use untargeted trace points unless they have been # explicitly requested by the user, since they cause a # serious performance penalty. # # If the requested file is not in code tracker's registry, # or the code tracker does not exist at all, # do not attempt to instrument now. # The caller should add the line to the list of pending lines # to instrument and install the hook when the file in # question is loaded (and hopefully, by then code tracking # is active, otherwise the line will never be instrumented.) raise_if_probe_in_loaded_features(probe, line_no, code_tracker) raise Error::DITargetNotDefined, "File not in code tracker registry: #{probe.file}:#{line_no}" end end elsif !permit_untargeted_trace_points # Same as previous comment, if untargeted trace points are not # explicitly defined, and we do not have code tracking, do not # instrument the method. raise_if_probe_in_loaded_features(probe, line_no, nil) raise Error::DITargetNotDefined, "File not in code tracker registry: #{probe.file}:#{line_no}" end if ret actual_path, iseq = ret end # If trace point is not targeted, we only need one trace point per file. # Creating a trace point for each probe does work but the performance # penalty will be taken for each trace point defined in the file. # Since untargeted trace points are only (currently) used internally # for benchmarking, and shouldn't be used in customer applications, # we always create a trace point here to reduce complexity. # # For targeted trace points, if multiple probes target the same # file and line, we also only need one trace point, but since the # overhead of targeted trace points is minimal, don't worry about # this optimization just yet and create a trace point for each probe. types = if iseq # When targeting trace points we can target the 'end' line of a method. # However, by adding the :return trace point we lose diagnostics # for lines that contain no executable code (e.g. comments only) # and thus cannot actually be instrumented. [:line, :return, :b_return] else [:line] end tp = TracePoint.new(*types) do |tp| line_trace_point_callback(probe, iseq, responder, tp) end # Internal sanity check - untargeted trace points create a huge # performance impact, and we absolutely do not want to set them # accidentally. if !iseq && !permit_untargeted_trace_points raise Error::InternalError, "Trying to use an untargeted trace point when user did not permit it" end lock.synchronize do if probe.instrumentation_trace_point # Already instrumented in another thread, warn? return end probe.instrumentation_trace_point = tp # actual_path could be nil if we don't use targeted trace points. probe.instrumented_path = actual_path # TracePoint#enable returns false when it succeeds. rv = if iseq tp.enable(target: iseq, target_line: line_no) else tp.enable end DI.instrumented_count_inc(:line) rv end true end |
#hook_method(probe, responder) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Method probes can only target instance methods. The implementation uses Module#prepend with a module that defines an instance method matching the probe's target — class/singleton methods (def self.foo, module_function) are not reachable via prepend on the class itself. Line probes are unaffected since they install via TracePoint, not method dispatch.
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/datadog/di/instrumenter.rb', line 142 def hook_method(probe, responder) # Reject method probes targeting any class or module in the Datadog # namespace. The tracer uses these classes internally while building # and dispatching probe snapshots; allowing a method probe on them # would let DI's own code paths re-enter the probe wrapper. Line # probes are unaffected (TracePoint is self-disabling during its # callback) and are not rejected here. type_name = probe.type_name if type_name && datadog_namespace_type_name?(type_name) raise Error::ProbeTargetForbidden, "Method probes on the Datadog namespace are not permitted: #{type_name}##{probe.method_name}" end lock.synchronize do if probe.instrumentation_module # Already instrumented, warn? return end end cls = symbolize_class_name(probe.type_name) method_name = probe.method_name! target_method = begin cls.instance_method(method_name) rescue NameError # The target method is not defined. # This could be because it will be explicitly defined later # (since classes can be reopened in Ruby) # or the method is virtual (provided by a method_missing handler). # In these cases we do not have a source location for the # target method here. nil end # Reject method probes whose target method resolves to Kernel#lambda, # including inherited targets. Every class inherits Kernel#lambda, so a # probe naming any type that does not override lambda (Object#lambda, # String#lambda, a plain user class, ...) prepends the wrapper ahead of # Kernel#lambda and reaches the wrapper's super(&block) path. On # Ruby 3.3+ that path raises ArgumentError for every lambda { ... } # call site passing a captured block, breaking lambda creation # process-wide. Resolving the method owner catches the inherited case # that a textual "Kernel" name match misses; a type that defines its # own lambda has a different owner and is left alone. Probing lambda # creation has no legitimate customer use case. See #5560. if method_name == "lambda" && target_method&.owner == ::Kernel raise Error::ProbeTargetForbidden, "Method probes on Kernel#lambda are not permitted: #{probe.type_name}##{method_name}" end loc = target_method&.source_location # @type var instrumenter: Instrumenter instrumenter = self mod = Module.new do # Argument delegation follows docs/Delegation.md: on Ruby 3+ # positional and keyword arguments are captured and forwarded # separately; on Ruby < 3 everything is captured into a single # splat that ruby2_keywords flags, which is the only way to forward # a trailing hash while preserving its positional-vs-keyword # identity. The pre-3 branch is what lets an empty trailing hash # (e.g. foo('x', {})) reach the original method intact. # # Re-entrancy guard: if we are already inside a DI method-probe # callback, skip DI processing and call the original method # directly. This prevents SystemStackError when a method probe is # set on a stdlib method that DI itself calls during method-probe # snapshot building (e.g., String#length, Hash#each). Line probes # do not enter the guard — they rely on Ruby's TracePoint, which # self-disables during its own callback. Nested invocations during # DI processing also bypass the rate limiter: they are not # user-observable probe firings, just internal calls that happen to # land on a probed method. Guard storage is fiber-local; # DI.in_probe?/enter_probe/leave_probe are implemented in C and # access it directly, bypassing Thread#[]/Thread#[]= method dispatch # so user probes on those cannot recurse. # # The original method is invoked via super. That super call lives # in a block passed to #run_method_probe and captures its binding # from inside this define_method block — the only place super # resolves to the prepended-on class's method. #run_method_probe # invokes it with yield, which does not dispatch Proc#call, so a # user probe on Proc#call cannot intercept the trampoline, and no # Proc is allocated for the block. if RubyVersion.is?(">= 3") define_method(method_name) do |*args, **kwargs, &target_block| # steep:ignore FallbackAny below: Steep cannot narrow the # **kwargs parameter inside this define_method block, so it # falls back to untyped at the super and run_method_probe sites. if DI.in_probe? return super(*args, **kwargs, &target_block) # steep:ignore FallbackAny end instrumenter.run_method_probe( args, kwargs, target_block, # steep:ignore FallbackAny self, probe, responder, loc, method_name, ) do super(*args, **kwargs, &target_block) # steep:ignore FallbackAny end end else define_method(method_name) do |*args, &target_block| if DI.in_probe? return super(*args, &target_block) end # The super block replays the original *args (closed over here) # so the ruby2_keywords-flagged trailing hash keeps its # identity. run_method_probe receives the serialization-split # arguments separately; forwarding does not use them. pos_args, kwargs = instrumenter.kwargs_from_splat(args) instrumenter.run_method_probe( pos_args, kwargs, target_block, self, probe, responder, loc, method_name, ) do super(*args, &target_block) end end ruby2_keywords(method_name) if respond_to?(:ruby2_keywords, true) end end lock.synchronize do if probe.instrumentation_module # Already instrumented from another thread return end probe.instrumentation_module = mod cls.send(:prepend, mod) DI.instrumented_count_inc(:method) end end |
#kwargs_from_splat(args) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
740 741 742 743 744 745 746 747 |
# File 'lib/datadog/di/instrumenter.rb', line 740 def kwargs_from_splat(args) last = args.last if DI.hash?(last) [args[0...-1] || [], last] else [args, {}] end end |
#probe_global_rate_limiter(probe) ⇒ Datadog::Core::TokenBucket
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns the process-wide rate limiter for the probe.
122 123 124 125 126 127 128 |
# File 'lib/datadog/di/instrumenter.rb', line 122 def probe_global_rate_limiter(probe) if probe.capturing? global_snapshot_rate_limiter else global_log_rate_limiter end end |
#run_method_probe(args, kwargs, target_block, target_self, probe, responder, loc, method_name) { ... } ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Body of the method probe wrapper. Extracted from the define_method block in #hook_method so the begin/ensure structure can use normal indentation. The original method is invoked with yield, calling the block passed by #hook_method; that block captures super's binding from inside the define_method block, the only place super resolves to the prepended-on class's method.
Performance: this method takes eight positional parameters, not keyword parameters, deliberately. Every probed method invocation passes through here on the firing/disabled/rate-limited paths. Keyword-argument calls in Ruby allocate a fresh Hash on every call to materialize the keyword bindings; with eight keyword arguments (~300-1000 ns of allocation per invocation), that hash dominated the wrapper's per-call overhead. Positional parameters skip the allocation entirely. The cost is a long unlabeled signature and an unlabeled call site in #hook_method — both small price for eliminating per-call allocation on the hot path. The argument order matches #hook_method's call site exactly; do not reorder without updating both sides.
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 |
# File 'lib/datadog/di/instrumenter.rb', line 502 def run_method_probe(args, kwargs, target_block, target_self, probe, responder, loc, method_name) # Disabled probe: skip DI processing entirely. enter_probe is not # called on this path so the guard is never set — there is no DI # work to guard, and any nested probed methods invoked by the # original method should fire normally without short-circuit. return yield unless probe.enabled? DI.enter_probe begin di_start_time = Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID) continue = true if condition = probe.condition begin # This context will be recreated later, unlike for line probes. # # We do not need the stack for condition evaluation, therefore # stack is not passed to Context here. context = Context.new( locals: serializer.combine_args(args, kwargs, target_self), target_self: target_self, probe: probe, settings: settings, serializer: serializer, ) continue = condition.satisfied?(context) rescue Exception => exc # standard:disable Lint/RescueException Datadog::DI.reraise_if_fatal(exc) # Evaluation error exception can be raised for "expected" # errors, we probably need another setting to control whether # these exceptions are propagated. raise if settings.dynamic_instrumentation.internal.propagate_all_exceptions && !exc.is_a?(DI::Error::ExpressionEvaluationError) if context # We want to report evaluation errors for conditions # as probe snapshots. However, if we failed to create # the context, we won't be able to report anything as # the probe notifier builder requires a context. begin responder.probe_condition_evaluation_failed_callback(context, exc) rescue Exception => nested_exc # standard:disable Lint/RescueException Datadog::DI.reraise_if_fatal(nested_exc) raise if settings.dynamic_instrumentation.internal.propagate_all_exceptions logger.debug { "di: error in probe condition evaluation failed callback: #{nested_exc.class}: #{nested_exc.}" } telemetry&.report(nested_exc, description: "Error in probe condition evaluation failed callback") end else raise if settings.dynamic_instrumentation.internal.propagate_all_exceptions logger.debug { "di: error evaluating condition without context (tracer bug?): #{exc.class}: #{exc.}" } telemetry&.report(exc, description: "Error evaluating condition without context") # If execution gets here, there is probably a bug in the tracer. end continue = false end end rate_limiter = probe.rate_limiter admitted = continue && (rate_limiter.nil? || rate_limiter.allow?) if admitted && !probe_global_rate_limiter(probe).allow? admitted = false logger.trace { "di: #{probe.type} probe #{probe.id}: skipping due to global rate limit" } end if admitted # Arguments may be mutated by the method, therefore # they need to be serialized prior to method invocation. serialized_entry_args = if probe.capture_snapshot? serializer.serialize_args(args, kwargs, target_self, **probe.snapshot_serializer_limits(settings)) end entry_capture_expressions = nil entry_capture_evaluation_errors = nil if probe.capture_entry_expressions? begin entry_context = Context.new( probe: probe, settings: settings, serializer: serializer, target_self: target_self, locals: serializer.combine_args(args, kwargs, target_self), ) entry_capture_expressions, entry_capture_evaluation_errors = capture_expression_evaluator.evaluate(probe, entry_context) rescue Exception => exc # standard:disable Lint/RescueException Datadog::DI.reraise_if_fatal(exc) raise if settings.dynamic_instrumentation.internal.propagate_all_exceptions logger.debug { "di: error evaluating entry-time capture expressions: #{exc.class}: #{exc.}" } telemetry&.report(exc, description: "Error evaluating entry-time capture expressions") end end # We intentionally do not use Core::Utils::Time.get_time # here because the time provider may be overridden by the # customer, and DI is not allowed to invoke customer code. start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) di_duration = Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID) - di_start_time # Release re-entrancy guard for the original method so that # probes on other methods (or recursive calls) fire normally # during user code execution. DI.leave_probe rv = nil begin # yield invokes the super block without dispatching Proc#call, # so a user probe on Proc#call cannot intercept the trampoline. # The guard was just released above so nested probes on the # customer method body fire normally — but Proc#call must # remain bypassed regardless, because the disabled-probe early # return at the top of this method also invokes the block. rv = yield rescue Exception => exc # standard:disable Lint/RescueException Datadog::DI.reraise_if_fatal(exc) # We will raise the (non-fatal) exception captured here later, # after the instrumentation callback runs. end # Re-acquire re-entrancy guard for DI post-processing # (building context, notification callback). DI.enter_probe end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) duration = end_time - start_time # Restart DI timer. # The DI execution duration covers time spent in DI code before # the customer method is invoked and time spent in DI code # after the customer method finishes. di_start_time = Process.clock_gettime(Process::CLOCK_THREAD_CPUTIME_ID) # The method itself is not part of the stack trace because # we are getting the stack trace from outside of the method. # Add the method in manually as the top frame. method_frame = if loc [Location.new(loc.first, loc.last, method_name)] else # For virtual and lazily-defined methods, we do not have # the original source location here, and they won't be # included in the stack trace currently. # TODO when begin/end trace points are added for local # variable capture in method probes, we should be able # to obtain actual method execution location and use # that location here. [] end # depth 2 skips run_method_probe and the wrapper define_method # block, leaving the user's call site as the first returned frame. # caller_locations is RBS-nilable but never nil at this depth. caller_locs = method_frame + (caller_locations(2) || []) # TODO capture arguments at exit capture_expression_locals = if probe.capture_expressions_only? serializer.combine_args(args, kwargs, target_self) end context = Context.new(locals: capture_expression_locals, target_self: target_self, probe: probe, settings: settings, serializer: serializer, serialized_entry_args: serialized_entry_args, entry_capture_expressions: entry_capture_expressions, entry_capture_evaluation_errors: entry_capture_evaluation_errors, caller_locations: caller_locs, return_value: rv, duration: duration, exception: exc,) begin responder.probe_executed_callback(context) check_and_disable_if_exceeded(probe, responder, di_start_time, di_duration) rescue Exception => di_exc # standard:disable Lint/RescueException Datadog::DI.reraise_if_fatal(di_exc) raise if settings.dynamic_instrumentation.internal.propagate_all_exceptions logger.debug { "di: unhandled exception in method probe: #{di_exc.class}: #{di_exc.}" } telemetry&.report(di_exc, description: "Unhandled exception in method probe") end if exc raise exc else rv end else # Condition not satisfied or rate-limited: skip DI processing # and call super. (The disabled-probe case is handled by the # early return at the top of this method, so it never reaches # this branch.) # # The guard must be released here (not relied on the ensure) # because the super block invokes the customer's method, which # may call other probed methods. Those nested probes should fire # normally — they would not if the guard were still set, # because the wrapper's early-return short-circuits when # DI.in_probe? is true. # # No post-processing in this branch, so we don't re-acquire # the guard after super. The ensure's leave_probe below is # a no-op here (guard already cleared) and serves the # firing branch above, where post-processing re-enters. DI.leave_probe # yield bypasses Proc#call dispatch — see the firing branch # above for the same rationale. yield end ensure DI.leave_probe end end |
#unhook(probe) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
440 441 442 443 444 445 446 447 448 449 |
# File 'lib/datadog/di/instrumenter.rb', line 440 def unhook(probe) if probe.method? unhook_method(probe) elsif probe.line? unhook_line(probe) else # TODO add test coverage for this path logger.debug { "di: unknown probe type to unhook: #{probe}" } end end |
#unhook_line(probe) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
418 419 420 421 422 423 424 425 426 427 |
# File 'lib/datadog/di/instrumenter.rb', line 418 def unhook_line(probe) lock.synchronize do if tp = probe.instrumentation_trace_point tp.disable probe.instrumentation_trace_point = nil DI.instrumented_count_dec(:line) end end end |
#unhook_method(probe) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
281 282 283 284 285 286 287 288 289 290 291 292 293 294 |
# File 'lib/datadog/di/instrumenter.rb', line 281 def unhook_method(probe) # Ruby does not permit removing modules from classes. # We can, however, remove method definitions from modules. # After this the modules remain in memory and stay included # in the classes but are empty (have no methods). lock.synchronize do if mod = probe.instrumentation_module mod.send(:remove_method, probe.method_name) probe.instrumentation_module = nil DI.instrumented_count_dec(:method) end end end |