require "erb" require "rack/insight/logging" require 'rack/insight/database' require 'rack/insight/instrumentation' require 'rack/insight/render' module Rack::Insight # Panels are also Rack middleware class Panel include ERB::Util include Rack::Insight::Logging include Rack::Insight::Render include Rack::Insight::Database::RequestDataClient include Rack::Insight::Instrumentation::Client attr_reader :request class << self include Rack::Insight::Logging attr_accessor :template_root, :is_probed, :has_table, :is_magic @is_probed = false # Once a panel is probed this should be set to true @has_table = true # default to true. Panels without tables override with self.has_table = false @is_magic = false # check this to wrap any functionality targeted at magic panels. def file_index return @file_index ||= Hash.new do |h,k| h[k] = [] end end def panel_exclusion return @panel_exclusion ||= [] end def from_file(rel_path) old_rel, Thread::current['rack-panel_file'] = Thread::current['rack-panel_file'], rel_path load_paths_to_check = Rack::Insight::Config.config[:panel_load_paths].length Rack::Insight::Config.config[:panel_load_paths].each_with_index do |load_path, index| begin require File::join(load_path, rel_path) break # once found rescue LoadError => e # TODO: If probes are defined for this panel, instantiate a magic panel # if self.has_custom_probes? if (index + 1) == load_paths_to_check # You have failed me for the last time! warn "Rack::Insight #{e.class}: Unable to find panel specified as '#{rel_path}'. Looked in the following :panel_load_paths: #{Rack::Insight::Config.config[:panel_load_paths].inspect}." end end end return (file_index[rel_path] - panel_exclusion) ensure Thread::current['rack-panel_file'] = old_rel end def set_sub_class_template_root(sub_class, path) sub_class.template_root = path end def current_panel_file(sub) file_name = nil matched_line = nil caller.each do |line| # First make sure we are not matching rack-insight's own panel class, which will be in the caller stack, # and which may match some custom load path added (try adding 'rack' as a custom load path!) # .*panel because the panels that ship with rack-insight also do not need custom template roots. next if line =~ /rack-insight.*\/lib\/rack\/insight\/.*panel.rb:/ Rack::Insight::Config.config[:panel_load_paths].each do |load_path| regex = %r{^[^:]*#{load_path}/([^:]*)\.rb:} md = regex.match line file_name = md[1] unless md.nil? matched_line = line unless file_name.nil? break unless file_name.nil? end break unless file_name.nil? end set_sub_class_template_root(sub, File.dirname(matched_line.split(':')[0])) if matched_line.respond_to?(:split) return Thread::current['rack-panel_file'] || file_name end def inherited(sub) if filename = current_panel_file(sub) logger.debug("panel inherited by #{sub.inspect} with template_root: #{sub.template_root}") if verbose(:high) Panel::file_index[filename] << sub else warn "Rack::Insight::Panel inherited by #{sub.name} outside rack-insight's :panel_load_paths. Discarded. Configured panel load paths are: #{Rack::Insight::Config.config[:panel_load_paths].inspect}" end end def excluded(klass = nil) Panel::panel_exclusion << klass || self end end def initialize(app) if panel_app #XXX use mappings @app = Rack::Cascade.new([panel_app, app]) else @app = app end # User has explicitly declared what classes/methods to probe: # Rack::Insight::Config.configure do |config| # config[:panel_configs][:log] = {:probes => {'Logger' => [:instance, :add] } } # # OR EQUIVALENTLY # config[:panel_configs][:log] = {:probes => ['Logger', :instance, :add] } # end panel_name = self.underscored_name.to_sym if self.has_custom_probes?(panel_name) custom_probes = Rack::Insight::Config.config[:panel_configs][panel_name][:probes] if custom_probes.kind_of?(Hash) probe(self) do custom_probes.each do |klass, method_probes| probe_type = method_probes.shift instrument klass do self.send("#{probe_type}_probe", *method_probes) end end end elsif custom_probes.kind_of?(Array) && custom_probes.length >=3 probe(self) do custom_probes.each do |probe| klass = probe.shift probe_type = probe.shift instrument klass do self.send("#{probe_type}_probe", *probe) end end end else raise "Expected Rack::Insight::Config.config[:panel_configs][#{panel_name}][:probes] to be a kind of Hash or an Array with length >= 3, but is a #{Rack::Insight::Config.config[:panel_configs][self.as_sym][:probes].class}" end end # Setup a table for the panel unless # 1. self.has_table = false has been set for the Panel class # 2. class instance variable @has_table has been set to false # 3. table_setup has already been called by the sub class' initializer if !has_table? table_setup(self.name) end #puts "Initalization Complete for #{panel_name}\n1. #{self.is_magic?} && 2. #{self.has_table?} && 3. #{self.is_probed?} 4. #{self.has_custom_probes?}" end def call(env) @env = env logger.debug{ "Before call: #{self.name}" } if verbose(:debug) before(env) status, headers, body = @app.call(env) @request = Rack::Request.new(env) logger.debug{ "After call: #{self.name}" } if verbose(:debug) after(env, status, headers, body) env["rack-insight.panels"] << self return [status, headers, body] end def panel_app nil end def self.panel_mappings {} end def has_table? !!self.class.has_table end def is_magic? !!self.class.is_magic end def has_content? true end def is_probed? !!self.class.is_probed end def has_custom_probes?(panel_name = self.underscored_name.to_sym) #puts "Rack::Insight::Config.config[:panel_configs][#{panel_name.inspect}]: #{Rack::Insight::Config.config[:panel_configs][panel_name].inspect}" Rack::Insight::Config.config[:panel_configs][panel_name].respond_to?(:[]) && !Rack::Insight::Config.config[:panel_configs][panel_name][:probes].nil? end # The name informs the table name, and the panel_configs hash among other things. # Override in subclass panels if you want a custom name def name self.underscored_name end # Mostly stolen from Rails' ActiveSupport' underscore method: # See activesupport/lib/active_support/inflector/methods.rb, line 77 # HTTPClientPanel => http_client # LogPanel => log # ActiveRecordPanel => active_record def underscored_name(word = self.class.to_s) @underscored_name ||= begin words = word.dup.split('::') word = words.last if word == 'Panel' word = words[-2] # Panel class is Panel... and this won't do. end #word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" } word.gsub!(/Panel$/,'') word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') word.gsub!(/([a-z\d])([A-Z])/,'\1_\2') word.tr!("-", "_") word.downcase! word end end def camelized_name(str = self.underscored_name) str.split('_').map {|w| w.capitalize}.join end def heading_for_request(number) if !self.has_table? heading else num = count(number) if num == 0 heading else "#{self.camelized_name} (#{num})" end end rescue 'XXX' # no panel should need this end def content_for_request(number) logger.info("Rack::Insight is using default content_for_request for #{self.class}") if verbose(:med) if !self.has_table? logger.info("#{self.class} is being used without a table") if verbose(:med) content elsif self.is_probed? invocations = retrieve(number) if invocations.length > 0 && invocations.first.is_a?(Rack::Insight::Panel::DefaultInvocation) logger.info("Rack::Insight is using magic content for #{self.class}, which is probed")# if verbose(:med) render_template 'default_invocation', :invocations => invocations, :name => self.camelized_name else logger.info("Rack::Insight has no data for magic content for #{self.class}, which is probed")# if verbose(:med) render_template 'no_data', :name => self.camelized_name end else content end rescue 'XXX' #XXX: no panel should need this end def heading self.camelized_name end def content logger.info("Rack::Insight is using default content for #{self.class}") if verbose(:med) html = "
Add a content method to your panel
' html end # Override in subclasses. # This is to make magic classes work. def after_detect(method_call, timing, args, result) #puts "Default After Detect for #{self.underscored_name}: 1. #{self.is_magic?} && 2. #{self.has_table?} && 3. #{self.is_probed?}" if self.is_magic? && self.has_table? && self.is_probed? store(@env, DefaultInvocation.new(method_call.method.to_s, timing, args, result, method_call.backtrace[2..-1])) end end def before(env) end def after(env, status, headers, body) end def render(template) end # For Magic Panels class DefaultInvocation < Struct.new :method, :time, :arguments, :result, :backtrace attr_accessor :method, :time, :arguments, :result, :backtrace include Rack::Insight::FilteredBacktrace def initialize(*args) @method = args[0] @time = [args[1].duration, args[1].delta_t] @arguments = args[2] @result = args[3] @backtrace = args[4] end def human_time "%.2fms" % (self.time * 1_000) end end end end