File: stack_prof.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (68 lines) | stat: -rw-r--r-- 2,278 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
62
63
64
65
66
67
68
# frozen_string_literal: true

require 'stackprof'

# Applies stackprof instrumentation to a given rspec context
# Use as context "your context", :stackprof do
# or as context "your context", stackprof: { mode: wall, interval: 100000 } do
# to change arguments to stackprof.
#
# Results will be gzipped and placed in tmp/ if running locally, or rspec/ if running in CI, and can be viewed
# with any json-compatible flamegraph viewer, such as speedscope.

module Support
  module StackProf
    def self.start(example)
      puts "Starting stackprof"
      raise "Cannot nest stackprof calls!" if ::StackProf.running?

      ::StackProf.start(**stackprof_args_for(example))
    end

    def self.finish(example)
      raise "Stackprof was not running!" unless ::StackProf.running?

      ::StackProf.stop
      puts 'finishing stackprof'
      location = example.class.metadata[:location]
      # Turn a file path like ./spec/path/to/spec.rb:123 into spec_path_to_spec_123
      location_sanitized = location.gsub('./', '').tr('/', '_').gsub('.rb', '').tr(':', '_')

      out_filepath = if ENV['CI']
                       "rspec/stackprof_#{location_sanitized}-#{ENV['CI_JOB_NAME_SLUG']}.json.gz"
                     else
                       "tmp/stackprof_#{location_sanitized}.json.gz"
                     end

      start_time = ::Gitlab::Metrics::System.monotonic_time
      Zlib::GzipWriter.open(out_filepath) do |gz|
        gz.puts Gitlab::Json.generate(::StackProf.results)
      end
      end_time = ::Gitlab::Metrics::System.monotonic_time
      puts "Wrote stackprof dump to #{out_filepath} in #{(end_time - start_time).round(2)}s"
    end

    def self.stackprof_args_for(example)
      caller_config = example.class.metadata[:stackprof]
      default = {
        mode: :wall,
        interval: 10100, # in us, 99hz
        raw: true # Needed for flamegraphs
      }
      # If called as `:stackprof`, the value will be a literal `true`
      return default unless caller_config.is_a?(Hash)

      default.merge(caller_config)
    end
  end
end

RSpec.configure do |config|
  config.before(:all, :stackprof) do |example|
    Support::StackProf.start(example)
  end

  config.after(:all, :stackprof) do |example|
    Support::StackProf.finish(example)
  end
end