techarch-newrelic_rpm 2.10.2

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