Class: ScoutApm::Agent
- Inherits:
-
Object
- Object
- ScoutApm::Agent
- Defined in:
- lib/scout_apm/agent.rb,
lib/scout_apm/agent/logging.rb,
lib/scout_apm/agent/reporting.rb
Overview
The agent gathers performance data from a Ruby application. One Agent instance is created per-Ruby process.
Each Agent object creates a worker thread (unless monitoring is disabled or we’re forking). The worker thread wakes up every Agent#period, merges in-memory metrics w/those saved to disk, saves tshe merged data to disk, and sends it to the Scout server.
Defined Under Namespace
Constant Summary collapse
- @@instance =
see self.instance
nil
Instance Attribute Summary collapse
-
#config ⇒ Object
Returns the value of attribute config.
-
#ignored_uris ⇒ Object
readonly
Returns the value of attribute ignored_uris.
-
#layaway ⇒ Object
Returns the value of attribute layaway.
-
#log_file ⇒ Object
path to the log file.
-
#logger ⇒ Object
Returns the value of attribute logger.
-
#metric_lookup ⇒ Object
Hash used to lookup metric ids based on their name and scope.
-
#options ⇒ Object
options passed to the agent when
#start
is called. -
#process_start_time ⇒ Object
readonly
used when creating slow transactions to report how far from startup the transaction was recorded.
-
#recorder ⇒ Object
readonly
Returns the value of attribute recorder.
-
#request_histograms ⇒ Object
readonly
Histogram of the cumulative requests since the start of the process.
-
#request_histograms_by_time ⇒ Object
readonly
Histogram of the requests, distinct by reporting period (minute) { StoreReportingPeriodTimestamp => RequestHistograms }.
-
#slow_job_policy ⇒ Object
readonly
Returns the value of attribute slow_job_policy.
-
#slow_request_policy ⇒ Object
readonly
Returns the value of attribute slow_request_policy.
-
#store ⇒ Object
Accessors below are for associated classes.
Class Method Summary collapse
-
.instance(options = {}) ⇒ Object
All access to the agent is thru this class method to ensure multiple Agent instances are not initialized per-Ruby process.
Instance Method Summary collapse
- #apm_enabled? ⇒ Boolean
-
#app_server_load_hook ⇒ Object
Sends a ping to APM right away, smoothes out onboarding Collects up any relevant info (framework, app server, system time, ruby version, etc).
- #app_server_missing?(options = {}) ⇒ Boolean
- #background_job_missing?(options = {}) ⇒ Boolean
- #background_worker_running? ⇒ Boolean
- #clean_old_percentiles ⇒ Object
- #clear_recorder ⇒ Object
- #create_recorder ⇒ Object
- #environment ⇒ Object
- #exit_handler_supported? ⇒ Boolean
-
#force? ⇒ Boolean
If true, the agent will start regardless of safety checks.
-
#initialize(options = {}) ⇒ Agent
constructor
Note - this doesn’t start instruments or the worker thread.
-
#install_exit_handler ⇒ Object
at_exit, calls Agent#shutdown to wrapup metric reporting.
- #install_instrument(instrument_klass) ⇒ Object
-
#load_instruments ⇒ Object
Loads the instrumention logic.
- #preconditions_met?(options = {}) ⇒ Boolean
-
#should_load_instruments?(options = {}) ⇒ Boolean
If we want to skip the app_server_check, then we must load it.
-
#shutdown ⇒ Object
Called via an at_exit handler, it: (1) Stops the background worker (2) Stores metrics locally (forcing current-minute metrics to be written) It does not attempt to actually report metrics.
-
#start(options = {}) ⇒ Object
This is called via
ScoutApm::Agent.instance.start
when ScoutApm is required in a Ruby application. -
#start_background_worker ⇒ Object
Creates the worker thread.
-
#start_background_worker? ⇒ Boolean
The worker thread will automatically start UNLESS: * A supported application server isn’t detected (example: running via Rails console) * A supported application server is detected, but it forks.
- #start_remote_server(bind, port) ⇒ Object
- #started? ⇒ Boolean
-
#use_remote_recorder(host, port) ⇒ Object
Execute this in the child process of a remote agent.
Methods included from Reporting
#add_metric_ids, #deliver_period, #headers, #log_deliver, #process_metrics, #report_to_server, #reporter
Methods included from Logging
#apply_log_format, #default_log_path, #determine_log_destination, #init_logger, #log_file_path, #log_level, #wants_stderr?, #wants_stdout?
Constructor Details
#initialize(options = {}) ⇒ Agent
Note - this doesn’t start instruments or the worker thread. This is handled via #start
as we don’t want to start the worker thread or install instrumentation if (1) disabled for this environment (2) a worker thread shouldn’t be started (when forking).
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/scout_apm/agent.rb', line 40 def initialize( = {}) @started = false @process_start_time = Time.now @options ||= # until the agent is started, there's no recorder @recorder = nil # Start up without attempting to load a configuration file. We need to be # able to lookup configuration options like "application_root" which would # then in turn influence where the configuration file came from. # # Later in initialization, we reset @config to include the file. @config = ScoutApm::Config.without_file @slow_request_policy = ScoutApm::SlowRequestPolicy.new @slow_job_policy = ScoutApm::SlowJobPolicy.new @request_histograms = ScoutApm::RequestHistograms.new @request_histograms_by_time = Hash.new { |h, k| h[k] = ScoutApm::RequestHistograms.new } @store = ScoutApm::Store.new @layaway = ScoutApm::Layaway.new(config, environment) @metric_lookup = Hash.new @installed_instruments = [] end |
Instance Attribute Details
#config ⇒ Object
Returns the value of attribute config.
15 16 17 |
# File 'lib/scout_apm/agent.rb', line 15 def config @config end |
#ignored_uris ⇒ Object (readonly)
Returns the value of attribute ignored_uris.
23 24 25 |
# File 'lib/scout_apm/agent.rb', line 23 def ignored_uris @ignored_uris end |
#layaway ⇒ Object
Returns the value of attribute layaway.
14 15 16 |
# File 'lib/scout_apm/agent.rb', line 14 def layaway @layaway end |
#log_file ⇒ Object
path to the log file
17 18 19 |
# File 'lib/scout_apm/agent.rb', line 17 def log_file @log_file end |
#logger ⇒ Object
Returns the value of attribute logger.
16 17 18 |
# File 'lib/scout_apm/agent.rb', line 16 def logger @logger end |
#metric_lookup ⇒ Object
Hash used to lookup metric ids based on their name and scope
19 20 21 |
# File 'lib/scout_apm/agent.rb', line 19 def metric_lookup @metric_lookup end |
#options ⇒ Object
options passed to the agent when #start
is called.
18 19 20 |
# File 'lib/scout_apm/agent.rb', line 18 def @options end |
#process_start_time ⇒ Object (readonly)
used when creating slow transactions to report how far from startup the transaction was recorded.
22 23 24 |
# File 'lib/scout_apm/agent.rb', line 22 def process_start_time @process_start_time end |
#recorder ⇒ Object (readonly)
Returns the value of attribute recorder.
13 14 15 |
# File 'lib/scout_apm/agent.rb', line 13 def recorder @recorder end |
#request_histograms ⇒ Object (readonly)
Histogram of the cumulative requests since the start of the process
26 27 28 |
# File 'lib/scout_apm/agent.rb', line 26 def request_histograms @request_histograms end |
#request_histograms_by_time ⇒ Object (readonly)
Histogram of the requests, distinct by reporting period (minute) { StoreReportingPeriodTimestamp => RequestHistograms }
30 31 32 |
# File 'lib/scout_apm/agent.rb', line 30 def request_histograms_by_time @request_histograms_by_time end |
#slow_job_policy ⇒ Object (readonly)
Returns the value of attribute slow_job_policy.
21 22 23 |
# File 'lib/scout_apm/agent.rb', line 21 def slow_job_policy @slow_job_policy end |
#slow_request_policy ⇒ Object (readonly)
Returns the value of attribute slow_request_policy.
20 21 22 |
# File 'lib/scout_apm/agent.rb', line 20 def slow_request_policy @slow_request_policy end |
#store ⇒ Object
Accessors below are for associated classes
12 13 14 |
# File 'lib/scout_apm/agent.rb', line 12 def store @store end |
Class Method Details
.instance(options = {}) ⇒ Object
All access to the agent is thru this class method to ensure multiple Agent instances are not initialized per-Ruby process.
33 34 35 |
# File 'lib/scout_apm/agent.rb', line 33 def self.instance( = {}) @@instance ||= self.new() end |
Instance Method Details
#apm_enabled? ⇒ Boolean
72 73 74 |
# File 'lib/scout_apm/agent.rb', line 72 def apm_enabled? config.value('monitor') end |
#app_server_load_hook ⇒ Object
Sends a ping to APM right away, smoothes out onboarding Collects up any relevant info (framework, app server, system time, ruby version, etc)
174 175 176 |
# File 'lib/scout_apm/agent.rb', line 174 def app_server_load_hook AppServerLoad.new.run end |
#app_server_missing?(options = {}) ⇒ Boolean
345 346 347 |
# File 'lib/scout_apm/agent.rb', line 345 def app_server_missing?( = {}) !environment.app_server_integration(true).found? && ![:skip_app_server_check] end |
#background_job_missing?(options = {}) ⇒ Boolean
349 350 351 |
# File 'lib/scout_apm/agent.rb', line 349 def background_job_missing?( = {}) environment.background_job_integration.nil? && ![:skip_background_job_check] end |
#background_worker_running? ⇒ Boolean
250 251 252 253 254 255 |
# File 'lib/scout_apm/agent.rb', line 250 def background_worker_running? @background_worker_thread && @background_worker_thread.alive? && @background_worker && @background_worker.running? end |
#clean_old_percentiles ⇒ Object
282 283 284 285 286 287 |
# File 'lib/scout_apm/agent.rb', line 282 def clean_old_percentiles request_histograms_by_time. keys. select {|| .age_in_seconds > 60 * 10 }. each {|| request_histograms_by_time.delete() } end |
#clear_recorder ⇒ Object
353 354 355 |
# File 'lib/scout_apm/agent.rb', line 353 def clear_recorder @recorder = nil end |
#create_recorder ⇒ Object
357 358 359 360 361 362 363 364 365 366 367 368 369 |
# File 'lib/scout_apm/agent.rb', line 357 def create_recorder if @recorder return @recorder end if config.value("async_recording") logger.debug("Using asynchronous recording") ScoutApm::BackgroundRecorder.new(logger).start else logger.debug("Using synchronous recording") ScoutApm::SynchronousRecorder.new(logger).start end end |
#environment ⇒ Object
68 69 70 |
# File 'lib/scout_apm/agent.rb', line 68 def environment ScoutApm::Environment.instance end |
#exit_handler_supported? ⇒ Boolean
178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/scout_apm/agent.rb', line 178 def exit_handler_supported? if environment.sinatra? logger.debug "Exit handler not supported for Sinatra" false elsif environment.jruby? logger.debug "Exit handler not supported for JRuby" false elsif environment.rubinius? logger.debug "Exit handler not supported for Rubinius" false else true end end |
#force? ⇒ Boolean
If true, the agent will start regardless of safety checks. Currently just used for testing.
77 78 79 |
# File 'lib/scout_apm/agent.rb', line 77 def force? @options[:force] end |
#install_exit_handler ⇒ Object
at_exit, calls Agent#shutdown to wrapup metric reporting.
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/scout_apm/agent.rb', line 194 def install_exit_handler logger.debug "Shutdown handler not supported" and return unless exit_handler_supported? logger.debug "Installing Shutdown Handler" at_exit do logger.info "Shutting down Scout Agent" # MRI 1.9 bug drops exit codes. # http://bugs.ruby-lang.org/issues/5218 if environment.ruby_19? status = $!.status if $!.is_a?(SystemExit) shutdown exit status if status else shutdown end end end |
#install_instrument(instrument_klass) ⇒ Object
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
# File 'lib/scout_apm/agent.rb', line 329 def install_instrument(instrument_klass) # Don't attempt to install the same instrument twice return if @installed_instruments.any? { |already_installed_instrument| instrument_klass === already_installed_instrument } # Allow users to skip individual instruments via the config file instrument_short_name = instrument_klass.name.split("::").last if (config.value("disabled_instruments") || []).include?(instrument_short_name) logger.info "Skipping Disabled Instrument: #{instrument_short_name} - To re-enable, change `disabled_instruments` key in scout_apm.yml" return end instance = instrument_klass.new @installed_instruments << instance instance.install end |
#load_instruments ⇒ Object
Loads the instrumention logic.
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
# File 'lib/scout_apm/agent.rb', line 298 def load_instruments case environment.framework when :rails then install_instrument(ScoutApm::Instruments::ActionControllerRails2) when :rails3_or_4 then install_instrument(ScoutApm::Instruments::ActionControllerRails3Rails4) install_instrument(ScoutApm::Instruments::RailsRouter) if config.value("detailed_middleware") install_instrument(ScoutApm::Instruments::MiddlewareDetailed) else install_instrument(ScoutApm::Instruments::MiddlewareSummary) end end install_instrument(ScoutApm::Instruments::ActionView) install_instrument(ScoutApm::Instruments::ActiveRecord) install_instrument(ScoutApm::Instruments::Moped) install_instrument(ScoutApm::Instruments::Mongoid) install_instrument(ScoutApm::Instruments::NetHttp) install_instrument(ScoutApm::Instruments::HttpClient) install_instrument(ScoutApm::Instruments::Redis) install_instrument(ScoutApm::Instruments::InfluxDB) install_instrument(ScoutApm::Instruments::Elasticsearch) install_instrument(ScoutApm::Instruments::Grape) rescue logger.warn "Exception loading instruments:" logger.warn $!. logger.warn $!.backtrace end |
#preconditions_met?(options = {}) ⇒ Boolean
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/scout_apm/agent.rb', line 81 def preconditions_met?(={}) if !apm_enabled? logger.warn "Monitoring isn't enabled for the [#{environment.env}] environment. #{force? ? 'Forcing agent to start' : 'Not starting agent'}" return false unless force? end if !environment.application_name logger.warn "An application name could not be determined. Specify the :name value in scout_apm.yml. #{force? ? 'Forcing agent to start' : 'Not starting agent'}." return false unless force? end if environment.interactive? logger.warn "Agent attempting to load in interactive mode. #{force? ? 'Forcing agent to start' : 'Not starting agent'}" return false unless force? end if app_server_missing?() && background_job_missing? if force? logger.warn "Agent starting (forced)" else logger.warn "Deferring agent start. Standing by for first request" end return false unless force? end if started? logger.warn "Already started agent." return false end if defined?(::ScoutRails) logger.warn "ScoutAPM is incompatible with the old Scout Rails plugin. Please remove scout_rails from your Gemfile" return false unless force? end true end |
#should_load_instruments?(options = {}) ⇒ Boolean
If we want to skip the app_server_check, then we must load it.
290 291 292 293 294 295 |
# File 'lib/scout_apm/agent.rb', line 290 def should_load_instruments?(={}) return true if [:skip_app_server_check] return true if config.value('dev_trace') return false if !apm_enabled? environment.app_server_integration.found? || !background_job_missing? end |
#shutdown ⇒ Object
Called via an at_exit handler, it: (1) Stops the background worker (2) Stores metrics locally (forcing current-minute metrics to be written) It does not attempt to actually report metrics.
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
# File 'lib/scout_apm/agent.rb', line 216 def shutdown logger.info "Shutting down ScoutApm" return if !started? return if @shutdown @shutdown = true if @background_worker logger.info("Stopping background worker") @background_worker.stop store.write_to_layaway(layaway, :force) if @background_worker_thread.alive? @background_worker_thread.wakeup @background_worker_thread.join end end end |
#start(options = {}) ⇒ Object
This is called via ScoutApm::Agent.instance.start
when ScoutApm is required in a Ruby application. It initializes the agent and starts the worker thread (if appropiate).
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
# File 'lib/scout_apm/agent.rb', line 121 def start( = {}) @options.merge!() @config = ScoutApm::Config.with_file(@config.value("config_file")) layaway.config = config init_logger logger.info "Attempting to start Scout Agent [#{ScoutApm::VERSION}] on [#{environment.hostname}]" @recorder = create_recorder @config.log_settings @ignored_uris = ScoutApm::IgnoredUris.new(config.value('ignore')) load_instruments if should_load_instruments?() if !@config.any_keys_found? logger.info("No configuration file loaded, and no configuration found in ENV. " + "For assistance configuring Scout, visit " + "http://help.apm.scoutapp.com/#configuration-options") end return false unless preconditions_met?() @started = true logger.info "Starting monitoring for [#{environment.application_name}]. Framework [#{environment.framework}] App Server [#{environment.app_server}] Background Job Framework [#{environment.background_job_name}]." [ ScoutApm::Instruments::Process::ProcessCpu.new(environment.processors, logger), ScoutApm::Instruments::Process::ProcessMemory.new(logger), ScoutApm::Instruments::PercentileSampler.new(logger, request_histograms_by_time), ].each { |s| store.add_sampler(s) } app_server_load_hook if environment.background_job_integration environment.background_job_integration.install logger.info "Installed Background Job Integration [#{environment.background_job_name}]" end # start_background_worker? is true on non-forking servers, and directly # starts the background worker. On forking servers, a server-specific # hook is inserted to start the background worker after forking. if start_background_worker? start_background_worker logger.info "Scout Agent [#{ScoutApm::VERSION}] Initialized" else environment.app_server_integration.install logger.info "Scout Agent [#{ScoutApm::VERSION}] loaded in [#{environment.app_server}] master process. Monitoring will start after server forks its workers." end end |
#start_background_worker ⇒ Object
Creates the worker thread. The worker thread is a loop that runs continuously. It sleeps for Agent#period and when it wakes, processes data, either saving it to disk or reporting to Scout.
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
# File 'lib/scout_apm/agent.rb', line 259 def start_background_worker if !apm_enabled? logger.debug "Not starting background worker as monitoring isn't enabled." return false end logger.info "Not starting background worker, already started" and return if background_worker_running? logger.info "Initializing worker thread." install_exit_handler @recorder = create_recorder logger.info("recorder is now: #{@recorder.class}") @background_worker = ScoutApm::BackgroundWorker.new @background_worker_thread = Thread.new do @background_worker.start { ScoutApm::Debug.instance.call_periodic_hooks ScoutApm::Agent.instance.process_metrics clean_old_percentiles } end end |
#start_background_worker? ⇒ Boolean
The worker thread will automatically start UNLESS:
-
A supported application server isn’t detected (example: running via Rails console)
-
A supported application server is detected, but it forks. In this case, the agent is started in the forked process.
243 244 245 246 247 248 |
# File 'lib/scout_apm/agent.rb', line 243 def start_background_worker? return true if environment.app_server == :thin return true if environment.app_server == :webrick return true if force? return !environment.forking? end |
#start_remote_server(bind, port) ⇒ Object
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
# File 'lib/scout_apm/agent.rb', line 371 def start_remote_server(bind, port) return if @remote_server && @remote_server.running? logger.info("Starting Remote Agent Server") # Start the listening web server only in parent process. @remote_server = ScoutApm::Remote::Server.new( bind, port, ScoutApm::Remote::Router.new(ScoutApm::SynchronousRecorder.new(logger), logger), logger ) @remote_server.start end |
#started? ⇒ Boolean
235 236 237 |
# File 'lib/scout_apm/agent.rb', line 235 def started? @started end |
#use_remote_recorder(host, port) ⇒ Object
Execute this in the child process of a remote agent. The parent is expected to have its accepting webserver up and running
389 390 391 392 393 |
# File 'lib/scout_apm/agent.rb', line 389 def use_remote_recorder(host, port) logger.debug("Becoming Remote Agent (reporting to: #{host}:#{port})") @recorder = ScoutApm::Remote::Recorder.new(host, port, logger) @store = ScoutApm::FakeStore.new end |