factorylabs-newrelic_rpm 2.10.2.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (160) hide show
  1. data/CHANGELOG +354 -0
  2. data/LICENSE +37 -0
  3. data/README-2.10.2.2 +10 -0
  4. data/README.md +138 -0
  5. data/bin/mongrel_rpm +33 -0
  6. data/bin/newrelic_cmd +4 -0
  7. data/cert/cacert.pem +34 -0
  8. data/install.rb +45 -0
  9. data/lib/new_relic/agent.rb +315 -0
  10. data/lib/new_relic/agent/agent.rb +647 -0
  11. data/lib/new_relic/agent/busy_calculator.rb +86 -0
  12. data/lib/new_relic/agent/chained_call.rb +13 -0
  13. data/lib/new_relic/agent/collection_helper.rb +66 -0
  14. data/lib/new_relic/agent/error_collector.rb +117 -0
  15. data/lib/new_relic/agent/instrumentation/active_merchant.rb +18 -0
  16. data/lib/new_relic/agent/instrumentation/active_record_instrumentation.rb +91 -0
  17. data/lib/new_relic/agent/instrumentation/authlogic.rb +8 -0
  18. data/lib/new_relic/agent/instrumentation/controller_instrumentation.rb +389 -0
  19. data/lib/new_relic/agent/instrumentation/data_mapper.rb +90 -0
  20. data/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb +12 -0
  21. data/lib/new_relic/agent/instrumentation/memcache.rb +24 -0
  22. data/lib/new_relic/agent/instrumentation/merb/controller.rb +26 -0
  23. data/lib/new_relic/agent/instrumentation/merb/errors.rb +8 -0
  24. data/lib/new_relic/agent/instrumentation/metric_frame.rb +199 -0
  25. data/lib/new_relic/agent/instrumentation/net.rb +21 -0
  26. data/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb +20 -0
  27. data/lib/new_relic/agent/instrumentation/rack.rb +109 -0
  28. data/lib/new_relic/agent/instrumentation/rails/action_controller.rb +59 -0
  29. data/lib/new_relic/agent/instrumentation/rails/action_web_service.rb +27 -0
  30. data/lib/new_relic/agent/instrumentation/rails/errors.rb +24 -0
  31. data/lib/new_relic/agent/instrumentation/sinatra.rb +39 -0
  32. data/lib/new_relic/agent/method_tracer.rb +348 -0
  33. data/lib/new_relic/agent/patch_const_missing.rb +125 -0
  34. data/lib/new_relic/agent/sampler.rb +46 -0
  35. data/lib/new_relic/agent/samplers/cpu_sampler.rb +50 -0
  36. data/lib/new_relic/agent/samplers/memory_sampler.rb +141 -0
  37. data/lib/new_relic/agent/samplers/mongrel_sampler.rb +23 -0
  38. data/lib/new_relic/agent/samplers/object_sampler.rb +24 -0
  39. data/lib/new_relic/agent/shim_agent.rb +21 -0
  40. data/lib/new_relic/agent/stats_engine.rb +22 -0
  41. data/lib/new_relic/agent/stats_engine/metric_stats.rb +116 -0
  42. data/lib/new_relic/agent/stats_engine/samplers.rb +74 -0
  43. data/lib/new_relic/agent/stats_engine/transactions.rb +154 -0
  44. data/lib/new_relic/agent/transaction_sampler.rb +315 -0
  45. data/lib/new_relic/agent/worker_loop.rb +118 -0
  46. data/lib/new_relic/commands/deployments.rb +145 -0
  47. data/lib/new_relic/commands/new_relic_commands.rb +30 -0
  48. data/lib/new_relic/control.rb +484 -0
  49. data/lib/new_relic/control/external.rb +13 -0
  50. data/lib/new_relic/control/merb.rb +24 -0
  51. data/lib/new_relic/control/rails.rb +151 -0
  52. data/lib/new_relic/control/ruby.rb +36 -0
  53. data/lib/new_relic/control/sinatra.rb +14 -0
  54. data/lib/new_relic/histogram.rb +89 -0
  55. data/lib/new_relic/local_environment.rb +299 -0
  56. data/lib/new_relic/merbtasks.rb +6 -0
  57. data/lib/new_relic/metric_data.rb +42 -0
  58. data/lib/new_relic/metric_parser.rb +124 -0
  59. data/lib/new_relic/metric_parser/action_mailer.rb +9 -0
  60. data/lib/new_relic/metric_parser/active_merchant.rb +26 -0
  61. data/lib/new_relic/metric_parser/active_record.rb +25 -0
  62. data/lib/new_relic/metric_parser/controller.rb +54 -0
  63. data/lib/new_relic/metric_parser/controller_cpu.rb +38 -0
  64. data/lib/new_relic/metric_parser/errors.rb +6 -0
  65. data/lib/new_relic/metric_parser/external.rb +50 -0
  66. data/lib/new_relic/metric_parser/mem_cache.rb +12 -0
  67. data/lib/new_relic/metric_parser/other_transaction.rb +15 -0
  68. data/lib/new_relic/metric_parser/view.rb +61 -0
  69. data/lib/new_relic/metric_parser/web_frontend.rb +14 -0
  70. data/lib/new_relic/metric_parser/web_service.rb +9 -0
  71. data/lib/new_relic/metric_spec.rb +67 -0
  72. data/lib/new_relic/metrics.rb +7 -0
  73. data/lib/new_relic/noticed_error.rb +23 -0
  74. data/lib/new_relic/rack/metric_app.rb +56 -0
  75. data/lib/new_relic/rack/mongrel_rpm.ru +25 -0
  76. data/lib/new_relic/rack/newrelic.yml +26 -0
  77. data/lib/new_relic/rack_app.rb +5 -0
  78. data/lib/new_relic/recipes.rb +82 -0
  79. data/lib/new_relic/stats.rb +362 -0
  80. data/lib/new_relic/transaction_analysis.rb +121 -0
  81. data/lib/new_relic/transaction_sample.rb +671 -0
  82. data/lib/new_relic/version.rb +54 -0
  83. data/lib/new_relic_api.rb +276 -0
  84. data/lib/newrelic_rpm.rb +45 -0
  85. data/lib/tasks/all.rb +4 -0
  86. data/lib/tasks/install.rake +7 -0
  87. data/lib/tasks/tests.rake +15 -0
  88. data/newrelic.yml +227 -0
  89. data/newrelic_rpm.gemspec +214 -0
  90. data/recipes/newrelic.rb +6 -0
  91. data/test/active_record_fixtures.rb +55 -0
  92. data/test/config/newrelic.yml +46 -0
  93. data/test/config/test_control.rb +38 -0
  94. data/test/new_relic/agent/active_record_instrumentation_test.rb +268 -0
  95. data/test/new_relic/agent/agent_controller_test.rb +254 -0
  96. data/test/new_relic/agent/agent_test_controller.rb +78 -0
  97. data/test/new_relic/agent/busy_calculator_test.rb +79 -0
  98. data/test/new_relic/agent/classloader_patch_test.rb +56 -0
  99. data/test/new_relic/agent/collection_helper_test.rb +125 -0
  100. data/test/new_relic/agent/error_collector_test.rb +173 -0
  101. data/test/new_relic/agent/method_tracer_test.rb +340 -0
  102. data/test/new_relic/agent/metric_data_test.rb +56 -0
  103. data/test/new_relic/agent/mock_ar_connection.rb +40 -0
  104. data/test/new_relic/agent/mock_scope_listener.rb +23 -0
  105. data/test/new_relic/agent/net_instrumentation_test.rb +63 -0
  106. data/test/new_relic/agent/rpm_agent_test.rb +125 -0
  107. data/test/new_relic/agent/stats_engine/metric_stats_test.rb +79 -0
  108. data/test/new_relic/agent/stats_engine/samplers_test.rb +88 -0
  109. data/test/new_relic/agent/stats_engine/stats_engine_test.rb +184 -0
  110. data/test/new_relic/agent/task_instrumentation_test.rb +177 -0
  111. data/test/new_relic/agent/testable_agent.rb +13 -0
  112. data/test/new_relic/agent/transaction_sample_builder_test.rb +195 -0
  113. data/test/new_relic/agent/transaction_sample_test.rb +186 -0
  114. data/test/new_relic/agent/transaction_sampler_test.rb +404 -0
  115. data/test/new_relic/agent/worker_loop_test.rb +103 -0
  116. data/test/new_relic/control_test.rb +110 -0
  117. data/test/new_relic/delayed_job_test.rb +108 -0
  118. data/test/new_relic/deployments_api_test.rb +68 -0
  119. data/test/new_relic/environment_test.rb +75 -0
  120. data/test/new_relic/metric_parser_test.rb +172 -0
  121. data/test/new_relic/metric_spec_test.rb +177 -0
  122. data/test/new_relic/shim_agent_test.rb +9 -0
  123. data/test/new_relic/stats_test.rb +291 -0
  124. data/test/new_relic/version_number_test.rb +76 -0
  125. data/test/test_helper.rb +53 -0
  126. data/test/ui/newrelic_controller_test.rb +14 -0
  127. data/test/ui/newrelic_helper_test.rb +53 -0
  128. data/ui/controllers/newrelic_controller.rb +220 -0
  129. data/ui/helpers/google_pie_chart.rb +49 -0
  130. data/ui/helpers/newrelic_helper.rb +320 -0
  131. data/ui/views/layouts/newrelic_default.rhtml +47 -0
  132. data/ui/views/newrelic/_explain_plans.rhtml +27 -0
  133. data/ui/views/newrelic/_sample.rhtml +19 -0
  134. data/ui/views/newrelic/_segment.rhtml +28 -0
  135. data/ui/views/newrelic/_segment_limit_message.rhtml +1 -0
  136. data/ui/views/newrelic/_segment_row.rhtml +14 -0
  137. data/ui/views/newrelic/_show_sample_detail.rhtml +24 -0
  138. data/ui/views/newrelic/_show_sample_sql.rhtml +20 -0
  139. data/ui/views/newrelic/_show_sample_summary.rhtml +3 -0
  140. data/ui/views/newrelic/_sql_row.rhtml +11 -0
  141. data/ui/views/newrelic/_stack_trace.rhtml +30 -0
  142. data/ui/views/newrelic/_table.rhtml +12 -0
  143. data/ui/views/newrelic/explain_sql.rhtml +42 -0
  144. data/ui/views/newrelic/images/arrow-close.png +0 -0
  145. data/ui/views/newrelic/images/arrow-open.png +0 -0
  146. data/ui/views/newrelic/images/blue_bar.gif +0 -0
  147. data/ui/views/newrelic/images/file_icon.png +0 -0
  148. data/ui/views/newrelic/images/gray_bar.gif +0 -0
  149. data/ui/views/newrelic/images/new-relic-rpm-desktop.gif +0 -0
  150. data/ui/views/newrelic/images/new_relic_rpm_desktop.gif +0 -0
  151. data/ui/views/newrelic/images/textmate.png +0 -0
  152. data/ui/views/newrelic/index.rhtml +57 -0
  153. data/ui/views/newrelic/javascript/prototype-scriptaculous.js +7288 -0
  154. data/ui/views/newrelic/javascript/transaction_sample.js +107 -0
  155. data/ui/views/newrelic/sample_not_found.rhtml +2 -0
  156. data/ui/views/newrelic/show_sample.rhtml +80 -0
  157. data/ui/views/newrelic/show_source.rhtml +3 -0
  158. data/ui/views/newrelic/stylesheets/style.css +484 -0
  159. data/ui/views/newrelic/threads.rhtml +52 -0
  160. metadata +238 -0
@@ -0,0 +1,86 @@
1
+ # This module supports calculation of actual time spent processing requests over the course of
2
+ # one harvest period. It's similar to what you would get if you just added up all the
3
+ # execution times of controller calls, however that will be inaccurate when requests
4
+ # span the minute boundaries. This module manages accounting of requests not yet
5
+ # completed.
6
+ #
7
+ # Calls are re-entrant. All start calls must be paired with finish calls, or a reset call.
8
+ module NewRelic::Agent::BusyCalculator
9
+
10
+ extend self
11
+
12
+ # For testability, add accessors:
13
+ attr_reader :harvest_start, :accumulator
14
+
15
+ def dispatcher_start(time)
16
+ Thread.current[:busy_entries] ||= 0
17
+ callers = Thread.current[:busy_entries] += 1
18
+ return if callers > 1
19
+ @lock.synchronize do
20
+ @entrypoint_stack.push time
21
+ end
22
+ end
23
+
24
+ def dispatcher_finish(end_time = Time.now.to_f)
25
+ callers = Thread.current[:busy_entries] -= 1
26
+ # Ignore nested calls
27
+ return if callers > 0
28
+ @lock.synchronize do
29
+ if @entrypoint_stack.empty?
30
+ NewRelic::Control.instance.log.error("Stack underflow tracking dispatcher entry and exit!\n #{caller.join(" \n")}")
31
+ else
32
+ @accumulator += (end_time - @entrypoint_stack.pop)
33
+ end
34
+ end
35
+ end
36
+
37
+ def busy_count
38
+ @entrypoint_stack.size
39
+ end
40
+
41
+ # Reset the state of the information accumulated by all threads,
42
+ # but only reset the recursion counter for this thread.
43
+ def reset
44
+ @entrypoint_stack = []
45
+ Thread.current[:busy_entries] = 0
46
+ @lock ||= Mutex.new
47
+ @accumulator = 0
48
+ @harvest_start = Time.now.to_f
49
+ end
50
+
51
+ self.reset
52
+
53
+ # Called before uploading to to the server to collect current busy stats.
54
+ def harvest_busy
55
+ busy = 0
56
+ t0 = Time.now.to_f
57
+ @lock.synchronize do
58
+ busy = accumulator
59
+ @accumulator = 0
60
+
61
+ # Walk through the stack and capture all times up to
62
+ # now for entrypoints
63
+ @entrypoint_stack.size.times do |frame|
64
+ busy += (t0 - @entrypoint_stack[frame])
65
+ @entrypoint_stack[frame] = t0
66
+ end
67
+
68
+ end
69
+
70
+ busy = 0.0 if busy < 0.0 # don't go below 0%
71
+
72
+ time_window = (t0 - harvest_start)
73
+ time_window = 1.0 if time_window == 0.0 # protect against divide by zero
74
+
75
+ busy = busy / time_window
76
+
77
+ instance_busy_stats.record_data_point busy
78
+ @harvest_start = t0
79
+ end
80
+ private
81
+ def instance_busy_stats
82
+ # Late binding on the Instance/busy stats
83
+ NewRelic::Agent.agent.stats_engine.get_stats_no_scope 'Instance/Busy'
84
+ end
85
+
86
+ end
@@ -0,0 +1,13 @@
1
+ # This is used to allow obfuscators to be chained.
2
+
3
+ class NewRelic::ChainedCall
4
+ def initialize(block1, block2)
5
+ @block1 = block1
6
+ @block2 = block2
7
+ end
8
+
9
+ def call(sql)
10
+ sql = @block1.call(sql)
11
+ @block2.call(sql)
12
+ end
13
+ end
@@ -0,0 +1,66 @@
1
+ module NewRelic::Agent::CollectionHelper
2
+ # Transform parameter hash into a hash whose values are strictly
3
+ # strings
4
+ def normalize_params(params)
5
+ case params
6
+ when Symbol, FalseClass, TrueClass, nil
7
+ params
8
+ when Numeric
9
+ truncate(params.to_s)
10
+ when String
11
+ truncate(params)
12
+ when Hash
13
+ new_params = {}
14
+ params.each do | key, value |
15
+ new_params[truncate(normalize_params(key),32)] = normalize_params(value)
16
+ end
17
+ new_params
18
+ when Array
19
+ params.first(20).map{|item| normalize_params(item)}
20
+ else
21
+ truncate(flatten(params))
22
+ end
23
+ end
24
+
25
+ # Return an array of strings (backtrace), cleaned up for readability
26
+ # Return nil if there is no backtrace
27
+
28
+ def strip_nr_from_backtrace(backtrace)
29
+ if backtrace
30
+ # this is for 1.9.1, where strings no longer have Enumerable
31
+ backtrace = backtrace.split("\n") if String === backtrace
32
+ # strip newrelic from the trace
33
+ backtrace = backtrace.reject {|line| line =~ /new_relic\/agent\// }
34
+ # rename methods back to their original state
35
+ backtrace = backtrace.collect {|line| line.gsub(/_without_(newrelic|trace)/, "")}
36
+ end
37
+ backtrace
38
+ end
39
+
40
+ private
41
+
42
+ # Convert any kind of object to a short string.
43
+ def flatten(object)
44
+ s = case object
45
+ when nil then ''
46
+ when object.instance_of?(String) then object
47
+ when String then String.new(object) # convert string subclasses to strings
48
+ else "#<#{object.class.to_s}>"
49
+ end
50
+ end
51
+ def truncate(string, len=256)
52
+ case string
53
+ when Symbol then string
54
+ when nil then ""
55
+ when String
56
+ real_string = flatten(string)
57
+ if real_string.size > len
58
+ real_string = real_string.slice(0...len)
59
+ real_string << "..."
60
+ end
61
+ real_string
62
+ else
63
+ truncate(flatten(string), len)
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,117 @@
1
+
2
+ module NewRelic::Agent
3
+ class ErrorCollector
4
+ include CollectionHelper
5
+
6
+ # Defined the methods that need to be stubbed out when the
7
+ # agent is disabled
8
+ module Shim #:nodoc:
9
+ def notice_error(*args); end
10
+ end
11
+
12
+ MAX_ERROR_QUEUE_LENGTH = 20 unless defined? MAX_ERROR_QUEUE_LENGTH
13
+
14
+ attr_accessor :enabled
15
+
16
+ def initialize
17
+ @errors = []
18
+ # lookup of exception class names to ignore. Hash for fast access
19
+ @ignore = {}
20
+ @ignore_filter = nil
21
+
22
+ config = NewRelic::Control.instance.fetch('error_collector', {})
23
+
24
+ @enabled = config.fetch('enabled', true)
25
+ @capture_source = config.fetch('capture_source', true)
26
+
27
+ ignore_errors = config.fetch('ignore_errors', "")
28
+ ignore_errors = ignore_errors.split(",")
29
+ ignore_errors.each { |error| error.strip! }
30
+ ignore(ignore_errors)
31
+ @lock = Mutex.new
32
+ end
33
+
34
+ def ignore_error_filter(&block)
35
+ @ignore_filter = block
36
+ end
37
+
38
+
39
+ # errors is an array of Exception Class Names
40
+ #
41
+ def ignore(errors)
42
+ errors.each { |error| @ignore[error] = true; log.debug("Ignoring error: '#{error}'") }
43
+ end
44
+
45
+ def notice_error(exception, request=nil, action_path=nil, filtered_params={})
46
+ return unless @enabled
47
+ return if @ignore[exception.class.name]
48
+ if @ignore_filter
49
+ exception = @ignore_filter.call(exception)
50
+ return if exception.nil?
51
+ end
52
+ NewRelic::Agent.get_stats("Errors/all").increment_count
53
+ return unless NewRelic::Agent.instance.should_send_errors
54
+
55
+ action_path ||= NewRelic::Agent.instance.stats_engine.scope_name || ''
56
+
57
+ data = {}
58
+
59
+ data[:request_params] = normalize_params(filtered_params) if NewRelic::Control.instance.capture_params
60
+
61
+ data[:custom_params] = normalize_params(NewRelic::Agent.instance.custom_params)
62
+
63
+ data[:request_uri] = request.path if request
64
+ data[:request_uri] ||= ""
65
+
66
+ data[:request_referer] = request.referer if request
67
+ data[:request_referer] ||= ""
68
+
69
+ data[:rails_root] = NewRelic::Control.instance.root
70
+
71
+ data[:file_name] = exception.file_name if exception.respond_to?('file_name')
72
+ data[:line_number] = exception.line_number if exception.respond_to?('line_number')
73
+
74
+ if @capture_source && exception.respond_to?('source_extract')
75
+ data[:source] = exception.source_extract
76
+ end
77
+
78
+ if exception.respond_to? 'original_exception'
79
+ inside_exception = exception.original_exception
80
+ else
81
+ inside_exception = exception
82
+ end
83
+
84
+ data[:stack_trace] = inside_exception ? inside_exception.backtrace : '<no stack trace>'
85
+
86
+ noticed_error = NewRelic::NoticedError.new(action_path, data, exception)
87
+
88
+ @lock.synchronize do
89
+ if @errors.length >= MAX_ERROR_QUEUE_LENGTH
90
+ log.info("The error reporting queue has reached #{MAX_ERROR_QUEUE_LENGTH}. This error will not be reported to RPM: #{exception.message}")
91
+ else
92
+ @errors << noticed_error
93
+ end
94
+ end
95
+ end
96
+
97
+ # Get the errors currently queued up. Unsent errors are left
98
+ # over from a previous unsuccessful attempt to send them to the server.
99
+ # We first clear out all unsent errors before sending the newly queued errors.
100
+ def harvest_errors(unsent_errors)
101
+ if unsent_errors && !unsent_errors.empty?
102
+ return unsent_errors
103
+ else
104
+ @lock.synchronize do
105
+ errors = @errors
106
+ @errors = []
107
+ return errors
108
+ end
109
+ end
110
+ end
111
+
112
+ private
113
+ def log
114
+ NewRelic::Control.instance.log
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,18 @@
1
+ # ActiveMerchant Instrumentation.
2
+
3
+ if defined? ActiveMerchant
4
+
5
+ ActiveMerchant::Billing::Gateway.implementations.each do |gateway|
6
+ gateway.class_eval do
7
+ implemented_methods = public_instance_methods(false)
8
+ gateway_name = self.name.split('::').last
9
+ [:authorize, :purchase, :credit, :void, :capture, :recurring].each do |operation|
10
+ if implemented_methods.include?(operation.to_s)
11
+ add_method_tracer operation, "ActiveMerchant/gateway/#{gateway_name}/#{operation}", :scoped_metric_only => true
12
+ add_method_tracer operation, "ActiveMerchant/gateway/#{gateway_name}", :push_scope => false
13
+ add_method_tracer operation, "ActiveMerchant/operation/#{operation}", :push_scope => false
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,91 @@
1
+
2
+ # NewRelic instrumentation for ActiveRecord
3
+ if defined?(ActiveRecord) && defined?(ActiveRecord::Base) && !NewRelic::Control.instance['skip_ar_instrumentation']
4
+
5
+ module NewRelic
6
+ module Agent
7
+ module Instrumentation
8
+ module ActiveRecordInstrumentation
9
+
10
+ def self.included(instrumented_class)
11
+ instrumented_class.class_eval do
12
+ alias_method :log_without_newrelic_instrumentation, :log
13
+ alias_method :log, :log_with_newrelic_instrumentation
14
+ protected :log
15
+ end
16
+ end
17
+
18
+ def log_with_newrelic_instrumentation(sql, name, &block)
19
+
20
+ return log_without_newrelic_instrumentation(sql, name, &block) unless NewRelic::Agent.is_execution_traced?
21
+
22
+ # Capture db config if we are going to try to get the explain plans
23
+ if (defined?(ActiveRecord::ConnectionAdapters::MysqlAdapter) && self.is_a?(ActiveRecord::ConnectionAdapters::MysqlAdapter)) ||
24
+ (defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) && self.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter))
25
+ supported_config = @config
26
+ end
27
+ if name && (parts = name.split " ") && parts.size == 2
28
+ model = parts.first
29
+ operation = parts.last.downcase
30
+ metric_name = case operation
31
+ when 'load' then 'find'
32
+ when 'indexes', 'columns' then nil # fall back to DirectSQL
33
+ when 'destroy', 'find', 'save', 'create' then operation
34
+ when 'update' then 'save'
35
+ else
36
+ if model == 'Join'
37
+ operation
38
+ end
39
+ end
40
+ metric = "ActiveRecord/#{model}/#{metric_name}" if metric_name
41
+ end
42
+
43
+ if metric.nil?
44
+ metric = NewRelic::Agent::Instrumentation::MetricFrame.database_metric_name
45
+ if metric.nil?
46
+ if sql =~ /^(select|update|insert|delete|show)/i
47
+ # Could not determine the model/operation so let's find a better
48
+ # metric. If it doesn't match the regex, it's probably a show
49
+ # command or some DDL which we'll ignore.
50
+ metric = "Database/SQL/#{$1.downcase}"
51
+ else
52
+ metric = "Database/SQL/other"
53
+ end
54
+ end
55
+ end
56
+
57
+ if !metric
58
+ log_without_newrelic_instrumentation(sql, name, &block)
59
+ else
60
+ metrics = [metric, "ActiveRecord/all"]
61
+ metrics << "ActiveRecord/#{metric_name}" if metric_name
62
+ self.class.trace_execution_scoped(metrics) do
63
+ t0 = Time.now.to_f
64
+ begin
65
+ log_without_newrelic_instrumentation(sql, name, &block)
66
+ ensure
67
+ NewRelic::Agent.instance.transaction_sampler.notice_sql(sql, supported_config, Time.now.to_f - t0)
68
+ end
69
+ end
70
+ end
71
+ end
72
+
73
+ end
74
+
75
+ # instrumentation to catch logged SQL statements in sampled transactions
76
+ ActiveRecord::ConnectionAdapters::AbstractAdapter.module_eval do
77
+ include ::NewRelic::Agent::Instrumentation::ActiveRecordInstrumentation
78
+ end
79
+
80
+ # This instrumentation will add an extra scope to the transaction traces
81
+ # which will show the code surrounding the query, inside the model find_by_sql
82
+ # method.
83
+ ActiveRecord::Base.class_eval do
84
+ class << self
85
+ add_method_tracer :find_by_sql, 'ActiveRecord/#{self.name}/find_by_sql', :metric => false
86
+ end
87
+ end unless NewRelic::Control.instance['disable_activerecord_instrumentation']
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,8 @@
1
+ if defined? Authlogic::Session::Base
2
+ Authlogic::Session::Base.class_eval do
3
+ # add_method_tracer :record, 'Authlogic/record'
4
+ class << self
5
+ add_method_tracer :find, 'Authlogic/find'
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,389 @@
1
+
2
+ module NewRelic::Agent::Instrumentation
3
+ # == NewRelic instrumentation for controllers
4
+ #
5
+ # This instrumentation is applied to the action controller by default if the agent
6
+ # is actively collecting statistics. It will collect statistics for the
7
+ # given action.
8
+ #
9
+ # In cases where you don't want to instrument the top level action, but instead
10
+ # have other methods which are dispatched to by your action, and you want to treat
11
+ # these as distinct actions, then what you need to do is use
12
+ # #perform_action_with_newrelic_trace
13
+ #
14
+ module ControllerInstrumentation
15
+
16
+ def self.included(clazz) # :nodoc:
17
+ clazz.extend(ClassMethods)
18
+ end
19
+
20
+ # This module is for importing stubs when the agent is disabled
21
+ module ClassMethodsShim # :nodoc:
22
+ def newrelic_ignore(*args); end
23
+ def newrelic_ignore_apdex(*args); end
24
+ end
25
+
26
+ module Shim # :nodoc:
27
+ def self.included(clazz)
28
+ clazz.extend(ClassMethodsShim)
29
+ end
30
+ def newrelic_notice_error(*args); end
31
+ def new_relic_trace_controller_action(*args); yield; end
32
+ def newrelic_metric_path; end
33
+ def perform_action_with_newrelic_trace(*args); yield; end
34
+ end
35
+
36
+ module ClassMethods
37
+ # Have NewRelic ignore actions in this controller. Specify the actions as hash options
38
+ # using :except and :only. If no actions are specified, all actions are ignored.
39
+ def newrelic_ignore(specifiers={})
40
+ newrelic_ignore_aspect('do_not_trace', specifiers)
41
+ end
42
+ # Have NewRelic omit apdex measurements on the given actions. Typically used for
43
+ # actions that are not user facing or that skew your overall apdex measurement.
44
+ # Accepts :except and :only options, as with #newrelic_ignore.
45
+ def newrelic_ignore_apdex(specifiers={})
46
+ newrelic_ignore_aspect('ignore_apdex', specifiers)
47
+ end
48
+
49
+ def newrelic_ignore_aspect(property, specifiers={}) # :nodoc:
50
+ if specifiers.empty?
51
+ self.newrelic_write_attr property, true
52
+ elsif ! (Hash === specifiers)
53
+ logger.error "newrelic_#{property} takes an optional hash with :only and :except lists of actions (illegal argument type '#{specifiers.class}')"
54
+ else
55
+ self.newrelic_write_attr property, specifiers
56
+ end
57
+ end
58
+
59
+ # Should be monkey patched into the controller class implemented
60
+ # with the inheritable attribute mechanism.
61
+ def newrelic_write_attr(attr_name, value) # :nodoc:
62
+ instance_variable_set "@#{attr_name}", value
63
+ end
64
+ def newrelic_read_attr(attr_name) # :nodoc:
65
+ instance_variable_get "@#{attr_name}"
66
+ end
67
+
68
+ # Add transaction tracing to the given method. This will treat
69
+ # the given method as a main entrypoint for instrumentation, just
70
+ # like controller actions are treated by default. Useful especially
71
+ # for background tasks.
72
+ #
73
+ # Example for background job:
74
+ # class Job
75
+ # include NewRelic::Agent::Instrumentation::ControllerInstrumentation
76
+ # def run(task)
77
+ # ...
78
+ # end
79
+ # # Instrument run so tasks show up under task.name. Note single
80
+ # # quoting to defer eval to runtime.
81
+ # add_transaction_tracer :run, :name => '#{args[0].name}'
82
+ # end
83
+ #
84
+ # Here's an example of a controller that uses a dispatcher
85
+ # action to invoke operations which you want treated as top
86
+ # level actions, so they aren't all lumped into the invoker
87
+ # action.
88
+ #
89
+ # MyController < ActionController::Base
90
+ # include NewRelic::Agent::Instrumentation::ControllerInstrumentation
91
+ # # dispatch the given op to the method given by the service parameter.
92
+ # def invoke_operation
93
+ # op = params['operation']
94
+ # send op
95
+ # end
96
+ # # Ignore the invoker to avoid double counting
97
+ # newrelic_ignore :only => 'invoke_operation'
98
+ # # Instrument the operations:
99
+ # add_transaction_tracer :print
100
+ # add_transaction_tracer :show
101
+ # add_transaction_tracer :forward
102
+ # end
103
+ #
104
+ # Here's an example of how to pass contextual information into the transaction
105
+ # so it will appear in transaction traces:
106
+ #
107
+ # class Job
108
+ # include NewRelic::Agent::Instrumentation::ControllerInstrumentation
109
+ # def process(account)
110
+ # ...
111
+ # end
112
+ # # Include the account name in the transaction details. Note the single
113
+ # # quotes to defer eval until call time.
114
+ # add_transaction_tracer :process, :params => '{ :account_name => args[0].name }'
115
+ # end
116
+ #
117
+ # See NewRelic::Agent::Instrumentation::ControllerInstrumentation#perform_action_with_newrelic_trace
118
+ # for the full list of available options.
119
+ #
120
+ def add_transaction_tracer(method, options={})
121
+ # The metric path:
122
+ options[:name] ||= method.to_s
123
+ # create the argument list:
124
+ options_arg = []
125
+ options.each do |key, value|
126
+ valuestr = case
127
+ when value.is_a?(Symbol)
128
+ value.inspect
129
+ when key == :params
130
+ value.to_s
131
+ else
132
+ %Q["#{value.to_s}"]
133
+ end
134
+ options_arg << %Q[:#{key} => #{valuestr}]
135
+ end
136
+ class_eval <<-EOC
137
+ def #{method.to_s}_with_newrelic_transaction_trace(*args, &block)
138
+ perform_action_with_newrelic_trace(#{options_arg.join(',')}) do
139
+ #{method.to_s}_without_newrelic_transaction_trace(*args, &block)
140
+ end
141
+ end
142
+ EOC
143
+ alias_method "#{method.to_s}_without_newrelic_transaction_trace", method.to_s
144
+ alias_method method.to_s, "#{method.to_s}_with_newrelic_transaction_trace"
145
+ end
146
+ end
147
+
148
+ # Must be implemented in the controller class:
149
+ # Determine the path that is used in the metric name for
150
+ # the called controller action. Of the form controller_path/action_name
151
+ #
152
+ def newrelic_metric_path(action_name_override = nil) # :nodoc:
153
+ raise "Not implemented!"
154
+ end
155
+
156
+ # Yield to the given block with NewRelic tracing. Used by
157
+ # default instrumentation on controller actions in Rails and Merb.
158
+ # But it can also be used in custom instrumentation of controller
159
+ # methods and background tasks.
160
+ #
161
+ # This is the method invoked by instrumentation added by the
162
+ # <tt>ClassMethods#add_transaction_tracer</tt>.
163
+ #
164
+ # Here's a more verbose version of the example shown in
165
+ # <tt>ClassMethods#add_transaction_tracer</tt> using this method instead of
166
+ # #add_transaction_tracer.
167
+ #
168
+ # Below is a controller with an +invoke_operation+ action which
169
+ # dispatches to more specific operation methods based on a
170
+ # parameter (very dangerous, btw!). With this instrumentation,
171
+ # the +invoke_operation+ action is ignored but the operation
172
+ # methods show up in RPM as if they were first class controller
173
+ # actions
174
+ #
175
+ # MyController < ActionController::Base
176
+ # include NewRelic::Agent::Instrumentation::ControllerInstrumentation
177
+ # # dispatch the given op to the method given by the service parameter.
178
+ # def invoke_operation
179
+ # op = params['operation']
180
+ # perform_action_with_newrelic_trace(:name => op) do
181
+ # send op, params['message']
182
+ # end
183
+ # end
184
+ # # Ignore the invoker to avoid double counting
185
+ # newrelic_ignore :only => 'invoke_operation'
186
+ # end
187
+ #
188
+ #
189
+ # When invoking this method explicitly as in the example above, pass in a
190
+ # block to measure with some combination of options:
191
+ #
192
+ # * <tt>:category => :controller</tt> indicates that this is a
193
+ # controller action and will appear with all the other actions. This
194
+ # is the default.
195
+ # * <tt>:category => :task</tt> indicates that this is a
196
+ # background task and will show up in RPM with other background
197
+ # tasks instead of in the controllers list
198
+ # * <tt>:category => :rack</tt> if you are instrumenting a rack
199
+ # middleware call. The <tt>:name</tt> is optional, useful if you
200
+ # have more than one potential transaction in the #call.
201
+ # * <tt>:category => :uri</tt> indicates that this is a
202
+ # web transaction whose name is a normalized URI, where 'normalized'
203
+ # means the URI does not have any elements with data in them such
204
+ # as in many REST URIs.
205
+ # * <tt>:name => action_name</tt> is used to specify the action
206
+ # name used as part of the metric name
207
+ # * <tt>:params => {...}</tt> to provide information about the context
208
+ # of the call, used in transaction trace display, for example:
209
+ # <tt>:params => { :account => @account.name, :file => file.name }</tt>
210
+ #
211
+ # Seldomly used options:
212
+ #
213
+ # * <tt>:force => true</tt> indicates you should capture all
214
+ # metrics even if the #newrelic_ignore directive was specified
215
+ # * <tt>:class_name => aClass.name</tt> is used to override the name
216
+ # of the class when used inside the metric name. Default is the
217
+ # current class.
218
+ # * <tt>:path => metric_path</tt> is *deprecated* in the public API. It
219
+ # allows you to set the entire metric after the category part. Overrides
220
+ # all the other options.
221
+ #
222
+ # If a single argument is passed in, it is treated as a metric
223
+ # path. This form is deprecated.
224
+ def perform_action_with_newrelic_trace(*args, &block)
225
+
226
+ NewRelic::Agent.instance.ensure_worker_thread_started
227
+
228
+ # Skip instrumentation based on the value of 'do_not_trace' and if
229
+ # we aren't calling directly with a block.
230
+ if !block_given? && _is_filtered?('do_not_trace')
231
+ # Also ignore all instrumentation in the call sequence
232
+ NewRelic::Agent.disable_all_tracing do
233
+ return perform_action_without_newrelic_trace(*args)
234
+ end
235
+ end
236
+
237
+ return perform_action_with_newrelic_profile(args, &block) if NewRelic::Control.instance.profiling?
238
+
239
+ frame_data = _push_metric_frame(block_given? ? args : [])
240
+
241
+ NewRelic::Agent.trace_execution_scoped frame_data.recorded_metrics, :force => frame_data.force_flag do
242
+ frame_data.start_transaction
243
+ begin
244
+ NewRelic::Agent::BusyCalculator.dispatcher_start frame_data.start
245
+ if block_given?
246
+ yield
247
+ else
248
+ perform_action_without_newrelic_trace(*args)
249
+ end
250
+ rescue Exception => e
251
+ frame_data.notice_error(e)
252
+ raise
253
+ ensure
254
+ NewRelic::Agent::BusyCalculator.dispatcher_finish
255
+ # Look for a metric frame in the thread local and process it.
256
+ # Clear the thread local when finished to ensure it only gets called once.
257
+ frame_data.record_apdex unless _is_filtered?('ignore_apdex')
258
+ frame_data.pop
259
+ end
260
+ end
261
+ end
262
+
263
+ protected
264
+ # Should be implemented in the dispatcher class
265
+ def newrelic_response_code; end
266
+
267
+ def newrelic_request_headers
268
+ self.respond_to?(:request) && self.request.respond_to?(:headers) && self.request.headers
269
+ end
270
+
271
+ private
272
+
273
+ # Profile the instrumented call. Dev mode only. Experimental.
274
+ def perform_action_with_newrelic_profile(args)
275
+ frame_data = _push_metric_frame(block_given? ? args : [])
276
+ NewRelic::Agent.trace_execution_scoped frame_data.metric_name do
277
+ MetricFrame.current(true).start_transaction
278
+ NewRelic::Agent.disable_all_tracing do
279
+ # turn on profiling
280
+ profile = RubyProf.profile do
281
+ if block_given?
282
+ yield
283
+ else
284
+ perform_action_without_newrelic_trace(*args)
285
+ end
286
+ end
287
+ NewRelic::Agent.instance.transaction_sampler.notice_profile profile
288
+ end
289
+ end
290
+ ensure
291
+ frame_data.pop
292
+ end
293
+
294
+ # Write a metric frame onto a thread local if there isn't already one there.
295
+ # If there is one, just update it.
296
+ def _push_metric_frame(args) # :nodoc:
297
+ frame_data = MetricFrame.current(true)
298
+
299
+ frame_data.apdex_start ||= _detect_upstream_wait(frame_data.start)
300
+
301
+ # If a block was passed in, then the arguments represent options for the instrumentation,
302
+ # not app method arguments.
303
+ if args.any?
304
+ frame_data.force_flag = args.last.is_a?(Hash) && args.last[:force]
305
+ category, path, available_params = _convert_args_to_path(args)
306
+ else
307
+ category = 'Controller'
308
+ path = newrelic_metric_path
309
+ available_params = self.respond_to?(:params) ? self.params : {}
310
+ end
311
+ frame_data.push(category, path)
312
+ frame_data.filtered_params = (respond_to? :filter_parameters) ? filter_parameters(available_params) : available_params
313
+ frame_data.available_request ||= (respond_to? :request) ? request : nil
314
+ frame_data
315
+ end
316
+
317
+ def _convert_args_to_path(args)
318
+ options = args.last.is_a?(Hash) ? args.pop : {}
319
+ category = 'Controller'
320
+ params = options[:params] || {}
321
+ unless path = options[:path]
322
+ category = case options[:category]
323
+ when :controller, nil then 'Controller'
324
+ when :task then 'Controller' #'OtherTransaction/Background' # 'Task'
325
+ when :rack then 'Controller/Rack' #'WebTransaction/Rack'
326
+ when :uri then 'Controller' #'WebTransaction/Uri'
327
+ when :sinatra then 'Controller/Sinatra' #'WebTransaction/Uri'
328
+ # for internal use only
329
+ else options[:category].to_s
330
+ end
331
+ # To be consistent with the ActionController::Base#controller_path used in rails to determine the
332
+ # metric path, we drop the controller off the end of the path if there is one.
333
+ action = options[:name] || args.first
334
+ metric_class = options[:class_name] || (self.is_a?(Class) ? self.name : self.class.name)
335
+
336
+ path = metric_class
337
+ path += ('/' + action) if action
338
+ end
339
+ [category, path, params]
340
+ end
341
+
342
+ # Filter out
343
+ def _is_filtered?(key)
344
+ ignore_actions = self.class.newrelic_read_attr(key) if self.class.respond_to? :newrelic_read_attr
345
+ case ignore_actions
346
+ when nil; false
347
+ when Hash
348
+ only_actions = Array(ignore_actions[:only])
349
+ except_actions = Array(ignore_actions[:except])
350
+ only_actions.include?(action_name.to_sym) || (except_actions.any? && !except_actions.include?(action_name.to_sym))
351
+ else
352
+ true
353
+ end
354
+ end
355
+
356
+ def _detect_upstream_wait(now)
357
+ if newrelic_request_headers
358
+ if entry_time = newrelic_request_headers['HTTP_X_REQUEST_START']
359
+ if queue_depth = newrelic_request_headers['HTTP_X_HEROKU_QUEUE_DEPTH']
360
+ http_entry_time = entry_time.to_f / 1e3
361
+ _record_heroku_queue_depth(queue_depth)
362
+ else # apache / nginx
363
+ apache_parsed_time = entry_time[/t=(\d+)/, 1]
364
+ http_entry_time = apache_parsed_time.to_f/1e6 if apache_parsed_time
365
+ end
366
+ end
367
+ end
368
+ # If we didn't find the custom header, look for the mongrel timestamp
369
+ http_entry_time ||= Thread.current[:started_on] and http_entry_time = http_entry_time.to_f
370
+ if http_entry_time
371
+ queue_stat = NewRelic::Agent.agent.stats_engine.get_stats_no_scope 'WebFrontend/Mongrel/Average Queue Time'
372
+ total_time = (now - http_entry_time)
373
+ queue_stat.trace_call(total_time) unless total_time < 0 # using remote timestamps could lead to negative queue time
374
+ end
375
+ http_entry_time || now
376
+ end
377
+
378
+ def _record_heroku_queue_depth(header)
379
+ length_stat = NewRelic::Agent.agent.stats_engine.get_stats_no_scope('Mongrel/Queue Length')
380
+ length_stat.trace_call(header.to_i)
381
+ end
382
+
383
+ def _dispatch_stat
384
+ NewRelic::Agent.agent.stats_engine.get_stats_no_scope 'HttpDispatcher'
385
+ end
386
+
387
+
388
+ end
389
+ end