honkster-newrelic_rpm 2.13.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (174) hide show
  1. data/CHANGELOG +462 -0
  2. data/LICENSE +37 -0
  3. data/README.rdoc +172 -0
  4. data/bin/mongrel_rpm +33 -0
  5. data/bin/newrelic +13 -0
  6. data/bin/newrelic_cmd +5 -0
  7. data/cert/cacert.pem +34 -0
  8. data/install.rb +9 -0
  9. data/lib/new_relic/agent.rb +382 -0
  10. data/lib/new_relic/agent/agent.rb +741 -0
  11. data/lib/new_relic/agent/busy_calculator.rb +91 -0
  12. data/lib/new_relic/agent/chained_call.rb +13 -0
  13. data/lib/new_relic/agent/error_collector.rb +131 -0
  14. data/lib/new_relic/agent/instrumentation/active_merchant.rb +18 -0
  15. data/lib/new_relic/agent/instrumentation/active_record_instrumentation.rb +92 -0
  16. data/lib/new_relic/agent/instrumentation/acts_as_solr.rb +45 -0
  17. data/lib/new_relic/agent/instrumentation/authlogic.rb +8 -0
  18. data/lib/new_relic/agent/instrumentation/controller_instrumentation.rb +409 -0
  19. data/lib/new_relic/agent/instrumentation/data_mapper.rb +58 -0
  20. data/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb +22 -0
  21. data/lib/new_relic/agent/instrumentation/memcache.rb +40 -0
  22. data/lib/new_relic/agent/instrumentation/merb/controller.rb +26 -0
  23. data/lib/new_relic/agent/instrumentation/merb/errors.rb +9 -0
  24. data/lib/new_relic/agent/instrumentation/metric_frame.rb +319 -0
  25. data/lib/new_relic/agent/instrumentation/net.rb +17 -0
  26. data/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb +22 -0
  27. data/lib/new_relic/agent/instrumentation/rack.rb +98 -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/rails3/action_controller.rb +45 -0
  32. data/lib/new_relic/agent/instrumentation/rails3/errors.rb +21 -0
  33. data/lib/new_relic/agent/instrumentation/sinatra.rb +46 -0
  34. data/lib/new_relic/agent/instrumentation/sunspot.rb +17 -0
  35. data/lib/new_relic/agent/instrumentation/unicorn_instrumentation.rb +10 -0
  36. data/lib/new_relic/agent/method_tracer.rb +350 -0
  37. data/lib/new_relic/agent/sampler.rb +50 -0
  38. data/lib/new_relic/agent/samplers/cpu_sampler.rb +54 -0
  39. data/lib/new_relic/agent/samplers/delayed_job_lock_sampler.rb +37 -0
  40. data/lib/new_relic/agent/samplers/memory_sampler.rb +142 -0
  41. data/lib/new_relic/agent/samplers/object_sampler.rb +24 -0
  42. data/lib/new_relic/agent/shim_agent.rb +25 -0
  43. data/lib/new_relic/agent/stats_engine.rb +24 -0
  44. data/lib/new_relic/agent/stats_engine/metric_stats.rb +118 -0
  45. data/lib/new_relic/agent/stats_engine/samplers.rb +83 -0
  46. data/lib/new_relic/agent/stats_engine/transactions.rb +149 -0
  47. data/lib/new_relic/agent/transaction_sampler.rb +330 -0
  48. data/lib/new_relic/agent/worker_loop.rb +81 -0
  49. data/lib/new_relic/collection_helper.rb +71 -0
  50. data/lib/new_relic/command.rb +85 -0
  51. data/lib/new_relic/commands/deployments.rb +105 -0
  52. data/lib/new_relic/commands/install.rb +81 -0
  53. data/lib/new_relic/control.rb +203 -0
  54. data/lib/new_relic/control/configuration.rb +149 -0
  55. data/lib/new_relic/control/frameworks/external.rb +13 -0
  56. data/lib/new_relic/control/frameworks/merb.rb +24 -0
  57. data/lib/new_relic/control/frameworks/rails.rb +126 -0
  58. data/lib/new_relic/control/frameworks/rails3.rb +60 -0
  59. data/lib/new_relic/control/frameworks/ruby.rb +36 -0
  60. data/lib/new_relic/control/frameworks/sinatra.rb +18 -0
  61. data/lib/new_relic/control/instrumentation.rb +95 -0
  62. data/lib/new_relic/control/logging_methods.rb +74 -0
  63. data/lib/new_relic/control/profiling.rb +24 -0
  64. data/lib/new_relic/control/server_methods.rb +88 -0
  65. data/lib/new_relic/delayed_job_injection.rb +27 -0
  66. data/lib/new_relic/histogram.rb +91 -0
  67. data/lib/new_relic/local_environment.rb +333 -0
  68. data/lib/new_relic/merbtasks.rb +6 -0
  69. data/lib/new_relic/metric_data.rb +42 -0
  70. data/lib/new_relic/metric_parser.rb +136 -0
  71. data/lib/new_relic/metric_parser/action_mailer.rb +9 -0
  72. data/lib/new_relic/metric_parser/active_merchant.rb +26 -0
  73. data/lib/new_relic/metric_parser/active_record.rb +28 -0
  74. data/lib/new_relic/metric_parser/apdex.rb +88 -0
  75. data/lib/new_relic/metric_parser/controller.rb +62 -0
  76. data/lib/new_relic/metric_parser/controller_cpu.rb +38 -0
  77. data/lib/new_relic/metric_parser/errors.rb +6 -0
  78. data/lib/new_relic/metric_parser/external.rb +50 -0
  79. data/lib/new_relic/metric_parser/mem_cache.rb +50 -0
  80. data/lib/new_relic/metric_parser/other_transaction.rb +36 -0
  81. data/lib/new_relic/metric_parser/view.rb +61 -0
  82. data/lib/new_relic/metric_parser/web_frontend.rb +14 -0
  83. data/lib/new_relic/metric_parser/web_service.rb +9 -0
  84. data/lib/new_relic/metric_spec.rb +67 -0
  85. data/lib/new_relic/metrics.rb +9 -0
  86. data/lib/new_relic/noticed_error.rb +24 -0
  87. data/lib/new_relic/rack/developer_mode.rb +257 -0
  88. data/lib/new_relic/rack/metric_app.rb +64 -0
  89. data/lib/new_relic/rack/mongrel_rpm.ru +26 -0
  90. data/lib/new_relic/rack/newrelic.yml +27 -0
  91. data/lib/new_relic/rack_app.rb +6 -0
  92. data/lib/new_relic/recipes.rb +82 -0
  93. data/lib/new_relic/stats.rb +368 -0
  94. data/lib/new_relic/timer_lib.rb +27 -0
  95. data/lib/new_relic/transaction_analysis.rb +119 -0
  96. data/lib/new_relic/transaction_sample.rb +586 -0
  97. data/lib/new_relic/url_rule.rb +14 -0
  98. data/lib/new_relic/version.rb +55 -0
  99. data/lib/new_relic_api.rb +276 -0
  100. data/lib/newrelic_rpm.rb +49 -0
  101. data/lib/tasks/all.rb +4 -0
  102. data/lib/tasks/install.rake +7 -0
  103. data/lib/tasks/tests.rake +15 -0
  104. data/newrelic.yml +246 -0
  105. data/newrelic_rpm.gemspec +254 -0
  106. data/recipes/newrelic.rb +6 -0
  107. data/test/active_record_fixtures.rb +55 -0
  108. data/test/config/newrelic.yml +48 -0
  109. data/test/config/test_control.rb +36 -0
  110. data/test/new_relic/agent/active_record_instrumentation_test.rb +286 -0
  111. data/test/new_relic/agent/agent_controller_test.rb +294 -0
  112. data/test/new_relic/agent/agent_test_controller.rb +77 -0
  113. data/test/new_relic/agent/busy_calculator_test.rb +81 -0
  114. data/test/new_relic/agent/collection_helper_test.rb +125 -0
  115. data/test/new_relic/agent/error_collector_test.rb +163 -0
  116. data/test/new_relic/agent/memcache_instrumentation_test.rb +103 -0
  117. data/test/new_relic/agent/method_tracer_test.rb +340 -0
  118. data/test/new_relic/agent/metric_data_test.rb +53 -0
  119. data/test/new_relic/agent/metric_frame_test.rb +51 -0
  120. data/test/new_relic/agent/mock_scope_listener.rb +23 -0
  121. data/test/new_relic/agent/net_instrumentation_test.rb +77 -0
  122. data/test/new_relic/agent/rpm_agent_test.rb +142 -0
  123. data/test/new_relic/agent/stats_engine/metric_stats_test.rb +79 -0
  124. data/test/new_relic/agent/stats_engine/samplers_test.rb +72 -0
  125. data/test/new_relic/agent/stats_engine/stats_engine_test.rb +184 -0
  126. data/test/new_relic/agent/task_instrumentation_test.rb +188 -0
  127. data/test/new_relic/agent/testable_agent.rb +13 -0
  128. data/test/new_relic/agent/transaction_sample_builder_test.rb +195 -0
  129. data/test/new_relic/agent/transaction_sample_test.rb +192 -0
  130. data/test/new_relic/agent/transaction_sampler_test.rb +385 -0
  131. data/test/new_relic/agent/worker_loop_test.rb +66 -0
  132. data/test/new_relic/control_test.rb +127 -0
  133. data/test/new_relic/deployments_api_test.rb +69 -0
  134. data/test/new_relic/environment_test.rb +75 -0
  135. data/test/new_relic/metric_parser_test.rb +226 -0
  136. data/test/new_relic/metric_spec_test.rb +177 -0
  137. data/test/new_relic/rack/episodes_test.rb +318 -0
  138. data/test/new_relic/shim_agent_test.rb +9 -0
  139. data/test/new_relic/stats_test.rb +312 -0
  140. data/test/new_relic/version_number_test.rb +89 -0
  141. data/test/test_contexts.rb +28 -0
  142. data/test/test_helper.rb +72 -0
  143. data/ui/helpers/developer_mode_helper.rb +359 -0
  144. data/ui/helpers/google_pie_chart.rb +49 -0
  145. data/ui/views/layouts/newrelic_default.rhtml +47 -0
  146. data/ui/views/newrelic/_explain_plans.rhtml +27 -0
  147. data/ui/views/newrelic/_sample.rhtml +20 -0
  148. data/ui/views/newrelic/_segment.rhtml +29 -0
  149. data/ui/views/newrelic/_segment_limit_message.rhtml +1 -0
  150. data/ui/views/newrelic/_segment_row.rhtml +14 -0
  151. data/ui/views/newrelic/_show_sample_detail.rhtml +24 -0
  152. data/ui/views/newrelic/_show_sample_sql.rhtml +20 -0
  153. data/ui/views/newrelic/_show_sample_summary.rhtml +3 -0
  154. data/ui/views/newrelic/_sql_row.rhtml +16 -0
  155. data/ui/views/newrelic/_stack_trace.rhtml +15 -0
  156. data/ui/views/newrelic/_table.rhtml +12 -0
  157. data/ui/views/newrelic/explain_sql.rhtml +43 -0
  158. data/ui/views/newrelic/file/images/arrow-close.png +0 -0
  159. data/ui/views/newrelic/file/images/arrow-open.png +0 -0
  160. data/ui/views/newrelic/file/images/blue_bar.gif +0 -0
  161. data/ui/views/newrelic/file/images/file_icon.png +0 -0
  162. data/ui/views/newrelic/file/images/gray_bar.gif +0 -0
  163. data/ui/views/newrelic/file/images/new-relic-rpm-desktop.gif +0 -0
  164. data/ui/views/newrelic/file/images/new_relic_rpm_desktop.gif +0 -0
  165. data/ui/views/newrelic/file/images/textmate.png +0 -0
  166. data/ui/views/newrelic/file/javascript/jquery-1.4.2.js +6240 -0
  167. data/ui/views/newrelic/file/javascript/transaction_sample.js +120 -0
  168. data/ui/views/newrelic/file/stylesheets/style.css +484 -0
  169. data/ui/views/newrelic/index.rhtml +59 -0
  170. data/ui/views/newrelic/sample_not_found.rhtml +2 -0
  171. data/ui/views/newrelic/show_sample.rhtml +79 -0
  172. data/ui/views/newrelic/show_source.rhtml +3 -0
  173. data/ui/views/newrelic/threads.rhtml +52 -0
  174. metadata +307 -0
@@ -0,0 +1,74 @@
1
+
2
+ module NewRelic
3
+ class Control
4
+ module LoggingMethods
5
+
6
+ attr_accessor :log_file
7
+
8
+ def log
9
+ # If we try to get a log before one has been set up, return a stdout log
10
+ unless @log
11
+ l = Logger.new(STDOUT)
12
+ l.level = Logger::INFO
13
+ return l
14
+ end
15
+ @log
16
+ end
17
+
18
+ # send the given message to STDOUT so that it shows
19
+ # up in the console. This should be used for important informational messages at boot.
20
+ # The to_stdout may be implemented differently by different config subclasses.
21
+ # This will NOT print anything if tracers are not enabled
22
+ def log!(msg, level=:info)
23
+ return unless should_log?
24
+ to_stdout msg
25
+ log.send level, msg if @log
26
+ end
27
+
28
+ def should_log?
29
+ @settings && agent_enabled?
30
+ end
31
+
32
+ # Control subclasses may override this, but it can be called multiple times.
33
+ def setup_log
34
+ @log_file = "#{log_path}/#{log_file_name}"
35
+ @log = Logger.new(@log_file) rescue nil
36
+
37
+ # change the format just for our logger
38
+
39
+ def log.format_message(severity, timestamp, progname, msg)
40
+ "[#{timestamp.strftime("%m/%d/%y %H:%M:%S %z")} #{Socket.gethostname} (#{$$})] #{severity} : #{msg}\n"
41
+ end
42
+
43
+ # set the log level as specified in the config file
44
+
45
+ case fetch("log_level","info").downcase
46
+ when "debug" then log.level = Logger::DEBUG
47
+ when "info" then log.level = Logger::INFO
48
+ when "warn" then log.level = Logger::WARN
49
+ when "error" then log.level = Logger::ERROR
50
+ when "fatal" then log.level = Logger::FATAL
51
+ else log.level = Logger::INFO
52
+ end
53
+ log
54
+ end
55
+
56
+ def to_stdout(msg)
57
+ STDOUT.puts "** [NewRelic] " + msg
58
+ end
59
+
60
+ def log_path
61
+ return if @log_path
62
+ @log_path = File.expand_path(fetch('log_file_path', 'log/'))
63
+ if !File.directory?(@log_path) && ! (Dir.mkdir(@log_path) rescue nil)
64
+ log!("Error creating New Relic log directory '#{@log_path}'", :error)
65
+ end
66
+ @log_path
67
+ end
68
+
69
+ def log_file_name
70
+ fetch('log_file_name', 'newrelic_agent.log')
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,24 @@
1
+ module NewRelic
2
+ class Control
3
+ module Profiling
4
+
5
+ # A flag used in dev mode to indicate if profiling is available
6
+ def profiling?
7
+ @profiling
8
+ end
9
+
10
+ def profiling_available?
11
+ @profiling_available ||=
12
+ begin
13
+ require 'ruby-prof'
14
+ true
15
+ rescue LoadError; end
16
+ end
17
+ # Set the flag for capturing profiles in dev mode. If RubyProf is not
18
+ # loaded a true value is ignored.
19
+ def profiling=(val)
20
+ @profiling = profiling_available? && val && defined?(RubyProf)
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,88 @@
1
+ module NewRelic
2
+ class Control
3
+
4
+ # Structs holding info for the remote server and proxy server
5
+ class Server < Struct.new :name, :port, :ip #:nodoc:
6
+ def to_s; "#{name}:#{port}"; end
7
+ end
8
+
9
+ ProxyServer = Struct.new :name, :port, :user, :password #:nodoc:
10
+
11
+ module ServerMethods
12
+
13
+ def server
14
+ @remote_server ||= server_from_host(nil)
15
+ end
16
+
17
+ def api_server
18
+ api_host = self['api_host'] || 'rpm.newrelic.com'
19
+ @api_server ||=
20
+ NewRelic::Control::Server.new \
21
+ api_host,
22
+ (self['api_port'] || self['port'] || (use_ssl? ? 443 : 80)).to_i,
23
+ nil
24
+ end
25
+
26
+ def proxy_server
27
+ @proxy_server ||=
28
+ NewRelic::Control::ProxyServer.new self['proxy_host'], self['proxy_port'], self['proxy_user'], self['proxy_pass']
29
+ end
30
+
31
+ def server_from_host(hostname=nil)
32
+ host = hostname || self['host'] || 'collector.newrelic.com'
33
+
34
+ # if the host is not an IP address, turn it into one
35
+ NewRelic::Control::Server.new host, (self['port'] || (use_ssl? ? 443 : 80)).to_i, convert_to_ip_address(host)
36
+ end
37
+
38
+ # Look up the ip address of the host using the pure ruby lookup
39
+ # to prevent blocking. If that fails, fall back to the regular
40
+ # IPSocket library. Return nil if we can't find the host ip
41
+ # address and don't have a good default.
42
+ def convert_to_ip_address(host)
43
+ # here we leave it as a host name since the cert verification
44
+ # needs it in host form
45
+ return host if verify_certificate?
46
+ return nil if host.nil? || host.downcase == "localhost"
47
+ # Fall back to known ip address in the common case
48
+ ip_address = '65.74.177.195' if host.downcase == 'collector.newrelic.com'
49
+ begin
50
+ ip_address = Resolv.getaddress(host)
51
+ log.info "Resolved #{host} to #{ip_address}"
52
+ rescue => e
53
+ log.warn "DNS Error caching IP address: #{e}"
54
+ log.debug e.backtrace.join("\n ")
55
+ ip_address = IPSocket::getaddress host rescue ip_address
56
+ end
57
+ ip_address
58
+ end
59
+
60
+ # Return the Net::HTTP with proxy configuration given the NewRelic::Control::Server object.
61
+ # Default is the collector but for api calls you need to pass api_server
62
+ #
63
+ # Experimental support for SSL verification:
64
+ # swap 'VERIFY_NONE' for 'VERIFY_PEER' line to try it out
65
+ # If verification fails, uncomment the 'http.ca_file' line
66
+ # and it will use the included certificate.
67
+ def http_connection(host = nil)
68
+ host ||= server
69
+ # Proxy returns regular HTTP if @proxy_host is nil (the default)
70
+ http_class = Net::HTTP::Proxy(proxy_server.name, proxy_server.port,
71
+ proxy_server.user, proxy_server.password)
72
+ http = http_class.new(host.ip || host.name, host.port)
73
+ log.debug("Http Connection opened to #{host.ip||host.name}:#{host.port}")
74
+ if use_ssl?
75
+ http.use_ssl = true
76
+ if verify_certificate?
77
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
78
+ http.ca_file = File.join(File.dirname(__FILE__), '..', '..', 'cert', 'cacert.pem')
79
+ else
80
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
81
+ end
82
+ end
83
+ http
84
+ end
85
+ end
86
+ end
87
+ end
88
+
@@ -0,0 +1,27 @@
1
+ # This installs some code to manually start the agent when a delayed job worker starts.
2
+ # It's not really instrumentation. It's more like a hook from DJ to RPM so it gets
3
+ # loaded at the time the RPM plugin initializes, which must be before the DJ worker
4
+ # initializes. Loaded from control.rb
5
+ module NewRelic
6
+ module DelayedJobInjection
7
+ extend self
8
+ attr_accessor :worker_name
9
+ end
10
+ end
11
+
12
+ Delayed::Worker.class_eval do
13
+ def initialize_with_new_relic(*args)
14
+ initialize_without_new_relic(*args)
15
+ worker_name = case
16
+ when self.respond_to?(:name) then self.name
17
+ when self.class.respond_to?(:default_name) then self.class.default_name
18
+ end
19
+ dispatcher_instance_id = worker_name || "host:#{Socket.gethostname} pid:#{Process.pid}" rescue "pid:#{Process.pid}"
20
+ say "RPM Monitoring DJ worker #{dispatcher_instance_id}"
21
+ NewRelic::DelayedJobInjection.worker_name = worker_name
22
+ NewRelic::Agent.manual_start :dispatcher => :delayed_job, :dispatcher_instance_id => dispatcher_instance_id
23
+ end
24
+
25
+ alias initialize_without_new_relic initialize
26
+ alias initialize initialize_with_new_relic
27
+ end if defined?(::Delayed::Worker) and not NewRelic::Control.instance['disable_dj']
@@ -0,0 +1,91 @@
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
+ module NewRelic
9
+ class Histogram
10
+
11
+ # Used to stub out API methods when the agent is not enabled
12
+ module Shim
13
+ def process(response_time); end
14
+ end
15
+ # Stores statistics for response times falling in a particular range.
16
+ # A bucket has a min and max response time. A response time event
17
+ # falls in a bucket if min <= r/t < max. A bucket also
18
+ # has an associated metric for reporting data to RPM. The
19
+ # bucket range is encoded in the metic name
20
+ class Bucket
21
+
22
+ attr_reader :min, :max, :stats
23
+
24
+ def initialize(min, max = nil)
25
+ @min = min
26
+ @max = max
27
+ end
28
+
29
+ def stats
30
+ NewRelic::Agent.get_stats("Response Times/#{min_millis}/#{max_millis}")
31
+ end
32
+
33
+ # This has return value like <=> but does something more
34
+ # than simply compare. If the value falls within range for
35
+ # the bucket, increment count and return 0; otherwise return
36
+ # a value < 0 if the value belongs in a bucket with a lower range
37
+ # you can guess what it returns if the value belongs in a bucket
38
+ # with a higher range. (Hint: it's not 0, and it's not less than zero.)
39
+ def process(value)
40
+ if value < min
41
+ return -1
42
+
43
+ # max == nil means unlimited max (last bucket)
44
+ elsif max && value >= max
45
+ return 1
46
+
47
+ else
48
+ stats.record_data_point(value)
49
+ return 0
50
+ end
51
+ end
52
+
53
+ def min_millis
54
+ (min * 1000).round
55
+ end
56
+
57
+ def max_millis
58
+ max.nil? ? nil : (max * 1000).round
59
+ end
60
+
61
+ def to_s
62
+ "#{min_millis} - #{max_millis}: #{stats.call_count}"
63
+ end
64
+ end
65
+
66
+ attr_reader :buckets
67
+
68
+ # Histogram uses apdex T / 10 as its minimum bucket size, and grows from there.
69
+ # 30 data points should be adequate resolution.
70
+ def initialize(first_bucket_max = 0.010, bucket_count = 30, multiplier = 1.3)
71
+ @buckets = []
72
+
73
+ min = 0
74
+ max = first_bucket_max
75
+
76
+ (bucket_count - 1).times do
77
+ @buckets << Bucket.new(min, max)
78
+ min = max
79
+ max *= multiplier
80
+ end
81
+ @buckets << Bucket.new(max)
82
+ end
83
+
84
+ def process(response_time)
85
+ buckets.each do |bucket|
86
+ found = bucket.process(response_time)
87
+ return if found == 0
88
+ end
89
+ end
90
+ end
91
+ end
@@ -0,0 +1,333 @@
1
+ require 'set'
2
+ require 'new_relic/version'
3
+
4
+ module NewRelic
5
+ # An instance of LocalEnvironment is responsible for determining
6
+ # three things:
7
+ #
8
+ # * Framework - :rails, :rails3, :merb, :ruby, :external, :test
9
+ # * Dispatcher - A supported dispatcher, or nil (:mongrel, :thin, :passenger, :webrick, etc)
10
+ # * Dispatcher Instance ID, which distinguishes agents on a single host from each other
11
+ #
12
+ # If the environment can't be determined, it will be set to
13
+ # nil and dispatcher_instance_id will have nil.
14
+ #
15
+ # NewRelic::LocalEnvironment should be accessed through NewRelic::Control#env (via the NewRelic::Control singleton).
16
+ class LocalEnvironment
17
+
18
+ attr_accessor :dispatcher # mongrel, thin, webrick, or possibly nil
19
+ attr_accessor :dispatcher_instance_id # used to distinguish instances of a dispatcher from each other, may be nil
20
+ attr_accessor :framework # rails, rails3, merb, external, ruby, test
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
+ # Extend self with any any submodules of LocalEnvironment. These can override
27
+ # the discover methods to discover new framworks and dispatchers.
28
+ NewRelic::LocalEnvironment.constants.each do | const |
29
+ mod = NewRelic::LocalEnvironment.const_get const
30
+ self.extend mod if mod.instance_of? Module
31
+ end
32
+
33
+ discover_framework
34
+ discover_dispatcher
35
+ @dispatcher = nil if @dispatcher == :none
36
+ @gems = Set.new
37
+ @plugins = Set.new
38
+ @config = Hash.new
39
+ end
40
+
41
+ # Add the given key/value pair to the app environment
42
+ # settings. Must pass either a value or a block. Block
43
+ # is called to get the value and any raised errors are
44
+ # silently ignored.
45
+ def append_environment_value name, value = nil
46
+ value = yield if block_given?
47
+ @config[name] = value if value
48
+ rescue Exception
49
+ # puts "#{e}\n #{e.backtrace.join("\n ")}"
50
+ raise if @framework == :test
51
+ end
52
+
53
+ def append_gem_list
54
+ @gems += yield
55
+ rescue Exception => e
56
+ # puts "#{e}\n #{e.backtrace.join("\n ")}"
57
+ raise if @framework == :test
58
+ end
59
+
60
+ def append_plugin_list
61
+ @plugins += yield
62
+ rescue Exception
63
+ # puts "#{e}\n #{e.backtrace.join("\n ")}"
64
+ raise if @framework == :test
65
+ end
66
+
67
+ def dispatcher_instance_id
68
+ if @dispatcher_instance_id.nil?
69
+ if @dispatcher.nil?
70
+ @dispatcher_instance_id = File.basename($0).split(".").first
71
+ end
72
+ end
73
+ @dispatcher_instance_id
74
+ end
75
+
76
+ # Collect base statistics about the environment and record them for
77
+ # comparison and change detection.
78
+ def gather_environment_info
79
+ append_environment_value 'Framework', @framework.to_s
80
+ append_environment_value 'Dispatcher', @dispatcher.to_s if @dispatcher
81
+ append_environment_value 'Dispatcher instance id', @dispatcher_instance_id if @dispatcher_instance_id
82
+ # This just creates a lot of keys
83
+ # append_environment_value('Application root') { File.expand_path(NewRelic::Control.instance.root) }
84
+ append_environment_value('Ruby version'){ RUBY_VERSION }
85
+ append_environment_value('Ruby description'){ RUBY_DESCRIPTION } if defined? ::RUBY_DESCRIPTION
86
+ append_environment_value('Ruby platform') { RUBY_PLATFORM }
87
+ append_environment_value('Ruby patchlevel') { RUBY_PATCHLEVEL }
88
+ if defined? ::JRUBY_VERSION
89
+ append_environment_value('JRuby version') { JRUBY_VERSION }
90
+ append_environment_value('Java VM version') { ENV_JAVA['java.vm.version']}
91
+ end
92
+ append_environment_value('OS version') { `uname -v` }
93
+ append_environment_value('OS') { `uname -s` } ||
94
+ append_environment_value('OS') { ENV['OS'] }
95
+ append_environment_value('Arch') { `uname -p` } ||
96
+ append_environment_value('Arch') { ENV['PROCESSOR_ARCHITECTURE'] }
97
+ # See what the number of cpus is, works only on linux.
98
+ @processors = append_environment_value('Processors') do
99
+ processors = File.readlines('/proc/cpuinfo').select { |line| line =~ /^processor\s*:/ }.size
100
+ raise "Cannot determine the number of processors in /proc/cpuinfo" unless processors > 0
101
+ processors
102
+ end if File.readable? '/proc/cpuinfo'
103
+ # The current Rails environment (development, test, or production).
104
+ append_environment_value('Environment') { NewRelic::Control.instance.env }
105
+ # Look for a capistrano file indicating the current revision:
106
+ rev_file = File.join(NewRelic::Control.instance.root, "REVISION")
107
+ if File.readable?(rev_file) && File.size(rev_file) < 64
108
+ append_environment_value('Revision') do
109
+ File.open(rev_file) { | file | file.readline.strip }
110
+ end
111
+ end
112
+ # The name of the database adapter for the current environment.
113
+ if defined? ::ActiveRecord
114
+ append_environment_value 'Database adapter' do
115
+ ActiveRecord::Base.configurations[RAILS_ENV]['adapter']
116
+ end
117
+ append_environment_value 'Database schema version' do
118
+ ActiveRecord::Migrator.current_version
119
+ end
120
+ end
121
+ if defined? ::DataMapper
122
+ append_environment_value 'DataMapper version' do
123
+ require 'dm-core/version'
124
+ DataMapper::VERSION
125
+ end
126
+ end
127
+ end
128
+ # Take a snapshot of the environment information for this application
129
+ # Returns an associative array
130
+ def snapshot
131
+ i = @config.to_a
132
+ i << [ 'Plugin List', @plugins.to_a] if not @plugins.empty?
133
+ i << [ 'Gems', @gems.to_a] if not @gems.empty?
134
+ i
135
+ end
136
+
137
+ def mongrel
138
+ # Note that the odd defined? sequence is necessary to work around a bug in an older version
139
+ # of JRuby.
140
+ return @mongrel if @mongrel || ! (defined?(::Mongrel) && defined?(::Mongrel::HttpServer))
141
+ ObjectSpace.each_object(Mongrel::HttpServer) do |mongrel|
142
+ @mongrel = mongrel
143
+ end unless defined?(::JRuby) && !JRuby.runtime.is_object_space_enabled
144
+ @mongrel
145
+ end
146
+
147
+ def unicorn
148
+ return @unicorn if @unicorn || ! (defined?(::Unicorn) && defined?(::Unicorn::HttpServer))
149
+ ObjectSpace.each_object(Unicorn::HttpServer) do |unicorn|
150
+ @unicorn = unicorn
151
+ end unless defined?(::JRuby) && !JRuby.runtime.is_object_space_enabled
152
+ @unicorn
153
+ end
154
+
155
+ # Obsolete method for DelayedJob instrumentation support. Now all DJ instrumentation
156
+ # is bundled in the newrelic_rpm gem and nobody should be invoking this method.
157
+ def delayed_worker=(worker)
158
+ $stderr.puts "WARNING: obsolete call to delayed_worker=(worker). Please remove custom DJ instrumentation."
159
+ end
160
+
161
+ private
162
+
163
+ # Although you can override the framework with NEWRELIC_DISPATCHER this
164
+ # is not advisable since it implies certain api's being available.
165
+ def discover_dispatcher
166
+ @dispatcher ||= ENV['NEWRELIC_DISPATCHER'] && ENV['NEWRELIC_DISPATCHER'].to_sym
167
+ dispatchers = %w[passenger torquebox glassfish thin mongrel litespeed webrick fastcgi unicorn sinatra]
168
+ while dispatchers.any? && @dispatcher.nil?
169
+ send 'check_for_'+(dispatchers.shift)
170
+ end
171
+ end
172
+
173
+ def discover_framework
174
+ # Although you can override the framework with NEWRELIC_FRAMEWORK this
175
+ # is not advisable since it implies certain api's being available.
176
+ #
177
+ # Note that the odd defined? sequence is necessary to work around a bug in an older version
178
+ # of JRuby.
179
+ @framework ||= case
180
+ when ENV['NEWRELIC_FRAMEWORK'] then ENV['NEWRELIC_FRAMEWORK'].to_sym
181
+ when defined?(::NewRelic::TEST) then :test
182
+ when defined?(::Merb) && defined?(::Merb::Plugins) then :merb
183
+ when defined?(::Rails) then check_rails_version
184
+ when defined?(::Sinatra) && defined?(::Sinatra::Base) then :sinatra
185
+ when defined?(::NewRelic::IA) then :external
186
+ else :ruby
187
+ end
188
+ end
189
+
190
+ def check_rails_version
191
+ if Rails::VERSION::MAJOR < 3
192
+ :rails
193
+ else
194
+ :rails3
195
+ end
196
+ end
197
+
198
+ def check_for_torquebox
199
+ return unless defined?(::JRuby) &&
200
+ ( Java::OrgTorqueboxRailsWebDeployers::RailsRackDeployer rescue nil)
201
+ @dispatcher = :torquebox
202
+ end
203
+
204
+ def check_for_glassfish
205
+ return unless defined?(::JRuby) &&
206
+ (((com.sun.grizzly.jruby.rack.DefaultRackApplicationFactory rescue nil) &&
207
+ defined?(com::sun::grizzly::jruby::rack::DefaultRackApplicationFactory)) ||
208
+ ((org.jruby.rack.DefaultRackApplicationFactory rescue nil) &&
209
+ defined?(org::jruby::rack::DefaultRackApplicationFactory)) ||
210
+ defined?(::GlassFish::Server))
211
+ @dispatcher = :glassfish
212
+ end
213
+
214
+ def check_for_webrick
215
+ return unless defined?(::WEBrick) && defined?(::WEBrick::VERSION)
216
+ @dispatcher = :webrick
217
+ if defined?(::OPTIONS) && OPTIONS.respond_to?(:fetch)
218
+ # OPTIONS is set by script/server
219
+ @dispatcher_instance_id = OPTIONS.fetch(:port)
220
+ end
221
+ @dispatcher_instance_id = default_port unless @dispatcher_instance_id
222
+ end
223
+
224
+ def check_for_fastcgi
225
+ return unless defined?(::FCGI)
226
+ @dispatcher = :fastcgi
227
+ end
228
+
229
+ # this case covers starting by mongrel_rails
230
+ def check_for_mongrel
231
+ return unless defined?(::Mongrel) && defined?(::Mongrel::HttpServer)
232
+ @dispatcher = :mongrel
233
+
234
+ # Get the port from the server if it's started
235
+
236
+ if mongrel && mongrel.respond_to?(:port)
237
+ @dispatcher_instance_id = mongrel.port.to_s
238
+ end
239
+
240
+ # Get the port from the configurator if one was created
241
+ if @dispatcher_instance_id.nil? && defined?(::Mongrel::Configurator)
242
+ ObjectSpace.each_object(Mongrel::Configurator) do |mongrel|
243
+ @dispatcher_instance_id = mongrel.defaults[:port] && mongrel.defaults[:port].to_s
244
+ end unless defined?(::JRuby) && !JRuby.runtime.is_object_space_enabled
245
+ end
246
+
247
+ # Still can't find the port. Let's look at ARGV to fall back
248
+ @dispatcher_instance_id = default_port if @dispatcher_instance_id.nil?
249
+ end
250
+
251
+ def check_for_unicorn
252
+ return unless defined?(::Unicorn) && defined?(::Unicorn::HttpServer)
253
+
254
+ # unlike mongrel, unicorn manages muliple threads and ports, so we
255
+ # have to map multiple processes into one instance, as we do with passenger
256
+ @dispatcher = :unicorn
257
+ end
258
+
259
+ def check_for_sinatra
260
+ return unless defined?(::Sinatra) && defined?(::Sinatra::Base)
261
+
262
+ begin
263
+ version = ::Sinatra::VERSION
264
+ rescue
265
+ $stderr.puts("Error determining Sinatra version")
266
+ end
267
+
268
+ if ::NewRelic::VersionNumber.new('0.9.2') > version
269
+ $stderr.puts("Your Sinatra version is #{version}, we highly recommend upgrading to >=0.9.2")
270
+ end
271
+
272
+ @dispatcher = :sinatra
273
+ end
274
+
275
+ def check_for_thin
276
+ if defined?(::Thin) && defined?(::Thin::Server)
277
+ # This case covers the thin web dispatcher
278
+ # Same issue as above- we assume only one instance per process
279
+ ObjectSpace.each_object(Thin::Server) do |thin_dispatcher|
280
+ @dispatcher = :thin
281
+ backend = thin_dispatcher.backend
282
+ # We need a way to uniquely identify and distinguish agents. The port
283
+ # works for this. When using sockets, use the socket file name.
284
+ if backend.respond_to? :port
285
+ @dispatcher_instance_id = backend.port
286
+ elsif backend.respond_to? :socket
287
+ @dispatcher_instance_id = backend.socket
288
+ else
289
+ raise "Unknown thin backend: #{backend}"
290
+ end
291
+ end # each thin instance
292
+ end
293
+ if defined?(::Thin) && defined?(::Thin::VERSION) && !@dispatcher
294
+ @dispatcher = :thin
295
+ @dispatcher_instance_id = default_port
296
+ end
297
+ end
298
+
299
+ def check_for_litespeed
300
+ if caller.pop =~ /fcgi-bin\/RailsRunner\.rb/
301
+ @dispatcher = :litespeed
302
+ end
303
+ end
304
+
305
+ def check_for_passenger
306
+ if (defined?(::Passenger) && defined?(::Passenger::AbstractServer)) || defined?(::IN_PHUSION_PASSENGER)
307
+ @dispatcher = :passenger
308
+ end
309
+ end
310
+
311
+
312
+ def default_port
313
+ require 'optparse'
314
+ # If nothing else is found, use the 3000 default
315
+ default_port = 3000
316
+ OptionParser.new do |opts|
317
+ opts.on("-p", "--port=port", String) { | p | default_port = p }
318
+ opts.parse(ARGV.clone) rescue nil
319
+ end
320
+ default_port
321
+ end
322
+
323
+ public
324
+ def to_s
325
+ s = "LocalEnvironment["
326
+ s << @framework.to_s
327
+ s << ";dispatcher=#{@dispatcher}" if @dispatcher
328
+ s << ";instance=#{@dispatcher_instance_id}" if @dispatcher_instance_id
329
+ s << "]"
330
+ end
331
+
332
+ end
333
+ end