genki-newrelic_rpm 2.10.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (158) hide show
  1. data/CHANGELOG +316 -0
  2. data/LICENSE +37 -0
  3. data/Manifest +156 -0
  4. data/README.md +138 -0
  5. data/Rakefile +22 -0
  6. data/bin/mongrel_rpm +33 -0
  7. data/bin/newrelic_cmd +4 -0
  8. data/cert/cacert.pem +34 -0
  9. data/genki-newrelic_rpm.gemspec +32 -0
  10. data/init.rb +38 -0
  11. data/install.rb +37 -0
  12. data/lib/new_relic/agent.rb +280 -0
  13. data/lib/new_relic/agent/agent.rb +627 -0
  14. data/lib/new_relic/agent/chained_call.rb +13 -0
  15. data/lib/new_relic/agent/collection_helper.rb +61 -0
  16. data/lib/new_relic/agent/error_collector.rb +125 -0
  17. data/lib/new_relic/agent/instrumentation/active_merchant.rb +18 -0
  18. data/lib/new_relic/agent/instrumentation/active_record_instrumentation.rb +83 -0
  19. data/lib/new_relic/agent/instrumentation/authlogic.rb +8 -0
  20. data/lib/new_relic/agent/instrumentation/controller_instrumentation.rb +368 -0
  21. data/lib/new_relic/agent/instrumentation/data_mapper.rb +90 -0
  22. data/lib/new_relic/agent/instrumentation/dispatcher_instrumentation.rb +132 -0
  23. data/lib/new_relic/agent/instrumentation/memcache.rb +21 -0
  24. data/lib/new_relic/agent/instrumentation/merb/controller.rb +26 -0
  25. data/lib/new_relic/agent/instrumentation/merb/dispatcher.rb +13 -0
  26. data/lib/new_relic/agent/instrumentation/merb/errors.rb +8 -0
  27. data/lib/new_relic/agent/instrumentation/net.rb +12 -0
  28. data/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb +20 -0
  29. data/lib/new_relic/agent/instrumentation/rack.rb +77 -0
  30. data/lib/new_relic/agent/instrumentation/rails/action_controller.rb +59 -0
  31. data/lib/new_relic/agent/instrumentation/rails/action_web_service.rb +27 -0
  32. data/lib/new_relic/agent/instrumentation/rails/dispatcher.rb +38 -0
  33. data/lib/new_relic/agent/instrumentation/rails/errors.rb +27 -0
  34. data/lib/new_relic/agent/instrumentation/sinatra.rb +39 -0
  35. data/lib/new_relic/agent/method_tracer.rb +277 -0
  36. data/lib/new_relic/agent/patch_const_missing.rb +125 -0
  37. data/lib/new_relic/agent/sampler.rb +12 -0
  38. data/lib/new_relic/agent/samplers/cpu_sampler.rb +49 -0
  39. data/lib/new_relic/agent/samplers/memory_sampler.rb +137 -0
  40. data/lib/new_relic/agent/samplers/mongrel_sampler.rb +22 -0
  41. data/lib/new_relic/agent/shim_agent.rb +21 -0
  42. data/lib/new_relic/agent/stats_engine.rb +24 -0
  43. data/lib/new_relic/agent/stats_engine/metric_stats.rb +111 -0
  44. data/lib/new_relic/agent/stats_engine/samplers.rb +71 -0
  45. data/lib/new_relic/agent/stats_engine/transactions.rb +155 -0
  46. data/lib/new_relic/agent/transaction_sampler.rb +319 -0
  47. data/lib/new_relic/agent/worker_loop.rb +118 -0
  48. data/lib/new_relic/commands/deployments.rb +145 -0
  49. data/lib/new_relic/commands/new_relic_commands.rb +30 -0
  50. data/lib/new_relic/control.rb +436 -0
  51. data/lib/new_relic/control/external.rb +13 -0
  52. data/lib/new_relic/control/merb.rb +22 -0
  53. data/lib/new_relic/control/rails.rb +143 -0
  54. data/lib/new_relic/control/ruby.rb +34 -0
  55. data/lib/new_relic/control/sinatra.rb +14 -0
  56. data/lib/new_relic/histogram.rb +89 -0
  57. data/lib/new_relic/local_environment.rb +285 -0
  58. data/lib/new_relic/merbtasks.rb +6 -0
  59. data/lib/new_relic/metric_data.rb +44 -0
  60. data/lib/new_relic/metric_parser.rb +120 -0
  61. data/lib/new_relic/metric_parser/action_mailer.rb +9 -0
  62. data/lib/new_relic/metric_parser/active_merchant.rb +26 -0
  63. data/lib/new_relic/metric_parser/active_record.rb +25 -0
  64. data/lib/new_relic/metric_parser/controller.rb +54 -0
  65. data/lib/new_relic/metric_parser/controller_cpu.rb +38 -0
  66. data/lib/new_relic/metric_parser/errors.rb +6 -0
  67. data/lib/new_relic/metric_parser/external.rb +50 -0
  68. data/lib/new_relic/metric_parser/mem_cache.rb +12 -0
  69. data/lib/new_relic/metric_parser/view.rb +61 -0
  70. data/lib/new_relic/metric_parser/web_frontend.rb +14 -0
  71. data/lib/new_relic/metric_parser/web_service.rb +9 -0
  72. data/lib/new_relic/metric_spec.rb +52 -0
  73. data/lib/new_relic/metrics.rb +7 -0
  74. data/lib/new_relic/noticed_error.rb +25 -0
  75. data/lib/new_relic/rack/metric_app.rb +56 -0
  76. data/lib/new_relic/rack/newrelic.ru +25 -0
  77. data/lib/new_relic/rack/newrelic.yml +25 -0
  78. data/lib/new_relic/rack_app.rb +5 -0
  79. data/lib/new_relic/recipes.rb +82 -0
  80. data/lib/new_relic/stats.rb +360 -0
  81. data/lib/new_relic/transaction_analysis.rb +121 -0
  82. data/lib/new_relic/transaction_sample.rb +583 -0
  83. data/lib/new_relic/version.rb +54 -0
  84. data/lib/new_relic_api.rb +315 -0
  85. data/lib/newrelic_rpm.rb +40 -0
  86. data/lib/tasks/all.rb +4 -0
  87. data/lib/tasks/install.rake +7 -0
  88. data/lib/tasks/tests.rake +13 -0
  89. data/newrelic.yml +214 -0
  90. data/recipes/newrelic.rb +6 -0
  91. data/test/active_record_fixtures.rb +55 -0
  92. data/test/config/newrelic.yml +46 -0
  93. data/test/config/test_control.rb +39 -0
  94. data/test/new_relic/agent/active_record_instrumentation_test.rb +234 -0
  95. data/test/new_relic/agent/agent_controller_test.rb +107 -0
  96. data/test/new_relic/agent/agent_test.rb +117 -0
  97. data/test/new_relic/agent/agent_test_controller.rb +44 -0
  98. data/test/new_relic/agent/classloader_patch_test.rb +56 -0
  99. data/test/new_relic/agent/collection_helper_test.rb +118 -0
  100. data/test/new_relic/agent/dispatcher_instrumentation_test.rb +76 -0
  101. data/test/new_relic/agent/error_collector_test.rb +155 -0
  102. data/test/new_relic/agent/method_tracer_test.rb +335 -0
  103. data/test/new_relic/agent/metric_data_test.rb +56 -0
  104. data/test/new_relic/agent/mock_ar_connection.rb +40 -0
  105. data/test/new_relic/agent/mock_scope_listener.rb +23 -0
  106. data/test/new_relic/agent/net_instrumentation_test.rb +51 -0
  107. data/test/new_relic/agent/stats_engine/metric_stats_test.rb +79 -0
  108. data/test/new_relic/agent/stats_engine/samplers_test.rb +78 -0
  109. data/test/new_relic/agent/stats_engine/stats_engine_test.rb +177 -0
  110. data/test/new_relic/agent/task_instrumentation_test.rb +67 -0
  111. data/test/new_relic/agent/testable_agent.rb +13 -0
  112. data/test/new_relic/agent/transaction_sample_builder_test.rb +195 -0
  113. data/test/new_relic/agent/transaction_sample_test.rb +146 -0
  114. data/test/new_relic/agent/transaction_sampler_test.rb +387 -0
  115. data/test/new_relic/agent/worker_loop_test.rb +103 -0
  116. data/test/new_relic/control_test.rb +94 -0
  117. data/test/new_relic/deployments_api_test.rb +68 -0
  118. data/test/new_relic/environment_test.rb +75 -0
  119. data/test/new_relic/metric_parser_test.rb +172 -0
  120. data/test/new_relic/metric_spec_test.rb +177 -0
  121. data/test/new_relic/shim_agent_test.rb +9 -0
  122. data/test/new_relic/stats_test.rb +291 -0
  123. data/test/new_relic/version_number_test.rb +74 -0
  124. data/test/test_helper.rb +38 -0
  125. data/test/ui/newrelic_controller_test.rb +14 -0
  126. data/test/ui/newrelic_helper_test.rb +53 -0
  127. data/ui/controllers/newrelic_controller.rb +214 -0
  128. data/ui/helpers/google_pie_chart.rb +55 -0
  129. data/ui/helpers/newrelic_helper.rb +314 -0
  130. data/ui/views/layouts/newrelic_default.rhtml +47 -0
  131. data/ui/views/newrelic/_explain_plans.rhtml +27 -0
  132. data/ui/views/newrelic/_sample.rhtml +15 -0
  133. data/ui/views/newrelic/_segment.rhtml +28 -0
  134. data/ui/views/newrelic/_segment_limit_message.rhtml +1 -0
  135. data/ui/views/newrelic/_segment_row.rhtml +14 -0
  136. data/ui/views/newrelic/_show_sample_detail.rhtml +24 -0
  137. data/ui/views/newrelic/_show_sample_sql.rhtml +20 -0
  138. data/ui/views/newrelic/_show_sample_summary.rhtml +3 -0
  139. data/ui/views/newrelic/_sql_row.rhtml +11 -0
  140. data/ui/views/newrelic/_stack_trace.rhtml +30 -0
  141. data/ui/views/newrelic/_table.rhtml +12 -0
  142. data/ui/views/newrelic/explain_sql.rhtml +42 -0
  143. data/ui/views/newrelic/images/arrow-close.png +0 -0
  144. data/ui/views/newrelic/images/arrow-open.png +0 -0
  145. data/ui/views/newrelic/images/blue_bar.gif +0 -0
  146. data/ui/views/newrelic/images/file_icon.png +0 -0
  147. data/ui/views/newrelic/images/gray_bar.gif +0 -0
  148. data/ui/views/newrelic/images/new_relic_rpm_desktop.gif +0 -0
  149. data/ui/views/newrelic/images/textmate.png +0 -0
  150. data/ui/views/newrelic/index.rhtml +45 -0
  151. data/ui/views/newrelic/javascript/prototype-scriptaculous.js +7288 -0
  152. data/ui/views/newrelic/javascript/transaction_sample.js +107 -0
  153. data/ui/views/newrelic/sample_not_found.rhtml +2 -0
  154. data/ui/views/newrelic/show_sample.rhtml +77 -0
  155. data/ui/views/newrelic/show_source.rhtml +3 -0
  156. data/ui/views/newrelic/stylesheets/style.css +433 -0
  157. data/ui/views/newrelic/threads.rhtml +52 -0
  158. metadata +327 -0
@@ -0,0 +1,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,22 @@
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
+ STDOUT.puts "NewRelic ~ " + msg
12
+ end
13
+
14
+ def init_config options={}
15
+ ::Merb::Plugins.add_rakefiles File.join(newrelic_root,"lib/tasks/all.rb")
16
+
17
+ # Merb gives you a Merb::Plugins.config hash...feel free to put your stuff in your piece of it
18
+ ::Merb::Plugins.config[:newrelic] = {
19
+ :config => self
20
+ }
21
+ end
22
+ end
@@ -0,0 +1,143 @@
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
+ RAILS_DEFAULT_LOGGER.info "New Relic Agent not running"
25
+ else
26
+ RAILS_DEFAULT_LOGGER.info "Starting the New Relic Agent"
27
+ install_developer_mode rails_config if developer_mode?
28
+ end
29
+ end
30
+
31
+ def install_developer_mode(rails_config)
32
+ return if @installed
33
+ @installed = true
34
+ controller_path = File.expand_path(File.join(newrelic_root, 'ui', 'controllers'))
35
+ helper_path = File.expand_path(File.join(newrelic_root, 'ui', 'helpers'))
36
+
37
+ if defined? ActiveSupport::Dependencies
38
+ Dir["#{helper_path}/*.rb"].each { |f| require f }
39
+ Dir["#{controller_path}/*.rb"].each { |f| require f }
40
+ elsif defined? Dependencies.load_paths
41
+ Dependencies.load_paths << controller_path
42
+ Dependencies.load_paths << helper_path
43
+ else
44
+ to_stdout "ERROR: Rails version #{Rails::VERSION::STRING} too old for developer mode to work."
45
+ return
46
+ end
47
+ install_devmode_route
48
+
49
+ # If we have the config object then add the controller path to the list.
50
+ # Otherwise we have to assume the controller paths have already been
51
+ # set and we can just append newrelic.
52
+
53
+ if rails_config
54
+ rails_config.controller_paths << controller_path
55
+ else
56
+ current_paths = ActionController::Routing.controller_paths
57
+ if current_paths.nil? || current_paths.empty?
58
+ to_stdout "WARNING: Unable to modify the routes in this version of Rails. Developer mode not available."
59
+ end
60
+ current_paths << controller_path
61
+ end
62
+
63
+ #ActionController::Routing::Routes.reload! unless NewRelic::Control.instance['skip_developer_route']
64
+
65
+ # inform user that the dev edition is available if we are running inside
66
+ # a webserver process
67
+ if @local_env.dispatcher_instance_id
68
+ port = @local_env.dispatcher_instance_id.to_s =~ /^\d+/ ? ":#{local_env.dispatcher_instance_id}" : ":port"
69
+ to_stdout "NewRelic Agent Developer Mode enabled."
70
+ to_stdout "To view performance information, go to http://localhost#{port}/newrelic"
71
+ end
72
+ end
73
+
74
+ def rails_version
75
+ @rails_version ||= NewRelic::VersionNumber.new(::Rails::VERSION::STRING)
76
+ end
77
+
78
+ protected
79
+
80
+ def install_devmode_route
81
+ # This is a monkey patch to inject the developer tool route into the
82
+ # parent app without requiring users to modify their routes. Of course this
83
+ # has the effect of adding a route indiscriminately which is frowned upon by
84
+ # some: http://www.ruby-forum.com/topic/126316#563328
85
+ ActionController::Routing::RouteSet.class_eval do
86
+ next if self.instance_methods.include? 'draw_with_newrelic_map'
87
+ def draw_with_newrelic_map
88
+ draw_without_newrelic_map do | map |
89
+ unless NewRelic::Control.instance['skip_developer_route']
90
+ map.named_route 'newrelic_developer', '/newrelic/:action/:id', :controller => 'newrelic'
91
+ map.named_route 'newrelic_file', '/newrelic/file/*file', :controller => 'newrelic', :action=>'file'
92
+ end
93
+ yield map
94
+ end
95
+ end
96
+ alias_method_chain :draw, :newrelic_map
97
+ end
98
+ end
99
+
100
+ def rails_vendor_root
101
+ File.join(root,'vendor','rails')
102
+ end
103
+
104
+ # Collect the Rails::Info into an associative array as well as the list of plugins
105
+ def append_environment_info
106
+ local_env.append_environment_value('Rails version'){ ::Rails::VERSION::STRING }
107
+ if rails_version >= NewRelic::VersionNumber.new('2.2.0')
108
+ local_env.append_environment_value('Rails threadsafe') do
109
+ ::Rails.configuration.action_controller.allow_concurrency == true
110
+ end
111
+ end
112
+ local_env.append_environment_value('Rails Env') { ENV['RAILS_ENV'] }
113
+ if rails_version >= NewRelic::VersionNumber.new('2.1.0')
114
+ local_env.append_gem_list do
115
+ ::Rails.configuration.gems.map do | gem |
116
+ version = (gem.respond_to?(:version) && gem.version) ||
117
+ (gem.specification.respond_to?(:version) && gem.specification.version)
118
+ gem.name + (version ? "(#{version})" : "")
119
+ end
120
+ end
121
+ # The plugins is configured manually. If it's nil, it loads everything non-deterministically
122
+ if ::Rails.configuration.plugins
123
+ local_env.append_plugin_list { ::Rails.configuration.plugins }
124
+ else
125
+ ::Rails.configuration.plugin_paths.each do |path|
126
+ local_env.append_plugin_list { Dir[File.join(path, '*')].collect{ |p| File.basename p if File.directory? p }.compact }
127
+ end
128
+ end
129
+ else
130
+ # Rails prior to 2.1, can't get the gems. Find plugins in the default location
131
+ local_env.append_plugin_list do
132
+ Dir[File.join(root, 'vendor', 'plugins', '*')].collect{ |p| File.basename p if File.directory? p }.compact
133
+ end
134
+ end
135
+ end
136
+
137
+ def install_shim
138
+ super
139
+ require 'new_relic/agent/instrumentation/controller_instrumentation'
140
+ ActionController::Base.send :include, NewRelic::Agent::Instrumentation::ControllerInstrumentation::Shim
141
+ end
142
+
143
+ end
@@ -0,0 +1,34 @@
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
+ files << File.join(ENV["HOME"], ".newrelic", "newrelic.yml")
20
+ files << File.join(ENV["HOME"], "newrelic.yml")
21
+ files << File.expand_path(ENV["NRCONFIG"]) if ENV["NRCONFIG"]
22
+ files.each do | file |
23
+ return File.expand_path(file) if File.exists? file
24
+ end
25
+ return File.expand_path(files.first)
26
+ end
27
+ def to_stdout(msg)
28
+ STDOUT.puts msg
29
+ end
30
+
31
+ def init_config(options={})
32
+ end
33
+
34
+ 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
+ @stats ||= 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,285 @@
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 platform') { RUBY_PLATFORM }
77
+ append_environment_value('Ruby patchlevel') { RUBY_PATCHLEVEL }
78
+ if defined? ::JRUBY_VERSION
79
+ append_environment_value('JRuby version') { JRUBY_VERSION }
80
+ append_environment_value('Java VM version') { ENV_JAVA['java.vm.version']}
81
+ end
82
+ append_environment_value('OS version') { `uname -v` }
83
+ append_environment_value('OS') { `uname -s` } ||
84
+ append_environment_value('OS') { ENV['OS'] }
85
+ append_environment_value('Arch') { `uname -p` } ||
86
+ append_environment_value('Arch') { ENV['PROCESSOR_ARCHITECTURE'] }
87
+ # See what the number of cpus is, works only on linux.
88
+ @processors = append_environment_value('Processors') do
89
+ processors = File.readlines('/proc/cpuinfo').select { |line| line =~ /^processor\s*:/ }.size
90
+ raise "Cannot determine the number of processors in /proc/cpuinfo" unless processors > 0
91
+ processors
92
+ end if File.readable? '/proc/cpuinfo'
93
+ # The current Rails environment (development, test, or production).
94
+ append_environment_value('Environment') { NewRelic::Control.instance.env }
95
+ # Look for a capistrano file indicating the current revision:
96
+ rev_file = File.join(NewRelic::Control.instance.root, "REVISION")
97
+ if File.readable?(rev_file) && File.size(rev_file) < 64
98
+ append_environment_value('Revision') do
99
+ File.open(rev_file) { | file | file.readline.strip }
100
+ end
101
+ end
102
+ # The name of the database adapter for the current environment.
103
+ if defined? ActiveRecord
104
+ append_environment_value 'Database adapter' do
105
+ ActiveRecord::Base.configurations[RAILS_ENV]['adapter']
106
+ end
107
+ append_environment_value 'Database schema version' do
108
+ ActiveRecord::Migrator.current_version
109
+ end
110
+ end
111
+ if defined? DataMapper
112
+ append_environment_value 'DataMapper version' do
113
+ require 'dm-core/version'
114
+ DataMapper::VERSION
115
+ end
116
+ end
117
+ end
118
+ # Take a snapshot of the environment information for this application
119
+ # Returns an associative array
120
+ def snapshot
121
+ i = @config.to_a
122
+ i << [ 'Plugin List', @plugins.to_a] if not @plugins.empty?
123
+ i << [ 'Gems', @gems.to_a] if not @gems.empty?
124
+ i
125
+ end
126
+
127
+ def mongrel
128
+ return @mongrel if @mongrel || ! defined? Mongrel::HttpServer
129
+ ObjectSpace.each_object(Mongrel::HttpServer) do |mongrel|
130
+ @mongrel = mongrel
131
+ end unless defined?(JRuby) && !JRuby.runtime.is_object_space_enabled
132
+ @mongrel
133
+ end
134
+
135
+ def unicorn
136
+ return @unicorn if @unicorn || ! defined? Unicorn::HttpServer
137
+ ObjectSpace.each_object(Unicorn::HttpServer) do |unicorn|
138
+ @unicorn = unicorn
139
+ end unless defined?(JRuby) && !JRuby.runtime.is_object_space_enabled
140
+ @unicorn
141
+ end
142
+
143
+ private
144
+
145
+ # Although you can override the framework with NEWRELIC_DISPATCHER this
146
+ # is not advisable since it implies certain api's being available.
147
+ def discover_dispatcher
148
+ @dispatcher = ENV['NEWRELIC_DISPATCHER'] && ENV['NEWRELIC_DISPATCHER'].to_sym
149
+ dispatchers = %w[passenger glassfish thin mongrel litespeed webrick fastcgi unicorn sinatra]
150
+ while dispatchers.any? && @dispatcher.nil?
151
+ send 'check_for_'+(dispatchers.shift)
152
+ end
153
+ end
154
+
155
+ def discover_framework
156
+ # Although you can override the framework with NEWRELIC_FRAMEWORK this
157
+ # is not advisable since it implies certain api's being available.
158
+ @framework = case
159
+ when ENV['NEWRELIC_FRAMEWORK'] then ENV['NEWRELIC_FRAMEWORK'].to_sym
160
+ when defined? NewRelic::TEST then :test
161
+ when defined? Merb::Plugins then :merb
162
+ when defined? Rails then :rails
163
+ when defined? Sinatra::Base then :sinatra
164
+ when defined? NewRelic::IA then :external
165
+ else :ruby
166
+ end
167
+ end
168
+
169
+ def check_for_glassfish
170
+ return unless defined?(::Java) &&
171
+ (((com.sun.grizzly.jruby.rack.DefaultRackApplicationFactory rescue nil) &&
172
+ defined?(com::sun::grizzly::jruby::rack::DefaultRackApplicationFactory)) ||
173
+ ((org.jruby.rack.DefaultRackApplicationFactory rescue nil) &&
174
+ defined?(org::jruby::rack::DefaultRackApplicationFactory)))
175
+ @dispatcher = :glassfish
176
+ end
177
+
178
+ def check_for_webrick
179
+ return unless defined?(WEBrick::VERSION)
180
+ @dispatcher = :webrick
181
+ if defined?(OPTIONS) && OPTIONS.respond_to?(:fetch)
182
+ # OPTIONS is set by script/server
183
+ @dispatcher_instance_id = OPTIONS.fetch(:port)
184
+ end
185
+ @dispatcher_instance_id = default_port unless @dispatcher_instance_id
186
+ end
187
+
188
+ def check_for_fastcgi
189
+ return unless defined? FCGI
190
+ @dispatcher = :fastcgi
191
+ end
192
+
193
+ # this case covers starting by mongrel_rails
194
+ def check_for_mongrel
195
+ return unless defined?(Mongrel::HttpServer)
196
+ @dispatcher = :mongrel
197
+
198
+ # Get the port from the server if it's started
199
+
200
+ if mongrel && mongrel.respond_to?(:port)
201
+ @dispatcher_instance_id = mongrel.port.to_s
202
+ end
203
+
204
+ # Get the port from the configurator if one was created
205
+ if @dispatcher_instance_id.nil? && defined?(Mongrel::Configurator)
206
+ ObjectSpace.each_object(Mongrel::Configurator) do |mongrel|
207
+ @dispatcher_instance_id = mongrel.defaults[:port] && mongrel.defaults[:port].to_s
208
+ end unless defined?(JRuby) && !JRuby.runtime.is_object_space_enabled
209
+ end
210
+
211
+ # Still can't find the port. Let's look at ARGV to fall back
212
+ @dispatcher_instance_id = default_port if @dispatcher_instance_id.nil?
213
+ end
214
+
215
+ def check_for_unicorn
216
+ return unless defined?(Unicorn::HttpServer)
217
+
218
+ # unlike mongrel, unicorn manages muliple threads and ports, so we
219
+ # have to map multiple processes into one instance, as we do with passenger
220
+ @dispatcher = :unicorn
221
+ end
222
+
223
+ def check_for_sinatra
224
+ return unless defined?(Sinatra::Base)
225
+ @dispatcher = :sinatra
226
+ end
227
+
228
+ def check_for_thin
229
+ if defined? Thin::Server
230
+ # This case covers the thin web dispatcher
231
+ # Same issue as above- we assume only one instance per process
232
+ ObjectSpace.each_object(Thin::Server) do |thin_dispatcher|
233
+ @dispatcher = :thin
234
+ backend = thin_dispatcher.backend
235
+ # We need a way to uniquely identify and distinguish agents. The port
236
+ # works for this. When using sockets, use the socket file name.
237
+ if backend.respond_to? :port
238
+ @dispatcher_instance_id = backend.port
239
+ elsif backend.respond_to? :socket
240
+ @dispatcher_instance_id = backend.socket
241
+ else
242
+ raise "Unknown thin backend: #{backend}"
243
+ end
244
+ end # each thin instance
245
+ end
246
+ if defined?(Thin::VERSION) && !@dispatcher
247
+ @dispatcher = :thin
248
+ @dispatcher_instance_id = default_port
249
+ end
250
+ end
251
+
252
+ def check_for_litespeed
253
+ if caller.pop =~ /fcgi-bin\/RailsRunner\.rb/
254
+ @dispatcher = :litespeed
255
+ end
256
+ end
257
+
258
+ def check_for_passenger
259
+ if defined?(Passenger::AbstractServer) || defined?(IN_PHUSION_PASSENGER)
260
+ @dispatcher = :passenger
261
+ end
262
+ end
263
+
264
+ def default_port
265
+ require 'optparse'
266
+ # If nothing else is found, use the 3000 default
267
+ default_port = 3000
268
+ OptionParser.new do |opts|
269
+ opts.on("-p", "--port=port", String) { | p | default_port = p }
270
+ opts.parse(ARGV.clone) rescue nil
271
+ end
272
+ default_port
273
+ end
274
+
275
+ public
276
+ def to_s
277
+ s = "LocalEnvironment["
278
+ s << @framework.to_s
279
+ s << ";dispatcher=#{@dispatcher}" if @dispatcher
280
+ s << ";instance=#{@dispatcher_instance_id}" if @dispatcher_instance_id
281
+ s << "]"
282
+ end
283
+
284
+ end
285
+ end