Skip to content

Commit

Permalink
Add sidekiq profiler middleware that puts periodic heap dumps on s3
Browse files Browse the repository at this point in the history
  • Loading branch information
stenington committed Apr 24, 2017
1 parent 4883e2a commit 7d819bd
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
9 changes: 9 additions & 0 deletions config/initializers/sidekiq.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,13 @@
if database_url = ENV['DATABASE_URL']
ActiveRecord::Base.establish_connection "#{database_url}?pool=25"
end

if ENV["PROFILE_SIDEKIQ"].present?
require "sidekiq_profiler"
ObjectSpace.trace_object_allocations_start
Sidekiq.logger.info "allocations tracing enabled"
config.server_middleware do |chain|
chain.add Sidekiq::Middleware::Server::Profiler
end
end
end
62 changes: 62 additions & 0 deletions lib/sidekiq_profiler.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
require "objspace"
require "tempfile"

class HeapDumpUploader < CarrierWave::Uploader::Base
storage :fog

def store_dir
"heap_dumps"
end
end

module Sidekiq
module Middleware
module Server
class Profiler

# Number of jobs to process before reporting
JOBS = ENV.fetch("SIDEKIQ_PROFILER_REPORT_INCREMENT") { 100 }.to_i
STAMP = Time.now.to_i

class << self
mattr_accessor :counter
self.counter = 0

def synchronize(&block)
@lock ||= Mutex.new
@lock.synchronize(&block)
end
end

def call(worker_instance, item, queue)
begin
yield
ensure
self.class.synchronize do
self.class.counter += 1

if self.class.counter % JOBS == 0
Sidekiq.logger.info "reporting allocations after #{self.class.counter} jobs"
GC.start
basename = "heap-#{STAMP}-#{self.class.counter}-"
f = Tempfile.new([basename, '.json'])
begin
ObjectSpace.dump_all(output: f)
Sidekiq.logger.info "heap saved to #{f.path}"
if ENV["UPLOAD_SIDEKIQ_HEAP_DUMPS"].present?
uploader = HeapDumpUploader.new
uploader.store!(f)
Sidekiq.logger.info "heap uploaded to #{uploader.url}"
end
ensure
f.close
f.unlink
end
end
end
end
end
end
end
end
end

0 comments on commit 7d819bd

Please sign in to comment.