techarch-newrelic_rpm 2.10.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (158) hide show
  1. data/CHANGELOG +335 -0
  2. data/LICENSE +37 -0
  3. data/Manifest +159 -0
  4. data/README.md +138 -0
  5. data/Rakefile +22 -0
  6. data/bin/mongrel_rpm +33 -0
  7. data/bin/newrelic_cmd +4 -0
  8. data/cert/cacert.pem +34 -0
  9. data/init.rb +38 -0
  10. data/install.rb +45 -0
  11. data/lib/new_relic/agent.rb +281 -0
  12. data/lib/new_relic/agent/agent.rb +636 -0
  13. data/lib/new_relic/agent/chained_call.rb +13 -0
  14. data/lib/new_relic/agent/collection_helper.rb +66 -0
  15. data/lib/new_relic/agent/error_collector.rb +121 -0
  16. data/lib/new_relic/agent/instrumentation/active_merchant.rb +18 -0
  17. data/lib/new_relic/agent/instrumentation/active_record_instrumentation.rb +88 -0
  18. data/lib/new_relic/agent/instrumentation/authlogic.rb +8 -0
  19. data/lib/new_relic/agent/instrumentation/controller_instrumentation.rb +437 -0
  20. data/lib/new_relic/agent/instrumentation/data_mapper.rb +90 -0
  21. data/lib/new_relic/agent/instrumentation/dispatcher_instrumentation.rb +167 -0
  22. data/lib/new_relic/agent/instrumentation/memcache.rb +24 -0
  23. data/lib/new_relic/agent/instrumentation/merb/controller.rb +26 -0
  24. data/lib/new_relic/agent/instrumentation/merb/dispatcher.rb +13 -0
  25. data/lib/new_relic/agent/instrumentation/merb/errors.rb +8 -0
  26. data/lib/new_relic/agent/instrumentation/net.rb +23 -0
  27. data/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb +20 -0
  28. data/lib/new_relic/agent/instrumentation/rack.rb +108 -0
  29. data/lib/new_relic/agent/instrumentation/rails/action_controller.rb +59 -0
  30. data/lib/new_relic/agent/instrumentation/rails/action_web_service.rb +27 -0
  31. data/lib/new_relic/agent/instrumentation/rails/dispatcher.rb +41 -0
  32. data/lib/new_relic/agent/instrumentation/rails/errors.rb +27 -0
  33. data/lib/new_relic/agent/instrumentation/sinatra.rb +39 -0
  34. data/lib/new_relic/agent/method_tracer.rb +349 -0
  35. data/lib/new_relic/agent/patch_const_missing.rb +125 -0
  36. data/lib/new_relic/agent/sampler.rb +12 -0
  37. data/lib/new_relic/agent/samplers/cpu_sampler.rb +49 -0
  38. data/lib/new_relic/agent/samplers/memory_sampler.rb +138 -0
  39. data/lib/new_relic/agent/samplers/mongrel_sampler.rb +22 -0
  40. data/lib/new_relic/agent/shim_agent.rb +21 -0
  41. data/lib/new_relic/agent/stats_engine.rb +22 -0
  42. data/lib/new_relic/agent/stats_engine/metric_stats.rb +111 -0
  43. data/lib/new_relic/agent/stats_engine/samplers.rb +71 -0
  44. data/lib/new_relic/agent/stats_engine/transactions.rb +152 -0
  45. data/lib/new_relic/agent/transaction_sampler.rb +310 -0
  46. data/lib/new_relic/agent/worker_loop.rb +118 -0
  47. data/lib/new_relic/commands/deployments.rb +145 -0
  48. data/lib/new_relic/commands/new_relic_commands.rb +30 -0
  49. data/lib/new_relic/control.rb +473 -0
  50. data/lib/new_relic/control/external.rb +13 -0
  51. data/lib/new_relic/control/merb.rb +22 -0
  52. data/lib/new_relic/control/rails.rb +145 -0
  53. data/lib/new_relic/control/ruby.rb +36 -0
  54. data/lib/new_relic/control/sinatra.rb +14 -0
  55. data/lib/new_relic/histogram.rb +89 -0
  56. data/lib/new_relic/local_environment.rb +328 -0
  57. data/lib/new_relic/merbtasks.rb +6 -0
  58. data/lib/new_relic/metric_data.rb +42 -0
  59. data/lib/new_relic/metric_parser.rb +124 -0
  60. data/lib/new_relic/metric_parser/action_mailer.rb +9 -0
  61. data/lib/new_relic/metric_parser/active_merchant.rb +26 -0
  62. data/lib/new_relic/metric_parser/active_record.rb +25 -0
  63. data/lib/new_relic/metric_parser/controller.rb +54 -0
  64. data/lib/new_relic/metric_parser/controller_cpu.rb +38 -0
  65. data/lib/new_relic/metric_parser/errors.rb +6 -0
  66. data/lib/new_relic/metric_parser/external.rb +50 -0
  67. data/lib/new_relic/metric_parser/mem_cache.rb +12 -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 +52 -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/newrelic.ru +25 -0
  76. data/lib/new_relic/rack/newrelic.yml +25 -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 +361 -0
  80. data/lib/new_relic/transaction_analysis.rb +121 -0
  81. data/lib/new_relic/transaction_sample.rb +666 -0
  82. data/lib/new_relic/version.rb +54 -0
  83. data/lib/new_relic_api.rb +313 -0
  84. data/lib/newrelic_rpm.rb +40 -0
  85. data/lib/tasks/all.rb +4 -0
  86. data/lib/tasks/install.rake +7 -0
  87. data/lib/tasks/tests.rake +13 -0
  88. data/newrelic.yml +227 -0
  89. data/recipes/newrelic.rb +6 -0
  90. data/techarch-newrelic_rpm.gemspec +32 -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 +39 -0
  94. data/test/new_relic/agent/active_record_instrumentation_test.rb +264 -0
  95. data/test/new_relic/agent/agent_controller_test.rb +107 -0
  96. data/test/new_relic/agent/agent_test.rb +119 -0
  97. data/test/new_relic/agent/agent_test_controller.rb +44 -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/dispatcher_instrumentation_test.rb +76 -0
  101. data/test/new_relic/agent/error_collector_test.rb +172 -0
  102. data/test/new_relic/agent/method_tracer_test.rb +340 -0
  103. data/test/new_relic/agent/metric_data_test.rb +56 -0
  104. data/test/new_relic/agent/mock_ar_connection.rb +40 -0
  105. data/test/new_relic/agent/mock_scope_listener.rb +23 -0
  106. data/test/new_relic/agent/net_instrumentation_test.rb +63 -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 +81 -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 +126 -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 +385 -0
  115. data/test/new_relic/agent/worker_loop_test.rb +103 -0
  116. data/test/new_relic/control_test.rb +113 -0
  117. data/test/new_relic/deployments_api_test.rb +68 -0
  118. data/test/new_relic/environment_test.rb +75 -0
  119. data/test/new_relic/metric_parser_test.rb +172 -0
  120. data/test/new_relic/metric_spec_test.rb +177 -0
  121. data/test/new_relic/shim_agent_test.rb +9 -0
  122. data/test/new_relic/stats_test.rb +291 -0
  123. data/test/new_relic/version_number_test.rb +74 -0
  124. data/test/test_helper.rb +38 -0
  125. data/test/ui/newrelic_controller_test.rb +14 -0
  126. data/test/ui/newrelic_helper_test.rb +53 -0
  127. data/ui/controllers/newrelic_controller.rb +220 -0
  128. data/ui/helpers/google_pie_chart.rb +55 -0
  129. data/ui/helpers/newrelic_helper.rb +317 -0
  130. data/ui/views/layouts/newrelic_default.rhtml +47 -0
  131. data/ui/views/newrelic/_explain_plans.rhtml +27 -0
  132. data/ui/views/newrelic/_sample.rhtml +19 -0
  133. data/ui/views/newrelic/_segment.rhtml +28 -0
  134. data/ui/views/newrelic/_segment_limit_message.rhtml +1 -0
  135. data/ui/views/newrelic/_segment_row.rhtml +14 -0
  136. data/ui/views/newrelic/_show_sample_detail.rhtml +24 -0
  137. data/ui/views/newrelic/_show_sample_sql.rhtml +20 -0
  138. data/ui/views/newrelic/_show_sample_summary.rhtml +3 -0
  139. data/ui/views/newrelic/_sql_row.rhtml +11 -0
  140. data/ui/views/newrelic/_stack_trace.rhtml +30 -0
  141. data/ui/views/newrelic/_table.rhtml +12 -0
  142. data/ui/views/newrelic/explain_sql.rhtml +42 -0
  143. data/ui/views/newrelic/images/arrow-close.png +0 -0
  144. data/ui/views/newrelic/images/arrow-open.png +0 -0
  145. data/ui/views/newrelic/images/blue_bar.gif +0 -0
  146. data/ui/views/newrelic/images/file_icon.png +0 -0
  147. data/ui/views/newrelic/images/gray_bar.gif +0 -0
  148. data/ui/views/newrelic/images/new_relic_rpm_desktop.gif +0 -0
  149. data/ui/views/newrelic/images/textmate.png +0 -0
  150. data/ui/views/newrelic/index.rhtml +57 -0
  151. data/ui/views/newrelic/javascript/prototype-scriptaculous.js +7288 -0
  152. data/ui/views/newrelic/javascript/transaction_sample.js +107 -0
  153. data/ui/views/newrelic/sample_not_found.rhtml +2 -0
  154. data/ui/views/newrelic/show_sample.rhtml +80 -0
  155. data/ui/views/newrelic/show_source.rhtml +3 -0
  156. data/ui/views/newrelic/stylesheets/style.css +484 -0
  157. data/ui/views/newrelic/threads.rhtml +52 -0
  158. metadata +330 -0
@@ -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,121 @@
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(agent = nil)
17
+ @agent = agent
18
+ @errors = []
19
+ # lookup of exception class names to ignore. Hash for fast access
20
+ @ignore = {}
21
+ @ignore_filter = nil
22
+
23
+ config = NewRelic::Control.instance.fetch('error_collector', {})
24
+
25
+ @enabled = config.fetch('enabled', true)
26
+ @capture_source = config.fetch('capture_source', true)
27
+
28
+ ignore_errors = config.fetch('ignore_errors', "")
29
+ ignore_errors = ignore_errors.split(",")
30
+ ignore_errors.each { |error| error.strip! }
31
+ ignore(ignore_errors)
32
+ @lock = Mutex.new
33
+ end
34
+
35
+ def ignore_error_filter(&block)
36
+ @ignore_filter = block
37
+ end
38
+
39
+
40
+ # errors is an array of Exception Class Names
41
+ #
42
+ def ignore(errors)
43
+ errors.each { |error| @ignore[error] = true; log.debug("Ignoring error: '#{error}'") }
44
+ end
45
+
46
+ def notice_error(exception, request=nil, action_path=nil, filtered_params={})
47
+ return unless @enabled
48
+ return if @ignore[exception.class.name]
49
+ if @ignore_filter
50
+ exception = @ignore_filter.call(exception)
51
+ return if exception.nil?
52
+ end
53
+
54
+ error_stat.increment_count
55
+
56
+ data = {}
57
+
58
+ action_path ||= ''
59
+
60
+ data[:request_params] = normalize_params(filtered_params) if NewRelic::Control.instance.capture_params
61
+
62
+ data[:custom_params] = normalize_params(@agent.custom_params) if @agent
63
+
64
+ data[:request_uri] = request.path if request
65
+ data[:request_uri] ||= ""
66
+
67
+ data[:request_referer] = request.referer if request
68
+ data[:request_referer] ||= ""
69
+
70
+ data[:rails_root] = NewRelic::Control.instance.root
71
+
72
+ data[:file_name] = exception.file_name if exception.respond_to?('file_name')
73
+ data[:line_number] = exception.line_number if exception.respond_to?('line_number')
74
+
75
+ if @capture_source && exception.respond_to?('source_extract')
76
+ data[:source] = exception.source_extract
77
+ end
78
+
79
+ if exception.respond_to? 'original_exception'
80
+ inside_exception = exception.original_exception
81
+ else
82
+ inside_exception = exception
83
+ end
84
+
85
+ data[:stack_trace] = inside_exception ? inside_exception.backtrace : '<no stack trace>'
86
+
87
+ noticed_error = NewRelic::NoticedError.new(action_path, data, exception)
88
+
89
+ @lock.synchronize do
90
+ if @errors.length >= MAX_ERROR_QUEUE_LENGTH
91
+ log.info("The error reporting queue has reached #{MAX_ERROR_QUEUE_LENGTH}. This error will not be reported to RPM: #{exception.message}")
92
+ else
93
+ @errors << noticed_error
94
+ end
95
+ end
96
+ end
97
+
98
+ # Get the errors currently queued up. Unsent errors are left
99
+ # over from a previous unsuccessful attempt to send them to the server.
100
+ # We first clear out all unsent errors before sending the newly queued errors.
101
+ def harvest_errors(unsent_errors)
102
+ if unsent_errors && !unsent_errors.empty?
103
+ return unsent_errors
104
+ else
105
+ @lock.synchronize do
106
+ errors = @errors
107
+ @errors = []
108
+ return errors
109
+ end
110
+ end
111
+ end
112
+
113
+ private
114
+ def error_stat
115
+ @error_stat ||= NewRelic::Agent.get_stats("Errors/all")
116
+ end
117
+ def log
118
+ NewRelic::Control.instance.log
119
+ end
120
+ end
121
+ 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,88 @@
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
+ if sql =~ /^(select|update|insert|delete|show)/i
45
+ # Could not determine the model/operation so let's find a better
46
+ # metric. If it doesn't match the regex, it's probably a show
47
+ # command or some DDL which we'll ignore.
48
+ metric = "Database/SQL/#{$1.downcase}"
49
+ else
50
+ metric = "Database/SQL/other"
51
+ end
52
+ end
53
+
54
+ if !metric
55
+ log_without_newrelic_instrumentation(sql, name, &block)
56
+ else
57
+ metrics = [metric, "ActiveRecord/all"]
58
+ metrics << "ActiveRecord/#{metric_name}" if metric_name
59
+ self.class.trace_execution_scoped(metrics) do
60
+ t0 = Time.now.to_f
61
+ begin
62
+ log_without_newrelic_instrumentation(sql, name, &block)
63
+ ensure
64
+ NewRelic::Agent.instance.transaction_sampler.notice_sql(sql, supported_config, Time.now.to_f - t0)
65
+ end
66
+ end
67
+ end
68
+ end
69
+
70
+ end
71
+
72
+ # instrumentation to catch logged SQL statements in sampled transactions
73
+ ActiveRecord::ConnectionAdapters::AbstractAdapter.module_eval do
74
+ include ::NewRelic::Agent::Instrumentation::ActiveRecordInstrumentation
75
+ end
76
+
77
+ # This instrumentation will add an extra scope to the transaction traces
78
+ # which will show the code surrounding the query, inside the model find_by_sql
79
+ # method.
80
+ ActiveRecord::Base.class_eval do
81
+ class << self
82
+ add_method_tracer :find_by_sql, 'ActiveRecord/#{self.name}/find_by_sql', :metric => false
83
+ end
84
+ end unless NewRelic::Control.instance['disable_activerecord_instrumentation']
85
+ end
86
+ end
87
+ end
88
+ 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,437 @@
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
+ if defined? JRuby
17
+ @@newrelic_java_classes_missing = false
18
+ begin
19
+ require 'java'
20
+ include_class 'java.lang.management.ManagementFactory'
21
+ include_class 'com.sun.management.OperatingSystemMXBean'
22
+ rescue
23
+ @@newrelic_java_classes_missing = true
24
+ end
25
+ end
26
+
27
+ def self.included(clazz) # :nodoc:
28
+ clazz.extend(ClassMethods)
29
+ end
30
+
31
+ # This module is for importing stubs when the agent is disabled
32
+ module ClassMethodsShim # :nodoc:
33
+ def newrelic_ignore(*args); end
34
+ def newrelic_ignore_apdex(*args); end
35
+ end
36
+
37
+ module Shim # :nodoc:
38
+ def self.included(clazz)
39
+ clazz.extend(ClassMethodsShim)
40
+ end
41
+ def newrelic_notice_error(*args); end
42
+ def new_relic_trace_controller_action(*args); yield; end
43
+ def newrelic_metric_path; end
44
+ def perform_action_with_newrelic_trace(*args); yield; end
45
+ end
46
+
47
+ module ClassMethods
48
+ # Have NewRelic ignore actions in this controller. Specify the actions as hash options
49
+ # using :except and :only. If no actions are specified, all actions are ignored.
50
+ def newrelic_ignore(specifiers={})
51
+ newrelic_ignore_aspect('do_not_trace', specifiers)
52
+ end
53
+ # Have NewRelic omit apdex measurements on the given actions. Typically used for
54
+ # actions that are not user facing or that skew your overall apdex measurement.
55
+ # Accepts :except and :only options, as with #newrelic_ignore.
56
+ def newrelic_ignore_apdex(specifiers={})
57
+ newrelic_ignore_aspect('ignore_apdex', specifiers)
58
+ end
59
+
60
+ def newrelic_ignore_aspect(property, specifiers={}) # :nodoc:
61
+ if specifiers.empty?
62
+ self.newrelic_write_attr property, true
63
+ elsif ! (Hash === specifiers)
64
+ logger.error "newrelic_#{property} takes an optional hash with :only and :except lists of actions (illegal argument type '#{specifiers.class}')"
65
+ else
66
+ self.newrelic_write_attr property, specifiers
67
+ end
68
+ end
69
+
70
+ # Should be monkey patched into the controller class implemented
71
+ # with the inheritable attribute mechanism.
72
+ def newrelic_write_attr(attr_name, value) # :nodoc:
73
+ instance_variable_set "@#{attr_name}", value
74
+ end
75
+ def newrelic_read_attr(attr_name) # :nodoc:
76
+ instance_variable_get "@#{attr_name}"
77
+ end
78
+
79
+ # Add transaction tracing to the given method. This will treat
80
+ # the given method as a main entrypoint for instrumentation, just
81
+ # like controller actions are treated by default. Useful especially
82
+ # for background tasks.
83
+ #
84
+ # Example for background job:
85
+ # class Job
86
+ # include NewRelic::Agent::Instrumentation::ControllerInstrumentation
87
+ # def run(task)
88
+ # ...
89
+ # end
90
+ # # Instrument run so tasks show up under task.name. Note single
91
+ # # quoting to defer eval to runtime.
92
+ # add_transaction_tracer :run, :name => '#{args[0].name}'
93
+ # end
94
+ #
95
+ # Here's an example of a controller that uses a dispatcher
96
+ # action to invoke operations which you want treated as top
97
+ # level actions, so they aren't all lumped into the invoker
98
+ # action.
99
+ #
100
+ # MyController < ActionController::Base
101
+ # include NewRelic::Agent::Instrumentation::ControllerInstrumentation
102
+ # # dispatch the given op to the method given by the service parameter.
103
+ # def invoke_operation
104
+ # op = params['operation']
105
+ # send op
106
+ # end
107
+ # # Ignore the invoker to avoid double counting
108
+ # newrelic_ignore :only => 'invoke_operation'
109
+ # # Instrument the operations:
110
+ # add_transaction_tracer :print
111
+ # add_transaction_tracer :show
112
+ # add_transaction_tracer :forward
113
+ # end
114
+ #
115
+ # Here's an example of how to pass contextual information into the transaction
116
+ # so it will appear in transaction traces:
117
+ #
118
+ # class Job
119
+ # include NewRelic::Agent::Instrumentation::ControllerInstrumentation
120
+ # def process(account)
121
+ # ...
122
+ # end
123
+ # # Include the account name in the transaction details. Note the single
124
+ # # quotes to defer eval until call time.
125
+ # add_transaction_tracer :process, :params => '{ :account_name => args[0].name }'
126
+ # end
127
+ #
128
+ # See NewRelic::Agent::Instrumentation::ControllerInstrumentation#perform_action_with_newrelic_trace
129
+ # for the full list of available options.
130
+ #
131
+ def add_transaction_tracer(method, options={})
132
+ # The metric path:
133
+ options[:name] ||= method.to_s
134
+ # create the argument list:
135
+ options_arg = []
136
+ options.each do |key, value|
137
+ valuestr = case
138
+ when value.is_a?(Symbol)
139
+ value.inspect
140
+ when key == :params
141
+ value.to_s
142
+ else
143
+ %Q["#{value.to_s}"]
144
+ end
145
+ options_arg << %Q[:#{key} => #{valuestr}]
146
+ end
147
+ class_eval <<-EOC
148
+ def #{method.to_s}_with_newrelic_transaction_trace(*args, &block)
149
+ NewRelic::Agent::Instrumentation::DispatcherInstrumentation.newrelic_dispatcher_start
150
+ perform_action_with_newrelic_trace(#{options_arg.join(',')}) do
151
+ #{method.to_s}_without_newrelic_transaction_trace(*args, &block)
152
+ end
153
+ ensure
154
+ NewRelic::Agent::Instrumentation::DispatcherInstrumentation.newrelic_dispatcher_finish
155
+ end
156
+ EOC
157
+ alias_method "#{method.to_s}_without_newrelic_transaction_trace", method.to_s
158
+ alias_method method.to_s, "#{method.to_s}_with_newrelic_transaction_trace"
159
+ end
160
+ end
161
+
162
+ # Must be implemented in the controller class:
163
+ # Determine the path that is used in the metric name for
164
+ # the called controller action. Of the form controller_path/action_name
165
+ #
166
+ def newrelic_metric_path(action_name_override = nil) # :nodoc:
167
+ raise "Not implemented!"
168
+ end
169
+
170
+ # Yield to the given block with NewRelic tracing. Used by
171
+ # default instrumentation on controller actions in Rails and Merb.
172
+ # But it can also be used in custom instrumentation of controller
173
+ # methods and background tasks.
174
+ #
175
+ # Here's a more verbose version of the example shown in
176
+ # <tt>ClassMethods#add_transaction_tracer</tt> using this method instead of
177
+ # #add_transaction_tracer.
178
+ #
179
+ # Below is a controller with an +invoke_operation+ action which
180
+ # dispatches to more specific operation methods based on a
181
+ # parameter (very dangerous, btw!). With this instrumentation,
182
+ # the +invoke_operation+ action is ignored but the operation
183
+ # methods show up in RPM as if they were first class controller
184
+ # actions
185
+ #
186
+ # MyController < ActionController::Base
187
+ # include NewRelic::Agent::Instrumentation::ControllerInstrumentation
188
+ # # dispatch the given op to the method given by the service parameter.
189
+ # def invoke_operation
190
+ # op = params['operation']
191
+ # perform_action_with_newrelic_trace(:name => op) do
192
+ # send op, params['message']
193
+ # end
194
+ # end
195
+ # # Ignore the invoker to avoid double counting
196
+ # newrelic_ignore :only => 'invoke_operation'
197
+ # end
198
+ #
199
+ # By passing a block in combination with specific arguments, you can
200
+ # invoke this directly to capture high level information in
201
+ # several contexts:
202
+ #
203
+ # * Pass <tt>:category => :controller</tt> and <tt>:name => actionname</tt>
204
+ # to treat the block as if it were a controller action, invoked
205
+ # inside a real action. <tt>:name</tt> is the name of the method, and is
206
+ # used in the metric name.
207
+ #
208
+ # When invoked directly, pass in a block to measure with some
209
+ # combination of options:
210
+ #
211
+ # * <tt>:category => :controller</tt> indicates that this is a
212
+ # controller action and will appear with all the other actions. This
213
+ # is the default.
214
+ # * <tt>:category => :task</tt> indicates that this is a
215
+ # background task and will show up in RPM with other background
216
+ # tasks instead of in the controllers list
217
+ # * <tt>:category => :rack</tt> if you are instrumenting a rack
218
+ # middleware call. The <tt>:name</tt> is optional, useful if you
219
+ # have more than one potential transaction in the #call.
220
+ # * <tt>:category => :uri</tt> indicates that this is a
221
+ # web transaction whose name is a normalized URI, where 'normalized'
222
+ # means the URI does not have any elements with data in them such
223
+ # as in many REST URIs.
224
+ # * <tt>:params => {...}</tt> to provide information about the context
225
+ # of the call, used in transaction trace display, for example:
226
+ # <tt>:params => { :account => @account.name, :file => file.name }</tt>
227
+ # * <tt>:name => action_name</tt> is used to specify the action
228
+ # name used as part of the metric name
229
+ # * <tt>:force => true</tt> indicates you should capture all
230
+ # metrics even if the #newrelic_ignore directive was specified
231
+ # * <tt>:class_name => aClass.name</tt> is used to override the name
232
+ # of the class when used inside the metric name. Default is the
233
+ # current class.
234
+ # * <tt>:path => metric_path</tt> is *deprecated* in the public API. It
235
+ # allows you to set the entire metric after the category part. Overrides
236
+ # all the other options.
237
+ #
238
+ # If a single argument is passed in, it is treated as a metric
239
+ # path. This form is deprecated.
240
+ def perform_action_with_newrelic_trace(*args, &block)
241
+
242
+ # Skip instrumentation based on the value of 'do_not_trace' and if
243
+ # we aren't calling directly with a block.
244
+ if !block_given? && _is_filtered?('do_not_trace')
245
+ # Tell the dispatcher instrumentation that we ignored this action and it shouldn't
246
+ # be counted for the overall HTTP operations measurement.
247
+ Thread.current[:newrelic_ignore_controller] = true
248
+ # Also ignore all instrumentation in the call sequence
249
+ NewRelic::Agent.disable_all_tracing do
250
+ return perform_action_without_newrelic_trace(*args)
251
+ end
252
+ end
253
+ agent = NewRelic::Agent.instance
254
+ stats_engine = agent.stats_engine
255
+
256
+ # reset this in case we came through a code path where the top level controller is ignored
257
+ Thread.current[:newrelic_ignore_controller] = nil
258
+ apdex_start = (Thread.current[:started_on] || Thread.current[:newrelic_dispatcher_start] || Time.now).to_f
259
+ force = false
260
+ # If a block was passed in, then the arguments represent options for the instrumentation,
261
+ # not app method arguments.
262
+ if block_given? && args.any?
263
+ force = args.last.is_a?(Hash) && args.last[:force]
264
+ category, path, available_params = _convert_args_to_path(args)
265
+ else
266
+ category = 'Controller'
267
+ path = newrelic_metric_path
268
+ available_params = self.respond_to?(:params) ? self.params : {}
269
+ end
270
+ metric_name = category + '/' + path
271
+
272
+ return perform_action_with_newrelic_profile(metric_name, path, args, &block) if NewRelic::Control.instance.profiling?
273
+
274
+ filtered_params = (respond_to? :filter_parameters) ? filter_parameters(available_params) : available_params
275
+
276
+ agent.ensure_worker_thread_started
277
+
278
+ NewRelic::Agent.trace_execution_scoped [metric_name, "Controller"], :force => force do
279
+ # Last one (innermost) to set the transaction name on the call stack wins.
280
+ stats_engine.transaction_name = metric_name
281
+ available_request = (respond_to? :request) ? request : nil
282
+ agent.transaction_sampler.notice_transaction(path, available_request, filtered_params)
283
+
284
+ jruby_cpu_start = _jruby_cpu_time
285
+ process_cpu_start = _process_cpu
286
+ failed = false
287
+
288
+ begin
289
+ # run the action
290
+ if block_given?
291
+ yield
292
+ else
293
+ perform_action_without_newrelic_trace(*args)
294
+ end
295
+ rescue Exception => e
296
+ NewRelic::Agent.instance.error_collector.notice_error(e, nil, metric_name, filtered_params)
297
+ failed = true
298
+ raise e
299
+ ensure
300
+ if NewRelic::Agent.is_execution_traced?
301
+ cpu_burn = nil
302
+ if process_cpu_start
303
+ cpu_burn = _process_cpu - process_cpu_start
304
+ elsif jruby_cpu_start
305
+ cpu_burn = _jruby_cpu_time - jruby_cpu_start
306
+ stats_engine.get_stats_no_scope(NewRelic::Metrics::USER_TIME).record_data_point(cpu_burn)
307
+ end
308
+ agent.transaction_sampler.notice_transaction_cpu_time(cpu_burn) if cpu_burn
309
+
310
+ # do the apdex bucketing
311
+ #
312
+ unless _is_filtered?('ignore_apdex')
313
+ ending = Time.now.to_f
314
+ # this uses the start of the dispatcher or the mongrel
315
+ # thread: causes apdex to show too little capacity
316
+ apdex_overall(apdex_start, ending, failed)
317
+ # this uses the start time of the controller action:
318
+ # does not include capacity problems since those aren't
319
+ # per controller
320
+ apdex_controller(apdex_start, ending, failed, path)
321
+ end
322
+ end
323
+ end
324
+ end
325
+ end
326
+
327
+ # Experimental
328
+ def perform_action_with_newrelic_profile(metric_name, path, args)
329
+ agent = NewRelic::Agent.instance
330
+ stats_engine = agent.stats_engine
331
+ NewRelic::Agent.trace_execution_scoped [metric_name, "Controller"] do
332
+ stats_engine.transaction_name = metric_name
333
+ NewRelic::Agent.disable_all_tracing do
334
+ available_params = self.respond_to?(:params) ? params : {}
335
+ # Not sure if we need to get the params and request...
336
+ filtered_params = (respond_to? :filter_parameters) ? filter_parameters(available_params) : available_params
337
+ available_request = (respond_to? :request) ? request : nil
338
+ agent.transaction_sampler.notice_transaction(path, available_request, filtered_params)
339
+
340
+ # turn on profiling
341
+ profile = RubyProf.profile do
342
+ if block_given?
343
+ yield
344
+ else
345
+ perform_action_without_newrelic_trace(*args)
346
+ end
347
+ end
348
+ agent.transaction_sampler.notice_profile profile
349
+ end
350
+ end
351
+ end
352
+
353
+ private
354
+
355
+ def apdex_overall_stat
356
+ NewRelic::Agent.instance.stats_engine.get_custom_stats("Apdex", NewRelic::ApdexStats)
357
+ end
358
+
359
+ def apdex_overall(start, ending, failed)
360
+ record_apdex(apdex_overall_stat, (ending - start), failed)
361
+ end
362
+
363
+ def apdex_controller(start, ending, failed, path)
364
+ controller_stat = NewRelic::Agent.instance.stats_engine.get_custom_stats("Apdex/#{path}", NewRelic::ApdexStats)
365
+ record_apdex(controller_stat, (ending - start), failed)
366
+ end
367
+
368
+ def record_apdex(stat, duration, failed)
369
+ apdex_t = NewRelic::Control.instance.apdex_t
370
+ case
371
+ when failed
372
+ stat.record_apdex_f
373
+ when duration <= apdex_t
374
+ stat.record_apdex_s
375
+ when duration <= 4 * apdex_t
376
+ stat.record_apdex_t
377
+ else
378
+ stat.record_apdex_f
379
+ end
380
+ end
381
+
382
+ protected
383
+
384
+ def _convert_args_to_path(args)
385
+ options = args.last.is_a?(Hash) ? args.pop : {}
386
+ category = 'Controller'
387
+ params = options[:params] || {}
388
+ unless path = options[:path]
389
+ category = case options[:category]
390
+ when :controller, nil then 'Controller'
391
+ when :task then 'OtherTransaction/Background' # 'Task'
392
+ when :rack then 'Controller/Rack' #'WebTransaction/Rack'
393
+ when :uri then 'Controller' #'WebTransaction/Uri'
394
+ # for internal use only
395
+ when :sinatra then 'Controller/Sinatra' #'WebTransaction/Uri'
396
+ else options[:category].to_s.capitalize
397
+ end
398
+ # To be consistent with the ActionController::Base#controller_path used in rails to determine the
399
+ # metric path, we drop the controller off the end of the path if there is one.
400
+ action = options[:name] || args.first
401
+ force = options[:force]
402
+ metric_class = options[:class_name] || (self.is_a?(Class) ? self.name : self.class.name)
403
+
404
+ path = metric_class
405
+ path += ('/' + action) if action
406
+ end
407
+ [category, path, params]
408
+ end
409
+ # Filter out
410
+ def _is_filtered?(key)
411
+ ignore_actions = self.class.newrelic_read_attr(key) if self.class.respond_to? :newrelic_read_attr
412
+ case ignore_actions
413
+ when nil; false
414
+ when Hash
415
+ only_actions = Array(ignore_actions[:only])
416
+ except_actions = Array(ignore_actions[:except])
417
+ only_actions.include?(action_name.to_sym) || (except_actions.any? && !except_actions.include?(action_name.to_sym))
418
+ else
419
+ true
420
+ end
421
+ end
422
+
423
+ def _process_cpu
424
+ return nil if defined? JRuby
425
+ p = Process.times
426
+ p.stime + p.utime
427
+ end
428
+
429
+ def _jruby_cpu_time # :nodoc:
430
+ return nil unless defined? JRuby and not @@newrelic_java_classes_missing
431
+ threadMBean = ManagementFactory.getThreadMXBean()
432
+ java_utime = threadMBean.getCurrentThreadUserTime() # ns
433
+ -1 == java_utime ? 0.0 : java_utime/1e9
434
+ end
435
+
436
+ end
437
+ end