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

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

Overview

Adds at_fork behavior; see parent module for details.

Instance Method Summary collapse

Instance Method Details

#fork ⇒ Object



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
# File 'lib/datadog/core/utils/at_fork_monkey_patch.rb', line 161

def fork
  snapshot = AtForkMonkeyPatch.snapshot_at_fork_blocks
  started = {}

  # If a block is provided, it must be wrapped to trigger callbacks.
  child_block = if block_given?
    proc do
      AtForkMonkeyPatch.run_at_fork_blocks(:child, snapshot: snapshot)

      # Invoke original block
      yield
    end
  end #: (^() -> void)?

  begin
    # Run pre-fork callbacks in the parent, just before forking.
    AtForkMonkeyPatch.run_at_fork_blocks(:before, snapshot: snapshot, started: started)

    # Start fork. If a block is provided, use the wrapped version.
    result = child_block.nil? ? super : super(&child_block)
  rescue Exception => e # rubocop:disable Lint/RescueException -- re-raised unchanged; we only need to run parent cleanup first
    # The fork or a before-fork callback failed and we are still in
    # the parent. Restore any state set up by earlier callbacks.
    AtForkMonkeyPatch.send(:run_parent_cleanup, snapshot, started, e)
    raise
  end

  # When fork gets called without a block, it returns twice:
  # If we're in the fork, result = nil: trigger child callbacks.
  # If we're in the parent, result = pid: trigger parent callbacks.
  # (If it gets called with a block, it only returns on the parent)
  if result.nil?
    AtForkMonkeyPatch.run_at_fork_blocks(:child, snapshot: snapshot)
  else
    AtForkMonkeyPatch.run_at_fork_blocks(:parent, snapshot: snapshot)
  end

  result
end