factorylabs-newrelic_rpm 2.10.2.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (160) hide show
  1. data/CHANGELOG +354 -0
  2. data/LICENSE +37 -0
  3. data/README-2.10.2.2 +10 -0
  4. data/README.md +138 -0
  5. data/bin/mongrel_rpm +33 -0
  6. data/bin/newrelic_cmd +4 -0
  7. data/cert/cacert.pem +34 -0
  8. data/install.rb +45 -0
  9. data/lib/new_relic/agent.rb +315 -0
  10. data/lib/new_relic/agent/agent.rb +647 -0
  11. data/lib/new_relic/agent/busy_calculator.rb +86 -0
  12. data/lib/new_relic/agent/chained_call.rb +13 -0
  13. data/lib/new_relic/agent/collection_helper.rb +66 -0
  14. data/lib/new_relic/agent/error_collector.rb +117 -0
  15. data/lib/new_relic/agent/instrumentation/active_merchant.rb +18 -0
  16. data/lib/new_relic/agent/instrumentation/active_record_instrumentation.rb +91 -0
  17. data/lib/new_relic/agent/instrumentation/authlogic.rb +8 -0
  18. data/lib/new_relic/agent/instrumentation/controller_instrumentation.rb +389 -0
  19. data/lib/new_relic/agent/instrumentation/data_mapper.rb +90 -0
  20. data/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb +12 -0
  21. data/lib/new_relic/agent/instrumentation/memcache.rb +24 -0
  22. data/lib/new_relic/agent/instrumentation/merb/controller.rb +26 -0
  23. data/lib/new_relic/agent/instrumentation/merb/errors.rb +8 -0
  24. data/lib/new_relic/agent/instrumentation/metric_frame.rb +199 -0
  25. data/lib/new_relic/agent/instrumentation/net.rb +21 -0
  26. data/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb +20 -0
  27. data/lib/new_relic/agent/instrumentation/rack.rb +109 -0
  28. data/lib/new_relic/agent/instrumentation/rails/action_controller.rb +59 -0
  29. data/lib/new_relic/agent/instrumentation/rails/action_web_service.rb +27 -0
  30. data/lib/new_relic/agent/instrumentation/rails/errors.rb +24 -0
  31. data/lib/new_relic/agent/instrumentation/sinatra.rb +39 -0
  32. data/lib/new_relic/agent/method_tracer.rb +348 -0
  33. data/lib/new_relic/agent/patch_const_missing.rb +125 -0
  34. data/lib/new_relic/agent/sampler.rb +46 -0
  35. data/lib/new_relic/agent/samplers/cpu_sampler.rb +50 -0
  36. data/lib/new_relic/agent/samplers/memory_sampler.rb +141 -0
  37. data/lib/new_relic/agent/samplers/mongrel_sampler.rb +23 -0
  38. data/lib/new_relic/agent/samplers/object_sampler.rb +24 -0
  39. data/lib/new_relic/agent/shim_agent.rb +21 -0
  40. data/lib/new_relic/agent/stats_engine.rb +22 -0
  41. data/lib/new_relic/agent/stats_engine/metric_stats.rb +116 -0
  42. data/lib/new_relic/agent/stats_engine/samplers.rb +74 -0
  43. data/lib/new_relic/agent/stats_engine/transactions.rb +154 -0
  44. data/lib/new_relic/agent/transaction_sampler.rb +315 -0
  45. data/lib/new_relic/agent/worker_loop.rb +118 -0
  46. data/lib/new_relic/commands/deployments.rb +145 -0
  47. data/lib/new_relic/commands/new_relic_commands.rb +30 -0
  48. data/lib/new_relic/control.rb +484 -0
  49. data/lib/new_relic/control/external.rb +13 -0
  50. data/lib/new_relic/control/merb.rb +24 -0
  51. data/lib/new_relic/control/rails.rb +151 -0
  52. data/lib/new_relic/control/ruby.rb +36 -0
  53. data/lib/new_relic/control/sinatra.rb +14 -0
  54. data/lib/new_relic/histogram.rb +89 -0
  55. data/lib/new_relic/local_environment.rb +299 -0
  56. data/lib/new_relic/merbtasks.rb +6 -0
  57. data/lib/new_relic/metric_data.rb +42 -0
  58. data/lib/new_relic/metric_parser.rb +124 -0
  59. data/lib/new_relic/metric_parser/action_mailer.rb +9 -0
  60. data/lib/new_relic/metric_parser/active_merchant.rb +26 -0
  61. data/lib/new_relic/metric_parser/active_record.rb +25 -0
  62. data/lib/new_relic/metric_parser/controller.rb +54 -0
  63. data/lib/new_relic/metric_parser/controller_cpu.rb +38 -0
  64. data/lib/new_relic/metric_parser/errors.rb +6 -0
  65. data/lib/new_relic/metric_parser/external.rb +50 -0
  66. data/lib/new_relic/metric_parser/mem_cache.rb +12 -0
  67. data/lib/new_relic/metric_parser/other_transaction.rb +15 -0
  68. data/lib/new_relic/metric_parser/view.rb +61 -0
  69. data/lib/new_relic/metric_parser/web_frontend.rb +14 -0
  70. data/lib/new_relic/metric_parser/web_service.rb +9 -0
  71. data/lib/new_relic/metric_spec.rb +67 -0
  72. data/lib/new_relic/metrics.rb +7 -0
  73. data/lib/new_relic/noticed_error.rb +23 -0
  74. data/lib/new_relic/rack/metric_app.rb +56 -0
  75. data/lib/new_relic/rack/mongrel_rpm.ru +25 -0
  76. data/lib/new_relic/rack/newrelic.yml +26 -0
  77. data/lib/new_relic/rack_app.rb +5 -0
  78. data/lib/new_relic/recipes.rb +82 -0
  79. data/lib/new_relic/stats.rb +362 -0
  80. data/lib/new_relic/transaction_analysis.rb +121 -0
  81. data/lib/new_relic/transaction_sample.rb +671 -0
  82. data/lib/new_relic/version.rb +54 -0
  83. data/lib/new_relic_api.rb +276 -0
  84. data/lib/newrelic_rpm.rb +45 -0
  85. data/lib/tasks/all.rb +4 -0
  86. data/lib/tasks/install.rake +7 -0
  87. data/lib/tasks/tests.rake +15 -0
  88. data/newrelic.yml +227 -0
  89. data/newrelic_rpm.gemspec +214 -0
  90. data/recipes/newrelic.rb +6 -0
  91. data/test/active_record_fixtures.rb +55 -0
  92. data/test/config/newrelic.yml +46 -0
  93. data/test/config/test_control.rb +38 -0
  94. data/test/new_relic/agent/active_record_instrumentation_test.rb +268 -0
  95. data/test/new_relic/agent/agent_controller_test.rb +254 -0
  96. data/test/new_relic/agent/agent_test_controller.rb +78 -0
  97. data/test/new_relic/agent/busy_calculator_test.rb +79 -0
  98. data/test/new_relic/agent/classloader_patch_test.rb +56 -0
  99. data/test/new_relic/agent/collection_helper_test.rb +125 -0
  100. data/test/new_relic/agent/error_collector_test.rb +173 -0
  101. data/test/new_relic/agent/method_tracer_test.rb +340 -0
  102. data/test/new_relic/agent/metric_data_test.rb +56 -0
  103. data/test/new_relic/agent/mock_ar_connection.rb +40 -0
  104. data/test/new_relic/agent/mock_scope_listener.rb +23 -0
  105. data/test/new_relic/agent/net_instrumentation_test.rb +63 -0
  106. data/test/new_relic/agent/rpm_agent_test.rb +125 -0
  107. data/test/new_relic/agent/stats_engine/metric_stats_test.rb +79 -0
  108. data/test/new_relic/agent/stats_engine/samplers_test.rb +88 -0
  109. data/test/new_relic/agent/stats_engine/stats_engine_test.rb +184 -0
  110. data/test/new_relic/agent/task_instrumentation_test.rb +177 -0
  111. data/test/new_relic/agent/testable_agent.rb +13 -0
  112. data/test/new_relic/agent/transaction_sample_builder_test.rb +195 -0
  113. data/test/new_relic/agent/transaction_sample_test.rb +186 -0
  114. data/test/new_relic/agent/transaction_sampler_test.rb +404 -0
  115. data/test/new_relic/agent/worker_loop_test.rb +103 -0
  116. data/test/new_relic/control_test.rb +110 -0
  117. data/test/new_relic/delayed_job_test.rb +108 -0
  118. data/test/new_relic/deployments_api_test.rb +68 -0
  119. data/test/new_relic/environment_test.rb +75 -0
  120. data/test/new_relic/metric_parser_test.rb +172 -0
  121. data/test/new_relic/metric_spec_test.rb +177 -0
  122. data/test/new_relic/shim_agent_test.rb +9 -0
  123. data/test/new_relic/stats_test.rb +291 -0
  124. data/test/new_relic/version_number_test.rb +76 -0
  125. data/test/test_helper.rb +53 -0
  126. data/test/ui/newrelic_controller_test.rb +14 -0
  127. data/test/ui/newrelic_helper_test.rb +53 -0
  128. data/ui/controllers/newrelic_controller.rb +220 -0
  129. data/ui/helpers/google_pie_chart.rb +49 -0
  130. data/ui/helpers/newrelic_helper.rb +320 -0
  131. data/ui/views/layouts/newrelic_default.rhtml +47 -0
  132. data/ui/views/newrelic/_explain_plans.rhtml +27 -0
  133. data/ui/views/newrelic/_sample.rhtml +19 -0
  134. data/ui/views/newrelic/_segment.rhtml +28 -0
  135. data/ui/views/newrelic/_segment_limit_message.rhtml +1 -0
  136. data/ui/views/newrelic/_segment_row.rhtml +14 -0
  137. data/ui/views/newrelic/_show_sample_detail.rhtml +24 -0
  138. data/ui/views/newrelic/_show_sample_sql.rhtml +20 -0
  139. data/ui/views/newrelic/_show_sample_summary.rhtml +3 -0
  140. data/ui/views/newrelic/_sql_row.rhtml +11 -0
  141. data/ui/views/newrelic/_stack_trace.rhtml +30 -0
  142. data/ui/views/newrelic/_table.rhtml +12 -0
  143. data/ui/views/newrelic/explain_sql.rhtml +42 -0
  144. data/ui/views/newrelic/images/arrow-close.png +0 -0
  145. data/ui/views/newrelic/images/arrow-open.png +0 -0
  146. data/ui/views/newrelic/images/blue_bar.gif +0 -0
  147. data/ui/views/newrelic/images/file_icon.png +0 -0
  148. data/ui/views/newrelic/images/gray_bar.gif +0 -0
  149. data/ui/views/newrelic/images/new-relic-rpm-desktop.gif +0 -0
  150. data/ui/views/newrelic/images/new_relic_rpm_desktop.gif +0 -0
  151. data/ui/views/newrelic/images/textmate.png +0 -0
  152. data/ui/views/newrelic/index.rhtml +57 -0
  153. data/ui/views/newrelic/javascript/prototype-scriptaculous.js +7288 -0
  154. data/ui/views/newrelic/javascript/transaction_sample.js +107 -0
  155. data/ui/views/newrelic/sample_not_found.rhtml +2 -0
  156. data/ui/views/newrelic/show_sample.rhtml +80 -0
  157. data/ui/views/newrelic/show_source.rhtml +3 -0
  158. data/ui/views/newrelic/stylesheets/style.css +484 -0
  159. data/ui/views/newrelic/threads.rhtml +52 -0
  160. metadata +238 -0
@@ -0,0 +1,116 @@
1
+ module NewRelic::Agent
2
+ class StatsEngine
3
+ module MetricStats
4
+ # The stats hash hashes either a metric name for an unscoped metric,
5
+ # or a metric_spec for a scoped metric value.
6
+ def lookup_stat(metric_name)
7
+ stats_hash[metric_name]
8
+ end
9
+
10
+ def metrics
11
+ stats_hash.keys.map(&:to_s)
12
+ end
13
+
14
+ def get_stats_no_scope(metric_name)
15
+ stats_hash[metric_name] ||= NewRelic::MethodTraceStats.new
16
+ end
17
+
18
+ # This version allows a caller to pass a stat class to use
19
+ #
20
+ def get_custom_stats(metric_name, stat_class)
21
+ stats_hash[metric_name] ||= stat_class.new
22
+ end
23
+
24
+ # If use_scope is true, two chained metrics are created, one with scope and one without
25
+ # If scoped_metric_only is true, only a scoped metric is created (used by rendering metrics which by definition are per controller only)
26
+ def get_stats(metric_name, use_scope = true, scoped_metric_only = false)
27
+
28
+ if scoped_metric_only
29
+ spec = NewRelic::MetricSpec.new metric_name, scope_name
30
+ stats = stats_hash[spec] ||= NewRelic::MethodTraceStats.new
31
+ else
32
+ stats = stats_hash[metric_name] ||= NewRelic::MethodTraceStats.new
33
+ if use_scope && scope_name
34
+ spec = NewRelic::MetricSpec.new metric_name, scope_name
35
+ scoped_stats = stats_hash[spec] ||= NewRelic::ScopedMethodTraceStats.new(stats)
36
+ stats = scoped_stats
37
+ end
38
+ end
39
+ stats
40
+ end
41
+
42
+ def lookup_stats(metric_name, scope_name = nil)
43
+ stats_hash[NewRelic::MetricSpec.new(metric_name, scope_name)] ||
44
+ stats_hash[metric_name]
45
+ end
46
+ # Harvest the timeslice data. First recombine current statss
47
+ # with any previously
48
+ # unsent metrics, clear out stats cache, and return the current
49
+ # stats.
50
+ # ---
51
+ # Note: this is not synchronized. There is still some risk in this and
52
+ # we will revisit later to see if we can make this more robust without
53
+ # sacrificing efficiency.
54
+ # +++
55
+ def harvest_timeslice_data(previous_timeslice_data, metric_ids)
56
+ timeslice_data = {}
57
+ poll harvest_samplers
58
+ stats_hash.keys.each do | metric_spec |
59
+
60
+
61
+ # get a copy of the stats collected since the last harvest, and clear
62
+ # the stats inside our hash table for the next time slice.
63
+ stats = stats_hash[metric_spec]
64
+
65
+ # we have an optimization for unscoped metrics
66
+ if !(metric_spec.is_a? NewRelic::MetricSpec)
67
+ metric_spec = NewRelic::MetricSpec.new metric_spec
68
+ end
69
+
70
+ if stats.nil?
71
+ raise "Nil stats for #{metric_spec.name} (#{metric_spec.scope})"
72
+ end
73
+
74
+ stats_copy = stats.clone
75
+ stats.reset
76
+
77
+ # if the previous timeslice data has not been reported (due to an error of some sort)
78
+ # then we need to merge this timeslice with the previously accumulated - but not sent
79
+ # data
80
+ previous_metric_data = previous_timeslice_data[metric_spec]
81
+ stats_copy.merge! previous_metric_data.stats unless previous_metric_data.nil?
82
+ stats_copy.round!
83
+
84
+ # don't bother collecting and reporting stats that have zero-values for this timeslice.
85
+ # significant performance boost and storage savings.
86
+ unless stats_copy.is_reset?
87
+
88
+ id = metric_ids[metric_spec]
89
+ metric_spec_for_transport = id ? nil : metric_spec
90
+
91
+ metric_data = NewRelic::MetricData.new(metric_spec_for_transport, stats_copy, id)
92
+
93
+ timeslice_data[metric_spec] = metric_data
94
+ end
95
+ end
96
+
97
+ timeslice_data
98
+ end
99
+
100
+ # Remove all stats. For test code only.
101
+ def clear_stats
102
+ stats_hash.clear
103
+ NewRelic::Agent::BusyCalculator.reset
104
+ end
105
+
106
+ # Reset each of the stats, such as when a new passenger instance starts up.
107
+ def reset_stats
108
+ stats_hash.values.each { |s| s.reset }
109
+ end
110
+
111
+ def stats_hash
112
+ @stats_hash ||= {}
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,74 @@
1
+ module NewRelic::Agent
2
+ class StatsEngine
3
+ module Shim # :nodoc:
4
+ def add_sampler(*args); end
5
+ def add_harvest_sampler(*args); end
6
+ def spawn_sampler_thread(*args); end
7
+ end
8
+
9
+ module Samplers
10
+
11
+ POLL_PERIOD = 10
12
+
13
+ def spawn_sampler_thread
14
+
15
+ return if !@sampler_process.nil? && @sampler_process == $$
16
+
17
+ # start up a thread that will periodically poll for metric samples
18
+ @sampler_thread = Thread.new do
19
+ while true do
20
+ begin
21
+ sleep POLL_PERIOD
22
+ poll periodic_samplers
23
+ end
24
+ end
25
+ end
26
+ @sampler_thread['newrelic_label'] = 'Sampler Tasks'
27
+ @sampler_process = $$
28
+ end
29
+
30
+ # Add an instance of Sampler to be invoked about every 10 seconds on a background
31
+ # thread.
32
+ def add_sampler sampler
33
+ periodic_samplers.each do |s|
34
+ raise "Sampler #{sampler.id} is already registered. Don't call add_sampler directly anymore." if s.id == sampler.id
35
+ end
36
+ periodic_samplers << sampler
37
+ sampler.stats_engine = self
38
+ log.debug "Adding sampler #{sampler.id.to_s}"
39
+ end
40
+
41
+ # Add a sampler to be invoked just before each harvest.
42
+ def add_harvest_sampler sampler
43
+ harvest_samplers << sampler
44
+ sampler.stats_engine = self
45
+ log.debug "Adding harvest time sampler: #{sampler.id.to_s}"
46
+ end
47
+
48
+ private
49
+
50
+ # Call poll on each of the samplers. Remove
51
+ # the sampler if it raises.
52
+ def poll(samplers)
53
+ samplers.delete_if do |sampled_item|
54
+ begin
55
+ sampled_item.poll
56
+ false # it's okay. don't delete it.
57
+ rescue Exception => e
58
+ log.error "Removing #{sampled_item} from list"
59
+ log.error e
60
+ log.debug e.backtrace.to_s
61
+ true # remove the sampler
62
+ end
63
+ end
64
+ end
65
+
66
+ def harvest_samplers
67
+ @harvest_samplers ||= []
68
+ end
69
+ def periodic_samplers
70
+ @periodic_samplers ||= []
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,154 @@
1
+ module NewRelic::Agent
2
+ class StatsEngine
3
+
4
+ # Defines methods that stub out the stats engine methods
5
+ # when the agent is disabled
6
+
7
+ class ScopeStackElement
8
+ attr_reader :name, :deduct_call_time_from_parent
9
+ attr_accessor :children_time
10
+ def initialize(name, deduct_call_time)
11
+ @name = name
12
+ @deduct_call_time_from_parent = deduct_call_time
13
+ @children_time = 0
14
+ end
15
+ end
16
+
17
+ module Transactions
18
+ module Shim # :nodoc:
19
+ def start_transaction(*args); end
20
+ def end_transaction; end
21
+ def push_scope(*args); end
22
+ def transaction_sampler=(*args); end
23
+ def scope_name=(*args); end
24
+ def scope_name; end
25
+ def pop_scope(*args); end
26
+ end
27
+
28
+ def transaction_sampler= sampler
29
+ fail "Can't add a scope listener midflight in a transaction" if scope_stack.any?
30
+ @transaction_sampler = sampler
31
+ end
32
+
33
+ def remove_transaction_sampler(l)
34
+ @transaction_sampler = nil
35
+ end
36
+
37
+ def push_scope(metric, time = Time.now.to_f, deduct_call_time_from_parent = true)
38
+
39
+ stack = scope_stack
40
+ if collecting_gc?
41
+ if stack.empty?
42
+ # reset the gc time so we only include gc time spent during this call
43
+ @last_gc_timestamp = GC.time
44
+ @last_gc_count = GC.collections
45
+ else
46
+ capture_gc_time
47
+ end
48
+ end
49
+ if @transaction_sampler
50
+ @transaction_sampler.notice_first_scope_push(time) if stack.empty?
51
+ @transaction_sampler.notice_push_scope metric, time
52
+ end
53
+ scope = ScopeStackElement.new(metric, deduct_call_time_from_parent)
54
+ stack.push scope
55
+ scope
56
+ end
57
+
58
+ def pop_scope(expected_scope, duration, time=Time.now.to_f)
59
+ capture_gc_time if collecting_gc?
60
+ stack = scope_stack
61
+ scope = stack.pop
62
+ fail "unbalanced pop from blame stack, got #{scope ? scope.name : 'nil'}, expected #{expected_scope ? expected_scope.name : 'nil'}" if scope != expected_scope
63
+
64
+ if !stack.empty?
65
+ if scope.deduct_call_time_from_parent
66
+ stack.last.children_time += duration
67
+ else
68
+ stack.last.children_time += scope.children_time
69
+ end
70
+ end
71
+
72
+ if @transaction_sampler
73
+ @transaction_sampler.notice_pop_scope(scope.name, time)
74
+ @transaction_sampler.notice_scope_empty(time) if stack.empty?
75
+ end
76
+ scope
77
+ end
78
+
79
+ def peek_scope
80
+ scope_stack.last
81
+ end
82
+
83
+ # set the name of the transaction for the current thread, which will be used
84
+ # to define the scope of all traced methods called on this thread until the
85
+ # scope stack is empty.
86
+ #
87
+ # currently the transaction name is the name of the controller action that
88
+ # is invoked via the dispatcher, but conceivably we could use other transaction
89
+ # names in the future if the traced application does more than service http request
90
+ # via controller actions
91
+ def scope_name=(transaction)
92
+ Thread::current[:newrelic_scope_name] = transaction
93
+ end
94
+
95
+ def scope_name
96
+ Thread::current[:newrelic_scope_name]
97
+ end
98
+
99
+ # Start a new transaction, unless one is already in progress
100
+ def start_transaction(name = nil)
101
+ Thread::current[:newrelic_scope_stack] ||= []
102
+ self.scope_name = name if name
103
+ end
104
+
105
+ # Try to clean up gracefully, otherwise we leave things hanging around on thread locals.
106
+ # If it looks like a transaction is still in progress, then maybe this is an inner transaction
107
+ # and is ignored.
108
+ #
109
+ def end_transaction
110
+ stack = scope_stack
111
+
112
+ if stack && stack.empty?
113
+ Thread::current[:newrelic_scope_stack] = nil
114
+ Thread::current[:newrelic_scope_name] = nil
115
+ end
116
+ end
117
+
118
+ private
119
+
120
+ # Make sure we don't do this in a multi-threaded environment
121
+ def collecting_gc?
122
+ @@collecting_gc ||= GC.respond_to?(:time) && GC.respond_to?(:collections) && !NewRelic::Control.instance.multi_threaded?
123
+ end
124
+
125
+ # Assumes collecting_gc?
126
+ def capture_gc_time
127
+ # Skip this if we are already in this segment
128
+ return if !scope_stack.empty? && scope_stack.last.name == "GC/cumulative"
129
+ num_calls = GC.collections - @last_gc_count
130
+ elapsed = (GC.time - @last_gc_timestamp).to_f
131
+ @last_gc_timestamp = GC.time
132
+ @last_gc_count = GC.collections
133
+ if num_calls > 0
134
+ # µs to seconds
135
+ elapsed = elapsed / 1000000.0
136
+ # Allocate the GC time to a scope as if the GC just ended
137
+ # right now.
138
+ time = Time.now.to_f
139
+ gc_scope = push_scope("GC/cumulative", time - elapsed)
140
+ # GC stats are collected into a blamed metric which allows
141
+ # us to show the stats controller by controller
142
+ gc_stats = NewRelic::Agent.get_stats(gc_scope.name, true)
143
+ gc_stats.record_multiple_data_points(elapsed, num_calls)
144
+ pop_scope(gc_scope, elapsed, time)
145
+ end
146
+ end
147
+
148
+ def scope_stack
149
+ Thread::current[:newrelic_scope_stack] ||= []
150
+ end
151
+
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,315 @@
1
+
2
+ module NewRelic::Agent
3
+
4
+ class TransactionSampler
5
+
6
+ # Module defining methods stubbed out when the agent is disabled
7
+ module Shim #:nodoc:
8
+ def notice_first_scope_push(*args); end
9
+ def notice_push_scope(*args); end
10
+ def notice_pop_scope(*args); end
11
+ def notice_scope_empty(*args); end
12
+ end
13
+
14
+ BUILDER_KEY = :transaction_sample_builder
15
+
16
+ attr_accessor :stack_trace_threshold, :random_sampling, :sampling_rate
17
+ attr_reader :samples, :last_sample
18
+
19
+ def initialize
20
+ @samples = []
21
+ @harvest_count = 0
22
+ @max_samples = 100
23
+ @random_sample = nil
24
+ config = NewRelic::Control.instance
25
+ sampler_config = config.fetch('transaction_tracer', {})
26
+ @segment_limit = sampler_config.fetch('limit_segments', 4000)
27
+ @stack_trace_threshold = sampler_config.fetch('stack_trace_threshold', 0.500).to_f
28
+ @samples_lock = Mutex.new
29
+ end
30
+
31
+ def current_sample_id
32
+ b=builder
33
+ b and b.sample_id
34
+ end
35
+
36
+ def disable
37
+ NewRelic::Agent.instance.stats_engine.remove_transaction_sampler self
38
+ end
39
+
40
+ def sampling_rate=(val)
41
+ @sampling_rate = val
42
+ @harvest_count = rand(val)
43
+ end
44
+
45
+ def notice_first_scope_push(time)
46
+ start_builder(time)
47
+ end
48
+
49
+ def notice_push_scope(scope, time=Time.now.to_f)
50
+
51
+ return unless builder
52
+
53
+ builder.trace_entry(scope, time)
54
+
55
+ # in developer mode, capture the stack trace with the segment.
56
+ # this is cpu and memory expensive and therefore should not be
57
+ # turned on in production mode
58
+ if NewRelic::Control.instance.developer_mode?
59
+ segment = builder.current_segment
60
+ if segment
61
+ # Strip stack frames off the top that match /new_relic/agent/
62
+ trace = caller
63
+ while trace.first =~/\/lib\/new_relic\/agent\//
64
+ trace.shift
65
+ end
66
+
67
+ trace = trace[0..39] if trace.length > 40
68
+ segment[:backtrace] = trace
69
+ end
70
+ end
71
+ end
72
+
73
+ def scope_depth
74
+ return 0 unless builder
75
+
76
+ builder.scope_depth
77
+ end
78
+
79
+ def notice_pop_scope(scope, time = Time.now.to_f)
80
+ return unless builder
81
+ builder.trace_exit(scope, time)
82
+ end
83
+
84
+ # This is called when we are done with the transaction. We've
85
+ # unwound the stack to the top level.
86
+ def notice_scope_empty(time=Time.now.to_f)
87
+
88
+ last_builder = builder
89
+ return unless last_builder
90
+
91
+ last_builder.finish_trace(time)
92
+ clear_builder
93
+ return if last_builder.ignored?
94
+
95
+ @samples_lock.synchronize do
96
+ @last_sample = last_builder.sample
97
+
98
+ @random_sample = @last_sample if @random_sampling
99
+
100
+ # ensure we don't collect more than a specified number of samples in memory
101
+ @samples << @last_sample if NewRelic::Control.instance.developer_mode?
102
+ @samples.shift while @samples.length > @max_samples
103
+
104
+ if @slowest_sample.nil? || @slowest_sample.duration < @last_sample.duration
105
+ @slowest_sample = @last_sample
106
+ end
107
+ end
108
+ end
109
+
110
+ def notice_transaction(path, request=nil, params={})
111
+ builder.set_transaction_info(path, request, params) if start_builder
112
+ end
113
+
114
+ def ignore_transaction
115
+ builder.ignore_transaction if builder
116
+ end
117
+ def notice_profile(profile)
118
+ builder.set_profile(profile) if builder
119
+ end
120
+
121
+ def notice_transaction_cpu_time(cpu_time)
122
+ builder.set_transaction_cpu_time(cpu_time) if builder
123
+ end
124
+
125
+
126
+ # some statements (particularly INSERTS with large BLOBS
127
+ # may be very large; we should trim them to a maximum usable length
128
+ # config is the driver configuration for the connection
129
+ MAX_SQL_LENGTH = 16384
130
+ def notice_sql(sql, config, duration)
131
+ return unless builder
132
+ if Thread::current[:record_sql] != false
133
+ segment = builder.current_segment
134
+ if segment
135
+ current_sql = segment[:sql]
136
+ sql = current_sql + ";\n" + sql if current_sql
137
+
138
+ if sql.length > (MAX_SQL_LENGTH - 4)
139
+ sql = sql[0..MAX_SQL_LENGTH-4] + '...'
140
+ end
141
+
142
+ segment[:sql] = sql
143
+ segment[:connection_config] = config
144
+ segment[:backtrace] = caller.join("\n") if duration >= @stack_trace_threshold
145
+ end
146
+ end
147
+ end
148
+
149
+
150
+ # get the set of collected samples, merging into previous samples,
151
+ # and clear the collected sample list.
152
+
153
+ def harvest(previous = nil, slow_threshold = 2.0)
154
+ result = []
155
+ previous ||= []
156
+
157
+ previous = [previous] unless previous.is_a?(Array)
158
+
159
+ previous_slowest = previous.inject(nil) {|a,ts| (a) ? ((a.duration > ts.duration) ? a : ts) : ts}
160
+
161
+ @samples_lock.synchronize do
162
+
163
+ if @random_sampling
164
+ @harvest_count += 1
165
+
166
+ if (@harvest_count % @sampling_rate) == 0
167
+ result << @random_sample if @random_sample
168
+ else
169
+ @random_sample = nil # if we don't nil this out, then we won't send the slowest if slowest == @random_sample
170
+ end
171
+ end
172
+
173
+ slowest = @slowest_sample
174
+ @slowest_sample = nil
175
+
176
+ if slowest && slowest != @random_sample && slowest.duration >= slow_threshold
177
+ if previous_slowest.nil? || previous_slowest.duration < slowest.duration
178
+ result << slowest
179
+ else
180
+ result << previous_slowest
181
+ end
182
+ end
183
+
184
+ @random_sample = nil
185
+ @last_sample = nil
186
+ end
187
+ # Truncate the samples at 2100 segments. The UI will clamp them at 2000 segments anyway.
188
+ # This will save us memory and bandwidth.
189
+ result.each { |sample| sample.truncate(@segment_limit) }
190
+ result
191
+ end
192
+
193
+ # reset samples without rebooting the web server
194
+ def reset!
195
+ @samples = []
196
+ @last_sample = nil
197
+ end
198
+
199
+ private
200
+
201
+ def start_builder(time=nil)
202
+ if Thread::current[:record_tt] == false || !NewRelic::Agent.is_execution_traced?
203
+ clear_builder
204
+ else
205
+ Thread::current[BUILDER_KEY] ||= TransactionSampleBuilder.new(time)
206
+ end
207
+ end
208
+ def builder
209
+ Thread::current[BUILDER_KEY]
210
+ end
211
+ def clear_builder
212
+ Thread::current[BUILDER_KEY] = nil
213
+ end
214
+
215
+ end
216
+
217
+ # a builder is created with every sampled transaction, to dynamically
218
+ # generate the sampled data. It is a thread-local object, and is not
219
+ # accessed by any other thread so no need for synchronization.
220
+ class TransactionSampleBuilder
221
+ attr_reader :current_segment, :sample
222
+
223
+ include CollectionHelper
224
+
225
+ def initialize(time=nil)
226
+ time ||= Time.now.to_f
227
+ @sample = NewRelic::TransactionSample.new(time)
228
+ @sample_start = time
229
+ @current_segment = @sample.root_segment
230
+ end
231
+
232
+ def sample_id
233
+ @sample.sample_id
234
+ end
235
+ def ignored?
236
+ @ignore || @sample.params[:path].nil?
237
+ end
238
+ def ignore_transaction
239
+ @ignore = true
240
+ end
241
+ def trace_entry(metric_name, time)
242
+ segment = @sample.create_segment(time - @sample_start, metric_name)
243
+ @current_segment.add_called_segment(segment)
244
+ @current_segment = segment
245
+ end
246
+
247
+ def trace_exit(metric_name, time)
248
+ if metric_name != @current_segment.metric_name
249
+ fail "unbalanced entry/exit: #{metric_name} != #{@current_segment.metric_name}"
250
+ end
251
+ @current_segment.end_trace(time - @sample_start)
252
+ @current_segment = @current_segment.parent_segment
253
+ end
254
+
255
+ def finish_trace(time)
256
+ # This should never get called twice, but in a rare case that we can't reproduce in house it does.
257
+ # log forensics and return gracefully
258
+ if @sample.frozen?
259
+ log = NewRelic::Control.instance.log
260
+
261
+ log.warn "Unexpected double-freeze of Transaction Trace Object."
262
+ log.info "Please send this diagnostic data to New Relic"
263
+ log.info @sample.to_s
264
+ return
265
+ end
266
+ @sample.root_segment.end_trace(time - @sample_start)
267
+ @sample.params[:custom_params] = normalize_params(NewRelic::Agent.instance.custom_params)
268
+ @sample.freeze
269
+ @current_segment = nil
270
+ end
271
+
272
+ def scope_depth
273
+ depth = -1 # have to account for the root
274
+ current = @current_segment
275
+
276
+ while(current)
277
+ depth += 1
278
+ current = current.parent_segment
279
+ end
280
+
281
+ depth
282
+ end
283
+
284
+ def freeze
285
+ @sample.freeze unless sample.frozen?
286
+ end
287
+
288
+ def set_profile(profile)
289
+ @sample.profile = profile
290
+ end
291
+
292
+ def set_transaction_info(path, request, params)
293
+ @sample.params[:path] = path
294
+
295
+ if NewRelic::Control.instance.capture_params
296
+ params = normalize_params params
297
+
298
+ @sample.params[:request_params].merge!(params)
299
+ @sample.params[:request_params].delete :controller
300
+ @sample.params[:request_params].delete :action
301
+ end
302
+ uri = params[:uri] || (request && request.path)
303
+ @sample.params[:uri] ||= uri if uri
304
+ end
305
+
306
+ def set_transaction_cpu_time(cpu_time)
307
+ @sample.params[:cpu_time] = cpu_time
308
+ end
309
+
310
+ def sample
311
+ @sample
312
+ end
313
+
314
+ end
315
+ end