Module: Datadog::Core::Utils::AtForkMonkeyPatch

Defined in:
lib/datadog/core/utils/at_fork_monkey_patch.rb

Overview

Monkey patches ‘Kernel#fork` and similar functions, adding an `at_fork` callback mechanism which is used to restart observability after the VM forks (e.g. in multiprocess Ruby apps).

Defined Under Namespace

Modules: KernelMonkeyPatch, ProcessMonkeyPatch

Class Method Summary collapse

Class Method Details

.apply!Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/datadog/core/utils/at_fork_monkey_patch.rb', line 16

def self.apply!
  return false unless supported?

  if RUBY_VERSION < '3.1'
    [
      ::Process.singleton_class, # Process.fork
      ::Kernel.singleton_class,  # Kernel.fork
      ::Object,                  # fork without explicit receiver (it's defined as a method in ::Kernel)
      # Note: Modifying Object as we do here is irreversible. During tests, this
      # change will stick around even if we otherwise stub `Process` and `Kernel`
    ].each { |target| target.prepend(KernelMonkeyPatch) }
  end

  ::Process.singleton_class.prepend(ProcessMonkeyPatch)

  true
end

.at_fork(stage, &block) ⇒ Object

Raises:

  • (ArgumentError)


40
41
42
43
44
45
46
47
# File 'lib/datadog/core/utils/at_fork_monkey_patch.rb', line 40

def self.at_fork(stage, &block)
  raise(ArgumentError, "Unsupported stage #{stage}") unless stage == :child
  raise(ArgumentError, 'Missing block argument') unless block

  AT_FORK_CHILD_BLOCKS << block

  true
end

.run_at_fork_blocks(stage) ⇒ Object

Raises:

  • (ArgumentError)


34
35
36
37
38
# File 'lib/datadog/core/utils/at_fork_monkey_patch.rb', line 34

def self.run_at_fork_blocks(stage)
  raise(ArgumentError, "Unsupported stage #{stage}") unless stage == :child

  AT_FORK_CHILD_BLOCKS.each(&:call)
end

.supported?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/datadog/core/utils/at_fork_monkey_patch.rb', line 12

def self.supported?
  Process.respond_to?(:fork)
end