honkster-newrelic_rpm 2.13.1

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