newrelic_rpm 2.9.9 → 2.10.3

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of newrelic_rpm might be problematic. Click here for more details.

Files changed (120) hide show
  1. data/CHANGELOG +117 -49
  2. data/bin/mongrel_rpm +2 -2
  3. data/install.rb +42 -33
  4. data/lib/new_relic/agent.rb +149 -39
  5. data/lib/new_relic/agent/agent.rb +139 -122
  6. data/lib/new_relic/agent/busy_calculator.rb +91 -0
  7. data/lib/new_relic/agent/collection_helper.rb +11 -2
  8. data/lib/new_relic/agent/error_collector.rb +33 -27
  9. data/lib/new_relic/agent/instrumentation/active_record_instrumentation.rb +30 -26
  10. data/lib/new_relic/agent/instrumentation/authlogic.rb +8 -0
  11. data/lib/new_relic/agent/instrumentation/controller_instrumentation.rb +316 -105
  12. data/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb +22 -0
  13. data/lib/new_relic/agent/instrumentation/memcache.rb +18 -12
  14. data/lib/new_relic/agent/instrumentation/merb/errors.rb +2 -1
  15. data/lib/new_relic/agent/instrumentation/metric_frame.rb +258 -0
  16. data/lib/new_relic/agent/instrumentation/net.rb +7 -11
  17. data/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb +1 -1
  18. data/lib/new_relic/agent/instrumentation/rack.rb +109 -0
  19. data/lib/new_relic/agent/instrumentation/rails/action_controller.rb +6 -5
  20. data/lib/new_relic/agent/instrumentation/rails/errors.rb +7 -7
  21. data/lib/new_relic/agent/instrumentation/sinatra.rb +46 -0
  22. data/lib/new_relic/agent/method_tracer.rb +305 -150
  23. data/lib/new_relic/agent/sampler.rb +34 -0
  24. data/lib/new_relic/agent/samplers/cpu_sampler.rb +11 -1
  25. data/lib/new_relic/agent/samplers/delayed_job_lock_sampler.rb +37 -0
  26. data/lib/new_relic/agent/samplers/memory_sampler.rb +22 -10
  27. data/lib/new_relic/agent/samplers/object_sampler.rb +24 -0
  28. data/lib/new_relic/agent/shim_agent.rb +10 -0
  29. data/lib/new_relic/agent/stats_engine.rb +16 -278
  30. data/lib/new_relic/agent/stats_engine/metric_stats.rb +118 -0
  31. data/lib/new_relic/agent/stats_engine/samplers.rb +81 -0
  32. data/lib/new_relic/agent/stats_engine/transactions.rb +149 -0
  33. data/lib/new_relic/agent/transaction_sampler.rb +73 -67
  34. data/lib/new_relic/agent/worker_loop.rb +69 -68
  35. data/lib/new_relic/commands/deployments.rb +4 -6
  36. data/lib/new_relic/control.rb +121 -60
  37. data/lib/new_relic/control/external.rb +13 -0
  38. data/lib/new_relic/control/merb.rb +2 -0
  39. data/lib/new_relic/control/rails.rb +16 -6
  40. data/lib/new_relic/control/ruby.rb +8 -5
  41. data/lib/new_relic/control/sinatra.rb +18 -0
  42. data/lib/new_relic/delayed_job_injection.rb +25 -0
  43. data/lib/new_relic/histogram.rb +89 -0
  44. data/lib/new_relic/local_environment.rb +64 -30
  45. data/lib/new_relic/metric_data.rb +15 -6
  46. data/lib/new_relic/metric_parser.rb +14 -1
  47. data/lib/new_relic/metric_parser/active_record.rb +14 -0
  48. data/lib/new_relic/metric_parser/controller.rb +5 -2
  49. data/lib/new_relic/metric_parser/external.rb +50 -0
  50. data/lib/new_relic/metric_parser/other_transaction.rb +15 -0
  51. data/lib/new_relic/metric_parser/web_frontend.rb +14 -0
  52. data/lib/new_relic/metric_spec.rb +39 -20
  53. data/lib/new_relic/metrics.rb +9 -7
  54. data/lib/new_relic/noticed_error.rb +6 -8
  55. data/lib/new_relic/rack/metric_app.rb +5 -4
  56. data/lib/new_relic/rack/{newrelic.ru → mongrel_rpm.ru} +4 -4
  57. data/lib/new_relic/rack/newrelic.yml +1 -0
  58. data/lib/new_relic/{rack.rb → rack_app.rb} +0 -0
  59. data/lib/new_relic/recipes.rb +1 -1
  60. data/lib/new_relic/stats.rb +40 -26
  61. data/lib/new_relic/transaction_analysis.rb +5 -2
  62. data/lib/new_relic/transaction_sample.rb +134 -55
  63. data/lib/new_relic/version.rb +27 -20
  64. data/lib/new_relic_api.rb +67 -47
  65. data/lib/newrelic_rpm.rb +5 -5
  66. data/lib/tasks/tests.rake +2 -0
  67. data/newrelic.yml +69 -29
  68. data/test/active_record_fixtures.rb +2 -2
  69. data/test/config/newrelic.yml +4 -7
  70. data/test/config/test_control.rb +1 -2
  71. data/test/new_relic/agent/active_record_instrumentation_test.rb +115 -31
  72. data/test/new_relic/agent/agent_controller_test.rb +274 -0
  73. data/test/new_relic/agent/agent_test_controller.rb +42 -6
  74. data/test/new_relic/agent/busy_calculator_test.rb +79 -0
  75. data/test/new_relic/agent/collection_helper_test.rb +10 -3
  76. data/test/new_relic/agent/error_collector_test.rb +35 -17
  77. data/test/new_relic/agent/method_tracer_test.rb +60 -20
  78. data/test/new_relic/agent/metric_data_test.rb +2 -2
  79. data/test/new_relic/agent/metric_frame_test.rb +51 -0
  80. data/test/new_relic/agent/net_instrumentation_test.rb +77 -0
  81. data/test/new_relic/agent/{agent_test.rb → rpm_agent_test.rb} +26 -5
  82. data/test/new_relic/agent/stats_engine/metric_stats_test.rb +79 -0
  83. data/test/new_relic/{samplers_test.rb → agent/stats_engine/samplers_test.rb} +23 -22
  84. data/test/new_relic/agent/{stats_engine_test.rb → stats_engine/stats_engine_test.rb} +19 -101
  85. data/test/new_relic/agent/task_instrumentation_test.rb +176 -0
  86. data/test/new_relic/agent/transaction_sample_builder_test.rb +2 -2
  87. data/test/new_relic/agent/transaction_sample_test.rb +53 -38
  88. data/test/new_relic/agent/transaction_sampler_test.rb +101 -33
  89. data/test/new_relic/agent/worker_loop_test.rb +16 -14
  90. data/test/new_relic/control_test.rb +26 -13
  91. data/test/new_relic/metric_parser_test.rb +31 -1
  92. data/test/new_relic/metric_spec_test.rb +2 -2
  93. data/test/new_relic/stats_test.rb +0 -8
  94. data/test/new_relic/version_number_test.rb +31 -1
  95. data/test/test_helper.rb +37 -1
  96. data/ui/controllers/newrelic_controller.rb +19 -11
  97. data/ui/helpers/google_pie_chart.rb +5 -11
  98. data/ui/helpers/newrelic_helper.rb +40 -35
  99. data/ui/views/layouts/newrelic_default.rhtml +7 -7
  100. data/ui/views/newrelic/_sample.rhtml +5 -1
  101. data/ui/views/newrelic/images/new-relic-rpm-desktop.gif +0 -0
  102. data/ui/views/newrelic/images/textmate.png +0 -0
  103. data/ui/views/newrelic/index.rhtml +13 -1
  104. data/ui/views/newrelic/show_sample.rhtml +5 -2
  105. data/ui/views/newrelic/stylesheets/style.css +54 -3
  106. metadata +65 -145
  107. data/Manifest +0 -143
  108. data/Rakefile +0 -22
  109. data/init.rb +0 -38
  110. data/lib/new_relic/agent/instrumentation/dispatcher_instrumentation.rb +0 -127
  111. data/lib/new_relic/agent/instrumentation/error_instrumentation.rb +0 -14
  112. data/lib/new_relic/agent/instrumentation/merb/dispatcher.rb +0 -13
  113. data/lib/new_relic/agent/instrumentation/rails/dispatcher.rb +0 -38
  114. data/lib/new_relic/agent/patch_const_missing.rb +0 -125
  115. data/lib/new_relic/agent/samplers/mongrel_sampler.rb +0 -22
  116. data/lib/new_relic/metric_parser/database.rb +0 -23
  117. data/newrelic_rpm.gemspec +0 -35
  118. data/test/new_relic/agent/classloader_patch_test.rb +0 -56
  119. data/test/new_relic/agent/controller_test.rb +0 -107
  120. data/test/new_relic/agent/dispatcher_instrumentation_test.rb +0 -70
@@ -0,0 +1,91 @@
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
8
+ # calls, or a reset call.
9
+ module NewRelic
10
+ module Agent
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.to_f)
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::Control.instance.log.error("Stack underflow tracking dispatcher entry and exit!\n #{caller.join(" \n")}")
34
+ else
35
+ @accumulator += (end_time - @entrypoint_stack.pop)
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.to_f
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.to_f
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])
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)
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
@@ -1,4 +1,6 @@
1
- module NewRelic::Agent::CollectionHelper
1
+ module NewRelic
2
+ module Agent
3
+ module CollectionHelper
2
4
  # Transform parameter hash into a hash whose values are strictly
3
5
  # strings
4
6
  def normalize_params(params)
@@ -53,9 +55,16 @@ module NewRelic::Agent::CollectionHelper
53
55
  when Symbol then string
54
56
  when nil then ""
55
57
  when String
56
- string.to_s.gsub(/^(.{#{len}})(.*)/) {$2.blank? ? $1 : $1 + "..."}
58
+ real_string = flatten(string)
59
+ if real_string.size > len
60
+ real_string = real_string.slice(0...len)
61
+ real_string << "..."
62
+ end
63
+ real_string
57
64
  else
58
65
  truncate(flatten(string), len)
59
66
  end
60
67
  end
61
68
  end
69
+ end
70
+ end
@@ -1,14 +1,20 @@
1
1
 
2
- module NewRelic::Agent
2
+ module NewRelic
3
+ module Agent
3
4
  class ErrorCollector
4
5
  include CollectionHelper
5
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
+
6
13
  MAX_ERROR_QUEUE_LENGTH = 20 unless defined? MAX_ERROR_QUEUE_LENGTH
7
14
 
8
15
  attr_accessor :enabled
9
16
 
10
- def initialize(agent = nil)
11
- @agent = agent
17
+ def initialize
12
18
  @errors = []
13
19
  # lookup of exception class names to ignore. Hash for fast access
14
20
  @ignore = {}
@@ -34,36 +40,38 @@ module NewRelic::Agent
34
40
  # errors is an array of Exception Class Names
35
41
  #
36
42
  def ignore(errors)
37
- errors.each { |error| @ignore[error] = true; log.debug("Ignoring error: '#{error}'") }
43
+ errors.each { |error| @ignore[error] = true; log.debug("Ignoring errors of type '#{error}'") }
38
44
  end
39
45
 
40
-
41
- def notice_error(exception, request=nil, action_path=nil, filtered_params={})
42
-
46
+ # Notice the error with the given available options:
47
+ #
48
+ # * :uri => The request path, minus any request params or query string.
49
+ # * :referer => The URI of the referer
50
+ # * :metric => The metric name associated with the transaction
51
+ # * :request_params => Request parameters, already filtered if necessary
52
+ # * :custom_params => Custom parameters
53
+ def notice_error(exception, options={})
43
54
  return unless @enabled
44
55
  return if @ignore[exception.class.name]
45
-
46
56
  if @ignore_filter
47
57
  exception = @ignore_filter.call(exception)
48
-
49
58
  return if exception.nil?
50
59
  end
51
-
52
- error_stat.increment_count
60
+
61
+ action_path = options[:metric] || NewRelic::Agent.instance.stats_engine.scope_name || ''
62
+ filtered_params = options[:request_params] || {}
63
+
64
+ NewRelic::Agent.get_stats("Errors/all").increment_count
65
+ return unless NewRelic::Agent.instance.should_send_errors
53
66
 
54
67
  data = {}
55
68
 
56
- action_path ||= ''
57
-
58
- data[:request_params] = normalize_params(filtered_params) if NewRelic::Control.instance.capture_params
69
+ data[:request_params] = normalize_params(options[:request_params]) if NewRelic::Control.instance.capture_params && options[:request_params]
59
70
 
60
- data[:custom_params] = normalize_params(@agent.custom_params) if @agent
61
-
62
- data[:request_uri] = request.path if request
63
- data[:request_uri] ||= ""
71
+ data[:custom_params] = normalize_params(options[:custom_params]) if options[:custom_params]
64
72
 
65
- data[:request_referer] = request.referer if request
66
- data[:request_referer] ||= ""
73
+ data[:request_uri] = options[:uri] || ''
74
+ data[:request_referer] = options[:referer] || ''
67
75
 
68
76
  data[:rails_root] = NewRelic::Control.instance.root
69
77
 
@@ -80,13 +88,13 @@ module NewRelic::Agent
80
88
  inside_exception = exception
81
89
  end
82
90
 
83
- data[:stack_trace] = inside_exception.backtrace
91
+ data[:stack_trace] = inside_exception ? inside_exception.backtrace : '<no stack trace>'
84
92
 
85
93
  noticed_error = NewRelic::NoticedError.new(action_path, data, exception)
86
94
 
87
95
  @lock.synchronize do
88
- if @errors.length >= MAX_ERROR_QUEUE_LENGTH
89
- log.info("The error reporting queue has reached #{MAX_ERROR_QUEUE_LENGTH}. This error will not be reported to RPM: #{exception.message}")
96
+ if @errors.length == MAX_ERROR_QUEUE_LENGTH
97
+ 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.message}")
90
98
  else
91
99
  @errors << noticed_error
92
100
  end
@@ -109,11 +117,9 @@ module NewRelic::Agent
109
117
  end
110
118
 
111
119
  private
112
- def error_stat
113
- @error_stat ||= NewRelic::Agent.get_stats("Errors/all")
114
- end
115
120
  def log
116
121
  NewRelic::Control.instance.log
117
122
  end
118
123
  end
119
- end
124
+ end
125
+ end
@@ -1,12 +1,12 @@
1
1
 
2
2
  # NewRelic instrumentation for ActiveRecord
3
- if defined?(ActiveRecord::Base) && !NewRelic::Control.instance['skip_ar_instrumentation']
4
-
3
+ if defined?(ActiveRecord) && defined?(ActiveRecord::Base) && !NewRelic::Control.instance['skip_ar_instrumentation']
4
+
5
5
  module NewRelic
6
6
  module Agent
7
7
  module Instrumentation
8
8
  module ActiveRecordInstrumentation
9
-
9
+
10
10
  def self.included(instrumented_class)
11
11
  instrumented_class.class_eval do
12
12
  alias_method :log_without_newrelic_instrumentation, :log
@@ -15,11 +15,10 @@ if defined?(ActiveRecord::Base) && !NewRelic::Control.instance['skip_ar_instrume
15
15
  end
16
16
  end
17
17
 
18
- def active_record_all_stats
19
- NewRelic::Agent.instance.stats_engine.get_stats_no_scope("ActiveRecord/all")
20
- end
21
-
22
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
+
23
22
  # Capture db config if we are going to try to get the explain plans
24
23
  if (defined?(ActiveRecord::ConnectionAdapters::MysqlAdapter) && self.is_a?(ActiveRecord::ConnectionAdapters::MysqlAdapter)) ||
25
24
  (defined?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter) && self.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLAdapter))
@@ -39,28 +38,34 @@ if defined?(ActiveRecord::Base) && !NewRelic::Control.instance['skip_ar_instrume
39
38
  end
40
39
  end
41
40
  metric = "ActiveRecord/#{model}/#{metric_name}" if metric_name
42
- end
43
- if metric.nil? && sql =~ /^(select|update|insert|delete)/i
44
- # Could not determine the model/operation so let's find a better
45
- # metric. If it doesn't match the regex, it's probably a show
46
- # command or some DDL which we'll ignore.
47
- metric = "Database/SQL/#{$1.downcase}"
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
48
55
  end
49
56
 
50
57
  if !metric
51
58
  log_without_newrelic_instrumentation(sql, name, &block)
52
59
  else
53
- self.class.trace_method_execution_with_scope metric, true, true do
60
+ metrics = [metric, "ActiveRecord/all"]
61
+ metrics << "ActiveRecord/#{metric_name}" if metric_name
62
+ self.class.trace_execution_scoped(metrics) do
54
63
  t0 = Time.now.to_f
55
- result = log_without_newrelic_instrumentation(sql, name, &block)
56
- duration = Time.now.to_f - t0
57
-
58
- NewRelic::Agent.instance.transaction_sampler.notice_sql(sql, supported_config, duration)
59
- # Record in the overall summary metric
60
- active_record_all_stats.record_data_point(duration)
61
- # Record in the summary metric for this operation
62
- NewRelic::Agent.instance.stats_engine.get_stats_no_scope("ActiveRecord/#{metric_name}").record_data_point(duration) if metric_name
63
- result
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
64
69
  end
65
70
  end
66
71
  end
@@ -71,7 +76,7 @@ if defined?(ActiveRecord::Base) && !NewRelic::Control.instance['skip_ar_instrume
71
76
  ActiveRecord::ConnectionAdapters::AbstractAdapter.module_eval do
72
77
  include ::NewRelic::Agent::Instrumentation::ActiveRecordInstrumentation
73
78
  end
74
-
79
+
75
80
  # This instrumentation will add an extra scope to the transaction traces
76
81
  # which will show the code surrounding the query, inside the model find_by_sql
77
82
  # method.
@@ -79,8 +84,7 @@ if defined?(ActiveRecord::Base) && !NewRelic::Control.instance['skip_ar_instrume
79
84
  class << self
80
85
  add_method_tracer :find_by_sql, 'ActiveRecord/#{self.name}/find_by_sql', :metric => false
81
86
  end
82
- end
83
-
87
+ end unless NewRelic::Control.instance['disable_activerecord_instrumentation']
84
88
  end
85
89
  end
86
90
  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
@@ -1,44 +1,33 @@
1
- # NewRelic instrumentation for controllers
2
- #
3
- # This instrumentation is applied to the action controller by default if the agent
4
- # is actively collecting statistics. It will collect statistics for the
5
- # given action.
6
- #
7
- # In cases where you don't want to instrument the top level action, but instead
8
- # have other methods which are dispatched to by your action, and you want to treat
9
- # these as distinct actions, then what you need to do is call newrelic_ignore
10
- # on the top level action, and manually instrument the called 'actions'.
11
- #
12
- # Here's an example of a controller with a send_message action which dispatches
13
- # to more specific send_servicename methods. This results in the controller
14
- # action stats showing up for send_servicename.
15
- #
16
- # MyController < ActionController::Base
17
- # newrelic_ignore :only => 'send_message'
18
- # # dispatch this action to the method given by the service parameter.
19
- # def send_message
20
- # service = params['service']
21
- # dispatch_to_method = "send_messge_to_#{service}"
22
- # perform_action_with_newrelic_trace(dispatch_to_method) do
23
- # send dispatch_to_method, params['message']
24
- # end
25
- # end
26
- # end
27
-
28
- module NewRelic::Agent::Instrumentation
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
+ #
29
18
  module ControllerInstrumentation
30
19
 
31
- def self.included(clazz)
20
+ def self.included(clazz) # :nodoc:
32
21
  clazz.extend(ClassMethods)
33
22
  end
34
23
 
35
24
  # This module is for importing stubs when the agent is disabled
36
- module ClassMethodsShim
25
+ module ClassMethodsShim # :nodoc:
37
26
  def newrelic_ignore(*args); end
38
27
  def newrelic_ignore_apdex(*args); end
39
28
  end
40
29
 
41
- module Shim
30
+ module Shim # :nodoc:
42
31
  def self.included(clazz)
43
32
  clazz.extend(ClassMethodsShim)
44
33
  end
@@ -71,12 +60,92 @@ module NewRelic::Agent::Instrumentation
71
60
  end
72
61
  end
73
62
 
74
- # Should be monkey patched into the controller class implemented with the inheritable attribute mechanism.
63
+ # Should be monkey patched into the controller class implemented
64
+ # with the inheritable attribute mechanism.
75
65
  def newrelic_write_attr(attr_name, value) # :nodoc:
76
66
  instance_variable_set "@#{attr_name}", value
77
67
  end
78
68
  def newrelic_read_attr(attr_name) # :nodoc:
79
- instance_variable_get "@#{attr_name}", value
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"
80
149
  end
81
150
  end
82
151
 
@@ -88,100 +157,201 @@ module NewRelic::Agent::Instrumentation
88
157
  raise "Not implemented!"
89
158
  end
90
159
 
91
- # Perform the current action with NewRelic tracing. Used in a method
92
- # chain via aliasing. Call directly if you want to instrument a specifc
93
- # block as if it were an action. Pass the block along with the path.
94
- # The metric is named according to the action name, or the given path if called
95
- # directly.
96
- def perform_action_with_newrelic_trace(*args)
97
- agent = NewRelic::Agent.instance
98
- stats_engine = agent.stats_engine
160
+ # Yield to the given block with NewRelic tracing. Used by
161
+ # default instrumentation on controller actions in Rails and Merb.
162
+ # But it can also be used in custom instrumentation of controller
163
+ # methods and background tasks.
164
+ #
165
+ # This is the method invoked by instrumentation added by the
166
+ # <tt>ClassMethods#add_transaction_tracer</tt>.
167
+ #
168
+ # Here's a more verbose version of the example shown in
169
+ # <tt>ClassMethods#add_transaction_tracer</tt> using this method instead of
170
+ # #add_transaction_tracer.
171
+ #
172
+ # Below is a controller with an +invoke_operation+ action which
173
+ # dispatches to more specific operation methods based on a
174
+ # parameter (very dangerous, btw!). With this instrumentation,
175
+ # the +invoke_operation+ action is ignored but the operation
176
+ # methods show up in RPM as if they were first class controller
177
+ # actions
178
+ #
179
+ # MyController < ActionController::Base
180
+ # include NewRelic::Agent::Instrumentation::ControllerInstrumentation
181
+ # # dispatch the given op to the method given by the service parameter.
182
+ # def invoke_operation
183
+ # op = params['operation']
184
+ # perform_action_with_newrelic_trace(:name => op) do
185
+ # send op, params['message']
186
+ # end
187
+ # end
188
+ # # Ignore the invoker to avoid double counting
189
+ # newrelic_ignore :only => 'invoke_operation'
190
+ # end
191
+ #
192
+ #
193
+ # When invoking this method explicitly as in the example above, pass in a
194
+ # block to measure with some combination of options:
195
+ #
196
+ # * <tt>:category => :controller</tt> indicates that this is a
197
+ # controller action and will appear with all the other actions. This
198
+ # is the default.
199
+ # * <tt>:category => :task</tt> indicates that this is a
200
+ # background task and will show up in RPM with other background
201
+ # tasks instead of in the controllers list
202
+ # * <tt>:category => :rack</tt> if you are instrumenting a rack
203
+ # middleware call. The <tt>:name</tt> is optional, useful if you
204
+ # have more than one potential transaction in the #call.
205
+ # * <tt>:category => :uri</tt> indicates that this is a
206
+ # web transaction whose name is a normalized URI, where 'normalized'
207
+ # means the URI does not have any elements with data in them such
208
+ # as in many REST URIs.
209
+ # * <tt>:name => action_name</tt> is used to specify the action
210
+ # name used as part of the metric name
211
+ # * <tt>:params => {...}</tt> to provide information about the context
212
+ # of the call, used in transaction trace display, for example:
213
+ # <tt>:params => { :account => @account.name, :file => file.name }</tt>
214
+ # These are treated similarly to request parameters in web transactions.
215
+ #
216
+ # Seldomly used options:
217
+ #
218
+ # * <tt>:force => true</tt> indicates you should capture all
219
+ # metrics even if the #newrelic_ignore directive was specified
220
+ # * <tt>:class_name => aClass.name</tt> is used to override the name
221
+ # of the class when used inside the metric name. Default is the
222
+ # current class.
223
+ # * <tt>:path => metric_path</tt> is *deprecated* in the public API. It
224
+ # allows you to set the entire metric after the category part. Overrides
225
+ # all the other options.
226
+ # * <tt>:request => Rack::Request#new(env)</tt> is used to pass in a
227
+ # request object that may respond to uri and referer.
228
+ #
229
+ # If a single argument is passed in, it is treated as a metric
230
+ # path. This form is deprecated.
231
+ def perform_action_with_newrelic_trace(*args, &block)
232
+
233
+ NewRelic::Agent.instance.ensure_worker_thread_started
99
234
 
100
235
  # Skip instrumentation based on the value of 'do_not_trace' and if
101
236
  # we aren't calling directly with a block.
102
- if !block_given? && is_filtered?(self.class.newrelic_read_attr('do_not_trace'))
103
- # Tell the dispatcher instrumentation that we ignored this action and it shouldn't
104
- # be counted for the overall HTTP operations measurement.
105
- Thread.current[:controller_ignored] = true
106
-
107
- return perform_action_without_newrelic_trace(*args)
237
+ if !block_given? && _is_filtered?('do_not_trace')
238
+ # Also ignore all instrumentation in the call sequence
239
+ NewRelic::Agent.disable_all_tracing do
240
+ return perform_action_without_newrelic_trace(*args)
241
+ end
108
242
  end
109
243
 
110
- # reset this in case we came through a code path where the top level controller is ignored
111
- Thread.current[:controller_ignored] = nil
244
+ return perform_action_with_newrelic_profile(args, &block) if NewRelic::Control.instance.profiling?
112
245
 
113
- start = Time.now.to_f
114
- agent.ensure_worker_thread_started
115
-
116
- # generate metrics for all all controllers (no scope)
117
- self.class.trace_method_execution_no_scope "Controller" do
118
- # assuming the first argument, if present, is the action name
119
- path = newrelic_metric_path(args.size > 0 ? args[0] : nil)
120
- controller_metric = "Controller/#{path}"
121
-
122
- self.class.trace_method_execution_with_scope controller_metric, true, true do
123
- stats_engine.transaction_name = controller_metric
124
-
125
- local_params = (respond_to? :filter_parameters) ? filter_parameters(params) : params
126
-
127
- agent.transaction_sampler.notice_transaction(path, request, local_params)
128
-
129
- t = Process.times.utime + Process.times.stime
130
-
131
- failed = false
132
-
246
+ frame_data = _push_metric_frame(block_given? ? args : [])
247
+ begin
248
+ NewRelic::Agent.trace_execution_scoped frame_data.recorded_metrics, :force => frame_data.force_flag do
249
+ frame_data.start_transaction
133
250
  begin
134
- # run the action
251
+ NewRelic::Agent::BusyCalculator.dispatcher_start frame_data.start
135
252
  if block_given?
136
253
  yield
137
254
  else
138
255
  perform_action_without_newrelic_trace(*args)
139
256
  end
140
257
  rescue Exception => e
141
- failed = true
142
- raise e
143
- ensure
144
- cpu_burn = (Process.times.utime + Process.times.stime) - t
145
- stats_engine.get_stats_no_scope("ControllerCPU/#{path}").record_data_point(cpu_burn)
146
- agent.transaction_sampler.notice_transaction_cpu_time(cpu_burn)
147
-
148
- # do the apdex bucketing
149
- #
150
- unless is_filtered?(self.class.newrelic_read_attr('ignore_apdex'))
151
- duration = Time.now.to_f - start
152
- controller_stat = stats_engine.get_custom_stats("Apdex/#{path}", NewRelic::ApdexStats)
153
- case
154
- when failed
155
- apdex_overall_stat.record_apdex_f # frustrated
156
- controller_stat.record_apdex_f
157
- when duration <= NewRelic::Control.instance['apdex_t']
158
- apdex_overall_stat.record_apdex_s # satisfied
159
- controller_stat.record_apdex_s
160
- when duration <= 4 * NewRelic::Control.instance['apdex_t']
161
- apdex_overall_stat.record_apdex_t # tolerating
162
- controller_stat.record_apdex_t
163
- else
164
- apdex_overall_stat.record_apdex_f # frustrated
165
- controller_stat.record_apdex_f
166
- end
167
- end
258
+ frame_data.notice_error(e)
259
+ raise
168
260
  end
169
261
  end
262
+ ensure
263
+ NewRelic::Agent::BusyCalculator.dispatcher_finish
264
+ # Look for a metric frame in the thread local and process it.
265
+ # Clear the thread local when finished to ensure it only gets called once.
266
+ frame_data.record_apdex unless _is_filtered?('ignore_apdex')
267
+ frame_data.pop
170
268
  end
171
- ensure
172
- # clear out the name of the traced transaction under all circumstances
173
- stats_engine.transaction_name = nil
269
+ end
270
+
271
+ protected
272
+ # Should be implemented in the dispatcher class
273
+ def newrelic_response_code; end
274
+
275
+ def newrelic_request_headers
276
+ self.respond_to?(:request) && self.request.respond_to?(:headers) && self.request.headers
174
277
  end
175
278
 
176
279
  private
177
- def apdex_overall_stat
178
- NewRelic::Agent.instance.stats_engine.get_custom_stats("Apdex", NewRelic::ApdexStats)
280
+
281
+ # Profile the instrumented call. Dev mode only. Experimental.
282
+ def perform_action_with_newrelic_profile(args)
283
+ frame_data = _push_metric_frame(block_given? ? args : [])
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
+ yield
291
+ else
292
+ perform_action_without_newrelic_trace(*args)
293
+ end
294
+ end
295
+ NewRelic::Agent.instance.transaction_sampler.notice_profile profile
296
+ end
297
+ end
298
+ ensure
299
+ frame_data.pop
179
300
  end
180
301
 
181
- def is_filtered?(ignore_actions)
302
+ # Write a metric frame onto a thread local if there isn't already one there.
303
+ # If there is one, just update it.
304
+ def _push_metric_frame(args) # :nodoc:
305
+ frame_data = NewRelic::Agent::Instrumentation::MetricFrame.current(true)
306
+
307
+ frame_data.apdex_start ||= _detect_upstream_wait(frame_data.start)
308
+ _record_queue_length
309
+ # If a block was passed in, then the arguments represent options for the instrumentation,
310
+ # not app method arguments.
311
+ if args.any?
312
+ if options = args.last.is_a?(Hash) && args.last
313
+ frame_data.force_flag = options[:force]
314
+ frame_data.request = options[:request] if options[:request]
315
+ end
316
+ category, path, available_params = _convert_args_to_path(args)
317
+ else
318
+ category = 'Controller'
319
+ path = newrelic_metric_path
320
+ available_params = self.respond_to?(:params) ? self.params : {}
321
+ frame_data.request = self.request if self.respond_to? :request
322
+ end
323
+ frame_data.push(category, path)
324
+ frame_data.filtered_params = (respond_to? :filter_parameters) ? filter_parameters(available_params) : available_params
325
+ frame_data
326
+ end
327
+
328
+ def _convert_args_to_path(args)
329
+ options = args.last.is_a?(Hash) ? args.pop : {}
330
+ params = options[:params] || {}
331
+ category = case options[:category]
332
+ when :controller, nil then 'Controller'
333
+ when :task then 'OtherTransaction/Background' # 'Task'
334
+ when :rack then 'Controller/Rack' #'WebTransaction/Rack'
335
+ when :uri then 'Controller' #'WebTransaction/Uri'
336
+ when :sinatra then 'Controller/Sinatra' #'WebTransaction/Uri'
337
+ # for internal use only
338
+ else options[:category].to_s
339
+ end
340
+ unless path = options[:path]
341
+ action = options[:name] || args.first
342
+ metric_class = options[:class_name] || (self.is_a?(Class) ? self.name : self.class.name)
343
+ path = metric_class
344
+ path += ('/' + action) if action
345
+ end
346
+ [category, path, params]
347
+ end
348
+
349
+ # Filter out
350
+ def _is_filtered?(key)
351
+ ignore_actions = self.class.newrelic_read_attr(key) if self.class.respond_to? :newrelic_read_attr
182
352
  case ignore_actions
183
- when nil; false
184
- when Hash
353
+ when nil; false
354
+ when Hash
185
355
  only_actions = Array(ignore_actions[:only])
186
356
  except_actions = Array(ignore_actions[:except])
187
357
  only_actions.include?(action_name.to_sym) || (except_actions.any? && !except_actions.include?(action_name.to_sym))
@@ -189,5 +359,46 @@ module NewRelic::Agent::Instrumentation
189
359
  true
190
360
  end
191
361
  end
362
+ # Take a guess at a measure representing the number of requests waiting in mongrel
363
+ # or heroku.
364
+ def _record_queue_length
365
+ if newrelic_request_headers
366
+ if queue_depth = newrelic_request_headers['HTTP_X_HEROKU_QUEUE_DEPTH']
367
+ queue_depth = queue_depth.to_i rescue nil
368
+ elsif mongrel = NewRelic::Control.instance.local_env.mongrel
369
+ # Always subtrace 1 for the active mongrel
370
+ queue_depth = [mongrel.workers.list.length.to_i - 1, 0].max rescue nil
371
+ end
372
+ NewRelic::Agent.agent.stats_engine.get_stats_no_scope('Mongrel/Queue Length').trace_call(queue_depth) if queue_depth
373
+ end
374
+ end
375
+
376
+ def _detect_upstream_wait(now)
377
+ if newrelic_request_headers
378
+ if entry_time = newrelic_request_headers['HTTP_X_REQUEST_START']
379
+ if newrelic_request_headers['HTTP_X_HEROKU_QUEUE_DEPTH'] # this is a heroku measure
380
+ http_entry_time = entry_time.to_f / 1e3
381
+ else # apache / nginx
382
+ apache_parsed_time = entry_time[/t=(\d+)/, 1]
383
+ http_entry_time = apache_parsed_time.to_f/1e6 if apache_parsed_time
384
+ end
385
+ end
386
+ end
387
+ # If we didn't find the custom header, look for the mongrel timestamp
388
+ http_entry_time ||= Thread.current[:started_on] and http_entry_time = http_entry_time.to_f
389
+ if http_entry_time
390
+ queue_stat = NewRelic::Agent.agent.stats_engine.get_stats_no_scope 'WebFrontend/Mongrel/Average Queue Time'
391
+ total_time = (now - http_entry_time)
392
+ queue_stat.trace_call(total_time) unless total_time < 0 # using remote timestamps could lead to negative queue time
393
+ end
394
+ http_entry_time || now
395
+ end
396
+
397
+ def _dispatch_stat
398
+ NewRelic::Agent.agent.stats_engine.get_stats_no_scope 'HttpDispatcher'
399
+ end
400
+
192
401
  end
193
402
  end
403
+ end
404
+ end