genki-newrelic_rpm 2.10.1

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 +316 -0
  2. data/LICENSE +37 -0
  3. data/Manifest +156 -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/genki-newrelic_rpm.gemspec +32 -0
  10. data/init.rb +38 -0
  11. data/install.rb +37 -0
  12. data/lib/new_relic/agent.rb +280 -0
  13. data/lib/new_relic/agent/agent.rb +627 -0
  14. data/lib/new_relic/agent/chained_call.rb +13 -0
  15. data/lib/new_relic/agent/collection_helper.rb +61 -0
  16. data/lib/new_relic/agent/error_collector.rb +125 -0
  17. data/lib/new_relic/agent/instrumentation/active_merchant.rb +18 -0
  18. data/lib/new_relic/agent/instrumentation/active_record_instrumentation.rb +83 -0
  19. data/lib/new_relic/agent/instrumentation/authlogic.rb +8 -0
  20. data/lib/new_relic/agent/instrumentation/controller_instrumentation.rb +368 -0
  21. data/lib/new_relic/agent/instrumentation/data_mapper.rb +90 -0
  22. data/lib/new_relic/agent/instrumentation/dispatcher_instrumentation.rb +132 -0
  23. data/lib/new_relic/agent/instrumentation/memcache.rb +21 -0
  24. data/lib/new_relic/agent/instrumentation/merb/controller.rb +26 -0
  25. data/lib/new_relic/agent/instrumentation/merb/dispatcher.rb +13 -0
  26. data/lib/new_relic/agent/instrumentation/merb/errors.rb +8 -0
  27. data/lib/new_relic/agent/instrumentation/net.rb +12 -0
  28. data/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb +20 -0
  29. data/lib/new_relic/agent/instrumentation/rack.rb +77 -0
  30. data/lib/new_relic/agent/instrumentation/rails/action_controller.rb +59 -0
  31. data/lib/new_relic/agent/instrumentation/rails/action_web_service.rb +27 -0
  32. data/lib/new_relic/agent/instrumentation/rails/dispatcher.rb +38 -0
  33. data/lib/new_relic/agent/instrumentation/rails/errors.rb +27 -0
  34. data/lib/new_relic/agent/instrumentation/sinatra.rb +39 -0
  35. data/lib/new_relic/agent/method_tracer.rb +277 -0
  36. data/lib/new_relic/agent/patch_const_missing.rb +125 -0
  37. data/lib/new_relic/agent/sampler.rb +12 -0
  38. data/lib/new_relic/agent/samplers/cpu_sampler.rb +49 -0
  39. data/lib/new_relic/agent/samplers/memory_sampler.rb +137 -0
  40. data/lib/new_relic/agent/samplers/mongrel_sampler.rb +22 -0
  41. data/lib/new_relic/agent/shim_agent.rb +21 -0
  42. data/lib/new_relic/agent/stats_engine.rb +24 -0
  43. data/lib/new_relic/agent/stats_engine/metric_stats.rb +111 -0
  44. data/lib/new_relic/agent/stats_engine/samplers.rb +71 -0
  45. data/lib/new_relic/agent/stats_engine/transactions.rb +155 -0
  46. data/lib/new_relic/agent/transaction_sampler.rb +319 -0
  47. data/lib/new_relic/agent/worker_loop.rb +118 -0
  48. data/lib/new_relic/commands/deployments.rb +145 -0
  49. data/lib/new_relic/commands/new_relic_commands.rb +30 -0
  50. data/lib/new_relic/control.rb +436 -0
  51. data/lib/new_relic/control/external.rb +13 -0
  52. data/lib/new_relic/control/merb.rb +22 -0
  53. data/lib/new_relic/control/rails.rb +143 -0
  54. data/lib/new_relic/control/ruby.rb +34 -0
  55. data/lib/new_relic/control/sinatra.rb +14 -0
  56. data/lib/new_relic/histogram.rb +89 -0
  57. data/lib/new_relic/local_environment.rb +285 -0
  58. data/lib/new_relic/merbtasks.rb +6 -0
  59. data/lib/new_relic/metric_data.rb +44 -0
  60. data/lib/new_relic/metric_parser.rb +120 -0
  61. data/lib/new_relic/metric_parser/action_mailer.rb +9 -0
  62. data/lib/new_relic/metric_parser/active_merchant.rb +26 -0
  63. data/lib/new_relic/metric_parser/active_record.rb +25 -0
  64. data/lib/new_relic/metric_parser/controller.rb +54 -0
  65. data/lib/new_relic/metric_parser/controller_cpu.rb +38 -0
  66. data/lib/new_relic/metric_parser/errors.rb +6 -0
  67. data/lib/new_relic/metric_parser/external.rb +50 -0
  68. data/lib/new_relic/metric_parser/mem_cache.rb +12 -0
  69. data/lib/new_relic/metric_parser/view.rb +61 -0
  70. data/lib/new_relic/metric_parser/web_frontend.rb +14 -0
  71. data/lib/new_relic/metric_parser/web_service.rb +9 -0
  72. data/lib/new_relic/metric_spec.rb +52 -0
  73. data/lib/new_relic/metrics.rb +7 -0
  74. data/lib/new_relic/noticed_error.rb +25 -0
  75. data/lib/new_relic/rack/metric_app.rb +56 -0
  76. data/lib/new_relic/rack/newrelic.ru +25 -0
  77. data/lib/new_relic/rack/newrelic.yml +25 -0
  78. data/lib/new_relic/rack_app.rb +5 -0
  79. data/lib/new_relic/recipes.rb +82 -0
  80. data/lib/new_relic/stats.rb +360 -0
  81. data/lib/new_relic/transaction_analysis.rb +121 -0
  82. data/lib/new_relic/transaction_sample.rb +583 -0
  83. data/lib/new_relic/version.rb +54 -0
  84. data/lib/new_relic_api.rb +315 -0
  85. data/lib/newrelic_rpm.rb +40 -0
  86. data/lib/tasks/all.rb +4 -0
  87. data/lib/tasks/install.rake +7 -0
  88. data/lib/tasks/tests.rake +13 -0
  89. data/newrelic.yml +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 +39 -0
  94. data/test/new_relic/agent/active_record_instrumentation_test.rb +234 -0
  95. data/test/new_relic/agent/agent_controller_test.rb +107 -0
  96. data/test/new_relic/agent/agent_test.rb +117 -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 +118 -0
  100. data/test/new_relic/agent/dispatcher_instrumentation_test.rb +76 -0
  101. data/test/new_relic/agent/error_collector_test.rb +155 -0
  102. data/test/new_relic/agent/method_tracer_test.rb +335 -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 +51 -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 +78 -0
  109. data/test/new_relic/agent/stats_engine/stats_engine_test.rb +177 -0
  110. data/test/new_relic/agent/task_instrumentation_test.rb +67 -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 +146 -0
  114. data/test/new_relic/agent/transaction_sampler_test.rb +387 -0
  115. data/test/new_relic/agent/worker_loop_test.rb +103 -0
  116. data/test/new_relic/control_test.rb +94 -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 +214 -0
  128. data/ui/helpers/google_pie_chart.rb +55 -0
  129. data/ui/helpers/newrelic_helper.rb +314 -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 +15 -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 +45 -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 +77 -0
  155. data/ui/views/newrelic/show_source.rhtml +3 -0
  156. data/ui/views/newrelic/stylesheets/style.css +433 -0
  157. data/ui/views/newrelic/threads.rhtml +52 -0
  158. metadata +327 -0
@@ -0,0 +1,14 @@
1
+ # The metric where the mongrel queue time is stored
2
+
3
+ class NewRelic::MetricParser::WebFrontend < NewRelic::MetricParser
4
+ def short_name
5
+ if segments.last == 'Average Queue Time'
6
+ 'Mongrel Average Queue Time'
7
+ else
8
+ super
9
+ end
10
+ end
11
+ def legend_name
12
+ 'Mongrel Wait'
13
+ end
14
+ end
@@ -0,0 +1,9 @@
1
+ class NewRelic::MetricParser::WebService < NewRelic::MetricParser
2
+ def is_web_service?
3
+ segments[1] != 'Soap' && segments[1] != 'Xml Rpc'
4
+ end
5
+
6
+ def webservice_call_rate_suffix
7
+ 'rpm'
8
+ end
9
+ end
@@ -0,0 +1,52 @@
1
+ # this struct uniquely defines a metric, optionally inside
2
+ # the call scope of another metric
3
+ class NewRelic::MetricSpec
4
+ attr_accessor :name
5
+ attr_accessor :scope
6
+
7
+ def initialize (metric_name, metric_scope = '')
8
+ self.name = metric_name
9
+ self.scope = metric_scope
10
+ end
11
+
12
+ def ==(o)
13
+ self.eql?(o)
14
+ end
15
+
16
+ def eql? o
17
+ self.class == o.class &&
18
+ name.eql?(o.name) &&
19
+ # coerce scope to a string and compare
20
+ (scope || '') == (o.scope || '')
21
+ end
22
+
23
+ def hash
24
+ h = name.hash
25
+ h ^= scope.hash unless scope.nil?
26
+ h
27
+ end
28
+ # return a new metric spec if the given regex
29
+ # matches the name or scope.
30
+ def sub(pattern, replacement, apply_to_scope = true)
31
+ return nil if name !~ pattern &&
32
+ (!apply_to_scope || scope.nil? || scope !~ pattern)
33
+ new_name = name.sub(pattern, replacement)
34
+ new_scope = (scope && scope.sub(pattern, replacement))
35
+ self.class.new new_name, new_scope
36
+ end
37
+
38
+ def to_s
39
+ "#{name}:#{scope}"
40
+ end
41
+
42
+ def to_json(*a)
43
+ {'name' => name,
44
+ 'scope' => scope}.to_json(*a)
45
+ end
46
+
47
+ def <=>(o)
48
+ namecmp = self.name <=> o.name
49
+ return namecmp if namecmp != 0
50
+ return (self.scope || '') <=> (o.scope || '')
51
+ end
52
+ end
@@ -0,0 +1,7 @@
1
+ module NewRelic::Metrics
2
+ CONTROLLER = "Controller"
3
+ DISPATCHER = "HttpDispatcher"
4
+ ACTIVE_RECORD = "ActiveRecord"
5
+ USER_TIME = "CPU/User Time"
6
+ MEMORY = "Memory/Physical"
7
+ end
@@ -0,0 +1,25 @@
1
+ # this class encapsulates an error that was noticed by RPM in a managed app.
2
+ # Unfortunately it was put in the agent in the global namespace early on and
3
+ # for backward compatibility it needs to remain here.
4
+ class NewRelic::NoticedError
5
+ attr_accessor :path, :timestamp, :params, :exception_class, :message
6
+
7
+ def initialize(path, data, exception)
8
+ self.path = path
9
+ self.params = data
10
+
11
+ self.exception_class = exception.class.name
12
+
13
+ if exception.respond_to?('original_exception')
14
+ self.message = exception.original_exception.message.to_s
15
+ else
16
+ self.message = exception.message.to_s
17
+ end
18
+
19
+ # clamp long messages to 4k so that we don't send a lot of
20
+ # overhead across the wire
21
+ self.message = self.message[0..4096] if self.message.length > 4096
22
+
23
+ self.timestamp = Time.now
24
+ end
25
+ end
@@ -0,0 +1,56 @@
1
+ require 'fileutils'
2
+ module NewRelic::Rack
3
+ class MetricApp
4
+ def initialize(options)
5
+ if options[:install]
6
+ FileUtils.copy File.join(File.dirname(__FILE__), "newrelic.yml"), "."
7
+ NewRelic::Control.instance.log.info "==============================="
8
+ NewRelic::Control.instance.log.info "A newrelic.yml template was copied to #{File.expand_path('.')}."
9
+ NewRelic::Control.instance.log.info "Please add a license key to the file and restart #{$0}"
10
+ exit 0
11
+ end
12
+ options[:app_name] ||= 'EPM Monitor'
13
+ options[:disable_samplers] = true
14
+ NewRelic::Agent.manual_start options
15
+ unless NewRelic::Control.instance.license_key
16
+ NewRelic::Control.instance.log.error "Please add a valid license key to newrelic.yml."
17
+ exit 1
18
+ end
19
+ end
20
+ def call(env)
21
+ request = ::Rack::Request.new env
22
+ segments = request.url.gsub(/^.*?\/metrics\//, '').split("?")[0].split("/")
23
+ metric = "Custom/" + segments.join("/")
24
+ raise "Expected value parameter!" unless request['value']
25
+ data = request['value'].to_f
26
+ stats = NewRelic::Agent.get_stats(metric, false)
27
+ stats.record_data_point data
28
+ response = ::Rack::Response.new "#{metric}=#{data}"
29
+ response.finish
30
+ end
31
+ end
32
+ class Status
33
+ def call(env)
34
+ request = ::Rack::Request.new env
35
+ data_url = "http://#{env['HTTP_HOST']}/metrics/path?value=nnn"
36
+ body = StringIO.new
37
+ body.puts "<html><body>"
38
+ body.puts "<h1>New Relic Actively Monitoring #{NewRelic::Control.instance.app_names.join(' and ')}</h1>"
39
+ body.puts "<p>To submit a metric value, use <a href='#{data_url}'>#{data_url}</a></p>"
40
+ body.puts "<h2>Request Details</h2>"
41
+ body.puts "<dl>"
42
+ body.puts "<dt>ip<dd>#{request.ip}"
43
+ body.puts "<dt>host<dd>#{request.host}"
44
+ body.puts "<dt>path<dd>#{request.url}"
45
+ body.puts "<dt>query<dd>#{request.query_string}"
46
+ body.puts "<dt>params<dd>#{request.params.inspect}"
47
+ body.puts "</dl>"
48
+ body.puts "<h2>Complete ENV</h2>"
49
+ body.puts "<ul>"
50
+ body.puts env.to_a.map{|k,v| "<li>#{k} = #{v}</li>" }.join("\n")
51
+ body.puts "</ul></body></html>"
52
+ response = ::Rack::Response.new body.string
53
+ response.finish
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,25 @@
1
+ # This is so that we don't detect a dispatcher like mongrel and think we are
2
+ # monitoring it.
3
+ ENV['NEWRELIC_DISPATCHER'] = 'none'
4
+
5
+ $LOAD_PATH << File.expand_path(File.join(File.dirname(__FILE__), '..','..'))
6
+
7
+ require 'new_relic/rack_app'
8
+
9
+ # Valid options which may be present in this binding:
10
+ # :license_key optional license key override
11
+ # :app_name optional name of app
12
+ # :logging optional, false to omit request logging to stdout
13
+
14
+ options ||= {}
15
+
16
+ use Rack::CommonLogger unless options[:logging] == false
17
+ use Rack::ShowExceptions
18
+ map "http://localhost/metrics" do
19
+ run NewRelic::Rack::MetricApp.new(options)
20
+ end
21
+ map "/" do
22
+ run NewRelic::Rack::Status.new
23
+ end
24
+
25
+
@@ -0,0 +1,25 @@
1
+ #
2
+ # This file configures the Rack NewRelic Metric Application. Place a copy of this file
3
+ # in the directory where you start the mongrel_rpm process.
4
+ #
5
+ common: &default_settings
6
+ log_level: info
7
+
8
+ # This is the key generated by script/create_admin
9
+ license_key: 'your_license_key_here'
10
+
11
+ # Replace this with the name of the application feeding
12
+ # metrics into the Metric application;
13
+ app_name: Application Monitor
14
+
15
+ # If RAILS_ENV or RUBY_ENV is defined to be one of the following
16
+ # these values will be overrides
17
+
18
+ production:
19
+ <<: *default_settings
20
+ app_name: Production Monitor
21
+
22
+ staging:
23
+ <<: *default_settings
24
+ app_name: Staging Monitor
25
+
@@ -0,0 +1,5 @@
1
+ require 'rack/response'
2
+ require 'newrelic_rpm'
3
+
4
+ # Rack middlewares and applications used by New Relic
5
+ require 'new_relic/rack/metric_app'
@@ -0,0 +1,82 @@
1
+ # When installed as a plugin this is loaded automatically.
2
+ #
3
+ # When installed as a gem, you need to add
4
+ # require 'new_relic/recipes'
5
+ # to your deploy.rb
6
+ #
7
+ # Defined deploy:notify_rpm which will send information about the deploy to RPM.
8
+ # The task will run on app servers except where no_release is true.
9
+ # If it fails, it will not affect the task execution or do a rollback.
10
+ #
11
+ make_notify_task = lambda do
12
+
13
+ namespace :newrelic do
14
+
15
+ # on all deployments, notify RPM
16
+ desc "Record a deployment in New Relic RPM (rpm.newrelic.com)"
17
+ task :notice_deployment, :roles => :app, :except => {:no_release => true } do
18
+ rails_env = fetch(:rails_env, "production")
19
+ require File.join(File.dirname(__FILE__), 'commands', 'deployments.rb')
20
+ begin
21
+ # Try getting the changelog from the server. Then fall back to local changelog
22
+ # if it doesn't work. Problem is that I don't know what directory the .git is
23
+ # in when using git. I could possibly use the remote cache but i don't know
24
+ # if that's always there.
25
+ =begin
26
+ run "cd #{current_release}; #{log_command}" do | io, stream_id, output |
27
+ changelog = output
28
+ end
29
+ =end
30
+ # allow overrides to be defined for revision, description, changelog and appname
31
+ rev = fetch(:newrelic_revision) if exists?(:newrelic_revision)
32
+ description = fetch(:newrelic_desc) if exists?(:newrelic_desc)
33
+ changelog = fetch(:newrelic_changelog) if exists?(:newrelic_changelog)
34
+ appname = fetch(:newrelic_appname) if exists?(:newrelic_appname)
35
+ if !changelog
36
+ logger.debug "Getting log of changes for New Relic Deployment details"
37
+ from_revision = source.next_revision(current_revision)
38
+ if scm == :git
39
+ log_command = "git log --no-color --pretty=format:' * %an: %s' --abbrev-commit --no-merges #{previous_revision}..#{real_revision}"
40
+ else
41
+ log_command = "#{source.log(from_revision)}"
42
+ end
43
+ changelog = `#{log_command}`
44
+ end
45
+ new_revision = rev || source.query_revision(source.head()) do |cmd|
46
+ logger.debug "executing locally: '#{cmd}'"
47
+ `#{cmd}`
48
+ end
49
+ deploy_options = { :environment => rails_env,
50
+ :revision => new_revision,
51
+ :changelog => changelog,
52
+ :description => description,
53
+ :appname => appname }
54
+ logger.debug "Uploading deployment to New Relic"
55
+ deployment = NewRelic::Commands::Deployments.new deploy_options
56
+ deployment.run
57
+ logger.info "Uploaded deployment information to New Relic"
58
+ rescue ScriptError => e
59
+ logger.info "error creating New Relic deployment (#{e})\n#{e.backtrace.join("\n")}"
60
+ rescue NewRelic::Commands::CommandFailure => e
61
+ logger.info "unable to notify New Relic of the deployment (#{e})... skipping"
62
+ rescue Capistrano::CommandError
63
+ logger.info "unable to notify New Relic of the deployment... skipping"
64
+ end
65
+ # WIP: For rollbacks, let's update the deployment we created with an indication of the failure:
66
+ # on_rollback do
67
+ # run(...)
68
+ # end
69
+ end
70
+ end
71
+ end
72
+ require 'capistrano/version'
73
+ if Capistrano::Version::MAJOR < 2
74
+ STDERR.puts "Unable to load #{__FILE__}\nNew Relic Capistrano hooks require at least version 2.0.0"
75
+ else
76
+ instance = Capistrano::Configuration.instance
77
+ if instance
78
+ instance.load &make_notify_task
79
+ else
80
+ make_notify_task.call
81
+ end
82
+ end
@@ -0,0 +1,360 @@
1
+
2
+ module NewRelic
3
+ module Stats
4
+
5
+ def absent?
6
+ # guess on absent values
7
+ call_count == 0
8
+ end
9
+
10
+ def time_str(value_ms)
11
+ case
12
+ when value_ms >= 10000
13
+ "%.1f s" % (value_ms / 1000.0)
14
+ when value_ms >= 5000
15
+ "%.2f s" % (value_ms / 1000.0)
16
+ else
17
+ "%.0f ms" % value_ms
18
+ end
19
+ end
20
+
21
+ def average_call_time
22
+ return 0 if call_count == 0
23
+ total_call_time / call_count
24
+ end
25
+ def average_exclusive_time
26
+ return 0 if call_count == 0
27
+ total_exclusive_time / call_count
28
+ end
29
+
30
+ def merge! (other_stats)
31
+ Array(other_stats).each do |s|
32
+ self.total_call_time += s.total_call_time
33
+ self.total_exclusive_time += s.total_exclusive_time
34
+ self.min_call_time = s.min_call_time if (s.min_call_time < min_call_time && s.call_count > 0) || call_count == 0
35
+ self.max_call_time = s.max_call_time if s.max_call_time > max_call_time
36
+ self.call_count += s.call_count
37
+ self.sum_of_squares += s.sum_of_squares if s.sum_of_squares
38
+ self.begin_time = s.begin_time if s.begin_time.to_f < begin_time.to_f || begin_time.to_f == 0.0
39
+ self.end_time = s.end_time if s.end_time.to_f > end_time.to_f
40
+ end
41
+
42
+ self
43
+ end
44
+
45
+ def merge (other_stats)
46
+ stats = self.clone
47
+ stats.merge! other_stats
48
+ end
49
+
50
+ # split into an array of timesclices whose
51
+ # time boundaries start on (begin_time + (n * duration)) and whose
52
+ # end time ends on (begin_time * (n + 1) * duration), except for the
53
+ # first and last elements, whose begin time and end time are the begin
54
+ # and end times of this stats instance, respectively. Yield to caller
55
+ # for the code that creates the actual stats instance
56
+ def split(rollup_begin_time, rollup_period)
57
+ rollup_begin_time = rollup_begin_time.to_f
58
+ rollup_begin_time += ((self.begin_time - rollup_begin_time) / rollup_period).floor * rollup_period
59
+
60
+ current_begin_time = self.begin_time
61
+ current_end_time = rollup_begin_time + rollup_period
62
+
63
+ return [self] if current_end_time >= self.end_time
64
+
65
+ timeslices = []
66
+ while current_end_time < self.end_time do
67
+ ts = yield(current_begin_time, current_end_time)
68
+ if ts
69
+ ts.fraction_of(self)
70
+ timeslices << ts
71
+ end
72
+ current_begin_time = current_end_time
73
+ current_end_time = current_begin_time + rollup_period
74
+ end
75
+
76
+ if self.end_time > current_begin_time
77
+ percentage = rollup_period / self.duration + (self.begin_time - rollup_begin_time) / rollup_period
78
+ ts = yield(current_begin_time, self.end_time)
79
+ if ts
80
+ ts.fraction_of(self)
81
+ timeslices << ts
82
+ end
83
+ end
84
+
85
+ timeslices
86
+ end
87
+
88
+ def is_reset?
89
+ call_count == 0 && total_call_time == 0.0 && total_exclusive_time == 0.0
90
+ end
91
+
92
+ def reset
93
+ self.call_count = 0
94
+ self.total_call_time = 0.0
95
+ self.total_exclusive_time = 0.0
96
+ self.min_call_time = 0.0
97
+ self.max_call_time = 0.0
98
+ self.sum_of_squares = 0.0
99
+ self.begin_time = Time.at(0)
100
+ self.end_time = Time.at(0)
101
+ end
102
+
103
+ def as_percentage_of(other_stats)
104
+ return 0 if other_stats.total_call_time == 0
105
+ return to_percentage(total_call_time / other_stats.total_call_time)
106
+ end
107
+
108
+ # the stat total_call_time is a percent
109
+ def as_percentage
110
+ return 0 if call_count == 0
111
+ to_percentage(total_call_time / call_count)
112
+ end
113
+
114
+ def duration
115
+ end_time - begin_time
116
+ end
117
+
118
+ def calls_per_minute
119
+ return 0 if duration.zero?
120
+ ((call_count / duration.to_f * 6000).round).to_f / 100
121
+ end
122
+
123
+ def calls_per_second
124
+ round_to_2 calls_per_minute / 60
125
+ end
126
+ def total_call_time_per_minute
127
+ 60.0 * time_percentage
128
+ end
129
+ def standard_deviation
130
+ return 0 if call_count < 2 || self.sum_of_squares.nil?
131
+
132
+ # Convert sum of squares into standard deviation based on
133
+ # formula for the standard deviation for the entire population
134
+ x = self.sum_of_squares - (self.call_count * (self.average_value**2))
135
+ return 0 if x <= 0
136
+
137
+ Math.sqrt(x / self.call_count)
138
+ end
139
+
140
+ # returns the time spent in this component as a percentage of the total
141
+ # time window.
142
+ def time_percentage
143
+ return 0 if duration == 0
144
+ total_call_time / duration
145
+ end
146
+
147
+ def exclusive_time_percentage
148
+ return 0 if duration == 0
149
+ total_exclusive_time / duration
150
+ end
151
+
152
+ alias average_value average_call_time
153
+ alias average_response_time average_call_time
154
+ alias requests_per_minute calls_per_minute
155
+
156
+ def to_s
157
+ s = "Begin=#{begin_time}, "
158
+ s << "Duration=#{duration} s, "
159
+ s << "Count=#{call_count}, "
160
+ s << "Total=#{to_ms(total_call_time)}, "
161
+ s << "Total Exclusive=#{to_ms(total_exclusive_time)}, "
162
+ s << "Avg=#{to_ms(average_call_time)}, "
163
+ s << "Min=#{to_ms(min_call_time)}, "
164
+ s << "Max=#{to_ms(max_call_time)}, "
165
+ s << "StdDev=#{to_ms(standard_deviation)}"
166
+ end
167
+
168
+ # Summary string to facilitate testing
169
+ def summary
170
+ format = "%m/%d %I:%M%p"
171
+ "[#{Time.at(begin_time).strftime(format)}, #{duration}s. #{call_count} calls; #{to_ms(average_call_time)}ms]"
172
+ end
173
+
174
+ # round all of the values to n decimal points
175
+ def round!
176
+ self.total_call_time = round_to_3(total_call_time)
177
+ self.total_exclusive_time = round_to_3(total_exclusive_time)
178
+ self.min_call_time = round_to_3(min_call_time)
179
+ self.max_call_time = round_to_3(max_call_time)
180
+ self.sum_of_squares = round_to_3(sum_of_squares)
181
+ self.begin_time = begin_time
182
+ self.end_time = end_time
183
+ end
184
+
185
+ # calculate this set of stats to be a percentage fraction
186
+ # of the provided stats, which has an overlapping time window.
187
+ # used as a key part of the split algorithm
188
+ def fraction_of(s)
189
+ min_end = (end_time < s.end_time ? end_time : s.end_time)
190
+ max_begin = (begin_time > s.begin_time ? begin_time : s.begin_time)
191
+ percentage = (min_end - max_begin) / s.duration
192
+
193
+ self.total_call_time = s.total_call_time * percentage
194
+ self.min_call_time = s.min_call_time
195
+ self.max_call_time = s.max_call_time
196
+ self.call_count = s.call_count * percentage
197
+ self.sum_of_squares = (s.sum_of_squares || 0) * percentage
198
+ end
199
+
200
+ # multiply the total time and rate by the given percentage
201
+ def multiply_by(percentage)
202
+ self.total_call_time = total_call_time * percentage
203
+ self.call_count = call_count * percentage
204
+ self.sum_of_squares = sum_of_squares * percentage
205
+
206
+ self
207
+ end
208
+
209
+
210
+ # returns s,t,f
211
+ def get_apdex
212
+ [@call_count, @total_call_time.to_i, @total_exclusive_time.to_i]
213
+ end
214
+
215
+ def apdex_score
216
+ s, t, f = get_apdex
217
+ (s.to_f + (t.to_f / 2)) / (s+t+f).to_f
218
+ end
219
+ private
220
+ def to_ms(number)
221
+ (number*1000).round
222
+ end
223
+ # utility method that converts floating point percentage values
224
+ # to integers as a percentage, to improve readability in ui
225
+ def to_percentage(value)
226
+ round_to_2(value * 100)
227
+ end
228
+
229
+ def round_to_2(val)
230
+ (val * 100).round / 100.0
231
+ end
232
+ def round_to_3(val)
233
+ (val * 1000).round / 1000.0
234
+ end
235
+ end
236
+
237
+
238
+ class StatsBase
239
+ include Stats
240
+
241
+ attr_accessor :call_count
242
+ attr_accessor :min_call_time
243
+ attr_accessor :max_call_time
244
+ attr_accessor :total_call_time
245
+ attr_accessor :total_exclusive_time
246
+ attr_accessor :sum_of_squares
247
+
248
+ def initialize
249
+ reset
250
+ end
251
+
252
+ def freeze
253
+ @end_time = Time.now
254
+ super
255
+ end
256
+
257
+ def to_json(*a)
258
+ {'call_count' => call_count,
259
+ 'min_call_time' => min_call_time,
260
+ 'max_call_time' => max_call_time,
261
+ 'total_call_time' => total_call_time,
262
+ 'total_exclusive_time' => total_exclusive_time,
263
+ 'sum_of_squares' => sum_of_squares}.to_json(*a)
264
+ end
265
+
266
+
267
+ # In this class, we explicitly don't track begin and end time here, to save space during
268
+ # cross process serialization via xml. Still the accessor methods must be provided for merge to work.
269
+ def begin_time=(t)
270
+ end
271
+
272
+ def end_time=(t)
273
+ end
274
+
275
+ def begin_time
276
+ 0.0
277
+ end
278
+
279
+ def end_time
280
+ 0.0
281
+ end
282
+ end
283
+
284
+
285
+ class BasicStats < StatsBase
286
+ end
287
+
288
+ class ApdexStats < StatsBase
289
+
290
+ def record_apdex_s
291
+ @call_count += 1
292
+ end
293
+
294
+ def record_apdex_t
295
+ @total_call_time += 1
296
+ end
297
+
298
+ def record_apdex_f
299
+ @total_exclusive_time += 1
300
+ end
301
+ end
302
+
303
+ # Statistics used to track the performance of traced methods
304
+ class MethodTraceStats < StatsBase
305
+
306
+ alias data_point_count call_count
307
+
308
+ # record a single data point into the statistical gatherer. The gatherer
309
+ # will aggregate all data points collected over a specified period and upload
310
+ # its data to the NewRelic server
311
+ def record_data_point(value, exclusive_time = value)
312
+ @call_count += 1
313
+ @total_call_time += value
314
+ @min_call_time = value if value < @min_call_time || @call_count == 1
315
+ @max_call_time = value if value > @max_call_time
316
+ @total_exclusive_time += exclusive_time
317
+
318
+ @sum_of_squares += (value * value)
319
+ self
320
+ end
321
+
322
+ alias trace_call record_data_point
323
+
324
+ def record_multiple_data_points(total_value, count=1)
325
+ return record_data_point(total_value) if count == 1
326
+ @call_count += count
327
+ @total_call_time += total_value
328
+ avg_val = total_value / count
329
+ @min_call_time = avg_val if avg_val < @min_call_time || @call_count == count
330
+ @max_call_time = avg_val if avg_val > @max_call_time
331
+ @total_exclusive_time += total_value
332
+ @sum_of_squares += (avg_val * avg_val) * count
333
+ self
334
+ end
335
+
336
+ def increment_count(value = 1)
337
+ @call_count += value
338
+ end
339
+
340
+ end
341
+
342
+ class ScopedMethodTraceStats < MethodTraceStats
343
+ def initialize(unscoped_stats)
344
+ super()
345
+ @unscoped_stats = unscoped_stats
346
+ end
347
+ def trace_call(call_time, exclusive_time = call_time)
348
+ @unscoped_stats.trace_call call_time, exclusive_time
349
+ super call_time, exclusive_time
350
+ end
351
+ def record_multiple_data_points(total_value, count=1)
352
+ @unscoped_stats.record_multiple_data_points(total_value, count)
353
+ super total_value, count
354
+ end
355
+ def unscoped_stats
356
+ @unscoped_stats
357
+ end
358
+ end
359
+ end
360
+