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,13 @@
1
+ # This is the control used when starting up in the context of
2
+ # The New Relic Infrastructure Agent. We want to call this
3
+ # out specifically because in this context we are not monitoring
4
+ # the running process, but actually external things.
5
+ require 'new_relic/control/ruby'
6
+
7
+ class NewRelic::Control::External < NewRelic::Control::Ruby
8
+
9
+ def init_config(options={})
10
+ super
11
+ end
12
+
13
+ end
@@ -0,0 +1,24 @@
1
+ class NewRelic::Control::Merb < NewRelic::Control
2
+
3
+ def env
4
+ @env ||= ::Merb.env
5
+ end
6
+ def root
7
+ ::Merb.root
8
+ end
9
+
10
+ def to_stdout(msg)
11
+ Merb.logger.info("NewRelic ~ " + msg)
12
+ rescue Exception => e
13
+ STDOUT.puts "NewRelic ~ " + msg
14
+ end
15
+
16
+ def init_config options={}
17
+ ::Merb::Plugins.add_rakefiles File.join(newrelic_root,"lib/tasks/all.rb")
18
+
19
+ # Merb gives you a Merb::Plugins.config hash...feel free to put your stuff in your piece of it
20
+ ::Merb::Plugins.config[:newrelic] = {
21
+ :config => self
22
+ }
23
+ end
24
+ end
@@ -0,0 +1,151 @@
1
+ # Control subclass instantiated when Rails is detected. Contains
2
+ # Rails specific configuration, instrumentation, environment values,
3
+ # etc.
4
+ class NewRelic::Control::Rails < NewRelic::Control
5
+
6
+ def env
7
+ @env ||= RAILS_ENV.dup
8
+ end
9
+ def root
10
+ RAILS_ROOT
11
+ end
12
+
13
+ def log_path
14
+ path = ::RAILS_DEFAULT_LOGGER.instance_eval do
15
+ File.dirname(@log.path) rescue File.dirname(@logdev.filename)
16
+ end rescue "#{root}/log"
17
+ File.expand_path(path)
18
+ end
19
+ # In versions of Rails prior to 2.0, the rails config was only available to
20
+ # the init.rb, so it had to be passed on from there.
21
+ def init_config(options={})
22
+ rails_config=options[:config]
23
+ if !agent_enabled?
24
+ # Might not be running if it does not think mongrel, thin, passenger, etc
25
+ # is running, if it things it's a rake task, or if the agent_enabled is false.
26
+ RAILS_DEFAULT_LOGGER.info "New Relic Agent not running."
27
+ else
28
+ RAILS_DEFAULT_LOGGER.info "Starting the New Relic Agent."
29
+ install_developer_mode rails_config if developer_mode?
30
+ end
31
+ end
32
+
33
+ def install_developer_mode(rails_config)
34
+ return if @installed
35
+ @installed = true
36
+ controller_path = File.expand_path(File.join(newrelic_root, 'ui', 'controllers'))
37
+ helper_path = File.expand_path(File.join(newrelic_root, 'ui', 'helpers'))
38
+
39
+ if defined? ActiveSupport::Dependencies
40
+ Dir["#{helper_path}/*.rb"].each { |f| require f }
41
+ Dir["#{controller_path}/*.rb"].each { |f| require f }
42
+ elsif defined? Dependencies.load_paths
43
+ Dependencies.load_paths << controller_path
44
+ Dependencies.load_paths << helper_path
45
+ else
46
+ to_stdout "ERROR: Rails version #{::Rails::VERSION::STRING} too old for developer mode to work."
47
+ return
48
+ end
49
+ install_devmode_route
50
+
51
+ # If we have the config object then add the controller path to the list.
52
+ # Otherwise we have to assume the controller paths have already been
53
+ # set and we can just append newrelic.
54
+
55
+ if rails_config
56
+ rails_config.controller_paths << controller_path
57
+ else
58
+ current_paths = ActionController::Routing.controller_paths
59
+ if current_paths.nil? || current_paths.empty?
60
+ to_stdout "WARNING: Unable to modify the routes in this version of Rails. Developer mode not available."
61
+ end
62
+ current_paths << controller_path
63
+ end
64
+
65
+ def to_stdout(message)
66
+ ::RAILS_DEFAULT_LOGGER.info(message)
67
+ rescue Exception => e
68
+ STDOUT.puts(message)
69
+ end
70
+
71
+ #ActionController::Routing::Routes.reload! unless NewRelic::Control.instance['skip_developer_route']
72
+
73
+ # inform user that the dev edition is available if we are running inside
74
+ # a webserver process
75
+ if @local_env.dispatcher_instance_id
76
+ port = @local_env.dispatcher_instance_id.to_s =~ /^\d+/ ? ":#{local_env.dispatcher_instance_id}" : ":port"
77
+ to_stdout "NewRelic Agent Developer Mode enabled."
78
+ to_stdout "To view performance information, go to http://localhost#{port}/newrelic"
79
+ end
80
+ end
81
+
82
+ def rails_version
83
+ @rails_version ||= NewRelic::VersionNumber.new(::Rails::VERSION::STRING)
84
+ end
85
+
86
+ protected
87
+
88
+ def install_devmode_route
89
+ # This is a monkey patch to inject the developer tool route into the
90
+ # parent app without requiring users to modify their routes. Of course this
91
+ # has the effect of adding a route indiscriminately which is frowned upon by
92
+ # some: http://www.ruby-forum.com/topic/126316#563328
93
+ ActionController::Routing::RouteSet.class_eval do
94
+ next if self.instance_methods.include? 'draw_with_newrelic_map'
95
+ def draw_with_newrelic_map
96
+ draw_without_newrelic_map do | map |
97
+ unless NewRelic::Control.instance['skip_developer_route']
98
+ map.named_route 'newrelic_developer', '/newrelic/:action/:id', :controller => 'newrelic'
99
+ map.named_route 'newrelic_file', '/newrelic/file/*file', :controller => 'newrelic', :action=>'file'
100
+ end
101
+ yield map
102
+ end
103
+ end
104
+ alias_method_chain :draw, :newrelic_map
105
+ end
106
+ end
107
+
108
+ def rails_vendor_root
109
+ File.join(root,'vendor','rails')
110
+ end
111
+
112
+ # Collect the Rails::Info into an associative array as well as the list of plugins
113
+ def append_environment_info
114
+ local_env.append_environment_value('Rails version'){ ::Rails::VERSION::STRING }
115
+ if rails_version >= NewRelic::VersionNumber.new('2.2.0')
116
+ local_env.append_environment_value('Rails threadsafe') do
117
+ ::Rails.configuration.action_controller.allow_concurrency == true
118
+ end
119
+ end
120
+ local_env.append_environment_value('Rails Env') { ENV['RAILS_ENV'] }
121
+ if rails_version >= NewRelic::VersionNumber.new('2.1.0')
122
+ local_env.append_gem_list do
123
+ ::Rails.configuration.gems.map do | gem |
124
+ version = (gem.respond_to?(:version) && gem.version) ||
125
+ (gem.specification.respond_to?(:version) && gem.specification.version)
126
+ gem.name + (version ? "(#{version})" : "")
127
+ end
128
+ end
129
+ # The plugins is configured manually. If it's nil, it loads everything non-deterministically
130
+ if ::Rails.configuration.plugins
131
+ local_env.append_plugin_list { ::Rails.configuration.plugins }
132
+ else
133
+ ::Rails.configuration.plugin_paths.each do |path|
134
+ local_env.append_plugin_list { Dir[File.join(path, '*')].collect{ |p| File.basename p if File.directory? p }.compact }
135
+ end
136
+ end
137
+ else
138
+ # Rails prior to 2.1, can't get the gems. Find plugins in the default location
139
+ local_env.append_plugin_list do
140
+ Dir[File.join(root, 'vendor', 'plugins', '*')].collect{ |p| File.basename p if File.directory? p }.compact
141
+ end
142
+ end
143
+ end
144
+
145
+ def install_shim
146
+ super
147
+ require 'new_relic/agent/instrumentation/controller_instrumentation'
148
+ ActionController::Base.send :include, NewRelic::Agent::Instrumentation::ControllerInstrumentation::Shim
149
+ end
150
+
151
+ end
@@ -0,0 +1,36 @@
1
+ # A control used when no framework is detected.
2
+ # Looks for a newrelic.yml file in several locations
3
+ # including ./, ./config, $HOME/.newrelic and $HOME/.
4
+ # It loads the settings from the newrelic.yml section
5
+ # based on the value of RUBY_ENV or RAILS_ENV.
6
+ class NewRelic::Control::Ruby < NewRelic::Control
7
+
8
+ def env
9
+ @env ||= ENV['RUBY_ENV'] || ENV['RAILS_ENV'] || 'development'
10
+ end
11
+ def root
12
+ @root ||= ENV['APP_ROOT'] || Dir['.']
13
+ end
14
+ # Check a sequence of file locations for newrelic.yml
15
+ def config_file
16
+ files = []
17
+ files << File.join(root,"config","newrelic.yml")
18
+ files << File.join(root,"newrelic.yml")
19
+ if ENV["HOME"]
20
+ files << File.join(ENV["HOME"], ".newrelic", "newrelic.yml")
21
+ files << File.join(ENV["HOME"], "newrelic.yml")
22
+ end
23
+ files << File.expand_path(ENV["NRCONFIG"]) if ENV["NRCONFIG"]
24
+ files.each do | file |
25
+ return File.expand_path(file) if File.exists? file
26
+ end
27
+ return File.expand_path(files.first)
28
+ end
29
+ def to_stdout(msg)
30
+ STDOUT.puts msg
31
+ end
32
+
33
+ def init_config(options={})
34
+ end
35
+
36
+ end
@@ -0,0 +1,14 @@
1
+
2
+ require 'new_relic/control/ruby'
3
+
4
+ class NewRelic::Control::Sinatra < NewRelic::Control::Ruby
5
+
6
+ # This is the control used when starting up in the context of
7
+ # The New Relic Infrastructure Agent. We want to call this
8
+ # out specifically because in this context we are not monitoring
9
+ # the running process, but actually external things.
10
+ def init_config(options={})
11
+ super
12
+ end
13
+
14
+ end
@@ -0,0 +1,89 @@
1
+ # Histogram is used for organizing response times
2
+ # into an 'Exponential Histogram'. Feature based in part on DHH proposal:
3
+ # http://37signals.com/svn/posts/1836-the-problem-with-averages
4
+ #
5
+ # Histogram builds a set of buckets of geometrically growing size, with the assumption that most
6
+ # apps have long-tail response times, and therefore you need the most granularity at the lowest
7
+ # r/t level.
8
+ class NewRelic::Histogram
9
+
10
+ # Used to stub out API methods when the agent is not enabled
11
+ module Shim
12
+ def process(response_time); end
13
+ end
14
+ # Stores statistics for response times falling in a particular range.
15
+ # A bucket has a min and max response time. A response time event
16
+ # falls in a bucket if min <= r/t < max. A bucket also
17
+ # has an associated metric for reporting data to RPM. The
18
+ # bucket range is encoded in the metic name
19
+ class Bucket
20
+
21
+ attr_reader :min, :max, :stats
22
+
23
+ def initialize(min, max = nil)
24
+ @min = min
25
+ @max = max
26
+ end
27
+
28
+ def stats
29
+ NewRelic::Agent.get_stats("Response Times/#{min_millis}/#{max_millis}")
30
+ end
31
+
32
+ # This has return value like <=> but does something more
33
+ # than simply compare. If the value falls within range for
34
+ # the bucket, increment count and return 0; otherwise return
35
+ # a value < 0 if the value belongs in a bucket with a lower range
36
+ # you can guess what it returns if the value belongs in a bucket
37
+ # with a higher range. (Hint: it's not 0, and it's not less than zero.)
38
+ def process(value)
39
+ if value < min
40
+ return -1
41
+
42
+ # max == nil means unlimited max (last bucket)
43
+ elsif max && value >= max
44
+ return 1
45
+
46
+ else
47
+ stats.record_data_point(value)
48
+ return 0
49
+ end
50
+ end
51
+
52
+ def min_millis
53
+ (min * 1000).round
54
+ end
55
+
56
+ def max_millis
57
+ max.nil? ? nil : (max * 1000).round
58
+ end
59
+
60
+ def to_s
61
+ "#{min_millis} - #{max_millis}: #{stats.call_count}"
62
+ end
63
+ end
64
+
65
+ attr_reader :buckets
66
+
67
+ # Histogram uses apdex T / 10 as its minimum bucket size, and grows from there.
68
+ # 30 data points should be adequate resolution.
69
+ def initialize(first_bucket_max = 0.010, bucket_count = 30, multiplier = 1.3)
70
+ @buckets = []
71
+
72
+ min = 0
73
+ max = first_bucket_max
74
+
75
+ (bucket_count - 1).times do
76
+ @buckets << Bucket.new(min, max)
77
+ min = max
78
+ max *= multiplier
79
+ end
80
+ @buckets << Bucket.new(max)
81
+ end
82
+
83
+ def process(response_time)
84
+ buckets.each do |bucket|
85
+ found = bucket.process(response_time)
86
+ return if found == 0
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,299 @@
1
+ require 'set'
2
+
3
+ module NewRelic
4
+ # An instance of LocalEnvironment is responsible for determining
5
+ # three things:
6
+ #
7
+ # * Framework - :rails, :merb, :ruby, :external, :test
8
+ # * Dispatcher - A supported dispatcher, or nil (:mongrel, :thin, :passenger, :webrick, etc)
9
+ # * Dispatcher Instance ID, which distinguishes agents on a single host from each other
10
+ #
11
+ # If the environment can't be determined, it will be set to
12
+ # nil and dispatcher_instance_id will have nil.
13
+ #
14
+ # NewRelic::LocalEnvironment should be accessed through NewRelic::Control#env (via the NewRelic::Control singleton).
15
+ class LocalEnvironment
16
+
17
+ attr_accessor :dispatcher # mongrel, thin, webrick, or possibly nil
18
+ attr_accessor :dispatcher_instance_id # used to distinguish instances of a dispatcher from each other, may be nil
19
+ attr_accessor :framework # rails, merb, external, ruby, test
20
+ attr_reader :mongrel # The mongrel instance, if there is one, captured as a convenience
21
+ attr_reader :processors # The number of cpus, if detected, or nil
22
+ alias environment dispatcher
23
+
24
+ def initialize
25
+ discover_framework
26
+ discover_dispatcher
27
+ @dispatcher = nil if @dispatcher == :none
28
+ @gems = Set.new
29
+ @plugins = Set.new
30
+ @config = Hash.new
31
+ end
32
+
33
+ # Add the given key/value pair to the app environment
34
+ # settings. Must pass either a value or a block. Block
35
+ # is called to get the value and any raised errors are
36
+ # silently ignored.
37
+ def append_environment_value name, value = nil
38
+ value = yield if block_given?
39
+ @config[name] = value if value
40
+ rescue Exception
41
+ # puts "#{e}\n #{e.backtrace.join("\n ")}"
42
+ raise if @framework == :test
43
+ end
44
+
45
+ def append_gem_list
46
+ @gems += yield
47
+ rescue Exception => e
48
+ # puts "#{e}\n #{e.backtrace.join("\n ")}"
49
+ raise if @framework == :test
50
+ end
51
+
52
+ def append_plugin_list
53
+ @plugins += yield
54
+ rescue Exception
55
+ # puts "#{e}\n #{e.backtrace.join("\n ")}"
56
+ raise if @framework == :test
57
+ end
58
+
59
+ def dispatcher_instance_id
60
+ if @dispatcher_instance_id.nil?
61
+ if @dispatcher.nil?
62
+ @dispatcher_instance_id = File.basename($0).split(".").first
63
+ end
64
+ end
65
+ @dispatcher_instance_id
66
+ end
67
+
68
+ # Collect base statistics about the environment and record them for
69
+ # comparison and change detection.
70
+ def gather_environment_info
71
+ append_environment_value 'Framework', @framework.to_s
72
+ append_environment_value 'Dispatcher', @dispatcher.to_s if @dispatcher
73
+ append_environment_value 'Dispatcher instance id', @dispatcher_instance_id if @dispatcher_instance_id
74
+ append_environment_value('Application root') { File.expand_path(NewRelic::Control.instance.root) }
75
+ append_environment_value('Ruby version'){ RUBY_VERSION }
76
+ append_environment_value('Ruby description'){ RUBY_DESCRIPTION } if defined? RUBY_DESCRIPTION
77
+ append_environment_value('Ruby platform') { RUBY_PLATFORM }
78
+ append_environment_value('Ruby patchlevel') { RUBY_PATCHLEVEL }
79
+ if defined? ::JRUBY_VERSION
80
+ append_environment_value('JRuby version') { JRUBY_VERSION }
81
+ append_environment_value('Java VM version') { ENV_JAVA['java.vm.version']}
82
+ end
83
+ append_environment_value('OS version') { `uname -v` }
84
+ append_environment_value('OS') { `uname -s` } ||
85
+ append_environment_value('OS') { ENV['OS'] }
86
+ append_environment_value('Arch') { `uname -p` } ||
87
+ append_environment_value('Arch') { ENV['PROCESSOR_ARCHITECTURE'] }
88
+ # See what the number of cpus is, works only on linux.
89
+ @processors = append_environment_value('Processors') do
90
+ processors = File.readlines('/proc/cpuinfo').select { |line| line =~ /^processor\s*:/ }.size
91
+ raise "Cannot determine the number of processors in /proc/cpuinfo" unless processors > 0
92
+ processors
93
+ end if File.readable? '/proc/cpuinfo'
94
+ # The current Rails environment (development, test, or production).
95
+ append_environment_value('Environment') { NewRelic::Control.instance.env }
96
+ # Look for a capistrano file indicating the current revision:
97
+ rev_file = File.join(NewRelic::Control.instance.root, "REVISION")
98
+ if File.readable?(rev_file) && File.size(rev_file) < 64
99
+ append_environment_value('Revision') do
100
+ File.open(rev_file) { | file | file.readline.strip }
101
+ end
102
+ end
103
+ # The name of the database adapter for the current environment.
104
+ if defined? ActiveRecord
105
+ append_environment_value 'Database adapter' do
106
+ ActiveRecord::Base.configurations[RAILS_ENV]['adapter']
107
+ end
108
+ append_environment_value 'Database schema version' do
109
+ ActiveRecord::Migrator.current_version
110
+ end
111
+ end
112
+ if defined? DataMapper
113
+ append_environment_value 'DataMapper version' do
114
+ require 'dm-core/version'
115
+ DataMapper::VERSION
116
+ end
117
+ end
118
+ end
119
+ # Take a snapshot of the environment information for this application
120
+ # Returns an associative array
121
+ def snapshot
122
+ i = @config.to_a
123
+ i << [ 'Plugin List', @plugins.to_a] if not @plugins.empty?
124
+ i << [ 'Gems', @gems.to_a] if not @gems.empty?
125
+ i
126
+ end
127
+
128
+ def mongrel
129
+ return @mongrel if @mongrel || ! defined? Mongrel::HttpServer
130
+ ObjectSpace.each_object(Mongrel::HttpServer) do |mongrel|
131
+ @mongrel = mongrel
132
+ end unless defined?(JRuby) && !JRuby.runtime.is_object_space_enabled
133
+ @mongrel
134
+ end
135
+
136
+ def unicorn
137
+ return @unicorn if @unicorn || ! defined? Unicorn::HttpServer
138
+ ObjectSpace.each_object(Unicorn::HttpServer) do |unicorn|
139
+ @unicorn = unicorn
140
+ end unless defined?(JRuby) && !JRuby.runtime.is_object_space_enabled
141
+ @unicorn
142
+ end
143
+
144
+ # Obsolete method for DelayedJob instrumentation support, which is
145
+ # now in the rpm_contrib gem.
146
+ def delayed_worker=(worker)
147
+ $stderr.puts "WARNING: DelayedJob instrumentation has been moved to the rpm_contrib gem."
148
+ end
149
+
150
+ private
151
+
152
+ # Although you can override the framework with NEWRELIC_DISPATCHER this
153
+ # is not advisable since it implies certain api's being available.
154
+ def discover_dispatcher
155
+ @dispatcher = ENV['NEWRELIC_DISPATCHER'] && ENV['NEWRELIC_DISPATCHER'].to_sym
156
+ dispatchers = %w[passenger torquebox glassfish thin mongrel litespeed webrick fastcgi unicorn sinatra]
157
+ while dispatchers.any? && @dispatcher.nil?
158
+ send 'check_for_'+(dispatchers.shift)
159
+ end
160
+ end
161
+
162
+ def discover_framework
163
+ # Although you can override the framework with NEWRELIC_FRAMEWORK this
164
+ # is not advisable since it implies certain api's being available.
165
+ @framework = case
166
+ when ENV['NEWRELIC_FRAMEWORK'] then ENV['NEWRELIC_FRAMEWORK'].to_sym
167
+ when defined? NewRelic::TEST then :test
168
+ when defined? Merb::Plugins then :merb
169
+ when defined? Rails then :rails
170
+ when defined? Sinatra::Base then :sinatra
171
+ when defined? NewRelic::IA then :external
172
+ else :ruby
173
+ end
174
+ end
175
+
176
+ def check_for_torquebox
177
+ return unless defined?(JRuby) &&
178
+ ( Java::OrgTorqueboxRailsWebDeployers::RailsRackDeployer rescue nil)
179
+ @dispatcher = :torquebox
180
+ end
181
+
182
+ def check_for_glassfish
183
+ return unless defined?(JRuby) &&
184
+ (((com.sun.grizzly.jruby.rack.DefaultRackApplicationFactory rescue nil) &&
185
+ defined?(com::sun::grizzly::jruby::rack::DefaultRackApplicationFactory)) ||
186
+ ((org.jruby.rack.DefaultRackApplicationFactory rescue nil) &&
187
+ defined?(org::jruby::rack::DefaultRackApplicationFactory)))
188
+ @dispatcher = :glassfish
189
+ end
190
+
191
+ def check_for_webrick
192
+ return unless defined?(WEBrick::VERSION)
193
+ @dispatcher = :webrick
194
+ if defined?(OPTIONS) && OPTIONS.respond_to?(:fetch)
195
+ # OPTIONS is set by script/server
196
+ @dispatcher_instance_id = OPTIONS.fetch(:port)
197
+ end
198
+ @dispatcher_instance_id = default_port unless @dispatcher_instance_id
199
+ end
200
+
201
+ def check_for_fastcgi
202
+ return unless defined? FCGI
203
+ @dispatcher = :fastcgi
204
+ end
205
+
206
+ # this case covers starting by mongrel_rails
207
+ def check_for_mongrel
208
+ return unless defined?(Mongrel::HttpServer)
209
+ @dispatcher = :mongrel
210
+
211
+ # Get the port from the server if it's started
212
+
213
+ if mongrel && mongrel.respond_to?(:port)
214
+ @dispatcher_instance_id = mongrel.port.to_s
215
+ end
216
+
217
+ # Get the port from the configurator if one was created
218
+ if @dispatcher_instance_id.nil? && defined?(Mongrel::Configurator)
219
+ ObjectSpace.each_object(Mongrel::Configurator) do |mongrel|
220
+ @dispatcher_instance_id = mongrel.defaults[:port] && mongrel.defaults[:port].to_s
221
+ end unless defined?(JRuby) && !JRuby.runtime.is_object_space_enabled
222
+ end
223
+
224
+ # Still can't find the port. Let's look at ARGV to fall back
225
+ @dispatcher_instance_id = default_port if @dispatcher_instance_id.nil?
226
+ end
227
+
228
+ def check_for_unicorn
229
+ return unless defined?(Unicorn::HttpServer)
230
+
231
+ # unlike mongrel, unicorn manages muliple threads and ports, so we
232
+ # have to map multiple processes into one instance, as we do with passenger
233
+ @dispatcher = :unicorn
234
+ end
235
+
236
+ def check_for_sinatra
237
+ return unless defined?(Sinatra::Base)
238
+ @dispatcher = :sinatra
239
+ end
240
+
241
+ def check_for_thin
242
+ if defined? Thin::Server
243
+ # This case covers the thin web dispatcher
244
+ # Same issue as above- we assume only one instance per process
245
+ ObjectSpace.each_object(Thin::Server) do |thin_dispatcher|
246
+ @dispatcher = :thin
247
+ backend = thin_dispatcher.backend
248
+ # We need a way to uniquely identify and distinguish agents. The port
249
+ # works for this. When using sockets, use the socket file name.
250
+ if backend.respond_to? :port
251
+ @dispatcher_instance_id = backend.port
252
+ elsif backend.respond_to? :socket
253
+ @dispatcher_instance_id = backend.socket
254
+ else
255
+ raise "Unknown thin backend: #{backend}"
256
+ end
257
+ end # each thin instance
258
+ end
259
+ if defined?(Thin::VERSION) && !@dispatcher
260
+ @dispatcher = :thin
261
+ @dispatcher_instance_id = default_port
262
+ end
263
+ end
264
+
265
+ def check_for_litespeed
266
+ if caller.pop =~ /fcgi-bin\/RailsRunner\.rb/
267
+ @dispatcher = :litespeed
268
+ end
269
+ end
270
+
271
+ def check_for_passenger
272
+ if defined?(Passenger::AbstractServer) || defined?(IN_PHUSION_PASSENGER)
273
+ @dispatcher = :passenger
274
+ end
275
+ end
276
+
277
+
278
+ def default_port
279
+ require 'optparse'
280
+ # If nothing else is found, use the 3000 default
281
+ default_port = 3000
282
+ OptionParser.new do |opts|
283
+ opts.on("-p", "--port=port", String) { | p | default_port = p }
284
+ opts.parse(ARGV.clone) rescue nil
285
+ end
286
+ default_port
287
+ end
288
+
289
+ public
290
+ def to_s
291
+ s = "LocalEnvironment["
292
+ s << @framework.to_s
293
+ s << ";dispatcher=#{@dispatcher}" if @dispatcher
294
+ s << ";instance=#{@dispatcher_instance_id}" if @dispatcher_instance_id
295
+ s << "]"
296
+ end
297
+
298
+ end
299
+ end