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_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- CORRELATION_DROP_SKIP_REASONS =
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.
Canonical guardrails skip reason recorded for each correlation sampler drop decision.
{ own_rate_limit: GuardrailsTelemetry::Reason::RATE_LIMIT_PROBE, global_budget: GuardrailsTelemetry::Reason::RATE_LIMIT_GLOBAL, top_gate: GuardrailsTelemetry::Reason::RATE_LIMIT_GLOBAL, trace_budget: GuardrailsTelemetry::Reason::RATE_LIMIT_TRACE_BUDGET, }.freeze
Instance Attribute Summary collapse
-
#capture_expression_evaluator ⇒ CaptureExpressionEvaluator
readonly
private
The capture expression evaluator.
- #code_tracker ⇒ Object private
- #correlation_sampler ⇒ Datadog::DI::CorrelationSampler readonly private
-
#global_log_rate_limiter ⇒ Datadog::Core::TokenBucket
readonly
private
Process-wide log rate limiter.
-
#guardrails_telemetry ⇒ GuardrailsTelemetry
readonly
private
The guardrails metric emitter.
- #logger ⇒ Object readonly private
- #serializer ⇒ Object readonly private
- #settings ⇒ Object readonly private
- #telemetry ⇒ Object readonly private
Class Method Summary collapse
Instance Method Summary collapse
-
#admit_condition_error_snapshot?(probe) ⇒ Boolean
private
Decides whether a condition-evaluation-failure notification may emit, after the probe's own condition-error limiter admitted it.
- #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, guardrails_telemetry:, capture_expression_evaluator:, correlation_sampler:, code_tracker: nil, telemetry: nil) ⇒ void
constructor
private
Initializes the instrumenter with its process-wide hard rate limiter and the coordination gate.
- #kwargs_from_splat(args) ⇒ Object private
-
#record_rate_limit_skip(reason, probe) ⇒ void
private
Emits the canonical rate-limit skip metric for a 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, guardrails_telemetry:, capture_expression_evaluator:, correlation_sampler:, code_tracker: nil, telemetry: nil) ⇒ void
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.
Initializes the instrumenter with its process-wide hard rate limiter and the coordination gate.
102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
# File 'lib/datadog/di/instrumenter.rb', line 102 def initialize(settings, serializer, logger, guardrails_telemetry:, capture_expression_evaluator:, correlation_sampler:, code_tracker: nil, telemetry: nil) @settings = settings @serializer = serializer @logger = logger @telemetry = telemetry @guardrails_telemetry = guardrails_telemetry @capture_expression_evaluator = capture_expression_evaluator @code_tracker = code_tracker @global_log_rate_limiter = Datadog::Core::TokenBucket.new(GLOBAL_LOG_RATE_LIMIT) @correlation_sampler = correlation_sampler @lock = Mutex.new end |
Instance Attribute Details
#capture_expression_evaluator ⇒ CaptureExpressionEvaluator (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.
The capture expression evaluator.
126 127 128 |
# File 'lib/datadog/di/instrumenter.rb', line 126 def capture_expression_evaluator @capture_expression_evaluator end |
#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.
127 128 129 |
# File 'lib/datadog/di/instrumenter.rb', line 127 def code_tracker @code_tracker end |
#correlation_sampler ⇒ Datadog::DI::CorrelationSampler (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.
129 130 131 |
# File 'lib/datadog/di/instrumenter.rb', line 129 def correlation_sampler @correlation_sampler 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.
139 140 141 |
# File 'lib/datadog/di/instrumenter.rb', line 139 def global_log_rate_limiter @global_log_rate_limiter end |
#guardrails_telemetry ⇒ GuardrailsTelemetry (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.
The guardrails metric emitter.
123 124 125 |
# File 'lib/datadog/di/instrumenter.rb', line 123 def guardrails_telemetry @guardrails_telemetry 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.
119 120 121 |
# File 'lib/datadog/di/instrumenter.rb', line 119 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.
118 119 120 |
# File 'lib/datadog/di/instrumenter.rb', line 118 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.
117 118 119 |
# File 'lib/datadog/di/instrumenter.rb', line 117 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.
120 121 122 |
# File 'lib/datadog/di/instrumenter.rb', line 120 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.
539 540 541 542 543 544 545 546 547 548 549 550 551 552 |
# File 'lib/datadog/di/instrumenter.rb', line 539 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
#admit_condition_error_snapshot?(probe) ⇒ Boolean
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.
Decides whether a condition-evaluation-failure notification may emit, after the probe's own condition-error limiter admitted it. A capturing probe's notification inside an active trace takes the correlation sampler's coordinated decision, consuming the trace's per-trace budget; every other notification, one with no active trace or from a non-capturing probe, consumes one GLOBAL token. Denials record the canonical rate-limit skip metric. A gate error fails open; the probe's condition-error limiter is the remaining throttle.
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 |
# File 'lib/datadog/di/instrumenter.rb', line 153 def admit_condition_error_snapshot?(probe) begin trace = current_trace if trace && probe.capturing? admitted, drop_reason = correlation_sampler.emit_with_reason?(probe, trace) else admitted = correlation_sampler.admit_process_wide_snapshot? drop_reason = :global_budget end rescue Exception => exc # standard:disable Lint/RescueException reraise_per_policy(exc) logger.debug { "[di-correlation] gate error, failing open to the probe's condition-error limiter: #{exc.class}: #{exc.message}" } telemetry&.report(exc, description: "Error in DI correlation gate") return true end unless admitted # A denial always carries its drop decision; Steep cannot infer # the pairing between the returned tuple's elements. # @type var drop_reason: Symbol record_rate_limit_skip(CORRELATION_DROP_SKIP_REASONS.fetch(drop_reason), probe) return false end true 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.
516 517 518 519 520 521 522 523 524 525 |
# File 'lib/datadog/di/instrumenter.rb', line 516 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.
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 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 |
# File 'lib/datadog/di/instrumenter.rb', line 388 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.
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 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 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 |
# File 'lib/datadog/di/instrumenter.rb', line 229 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.
960 961 962 963 964 965 966 967 |
# File 'lib/datadog/di/instrumenter.rb', line 960 def kwargs_from_splat(args) last = args.last if DI.hash?(last) [args[0...-1] || [], last] else [args, {}] end end |
#record_rate_limit_skip(reason, probe) ⇒ void
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.
This method returns an undefined value.
Emits the canonical rate-limit skip metric for a probe.
186 187 188 189 190 191 192 193 194 195 196 197 |
# File 'lib/datadog/di/instrumenter.rb', line 186 def record_rate_limit_skip(reason, probe) limit = rate_limit_skip_limit(reason) logger.trace do "di: #{probe.type} probe #{probe.id}: skipping due to #{limit}" \ " (#{reason})" end guardrails_telemetry.skipped( reason: reason, probe: probe, ) nil 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.
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 |
# File 'lib/datadog/di/instrumenter.rb', line 707 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 # The trace is captured at admission, before the customer method # runs: a method that finishes the active trace or starts a new one # must not relabel the snapshot away from the trace whose budget the # gate consumed, nor pair that trace with a span of the replacement # trace. The gate passes its own resolution to the block, so an # admitted capturing hit resolves the trace once. The declaration sits # above the begin/ensure body: steep drops @type var annotations # inside a body that has an ensure clause. # @type var admission_trace: Datadog::Tracing::TraceOperation? admission_trace = nil 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, evaluation_deadline: serializer.evaluation_deadline) 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) # An evaluation timeout is an internal budget abort, so it # stays contained even under propagate_all_exceptions. record_condition_evaluation_timeout(probe, exc) 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, condition, 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.message}" } 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.message}" } 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 admitted = continue && emit?(probe) { |trace| admission_trace = trace } admission_span = active_span_at_admission if admitted 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, deadline: serializer.serialization_deadline, **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_result = capture_expression_evaluator.evaluate(probe, entry_context) entry_capture_expressions = entry_capture_result.serialized_values entry_capture_evaluation_errors = entry_capture_result.errors 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.message}" } 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, admission_trace: admission_trace, admission_span: admission_span, 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.message}" } 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.
527 528 529 530 531 532 533 534 535 536 |
# File 'lib/datadog/di/instrumenter.rb', line 527 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.
505 506 507 508 509 510 511 512 513 514 |
# File 'lib/datadog/di/instrumenter.rb', line 505 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.
368 369 370 371 372 373 374 375 376 377 378 379 380 381 |
# File 'lib/datadog/di/instrumenter.rb', line 368 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 |