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,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,67 @@
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
+ MAX_LENGTH = 100
8
+ # Need a "zero-arg" constructor so it can be instantiated from java (using
9
+ # jruby) for sending responses to ruby agents from the java collector.
10
+ #
11
+ def initialize(metric_name = '', metric_scope = '')
12
+ self.name = (metric_name || '') && metric_name[0...MAX_LENGTH]
13
+ self.scope = metric_scope && metric_scope[0...MAX_LENGTH]
14
+ end
15
+
16
+ def truncate!
17
+ self.name = name[0...100] if name && name.size > 100
18
+ self.scope = scope[0...100] if scope && scope.size > 100
19
+ end
20
+
21
+ def ==(o)
22
+ self.eql?(o)
23
+ end
24
+
25
+ def eql? o
26
+ self.class == o.class &&
27
+ name.eql?(o.name) &&
28
+ # coerce scope to a string and compare
29
+ (scope || '') == (o.scope || '')
30
+ end
31
+
32
+ def hash
33
+ h = name.hash
34
+ h ^= scope.hash unless scope.nil?
35
+ h
36
+ end
37
+ # return a new metric spec if the given regex
38
+ # matches the name or scope.
39
+ def sub(pattern, replacement, apply_to_scope = true)
40
+ return nil if name !~ pattern &&
41
+ (!apply_to_scope || scope.nil? || scope !~ pattern)
42
+ new_name = name.sub(pattern, replacement)[0...MAX_LENGTH]
43
+
44
+ if apply_to_scope
45
+ new_scope = (scope && scope.sub(pattern, replacement)[0...MAX_LENGTH])
46
+ else
47
+ new_scope = scope
48
+ end
49
+
50
+ self.class.new new_name, new_scope
51
+ end
52
+
53
+ def to_s
54
+ "#{name}:#{scope}"
55
+ end
56
+
57
+ def to_json(*a)
58
+ {'name' => name,
59
+ 'scope' => scope}.to_json(*a)
60
+ end
61
+
62
+ def <=>(o)
63
+ namecmp = self.name <=> o.name
64
+ return namecmp if namecmp != 0
65
+ return (self.scope || '') <=> (o.scope || '')
66
+ end
67
+ 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 "/" do
19
+ run NewRelic::Rack::Status.new
20
+ end
21
+ map "/metrics" do
22
+ run NewRelic::Rack::MetricApp.new(options)
23
+ end
24
+
25
+
@@ -0,0 +1,26 @@
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
+ enabled: true
8
+
9
+ # This is the key generated by script/create_admin
10
+ license_key: 'your_license_key_here'
11
+
12
+ # Replace this with the name of the application feeding
13
+ # metrics into the Metric application;
14
+ app_name: Application Monitor
15
+
16
+ # If RAILS_ENV or RUBY_ENV is defined to be one of the following
17
+ # these values will be overrides
18
+
19
+ production:
20
+ <<: *default_settings
21
+ app_name: Production Monitor
22
+
23
+ staging:
24
+ <<: *default_settings
25
+ app_name: Staging Monitor
26
+
@@ -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,362 @@
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 timeslices 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
+
221
+ private
222
+ def to_ms(number)
223
+ (number*1000).round
224
+ end
225
+ # utility method that converts floating point percentage values
226
+ # to integers as a percentage, to improve readability in ui
227
+ def to_percentage(value)
228
+ round_to_2(value * 100)
229
+ end
230
+
231
+ def round_to_2(val)
232
+ (val * 100).round / 100.0
233
+ end
234
+ def round_to_3(val)
235
+ (val * 1000).round / 1000.0
236
+ end
237
+ end
238
+
239
+
240
+ class StatsBase
241
+ include Stats
242
+
243
+ attr_accessor :call_count
244
+ attr_accessor :min_call_time
245
+ attr_accessor :max_call_time
246
+ attr_accessor :total_call_time
247
+ attr_accessor :total_exclusive_time
248
+ attr_accessor :sum_of_squares
249
+
250
+ def initialize
251
+ reset
252
+ end
253
+
254
+ def freeze
255
+ @end_time = Time.now
256
+ super
257
+ end
258
+
259
+ def to_json(*a)
260
+ {'call_count' => call_count,
261
+ 'min_call_time' => min_call_time,
262
+ 'max_call_time' => max_call_time,
263
+ 'total_call_time' => total_call_time,
264
+ 'total_exclusive_time' => total_exclusive_time,
265
+ 'sum_of_squares' => sum_of_squares}.to_json(*a)
266
+ end
267
+
268
+
269
+ # In this class, we explicitly don't track begin and end time here, to save space during
270
+ # cross process serialization via xml. Still the accessor methods must be provided for merge to work.
271
+ def begin_time=(t)
272
+ end
273
+
274
+ def end_time=(t)
275
+ end
276
+
277
+ def begin_time
278
+ 0.0
279
+ end
280
+
281
+ def end_time
282
+ 0.0
283
+ end
284
+ end
285
+
286
+
287
+ class BasicStats < StatsBase
288
+ end
289
+
290
+ class ApdexStats < StatsBase
291
+
292
+ def record_apdex_s
293
+ @call_count += 1
294
+ end
295
+
296
+ def record_apdex_t
297
+ @total_call_time += 1
298
+ end
299
+
300
+ def record_apdex_f
301
+ @total_exclusive_time += 1
302
+ end
303
+ end
304
+
305
+ # Statistics used to track the performance of traced methods
306
+ class MethodTraceStats < StatsBase
307
+
308
+ alias data_point_count call_count
309
+
310
+ # record a single data point into the statistical gatherer. The gatherer
311
+ # will aggregate all data points collected over a specified period and upload
312
+ # its data to the NewRelic server
313
+ def record_data_point(value, exclusive_time = value)
314
+ @call_count += 1
315
+ @total_call_time += value
316
+ @min_call_time = value if value < @min_call_time || @call_count == 1
317
+ @max_call_time = value if value > @max_call_time
318
+ @total_exclusive_time += exclusive_time
319
+
320
+ @sum_of_squares += (value * value)
321
+ self
322
+ end
323
+
324
+ alias trace_call record_data_point
325
+
326
+ def record_multiple_data_points(total_value, count=1)
327
+ return record_data_point(total_value) if count == 1
328
+ @call_count += count
329
+ @total_call_time += total_value
330
+ avg_val = total_value / count
331
+ @min_call_time = avg_val if avg_val < @min_call_time || @call_count == count
332
+ @max_call_time = avg_val if avg_val > @max_call_time
333
+ @total_exclusive_time += total_value
334
+ @sum_of_squares += (avg_val * avg_val) * count
335
+ self
336
+ end
337
+
338
+ def increment_count(value = 1)
339
+ @call_count += value
340
+ end
341
+
342
+ end
343
+
344
+ class ScopedMethodTraceStats < MethodTraceStats
345
+ def initialize(unscoped_stats)
346
+ super()
347
+ @unscoped_stats = unscoped_stats
348
+ end
349
+ def trace_call(call_time, exclusive_time = call_time)
350
+ @unscoped_stats.trace_call call_time, exclusive_time
351
+ super call_time, exclusive_time
352
+ end
353
+ def record_multiple_data_points(total_value, count=1)
354
+ @unscoped_stats.record_multiple_data_points(total_value, count)
355
+ super total_value, count
356
+ end
357
+ def unscoped_stats
358
+ @unscoped_stats
359
+ end
360
+ end
361
+ end
362
+