Class: Sidekiq::Profiler

Inherits:
Object
  • Object
show all
Includes:
Component
Defined in:
lib/sidekiq/profiler.rb

Overview

Allows the user to profile jobs running in production. See details in the Profiling wiki page.

Constant Summary collapse

EXPIRY =

1 day

86400
DEFAULT_OPTIONS =
{
  mode: :wall
}

Instance Attribute Summary

Attributes included from Component

#config

Instance Method Summary collapse

Methods included from Component

#default_tag, #fire_event, #handle_exception, #hostname, #identity, #inspect, #logger, #mono_ms, #process_nonce, #real_ms, #redis, #safe_thread, #tid, #watchdog

Constructor Details

#initialize(config) ⇒ Profiler

Returns a new instance of Profiler.



14
15
16
17
# File 'lib/sidekiq/profiler.rb', line 14

def initialize(config)
  @config = config
  @vernier_output_dir = ENV.fetch("VERNIER_OUTPUT_DIR") { Dir.tmpdir }
end

Instance Method Details

#call(job, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/sidekiq/profiler.rb', line 19

def call(job, &block)
  return yield unless job["profile"]

  token = job["profile"]
  type = job["class"]
  jid = job["jid"]
  started_at = Time.now

  rundata = {
    started_at: started_at.to_i,
    token: token,
    type: type,
    jid: jid,
    # .gz extension tells Vernier to compress the data
    filename: File.join(
      @vernier_output_dir,
      "#{token}-#{type}-#{jid}-#{started_at.strftime("%Y%m%d-%H%M%S")}.json.gz"
    )
  }
  profiler_options = profiler_options(job, rundata)

  require "vernier"
  begin
    a = Time.now
    rc = Vernier.profile(**profiler_options, &block)
    b = Time.now

    # Failed jobs will raise an exception on previous line and skip this
    # block. Only successful jobs will persist profile data to Redis.
    key = "#{token}-#{jid}"
    data = File.read(rundata[:filename])
    redis do |conn|
      conn.multi do |m|
        m.zadd("profiles", Time.now.to_f + EXPIRY, key)
        m.hset(key, rundata.merge(elapsed: (b - a), data: data, size: data.bytesize))
        m.expire(key, EXPIRY)
      end
    end
    rc
  ensure
    FileUtils.rm_f(rundata[:filename])
  end
end