2018-11-19 21:01:13 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2016-07-15 11:46:39 -04:00
|
|
|
require 'ruby-prof'
|
|
|
|
|
|
|
|
module Gitlab
|
|
|
|
module RequestProfiler
|
|
|
|
class Middleware
|
|
|
|
def initialize(app)
|
|
|
|
@app = app
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
|
|
|
if profile?(env)
|
|
|
|
call_with_profiling(env)
|
|
|
|
else
|
|
|
|
@app.call(env)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def profile?(env)
|
|
|
|
header_token = env['HTTP_X_PROFILE_TOKEN']
|
|
|
|
return unless header_token.present?
|
|
|
|
|
2017-02-02 04:21:14 -05:00
|
|
|
profile_token = Gitlab::RequestProfiler.profile_token
|
2016-07-15 11:46:39 -04:00
|
|
|
return unless profile_token.present?
|
|
|
|
|
|
|
|
header_token == profile_token
|
|
|
|
end
|
|
|
|
|
|
|
|
def call_with_profiling(env)
|
|
|
|
ret = nil
|
|
|
|
result = RubyProf::Profile.profile do
|
2016-08-01 10:55:50 -04:00
|
|
|
ret = catch(:warden) do
|
|
|
|
@app.call(env)
|
|
|
|
end
|
2016-07-15 11:46:39 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
printer = RubyProf::CallStackPrinter.new(result)
|
|
|
|
file_name = "#{env['PATH_INFO'].tr('/', '|')}_#{Time.current.to_i}.html"
|
|
|
|
file_path = "#{PROFILES_DIR}/#{file_name}"
|
|
|
|
|
|
|
|
FileUtils.mkdir_p(PROFILES_DIR)
|
|
|
|
File.open(file_path, 'wb') do |file|
|
|
|
|
printer.print(file)
|
|
|
|
end
|
|
|
|
|
2016-08-01 10:55:50 -04:00
|
|
|
if ret.is_a?(Array)
|
|
|
|
ret
|
|
|
|
else
|
|
|
|
throw(:warden, ret)
|
|
|
|
end
|
2016-07-15 11:46:39 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|