Module: NewRelic::Agent::Agent::InstanceMethods

Includes:
Connect, Start, StartWorkerThread
Included in:
NewRelic::Agent::Agent
Defined in:
lib/new_relic/agent/agent.rb

Overview

Holds all the methods defined on NewRelic::Agent::Agent instances

Defined Under Namespace

Modules: Connect, Start, StartWorkerThread

Instance Attribute Summary collapse

Attributes included from Connect

#connect_attempts

Instance Method Summary collapse

Methods included from Connect

#apdex_f, #connect_retry_period, #connect_settings, #connect_to_server, #connected?, #disconnect, #disconnected?, #environment_for_connect, #finish_setup, #handle_license_error, #handle_unrecoverable_agent_error, #log_collector_messages, #log_connection!, #log_error, #note_connect_failure, #query_server_for_configuration, #should_connect?

Methods included from StartWorkerThread

#catch_errors, #create_and_run_worker_loop, #deferred_work!, #handle_force_disconnect, #handle_force_restart, #handle_other_error, #handle_server_connection_problem, #log_worker_loop_start

Methods included from Start

#already_started?, #check_config_and_start_agent, #connect_in_foreground, #correct_license_length, #defer_for_resque?, #disabled?, #has_correct_license_key?, #has_license_key?, #install_exit_handler, #log_app_names, #log_dispatcher, #log_environment, #log_if, #log_startup, #log_unless, #log_version_and_pid, #monitoring?, #using_forking_dispatcher?, #using_sinatra?, #weird_ruby?

Instance Attribute Details

#beacon_configurationObject (readonly)

a configuration for the Real User Monitoring system - handles things like static setup of the header for inclusion into pages



95
96
97
# File 'lib/new_relic/agent/agent.rb', line 95

def beacon_configuration
  @beacon_configuration
end

#cross_process_encoding_bytesObject (readonly)

Returns the value of attribute cross_process_encoding_bytes.



98
99
100
# File 'lib/new_relic/agent/agent.rb', line 98

def cross_process_encoding_bytes
  @cross_process_encoding_bytes
end

#cross_process_idObject (readonly)

cross process id’s and encoding



97
98
99
# File 'lib/new_relic/agent/agent.rb', line 97

def cross_process_id
  @cross_process_id
end

#error_collectorObject (readonly)

error collector is a simple collection of recorded errors



82
83
84
# File 'lib/new_relic/agent/agent.rb', line 82

def error_collector
  @error_collector
end

#eventsObject (readonly)

Global events dispatcher. This will provides our primary mechanism for agent-wide events, such as finishing configuration, error notification and request before/after from Rack.



104
105
106
# File 'lib/new_relic/agent/agent.rb', line 104

def events
  @events
end

#metric_idsObject (readonly)

a cached set of metric_ids to save the collector some time - it returns a metric id for every metric name we send it, and in the future we transmit using the metric id only



88
89
90
# File 'lib/new_relic/agent/agent.rb', line 88

def metric_ids
  @metric_ids
end

#obfuscatorObject (readonly)

holds a proc that is used to obfuscate sql statements



73
74
75
# File 'lib/new_relic/agent/agent.rb', line 73

def obfuscator
  @obfuscator
end

#record_sqlObject (readonly)

whether we should record raw, obfuscated, or no sql



84
85
86
# File 'lib/new_relic/agent/agent.rb', line 84

def record_sql
  @record_sql
end

#serviceObject

service for communicating with collector



100
101
102
# File 'lib/new_relic/agent/agent.rb', line 100

def service
  @service
end

#sql_samplerObject (readonly)

Returns the value of attribute sql_sampler.



78
79
80
# File 'lib/new_relic/agent/agent.rb', line 78

def sql_sampler
  @sql_sampler
end

#stats_engineObject (readonly)

the statistics engine that holds all the timeslice data



75
76
77
# File 'lib/new_relic/agent/agent.rb', line 75

def stats_engine
  @stats_engine
end

#thread_profilerObject (readonly)

begins a thread profile session when instructed by agent commands



80
81
82
# File 'lib/new_relic/agent/agent.rb', line 80

def thread_profiler
  @thread_profiler
end

#transaction_samplerObject (readonly)

the transaction sampler that handles recording transactions



77
78
79
# File 'lib/new_relic/agent/agent.rb', line 77

def transaction_sampler
  @transaction_sampler
end

#url_rulesObject (readonly)

in theory a set of rules applied by the agent to the output of its metrics. Currently unimplemented



91
92
93
# File 'lib/new_relic/agent/agent.rb', line 91

def url_rules
  @url_rules
end

Instance Method Details

#after_fork(options = {}) ⇒ Object

This method should be called in a forked process after a fork. It assumes the parent process initialized the agent, but does not assume the agent started.

The call is idempotent, but not re-entrant.

  • It clears any metrics carried over from the parent process

  • Restarts the sampler thread if necessary

  • Initiates a new agent run and worker loop unless that was done in the parent process and :force_reconnect is not true

Options:

  • :force_reconnect => true to force the spawned process to establish a new connection, such as when forking a long running process. The default is false–it will only connect to the server if the parent had not connected.

  • :keep_retrying => false if we try to initiate a new connection, this tells me to only try it once so this method returns quickly if there is some kind of latency with the server.



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/new_relic/agent/agent.rb', line 182

def after_fork(options={})
  @forked = true
  Agent.config.apply_config(NewRelic::Agent::Configuration::ManualSource.new(options), 1)

  if channel_id = options[:report_to_channel]
    @service = NewRelic::Agent::PipeService.new(channel_id)
    if connected?
      @connected_pid = $$
      @metric_ids = {}
    else
      ::NewRelic::Agent.logger.debug("Child process #{$$} not reporting to non-connected parent.")
      @service.shutdown(Time.now)
      disconnect
    end
  end

  return if !Agent.config[:agent_enabled] ||
    !Agent.config[:monitor_mode] ||
    disconnected? ||
    @worker_thread && @worker_thread.alive?

  ::NewRelic::Agent.logger.debug "Starting the worker thread in #{$$} after forking."

  # Clear out stats that are left over from parent process
  reset_stats

  # Don't ever check to see if this is a spawner.  If we're in a forked process
  # I'm pretty sure we're not also forking new instances.
  start_worker_thread(options)
  @stats_engine.start_sampler_thread
end

#end_transactionObject

Tells the statistics engine we are ending a transaction



266
267
268
# File 'lib/new_relic/agent/agent.rb', line 266

def end_transaction
  @stats_engine.end_transaction
end

#forked?Boolean

Returns:

  • (Boolean)


214
215
216
# File 'lib/new_relic/agent/agent.rb', line 214

def forked?
  @forked
end

#merge_data_from(data) ⇒ Object

Accepts data as provided by the serialize method and merges it into our current collection of data to send. Can be dangerous if we re-merge the same data more than once - it will be sent multiple times.



796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
# File 'lib/new_relic/agent/agent.rb', line 796

def merge_data_from(data)
  metrics, transaction_traces, errors = data
  @stats_engine.merge_data(metrics) if metrics
  if transaction_traces && transaction_traces.respond_to?(:any?) &&
      transaction_traces.any?
    if @traces
      @traces += transaction_traces
    else
      @traces = transaction_traces
    end
  end
  if errors && errors.respond_to?(:each)
    errors.each do |err|
      @error_collector.add_to_error_queue(err)
    end
  end
end

#pop_trace_execution_flagObject

Pop the current trace execution status. Restore trace execution status to what it was before we pushed the current flag.



303
304
305
# File 'lib/new_relic/agent/agent.rb', line 303

def pop_trace_execution_flag
  Thread.current[:newrelic_untraced].pop if Thread.current[:newrelic_untraced]
end

#push_trace_execution_flag(should_trace = false) ⇒ Object

Push flag indicating whether we should be tracing in this thread. This uses a stack which allows us to disable tracing children of a transaction without affecting the tracing of the whole transaction



292
293
294
295
296
297
298
299
# File 'lib/new_relic/agent/agent.rb', line 292

def push_trace_execution_flag(should_trace=false)
  value = Thread.current[:newrelic_untraced]
  if (value.nil?)
    Thread.current[:newrelic_untraced] = []
  end

  Thread.current[:newrelic_untraced] << should_trace
end

#record_transaction(duration_seconds, options = {}) ⇒ Object

fakes out a transaction that did not happen in this process by creating apdex, summary metrics, and recording statistics for the transaction

This method is deprecated - it may be removed in future versions of the agent



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
# File 'lib/new_relic/agent/agent.rb', line 132

def record_transaction(duration_seconds, options={})
  is_error = options['is_error'] || options['error_message'] || options['exception']
  metric = options['metric']
  metric ||= options['uri'] # normalize this with url rules
  raise "metric or uri arguments required" unless metric
  metric_info = NewRelic::MetricParser::MetricParser.for_metric_named(metric)

  if metric_info.is_web_transaction?
    NewRelic::Agent::Instrumentation::MetricFrame.record_apdex(metric_info, duration_seconds, duration_seconds, is_error)
  end
  metrics = metric_info.summary_metrics

  metrics << metric
  metrics.each do |name|
    stats = stats_engine.get_stats_no_scope(name)
    stats.record_data_point(duration_seconds)
  end

  if is_error
    if options['exception']
      e = options['exception']
    elsif options['error_message']
      e = StandardError.new options['error_message']
    else
      e = StandardError.new 'Unknown Error'
    end
    error_collector.notice_error e, :uri => options['uri'], :metric => metric
  end
  # busy time ?
end

#reset_statsObject

Clear out the metric data, errors, and transaction traces, making sure the agent is in a fresh state



499
500
501
502
503
504
505
506
# File 'lib/new_relic/agent/agent.rb', line 499

def reset_stats
  @stats_engine.reset_stats
  @unsent_errors = []
  @traces = nil
  @unsent_timeslice_data = {}
  @last_harvest_time = Time.now
  @launch_time = Time.now
end

#serializeObject

Serialize all the important data that the agent might want to send to the server. We could be sending this to file ( common in short-running background transactions ) or alternately we could serialize via a pipe or socket to a local aggregation device



781
782
783
784
785
786
787
788
789
# File 'lib/new_relic/agent/agent.rb', line 781

def serialize
  accumulator = []
  accumulator[1] = harvest_transaction_traces if @transaction_sampler
  accumulator[2] = harvest_errors if @error_collector
  accumulator[0] = harvest_timeslice_data
  reset_stats
  @metric_ids = {}
  accumulator
end

#set_record_sql(should_record) ⇒ Object

Sets a thread local variable as to whether we should or should not record sql in the current thread. Returns the previous value, if there is one



273
274
275
276
277
# File 'lib/new_relic/agent/agent.rb', line 273

def set_record_sql(should_record)
  prev = Thread::current[:record_sql]
  Thread::current[:record_sql] = should_record
  prev.nil? || prev
end

#set_record_tt(should_record) ⇒ Object

Sets a thread local variable as to whether we should or should not record transaction traces in the current thread. Returns the previous value, if there is one



282
283
284
285
286
# File 'lib/new_relic/agent/agent.rb', line 282

def set_record_tt(should_record)
  prev = Thread::current[:record_tt]
  Thread::current[:record_tt] = should_record
  prev.nil? || prev
end

#shutdown(options = {}) ⇒ Object

Attempt a graceful shutdown of the agent, running the worker loop if it exists and is running.

Options: :force_send => (true/false) # force the agent to send data



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/new_relic/agent/agent.rb', line 228

def shutdown(options={})
  run_loop_before_exit = Agent.config[:force_send]
  return if not started?
  if @worker_loop
    @worker_loop.run_task if run_loop_before_exit
    @worker_loop.stop
  end

  ::NewRelic::Agent.logger.info "Starting Agent shutdown"

  # if litespeed, then ignore all future SIGUSR1 - it's
  # litespeed trying to shut us down
  if Agent.config[:dispatcher] == :litespeed
    Signal.trap("SIGUSR1", "IGNORE")
    Signal.trap("SIGTERM", "IGNORE")
  end

  begin
    NewRelic::Agent.disable_all_tracing do
      graceful_disconnect
    end
  rescue => e
    ::NewRelic::Agent.logger.error e
  end
  NewRelic::Agent.config.remove_config do |config|
    config.class == NewRelic::Agent::Configuration::ManualSource ||
      config.class == NewRelic::Agent::Configuration::ServerSource
  end
  @started = nil
  Control.reset
end

#startObject

Logs a bunch of data and starts the agent, if needed



482
483
484
485
486
487
488
489
490
491
492
493
494
495
# File 'lib/new_relic/agent/agent.rb', line 482

def start
  return if already_started? || disabled?

  if defer_for_resque?
    ::NewRelic::Agent.logger.debug "Deferring startup for Resque in case it daemonizes"
    return
  end

  @started = true
  @local_host = determine_host
  log_startup
  check_config_and_start_agent
  log_version_and_pid
end

#start_transactionObject

Tells the statistics engine we are starting a new transaction



261
262
263
# File 'lib/new_relic/agent/agent.rb', line 261

def start_transaction
  @stats_engine.start_transaction
end

#started?Boolean

True if we have initialized and completed ‘start’

Returns:

  • (Boolean)


219
220
221
# File 'lib/new_relic/agent/agent.rb', line 219

def started?
  @started
end

#unsent_errors_sizeObject

Returns the length of the unsent errors array, if it exists, otherwise nil



109
110
111
# File 'lib/new_relic/agent/agent.rb', line 109

def unsent_errors_size
  @unsent_errors.length if @unsent_errors
end

#unsent_timeslice_dataObject

Initializes the unsent timeslice data hash, if needed, and returns the number of keys it contains



121
122
123
124
# File 'lib/new_relic/agent/agent.rb', line 121

def unsent_timeslice_data
  @unsent_timeslice_data ||= {}
  @unsent_timeslice_data.keys.length
end

#unsent_traces_sizeObject

Returns the length of the traces array, if it exists, otherwise nil



115
116
117
# File 'lib/new_relic/agent/agent.rb', line 115

def unsent_traces_size
  @traces.length if @traces
end