Class: Rack::MiniProfiler
- Inherits:
-
Object
- Object
- Rack::MiniProfiler
- Extended by:
- ProfilingMethods
- Defined in:
- lib/mini_profiler/config.rb,
lib/mini_profiler/version.rb,
lib/mini_profiler/profiler.rb,
lib/patches/db/activerecord.rb,
lib/mini_profiler/asset_version.rb,
lib/mini_profiler/client_settings.rb,
lib/mini_profiler/timer_struct/sql.rb,
lib/mini_profiler/profiling_methods.rb,
lib/mini_profiler/timer_struct/base.rb,
lib/mini_profiler/timer_struct/page.rb,
lib/mini_profiler/storage/file_store.rb,
lib/mini_profiler/storage/redis_store.rb,
lib/mini_profiler/timer_struct/client.rb,
lib/mini_profiler/timer_struct/custom.rb,
lib/mini_profiler/storage/memory_store.rb,
lib/mini_profiler/timer_struct/request.rb,
lib/mini_profiler/storage/abstract_store.rb,
lib/mini_profiler/storage/memcache_store.rb
Defined Under Namespace
Modules: ActiveRecordInstrumentation, ProfilingMethods, TimerStruct Classes: AbstractStore, ClientSettings, Config, Context, FileStore, GCProfiler, MemcacheStore, MemoryStore, RedisStore
Constant Summary collapse
- VERSION =
'0.9.3'
- ASSET_VERSION =
'9db1f8db18400644bd5c7449e5295620'.freeze
Class Method Summary collapse
- .authorize_request ⇒ Object
-
.config ⇒ Object
So we can change the configuration if we want.
- .create_current(env = {}, options = {}) ⇒ Object
- .current ⇒ Object
- .current=(c) ⇒ Object
- .deauthorize_request ⇒ Object
-
.discard_results ⇒ Object
discard existing results, don’t track this request.
- .generate_id ⇒ Object
- .request_authorized? ⇒ Boolean
- .reset_config ⇒ Object
- .share_template ⇒ Object
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#cancel_auto_inject(env) ⇒ Object
cancels automatic injection of profile script for the current page.
- #config ⇒ Object
- #current ⇒ Object
- #current=(c) ⇒ Object
- #dump_env(env) ⇒ Object
- #dump_exceptions(exceptions) ⇒ Object
- #flamegraph(graph) ⇒ Object
-
#get_profile_script(env) ⇒ Object
get_profile_script returns script to be injected inside current html page By default, profile_script is appended to the end of all html requests automatically.
- #help(client_settings) ⇒ Object
- #ids(env) ⇒ Object
- #ids_comma_separated(env) ⇒ Object
- #ids_json(env) ⇒ Object
-
#initialize(app, config = nil) ⇒ MiniProfiler
constructor
options: :auto_inject - should script be automatically injected on every html page (not xhr).
- #inject(fragment, script) ⇒ Object
- #inject_profiler(env, status, headers, body) ⇒ Object
- #serve_html(env) ⇒ Object
- #serve_results(env) ⇒ Object
- #text_result(body) ⇒ Object
- #user(env) ⇒ Object
Methods included from ProfilingMethods
counter, counter_method, finish_step, profile_method, record_sql, start_step, step, uncounter_method, unprofile_method
Constructor Details
#initialize(app, config = nil) ⇒ MiniProfiler
options: :auto_inject - should script be automatically injected on every html page (not xhr)
63 64 65 66 67 68 69 70 71 72 |
# File 'lib/mini_profiler/profiler.rb', line 63 def initialize(app, config = nil) MiniProfiler.config.merge!(config) @config = MiniProfiler.config @app = app @config.base_url_path << "/" unless @config.base_url_path.end_with? "/" unless @config.storage_instance @config.storage_instance = @config.storage.new(@config.) end @storage = @config.storage_instance end |
Class Method Details
.authorize_request ⇒ Object
46 47 48 |
# File 'lib/mini_profiler/profiler.rb', line 46 def Thread.current[:mp_authorized] = true end |
.config ⇒ Object
So we can change the configuration if we want
16 17 18 |
# File 'lib/mini_profiler/profiler.rb', line 16 def config @config ||= Config.default end |
.create_current(env = {}, options = {}) ⇒ Object
38 39 40 41 42 43 44 |
# File 'lib/mini_profiler/profiler.rb', line 38 def create_current(env={}, ={}) # profiling the request self.current = Context.new self.current.inject_js = config.auto_inject && (!env['HTTP_X_REQUESTED_WITH'].eql? 'XMLHttpRequest') self.current.page_struct = TimerStruct::Page.new(env) self.current.current_timer = current.page_struct[:root] end |
.current ⇒ Object
24 25 26 |
# File 'lib/mini_profiler/profiler.rb', line 24 def current Thread.current[:mini_profiler_private] end |
.current=(c) ⇒ Object
28 29 30 31 |
# File 'lib/mini_profiler/profiler.rb', line 28 def current=(c) # we use TLS cause we need access to this from sql blocks and code blocks that have no access to env Thread.current[:mini_profiler_private] = c end |
.deauthorize_request ⇒ Object
50 51 52 |
# File 'lib/mini_profiler/profiler.rb', line 50 def Thread.current[:mp_authorized] = nil end |
.discard_results ⇒ Object
discard existing results, don’t track this request
34 35 36 |
# File 'lib/mini_profiler/profiler.rb', line 34 def discard_results self.current.discard = true if current end |
.generate_id ⇒ Object
7 8 9 |
# File 'lib/mini_profiler/profiler.rb', line 7 def generate_id rand(36**20).to_s(36) end |
.request_authorized? ⇒ Boolean
54 55 56 |
# File 'lib/mini_profiler/profiler.rb', line 54 def Thread.current[:mp_authorized] end |
.reset_config ⇒ Object
11 12 13 |
# File 'lib/mini_profiler/profiler.rb', line 11 def reset_config @config = Config.default end |
.share_template ⇒ Object
20 21 22 |
# File 'lib/mini_profiler/profiler.rb', line 20 def share_template @share_template ||= ::File.read(::File.("../html/share.html", ::File.dirname(__FILE__))) end |
Instance Method Details
#call(env) ⇒ Object
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
# File 'lib/mini_profiler/profiler.rb', line 152 def call(env) client_settings = ClientSettings.new(env) status = headers = body = nil query_string = env['QUERY_STRING'] path = env['PATH_INFO'] skip_it = (@config. && !@config..call(env)) || (@config.skip_paths && @config.skip_paths.any?{ |p| path[0,p.length] == p}) || query_string =~ /pp=skip/ = client_settings. if skip_it || (@config. == :whitelist && !) status,headers,body = @app.call(env) if !skip_it && @config. == :whitelist && ! && MiniProfiler. client_settings.write!(headers) end return [status,headers,body] end # handle all /mini-profiler requests here return serve_html(env) if path.start_with? @config.base_url_path = client_settings.disable_profiling? # manual session disable / enable if query_string =~ /pp=disable/ || skip_it = true end if query_string =~ /pp=enable/ && (@config. != :whitelist || MiniProfiler.) skip_it = false config.enabled = true end if skip_it || !config.enabled status,headers,body = @app.call(env) client_settings.disable_profiling = true client_settings.write!(headers) return [status,headers,body] else client_settings.disable_profiling = false end if query_string =~ /pp=profile-gc/ current.measure = false if current if query_string =~ /pp=profile-gc-time/ return Rack::MiniProfiler::GCProfiler.new.profile_gc_time(@app, env) elsif query_string =~ /pp=profile-gc-ruby-head/ result = StringIO.new report = MemoryProfiler.report do _,_,body = @app.call(env) body.close if body.respond_to? :close end report.pretty_print(result) return text_result(result.string) else return Rack::MiniProfiler::GCProfiler.new.profile_gc(@app, env) end end MiniProfiler.create_current(env, @config) MiniProfiler. if @config. == :whitelist if query_string =~ /pp=normal-backtrace/ client_settings.backtrace_level = ClientSettings::BACKTRACE_DEFAULT elsif query_string =~ /pp=no-backtrace/ current.skip_backtrace = true client_settings.backtrace_level = ClientSettings::BACKTRACE_NONE elsif query_string =~ /pp=full-backtrace/ || client_settings.backtrace_full? current.full_backtrace = true client_settings.backtrace_level = ClientSettings::BACKTRACE_FULL elsif client_settings.backtrace_none? current.skip_backtrace = true end flamegraph = nil trace_exceptions = query_string =~ /pp=trace-exceptions/ && defined? TracePoint status, headers, body, exceptions,trace = nil start = Time.now if trace_exceptions exceptions = [] trace = TracePoint.new(:raise) do |tp| exceptions << tp.raised_exception end trace.enable end begin # Strip all the caching headers so we don't get 304s back # This solves a very annoying bug where rack mini profiler never shows up if config.disable_caching env['HTTP_IF_MODIFIED_SINCE'] = '' env['HTTP_IF_NONE_MATCH'] = '' end if query_string =~ /pp=flamegraph/ unless defined?(Flamegraph) && Flamegraph.respond_to?(:generate) flamegraph = "Please install the flamegraph gem and require it: add gem 'flamegraph' to your Gemfile" status,headers,body = @app.call(env) else # do not sully our profile with mini profiler timings current.measure = false match_data = query_string.match(/flamegraph_sample_rate=([\d\.]+)/) mode = query_string =~ /mode=c/ ? :c : :ruby if match_data && !match_data[1].to_f.zero? sample_rate = match_data[1].to_f else sample_rate = config.flamegraph_sample_rate end flamegraph = Flamegraph.generate(nil, :fidelity => sample_rate, :embed_resources => query_string =~ /embed/, :mode => mode) do status,headers,body = @app.call(env) end end else status,headers,body = @app.call(env) end client_settings.write!(headers) ensure trace.disable if trace end skip_it = current.discard if (config. == :whitelist && !MiniProfiler.) # this is non-obvious, don't kill the profiling cookie on errors or short requests # this ensures that stuff that never reaches the rails stack does not kill profiling if status == 200 && ((Time.now - start) > 0.1) client_settings.(headers) end skip_it = true end return [status,headers,body] if skip_it # we must do this here, otherwise current[:discard] is not being properly treated if trace_exceptions body.close if body.respond_to? :close return dump_exceptions exceptions end if query_string =~ /pp=env/ body.close if body.respond_to? :close return dump_env env end if query_string =~ /pp=help/ body.close if body.respond_to? :close return help(client_settings) end page_struct = current.page_struct page_struct[:user] = user(env) page_struct[:root].record_time((Time.now - start) * 1000) if flamegraph body.close if body.respond_to? :close return self.flamegraph(flamegraph) end begin # no matter what it is, it should be unviewed, otherwise we will miss POST @storage.set_unviewed(page_struct[:user], page_struct[:id]) @storage.save(page_struct) # inject headers, script if headers['Content-Type'] && status == 200 client_settings.write!(headers) result = inject_profiler(env,status,headers,body) return result if result end rescue Exception => e if @config.storage_failure != nil @config.storage_failure.call(e) end end client_settings.write!(headers) [status, headers, body] ensure # Make sure this always happens self.current = nil end |
#cancel_auto_inject(env) ⇒ Object
cancels automatic injection of profile script for the current page
540 541 542 |
# File 'lib/mini_profiler/profiler.rb', line 540 def cancel_auto_inject(env) current.inject_js = false end |
#config ⇒ Object
147 148 149 |
# File 'lib/mini_profiler/profiler.rb', line 147 def config @config end |
#current ⇒ Object
138 139 140 |
# File 'lib/mini_profiler/profiler.rb', line 138 def current MiniProfiler.current end |
#current=(c) ⇒ Object
142 143 144 |
# File 'lib/mini_profiler/profiler.rb', line 142 def current=(c) MiniProfiler.current = c end |
#dump_env(env) ⇒ Object
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
# File 'lib/mini_profiler/profiler.rb', line 427 def dump_env(env) body = "Rack Environment\n---------------\n" env.each do |k,v| body << "#{k}: #{v}\n" end body << "\n\nEnvironment\n---------------\n" ENV.each do |k,v| body << "#{k}: #{v}\n" end body << "\n\nRuby Version\n---------------\n" body << "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL}\n" body << "\n\nInternals\n---------------\n" body << "Storage Provider #{config.storage_instance}\n" body << "User #{user(env)}\n" body << config.storage_instance.diagnostics(user(env)) rescue "no diagnostics implemented for storage" text_result(body) end |
#dump_exceptions(exceptions) ⇒ Object
417 418 419 420 421 422 423 424 425 |
# File 'lib/mini_profiler/profiler.rb', line 417 def dump_exceptions(exceptions) headers = {'Content-Type' => 'text/plain'} body = "Exceptions (#{exceptions.length} raised during request)\n\n" exceptions.each do |e| body << "#{e.class} #{e.}\n#{e.backtrace.join("\n")}\n\n\n\n" end [200, headers, [body]] end |
#flamegraph(graph) ⇒ Object
479 480 481 482 |
# File 'lib/mini_profiler/profiler.rb', line 479 def flamegraph(graph) headers = {'Content-Type' => 'text/html'} [200, headers, [graph]] end |
#get_profile_script(env) ⇒ Object
get_profile_script returns script to be injected inside current html page By default, profile_script is appended to the end of all html requests automatically. Calling get_profile_script cancels automatic append for the current page Use it when:
-
you have disabled auto append behaviour throught :auto_inject => false flag
-
you do not want script to be automatically appended for the current page. You can also call cancel_auto_inject
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 |
# File 'lib/mini_profiler/profiler.rb', line 503 def get_profile_script(env) path = "#{env['SCRIPT_NAME']}#{@config.base_url_path}" settings = { :path => path, :version => MiniProfiler::ASSET_VERSION, :position => @config.position, :showTrivial => false, :showChildren => false, :maxTracesToShow => 10, :showControls => false, :authorized => true, :toggleShortcut => @config.toggle_shortcut, :startHidden => @config.start_hidden } if current && current.page_struct settings[:ids] = ids_comma_separated(env) settings[:currentId] = current.page_struct[:id] else settings[:ids] = [] settings[:currentId] = "" end # TODO : cache this snippet script = IO.read(::File.('../html/profile_handler.js', ::File.dirname(__FILE__))) # replace the variables settings.each do |k,v| regex = Regexp.new("\\{#{k.to_s}\\}") script.gsub!(regex, v.to_s) end current.inject_js = false if current script end |
#help(client_settings) ⇒ Object
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
# File 'lib/mini_profiler/profiler.rb', line 454 def help(client_settings) headers = {'Content-Type' => 'text/plain'} body = "Append the following to your query string: pp=help : display this screen pp=env : display the rack environment pp=skip : skip mini profiler for this request pp=no-backtrace #{"(*) " if client_settings.backtrace_none?}: don't collect stack traces from all the SQL executed (sticky, use pp=normal-backtrace to enable) pp=normal-backtrace #{"(*) " if client_settings.backtrace_default?}: collect stack traces from all the SQL executed and filter normally pp=full-backtrace #{"(*) " if client_settings.backtrace_full?}: enable full backtraces for SQL executed (use pp=normal-backtrace to disable) pp=disable : disable profiling for this session pp=enable : enable profiling for this session (if previously disabled) pp=profile-gc: perform gc profiling on this request, analyzes ObjectSpace generated by request (ruby 1.9.3 only) pp=profile-gc-time: perform built-in gc profiling on this request (ruby 1.9.3 only) pp=profile-gc-ruby-head: requires the memory_profiler gem, new location based report pp=flamegraph: works best on Ruby 2.0, a graph representing sampled activity (requires the flamegraph gem). pp=flamegraph&flamegraph_sample_rate=1: creates a flamegraph with the specified sample rate (in ms). Overrides value set in config pp=flamegraph_embed: works best on Ruby 2.0, a graph representing sampled activity (requires the flamegraph gem), embedded resources for use on an intranet. pp=trace-exceptions: requires Ruby 2.0, will return all the spots where your application raises execptions " client_settings.write!(headers) [200, headers, [body]] end |
#ids(env) ⇒ Object
484 485 486 487 |
# File 'lib/mini_profiler/profiler.rb', line 484 def ids(env) # cap at 10 ids, otherwise there is a chance you can blow the header ([current.page_struct[:id]] + (@storage.get_unviewed_ids(user(env)) || [])[0..8]).uniq end |
#ids_comma_separated(env) ⇒ Object
493 494 495 |
# File 'lib/mini_profiler/profiler.rb', line 493 def ids_comma_separated(env) ids(env).join(",") end |
#ids_json(env) ⇒ Object
489 490 491 |
# File 'lib/mini_profiler/profiler.rb', line 489 def ids_json(env) ::JSON.generate(ids(env)) end |
#inject(fragment, script) ⇒ Object
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 |
# File 'lib/mini_profiler/profiler.rb', line 380 def inject(fragment, script) if fragment.match(/<\/body>/i) # explicit </body> regex = /<\/body>/i close_tag = '</body>' elsif fragment.match(/<\/html>/i) # implicit </body> regex = /<\/html>/i close_tag = '</html>' else # implicit </body> and </html>. Don't do anything. return fragment end matches = fragment.scan(regex).length index = 1 fragment.gsub(regex) do # though malformed there is an edge case where /body exists earlier in the html, work around if index < matches index += 1 close_tag else # if for whatever crazy reason we dont get a utf string, # just force the encoding, no utf in the mp scripts anyway if script.respond_to?(:encoding) && script.respond_to?(:force_encoding) (script + close_tag).force_encoding(fragment.encoding) else script + close_tag end end end end |
#inject_profiler(env, status, headers, body) ⇒ Object
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
# File 'lib/mini_profiler/profiler.rb', line 347 def inject_profiler(env,status,headers,body) # mini profiler is meddling with stuff, we can not cache cause we will get incorrect data # Rack::ETag has already inserted some nonesense in the chain content_type = headers['Content-Type'] if config.disable_caching headers.delete('ETag') headers.delete('Date') end headers['Cache-Control'] = "#{"no-store, " if config.disable_caching}must-revalidate, private, max-age=0" # inject header if headers.is_a? Hash headers['X-MiniProfiler-Ids'] = ids_json(env) end if current.inject_js && content_type =~ /text\/html/ response = Rack::Response.new([], status, headers) script = self.get_profile_script(env) if String === body response.write inject(body,script) else body.each { |fragment| response.write inject(fragment, script) } end body.close if body.respond_to? :close response.finish else nil end end |
#serve_html(env) ⇒ Object
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/mini_profiler/profiler.rb', line 115 def serve_html(env) file_name = env['PATH_INFO'][(@config.base_url_path.length)..1000] return serve_results(env) if file_name.eql?('results') full_path = ::File.("../html/#{file_name}", ::File.dirname(__FILE__)) return [404, {}, ["Not found"]] unless ::File.exists? full_path f = Rack::File.new nil f.path = full_path begin f.cache_control = "max-age:86400" f.serving env rescue # old versions of rack have a different api status, headers, body = f.serving headers.merge! 'Cache-Control' => "max-age:86400" [status, headers, body] end end |
#serve_results(env) ⇒ Object
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/mini_profiler/profiler.rb', line 78 def serve_results(env) request = Rack::Request.new(env) id = request[:id] page_struct = @storage.load(id) unless page_struct @storage.set_viewed(user(env), id) id = ERB::Util.html_escape(request['id']) user_info = ERB::Util.html_escape(user(env)) return [404, {}, ["Request not found: #{id} - user #{user_info}"]] end unless page_struct[:has_user_viewed] page_struct[:client_timings] = TimerStruct::Client.init_from_form_data(env, page_struct) page_struct[:has_user_viewed] = true @storage.save(page_struct) @storage.set_viewed(user(env), id) end result_json = page_struct.to_json # If we're an XMLHttpRequest, serve up the contents as JSON if request.xhr? [200, { 'Content-Type' => 'application/json'}, [result_json]] else # Otherwise give the HTML back html = MiniProfiler.share_template.dup html.gsub!(/\{path\}/, "#{env['SCRIPT_NAME']}#{@config.base_url_path}") html.gsub!(/\{version\}/, MiniProfiler::ASSET_VERSION) html.gsub!(/\{json\}/, result_json) html.gsub!(/\{includes\}/, get_profile_script(env)) html.gsub!(/\{name\}/, page_struct[:name]) html.gsub!(/\{duration\}/, "%.1f" % page_struct.duration_ms) [200, {'Content-Type' => 'text/html'}, [html]] end end |
#text_result(body) ⇒ Object
449 450 451 452 |
# File 'lib/mini_profiler/profiler.rb', line 449 def text_result(body) headers = {'Content-Type' => 'text/plain'} [200, headers, [body]] end |
#user(env) ⇒ Object
74 75 76 |
# File 'lib/mini_profiler/profiler.rb', line 74 def user(env) @config.user_provider.call(env) end |