Skip to content

Commit

Permalink
Merge pull request #3747 from DataDog/tonycthsu/fix-injection
Browse files Browse the repository at this point in the history
Fix lib injection with fork
  • Loading branch information
TonyCTHsu committed Jul 5, 2024
2 parents da8b886 + 89dffeb commit ac9cae5
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions lib-injection/host_inject.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
require 'json'

def dd_debug_log(msg)
$stdout.puts "[datadog] #{msg}" if ENV['DD_TRACE_DEBUG'] == 'true'
pid = Process.respond_to?(:pid) ? Process.pid : 0 # Not available on all platforms
$stdout.puts "[datadog][#{pid}][#{$0}] #{msg}" if ENV['DD_TRACE_DEBUG'] == 'true'
end

def dd_error_log(msg)
warn "[datadog] #{msg}"
pid = Process.respond_to?(:pid) ? Process.pid : 0 # Not available on all platforms
warn "[datadog][#{pid}][#{$0}] #{msg}"
end

def dd_skip_injection!
Expand Down Expand Up @@ -92,8 +94,19 @@ def dd_send_telemetry(events)
return # Skip injection
end

unless Process.respond_to?(:fork)
dd_debug_log 'Fork not supported... skipping injection'
return
end

already_installed = ['ddtrace', 'datadog'].any? do |gem|
!!Bundler::CLI::Common.select_spec(gem) rescue false
fork {
$stdout = File.new("/dev/null", "w")
$stderr = File.new("/dev/null", "w")
Bundler::CLI::Common.select_spec(gem)
}
_, status = Process.wait2
status.success?
end

if already_installed
Expand Down Expand Up @@ -144,7 +157,14 @@ def dd_send_telemetry(events)
'libddwaf',
'datadog'
].each do |gem|
if (Bundler::CLI::Common.select_spec(gem) rescue false)
fork {
$stdout = File.new("/dev/null", "w")
$stderr = File.new("/dev/null", "w")
Bundler::CLI::Common.select_spec(gem)
}

_, status = Process.wait2
if status.success?
dd_debug_log "#{gem} already installed... skipping..."
next
end
Expand Down Expand Up @@ -191,7 +211,8 @@ def dd_send_telemetry(events)
]
)
end
warn "[datadog] Injection failed: #{e.class.name} #{e.message}\nBacktrace: #{e.backtrace.join("\n")}"
pid = Process.respond_to?(:pid) ? Process.pid : 0 # Not available on all platforms
warn "[datadog][#{pid}][#{$0}] Injection failed: #{e.class.name} #{e.message}\nBacktrace: #{e.backtrace.join("\n")}"

# Skip injection if the environment variable is set
ENV['DD_TRACE_SKIP_LIB_INJECTION'] = 'true'
Expand Down

0 comments on commit ac9cae5

Please sign in to comment.