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,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,23 @@
1
+ # This class encapsulates an error that was noticed by RPM in a managed app.
2
+ class NewRelic::NoticedError
3
+ attr_accessor :path, :timestamp, :params, :exception_class, :message
4
+
5
+ def initialize(path, data, exception, timestamp = Time.now)
6
+ self.path = path
7
+ self.params = data
8
+
9
+ self.exception_class = exception ? exception.class.name : '<no exception>'
10
+
11
+ if exception.respond_to?('original_exception')
12
+ self.message = exception.original_exception.message.to_s
13
+ else
14
+ self.message = (exception || '<no message>').to_s
15
+ end
16
+
17
+ # clamp long messages to 4k so that we don't send a lot of
18
+ # overhead across the wire
19
+ self.message = self.message[0..4095] if self.message.length > 4096
20
+
21
+ self.timestamp = timestamp
22
+ end
23
+ 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(:newrelic_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,361 @@
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_exclusive_time = s.total_exclusive_time * percentage
194
+ self.total_call_time = s.total_call_time * percentage
195
+ self.min_call_time = s.min_call_time
196
+ self.max_call_time = s.max_call_time
197
+ self.call_count = s.call_count * percentage
198
+ self.sum_of_squares = (s.sum_of_squares || 0) * percentage
199
+ end
200
+
201
+ # multiply the total time and rate by the given percentage
202
+ def multiply_by(percentage)
203
+ self.total_call_time = total_call_time * percentage
204
+ self.call_count = call_count * percentage
205
+ self.sum_of_squares = sum_of_squares * percentage
206
+
207
+ self
208
+ end
209
+
210
+
211
+ # returns s,t,f
212
+ def get_apdex
213
+ [@call_count, @total_call_time.to_i, @total_exclusive_time.to_i]
214
+ end
215
+
216
+ def apdex_score
217
+ s, t, f = get_apdex
218
+ (s.to_f + (t.to_f / 2)) / (s+t+f).to_f
219
+ end
220
+ private
221
+ def to_ms(number)
222
+ (number*1000).round
223
+ end
224
+ # utility method that converts floating point percentage values
225
+ # to integers as a percentage, to improve readability in ui
226
+ def to_percentage(value)
227
+ round_to_2(value * 100)
228
+ end
229
+
230
+ def round_to_2(val)
231
+ (val * 100).round / 100.0
232
+ end
233
+ def round_to_3(val)
234
+ (val * 1000).round / 1000.0
235
+ end
236
+ end
237
+
238
+
239
+ class StatsBase
240
+ include Stats
241
+
242
+ attr_accessor :call_count
243
+ attr_accessor :min_call_time
244
+ attr_accessor :max_call_time
245
+ attr_accessor :total_call_time
246
+ attr_accessor :total_exclusive_time
247
+ attr_accessor :sum_of_squares
248
+
249
+ def initialize
250
+ reset
251
+ end
252
+
253
+ def freeze
254
+ @end_time = Time.now
255
+ super
256
+ end
257
+
258
+ def to_json(*a)
259
+ {'call_count' => call_count,
260
+ 'min_call_time' => min_call_time,
261
+ 'max_call_time' => max_call_time,
262
+ 'total_call_time' => total_call_time,
263
+ 'total_exclusive_time' => total_exclusive_time,
264
+ 'sum_of_squares' => sum_of_squares}.to_json(*a)
265
+ end
266
+
267
+
268
+ # In this class, we explicitly don't track begin and end time here, to save space during
269
+ # cross process serialization via xml. Still the accessor methods must be provided for merge to work.
270
+ def begin_time=(t)
271
+ end
272
+
273
+ def end_time=(t)
274
+ end
275
+
276
+ def begin_time
277
+ 0.0
278
+ end
279
+
280
+ def end_time
281
+ 0.0
282
+ end
283
+ end
284
+
285
+
286
+ class BasicStats < StatsBase
287
+ end
288
+
289
+ class ApdexStats < StatsBase
290
+
291
+ def record_apdex_s
292
+ @call_count += 1
293
+ end
294
+
295
+ def record_apdex_t
296
+ @total_call_time += 1
297
+ end
298
+
299
+ def record_apdex_f
300
+ @total_exclusive_time += 1
301
+ end
302
+ end
303
+
304
+ # Statistics used to track the performance of traced methods
305
+ class MethodTraceStats < StatsBase
306
+
307
+ alias data_point_count call_count
308
+
309
+ # record a single data point into the statistical gatherer. The gatherer
310
+ # will aggregate all data points collected over a specified period and upload
311
+ # its data to the NewRelic server
312
+ def record_data_point(value, exclusive_time = value)
313
+ @call_count += 1
314
+ @total_call_time += value
315
+ @min_call_time = value if value < @min_call_time || @call_count == 1
316
+ @max_call_time = value if value > @max_call_time
317
+ @total_exclusive_time += exclusive_time
318
+
319
+ @sum_of_squares += (value * value)
320
+ self
321
+ end
322
+
323
+ alias trace_call record_data_point
324
+
325
+ def record_multiple_data_points(total_value, count=1)
326
+ return record_data_point(total_value) if count == 1
327
+ @call_count += count
328
+ @total_call_time += total_value
329
+ avg_val = total_value / count
330
+ @min_call_time = avg_val if avg_val < @min_call_time || @call_count == count
331
+ @max_call_time = avg_val if avg_val > @max_call_time
332
+ @total_exclusive_time += total_value
333
+ @sum_of_squares += (avg_val * avg_val) * count
334
+ self
335
+ end
336
+
337
+ def increment_count(value = 1)
338
+ @call_count += value
339
+ end
340
+
341
+ end
342
+
343
+ class ScopedMethodTraceStats < MethodTraceStats
344
+ def initialize(unscoped_stats)
345
+ super()
346
+ @unscoped_stats = unscoped_stats
347
+ end
348
+ def trace_call(call_time, exclusive_time = call_time)
349
+ @unscoped_stats.trace_call call_time, exclusive_time
350
+ super call_time, exclusive_time
351
+ end
352
+ def record_multiple_data_points(total_value, count=1)
353
+ @unscoped_stats.record_multiple_data_points(total_value, count)
354
+ super total_value, count
355
+ end
356
+ def unscoped_stats
357
+ @unscoped_stats
358
+ end
359
+ end
360
+ end
361
+