From 3e03fd3847dc3a6d8a52704bd7c0219652e89391 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Tue, 31 Jan 2023 16:13:27 +0100 Subject: [PATCH] Dump heap from a fork Dumping the heap can lock the VM for a very long time. If you attempt to do this on a webserver process with a timeout it's very likely you'll hit it and the process might get killed before the dump completes. Worse, if the process was processing some requests or jobs, they might timeout because of it. Using fork we can make a snapshot of the heap in a very short time (relative to the dump itself) and savely dump without disrupting the original process. If you are familiar with how Redis does sanopshoting, it's very similar. --- lib/rbtrace/cli.rb | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/rbtrace/cli.rb b/lib/rbtrace/cli.rb index 45fe7e9..d54de18 100644 --- a/lib/rbtrace/cli.rb +++ b/lib/rbtrace/cli.rb @@ -503,7 +503,19 @@ def self.run temp.unlink end - tracer.eval("file = File.open('#{filename}', 'w'); ObjectSpace.dump_all(output: file); file.close") + tracer.eval(<<-RUBY) + Thread.new do + Thread.current.name = '__RBTrace__' + pid = ::Process.fork do + file = File.open('#{filename}.tmp', 'w') + ObjectSpace.dump_all(output: file) + file.close + File.rename('#{filename}.tmp', '#{filename}') + exit!(0) + end + Process.waitpid(pid) + end + RUBY puts "Heapdump being written to #{filename}" elsif opts[:shapesdump_given] @@ -517,7 +529,19 @@ def self.run temp.unlink end - tracer.eval("file = File.open('#{filename}', 'w'); ObjectSpace.dump_shapes(output: file); file.close") + tracer.eval(<<-RUBY) + Thread.new do + Thread.current.name = '__RBTrace__' + pid = ::Process.fork do + file = File.open('#{filename}.tmp', 'w') + ObjectSpace.dump_shapes(output: file) + file.close + File.rename('#{filename}.tmp', '#{filename}') + exit!(0) + end + Process.waitpid(pid) + end + RUBY puts "Shapes dump being written to #{filename}" elsif opts[:eval_given]