Created
November 18, 2025 20:45
-
-
Save skojin/cda7ec1f8d01cd62e067cf7e1487a903 to your computer and use it in GitHub Desktop.
Get ObjectSpace heap dump via signal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # frozen_string_literal: true | |
| # Heap Dump Signal Trap | |
| # | |
| # Send CONT signal to the process to trigger a heap dump. | |
| # | |
| # Usage: | |
| # kill -CONT <pid> | |
| # | |
| # Output: | |
| # - First signal: Starts object allocation tracking (no dump created) | |
| # - Subsequent signals: Creates /tmp/heap-1.json, /tmp/heap-2.json, etc. | |
| # - Logs: /tmp/heapdump.log | |
| # | |
| # Analysis tools: | |
| # - https://github.com/Shopify/heap-profiler | |
| # - https://github.com/zombocom/heapy | |
| # - https://github.com/jhawthorn/sheap | |
| # - https://github.com/oxidize-rb/reap | |
| heap_dump_counter = -1 | |
| Signal.trap("CONT") do | |
| Thread.new do | |
| heap_dump_counter += 1 | |
| # Check if this is the first signal | |
| if heap_dump_counter.zero? | |
| require 'objspace' | |
| ObjectSpace.trace_object_allocations_start | |
| File.open("/tmp/heapdump.log", "a") do |f| | |
| f.puts "[#{Time.now.iso8601}] [PID:#{Process.pid}] ObjectSpace.trace_object_allocations_start" | |
| end | |
| next | |
| end | |
| filename = "/tmp/heap-#{heap_dump_counter}.json" | |
| File.open("/tmp/heapdump.log", "a") do |f| | |
| f.puts "[#{Time.now.iso8601}] [PID:#{Process.pid}] Creating heap dump: #{filename}" | |
| end | |
| # Trigger garbage collection before dump for cleaner results | |
| GC.start | |
| File.open(filename, "w") do |file| | |
| ObjectSpace.dump_all(output: file) | |
| end | |
| file_size = File.size(filename) / 1024 / 1024 # Size in MB | |
| File.open("/tmp/heapdump.log", "a") { |f| | |
| f.puts "[#{Time.now.iso8601}] [PID:#{Process.pid}] Heap dump created: #{filename} (#{file_size} MB)" | |
| } | |
| rescue => ex | |
| File.open("/tmp/heapdump.log", "a") { |f| | |
| f.puts "[#{Time.now.iso8601}] [PID:#{Process.pid}] ERROR: #{ex.message}\n#{ex.backtrace.join("\n")}" | |
| } | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment