Class: NewRelic::Agent::Transaction

Inherits:
Object
  • Object
show all
Includes:
Tracing
Defined in:
lib/new_relic/agent/transaction.rb,
lib/new_relic/agent/transaction/trace.rb,
lib/new_relic/agent/transaction/segment.rb,
lib/new_relic/agent/transaction/tracing.rb,
lib/new_relic/agent/transaction/trace_node.rb,
lib/new_relic/agent/transaction/trace_builder.rb,
lib/new_relic/agent/transaction/trace_context.rb,
lib/new_relic/agent/transaction/abstract_segment.rb,
lib/new_relic/agent/transaction/datastore_segment.rb,
lib/new_relic/agent/transaction/distributed_tracer.rb,
lib/new_relic/agent/transaction/request_attributes.rb,
lib/new_relic/agent/transaction/distributed_tracing.rb,
lib/new_relic/agent/transaction/slowest_sample_buffer.rb,
lib/new_relic/agent/transaction/message_broker_segment.rb,
lib/new_relic/agent/transaction/external_request_segment.rb,
lib/new_relic/agent/transaction/synthetics_sample_buffer.rb,
lib/new_relic/agent/transaction/transaction_sample_buffer.rb

Overview

This class represents a single transaction (usually mapping to one web request or background job invocation) instrumented by the Ruby agent.

Defined Under Namespace

Modules: DistributedTracing, TraceBuilder, TraceContext, Tracing Classes: AbstractSegment, DatastoreSegment, DistributedTracer, ExternalRequestSegment, MessageBrokerSegment, RequestAttributes, Segment, SlowestSampleBuffer, SyntheticsSampleBuffer, Trace, TraceNode, TransactionSampleBuffer

Constant Summary collapse

NESTED_TRANSACTION_PREFIX =

for nested transactions

'Nested/'
CONTROLLER_PREFIX =
'Controller/'
MIDDLEWARE_PREFIX =
'Middleware/Rack/'
OTHER_TRANSACTION_PREFIX =
'OtherTransaction/'
TASK_PREFIX =
"#{OTHER_TRANSACTION_PREFIX}Background/"
RAKE_PREFIX =
"#{OTHER_TRANSACTION_PREFIX}Rake/"
MESSAGE_PREFIX =
"#{OTHER_TRANSACTION_PREFIX}Message/"
RACK_PREFIX =
"#{CONTROLLER_PREFIX}Rack/"
RODA_PREFIX =
"#{CONTROLLER_PREFIX}Roda/"
SINATRA_PREFIX =
"#{CONTROLLER_PREFIX}Sinatra/"
GRAPE_PREFIX =
"#{CONTROLLER_PREFIX}Grape/"
ACTION_CABLE_PREFIX =
"#{CONTROLLER_PREFIX}ActionCable/"
WEB_TRANSACTION_CATEGORIES =
%i[action_cable controller grape middleware rack roda sinatra web uri].freeze
MIDDLEWARE_SUMMARY_METRICS =
['Middleware/all'].freeze
WEB_SUMMARY_METRIC =
'HttpDispatcher'
OTHER_SUMMARY_METRIC =
"#{OTHER_TRANSACTION_PREFIX}all"
QUEUE_TIME_METRIC =
'WebFrontend/QueueTime'
APDEX_S =
'S'
APDEX_T =
'T'
APDEX_F =
'F'
APDEX_ALL_METRIC =
'ApdexAll'
APDEX_METRIC =
'Apdex'
APDEX_OTHER_METRIC =
'ApdexOther'
APDEX_TXN_METRIC_PREFIX =
'Apdex/'
APDEX_OTHER_TXN_METRIC_PREFIX =
'ApdexOther/Transaction/'
JRUBY_CPU_TIME_ERROR =
'Error calculating JRuby CPU Time'
@@java_classes_loaded =
false

Instance Attribute Summary collapse

Attributes included from Tracing

#async, #current_segment_by_thread, #total_time

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Tracing

#add_segment, #async?, #segment_complete, #segment_limit, #thread_starting_span

Constructor Details

#initialize(category, options) ⇒ Transaction

Returns a new instance of Transaction.



216
217
218
219
220
221
222
223
224
225
226
227
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
259
260
261
262
263
264
265
# File 'lib/new_relic/agent/transaction.rb', line 216

def initialize(category, options)
  @nesting_max_depth = 0
  @current_segment_by_thread = {}
  @current_segment_lock = Mutex.new
  @segment_lock = Mutex.new
  @finish_mutex = Mutex.new
  @segments = []

  self.default_name = options[:transaction_name]
  @overridden_name = nil
  @frozen_name = nil

  @category = category
  @start_time = Process.clock_gettime(Process::CLOCK_REALTIME)
  @end_time = nil
  @duration = nil

  @apdex_start = options[:apdex_start_time] || @start_time
  @jruby_cpu_start = jruby_cpu_time
  @process_cpu_start = process_cpu
  @gc_start_snapshot = NewRelic::Agent::StatsEngine::GCProfiler.take_snapshot
  @filtered_params = options[:filtered_params] || {}

  @exceptions = {}
  @metrics = TransactionMetrics.new
  @logs = PrioritySampledBuffer.new(NewRelic::Agent.instance.log_event_aggregator.capacity)
  @guid = NewRelic::Agent::GuidGenerator.generate_guid

  @ignore_this_transaction = false
  @ignore_apdex = options.fetch(:ignore_apdex, false)
  @ignore_enduser = options.fetch(:ignore_enduser, false)
  @ignore_trace = false

  @sampled = nil
  @priority = nil

  @starting_thread_id = TransactionTimeAggregator.current_execution_context_id
  @starting_segment_key = current_segment_key

  @attributes = Attributes.new(NewRelic::Agent.instance.attribute_filter)
  @log_attributes = nil

  merge_request_parameters(@filtered_params)

  if request = options[:request]
    @request_attributes = RequestAttributes.new(request)
  else
    @request_attributes = nil
  end
end

Instance Attribute Details

#apdex_startObject

A Time instance used for calculating the apdex score, which might end up being @start, or it might be further upstream if we can find a request header for the queue entry time



64
65
66
# File 'lib/new_relic/agent/transaction.rb', line 64

def apdex_start
  @apdex_start
end

#attributesObject (readonly)



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

def attributes
  @attributes
end

#categoryObject (readonly)



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

def category
  @category
end

#durationObject (readonly)



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

def duration
  @duration
end

#end_timeObject (readonly)



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

def end_time
  @end_time
end

#exceptionsObject



66
67
68
# File 'lib/new_relic/agent/transaction.rb', line 66

def exceptions
  @exceptions
end

#filtered_paramsObject



66
67
68
# File 'lib/new_relic/agent/transaction.rb', line 66

def filtered_params
  @filtered_params
end

#gc_start_snapshotObject (readonly)



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

def gc_start_snapshot
  @gc_start_snapshot
end

#guidObject (readonly)



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

def guid
  @guid
end

#http_response_codeObject



66
67
68
# File 'lib/new_relic/agent/transaction.rb', line 66

def http_response_code
  @http_response_code
end

#jruby_cpu_startObject



66
67
68
# File 'lib/new_relic/agent/transaction.rb', line 66

def jruby_cpu_start
  @jruby_cpu_start
end

#logsObject (readonly)



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

def logs
  @logs
end

#metricsObject (readonly)



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

def metrics
  @metrics
end

#nesting_max_depthObject (readonly)



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

def nesting_max_depth
  @nesting_max_depth
end

#parent_span_idObject



66
67
68
# File 'lib/new_relic/agent/transaction.rb', line 66

def parent_span_id
  @parent_span_id
end

#payloadObject (readonly)



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

def payload
  @payload
end

#priorityObject



338
339
340
341
342
343
344
345
346
347
# File 'lib/new_relic/agent/transaction.rb', line 338

def priority
  @priority ||= case NewRelic::Agent.config[:'distributed_tracing.sampler.root']
  when 'adaptive', 'trace_id_ratio_based'
    default_priority
  when 'always_on'
    2.0
  when 'always_off'
    0
  end
end

#process_cpu_startObject



66
67
68
# File 'lib/new_relic/agent/transaction.rb', line 66

def process_cpu_start
  @process_cpu_start
end

#raw_synthetics_headerObject

Fields for tracking synthetics requests



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

def raw_synthetics_header
  @raw_synthetics_header
end

#raw_synthetics_info_headerObject

Fields for tracking synthetics requests



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

def raw_synthetics_info_header
  @raw_synthetics_info_header
end

#response_content_lengthObject



66
67
68
# File 'lib/new_relic/agent/transaction.rb', line 66

def response_content_length
  @response_content_length
end

#response_content_typeObject



66
67
68
# File 'lib/new_relic/agent/transaction.rb', line 66

def response_content_type
  @response_content_type
end

#response_statusObject



66
67
68
# File 'lib/new_relic/agent/transaction.rb', line 66

def response_status
  @response_status
end

#sampled=(value) ⇒ Object (writeonly)



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

def sampled=(value)
  @sampled = value
end

#segmentsObject (readonly)



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

def segments
  @segments
end

#start_timeObject

A Time instance for the start time, never nil



59
60
61
# File 'lib/new_relic/agent/transaction.rb', line 59

def start_time
  @start_time
end

#synthetics_info_payloadObject

Fields for tracking synthetics requests



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

def synthetics_info_payload
  @synthetics_info_payload
end

#synthetics_payloadObject

Fields for tracking synthetics requests



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

def synthetics_payload
  @synthetics_payload
end

#transaction_traceObject (readonly)

Populated with the trace sample once this transaction is completed.



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

def transaction_trace
  @transaction_trace
end

Class Method Details

.abort_transaction!Object

discards the currently saved transaction information



137
138
139
140
141
# File 'lib/new_relic/agent/transaction.rb', line 137

def self.abort_transaction!
  if txn = Tracer.current_transaction
    txn.abort_transaction!
  end
end

.add_agent_attribute(key, value, default_destinations) ⇒ Object



177
178
179
180
181
182
183
# File 'lib/new_relic/agent/transaction.rb', line 177

def self.add_agent_attribute(key, value, default_destinations)
  if txn = tl_current
    txn.add_agent_attribute(key, value, default_destinations)
  else
    NewRelic::Agent.logger.debug("Attempted to add agent attribute: #{key} without transaction")
  end
end

.apdex_bucket(duration, failed, apdex_t) ⇒ Object



164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/new_relic/agent/transaction.rb', line 164

def self.apdex_bucket(duration, failed, apdex_t)
  case
  when failed
    :apdex_f
  when duration <= apdex_t
    :apdex_s
  when duration <= apdex_t * 4
    :apdex_t
  else
    :apdex_f
  end
end

.merge_untrusted_agent_attributes(attributes, prefix, default_destinations) ⇒ Object



191
192
193
194
195
196
197
# File 'lib/new_relic/agent/transaction.rb', line 191

def self.merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
  if txn = tl_current
    txn.merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
  else
    NewRelic::Agent.logger.debug('Attempted to merge untrusted attributes without transaction')
  end
end

.name_from_partial(partial_name, category) ⇒ Object



116
117
118
119
# File 'lib/new_relic/agent/transaction.rb', line 116

def self.name_from_partial(partial_name, category)
  namer = Instrumentation::ControllerInstrumentation::TransactionNamer
  "#{namer.prefix_for_category(self, category)}#{partial_name}"
end

.nested_transaction_name(name) ⇒ Object



128
129
130
131
132
133
134
# File 'lib/new_relic/agent/transaction.rb', line 128

def self.nested_transaction_name(name)
  if name.start_with?(CONTROLLER_PREFIX, OTHER_TRANSACTION_PREFIX)
    "#{NESTED_TRANSACTION_PREFIX}#{name}"
  else
    name
  end
end

.notice_error(e, options = {}) ⇒ Object

See NewRelic::Agent.notice_error for options and commentary



144
145
146
147
148
149
150
# File 'lib/new_relic/agent/transaction.rb', line 144

def self.notice_error(e, options = {})
  if txn = Tracer.current_transaction
    txn.notice_error(e, options)
  elsif NewRelic::Agent.instance
    NewRelic::Agent.instance.error_collector.notice_error(e, options)
  end
end

.recording_web_transaction?Boolean

Returns truthy if the current in-progress transaction is considered a a web transaction (as opposed to, e.g., a background transaction).

Returns:

  • (Boolean)


157
158
159
160
161
162
# File 'lib/new_relic/agent/transaction.rb', line 157

def self.recording_web_transaction? # THREAD_LOCAL_ACCESS
  NewRelic::Agent.record_api_supportability_metric(:recording_web_transaction?)

  txn = tl_current
  txn&.recording_web_transaction?
end

.set_default_transaction_name(partial_name, category = nil) ⇒ Object

THREAD_LOCAL_ACCESS



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

def self.set_default_transaction_name(partial_name, category = nil) # THREAD_LOCAL_ACCESS
  txn = tl_current
  name = name_from_partial(partial_name, category || txn.category)
  txn.set_default_transaction_name(name, category)
end

.set_overriding_transaction_name(partial_name, category = nil) ⇒ Object

THREAD_LOCAL_ACCESS



108
109
110
111
112
113
114
# File 'lib/new_relic/agent/transaction.rb', line 108

def self.set_overriding_transaction_name(partial_name, category = nil) # THREAD_LOCAL_ACCESS
  txn = tl_current
  return unless txn

  name = name_from_partial(partial_name, category || txn.category)
  txn.set_overriding_transaction_name(name, category)
end

.start_new_transaction(state, category, options) ⇒ Object



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

def self.start_new_transaction(state, category, options)
  txn = Transaction.new(category, options)
  state.reset(txn)
  txn.start(options)
  txn
end

.tl_currentObject

Return the currently active transaction, or nil.



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

def self.tl_current
  Tracer.current_transaction
end

Instance Method Details

#abort_transaction!Object

Call this to ensure that the current transaction trace is not saved To fully ignore all metrics and errors, use ignore! instead.



533
534
535
# File 'lib/new_relic/agent/transaction.rb', line 533

def abort_transaction!
  @ignore_trace = true
end

#add_agent_attribute(key, value, default_destinations) ⇒ Object



185
186
187
188
189
# File 'lib/new_relic/agent/transaction.rb', line 185

def add_agent_attribute(key, value, default_destinations)
  @attributes.add_agent_attribute(key, value, default_destinations)
  # the following line needs else branch coverage
  current_segment.add_agent_attribute(key, value) if current_segment # rubocop:disable Style/SafeNavigation
end

#add_custom_attributes(p) ⇒ Object



935
936
937
# File 'lib/new_relic/agent/transaction.rb', line 935

def add_custom_attributes(p)
  attributes.merge_custom_attributes(p)
end

#add_log_event(event) ⇒ Object



948
949
950
# File 'lib/new_relic/agent/transaction.rb', line 948

def add_log_event(event)
  logs.append(event: event)
end

#add_transaction_log_attributes(params) ⇒ Object



939
940
941
942
# File 'lib/new_relic/agent/transaction.rb', line 939

def add_transaction_log_attributes(params)
  @log_attributes ||= LogEventAttributes.new
  @log_attributes.add_custom_attributes(params)
end

#apdex_bucket(duration, current_apdex_t) ⇒ Object



870
871
872
# File 'lib/new_relic/agent/transaction.rb', line 870

def apdex_bucket(duration, current_apdex_t)
  self.class.apdex_bucket(duration, had_error_affecting_apdex?, current_apdex_t)
end

#apdex_tObject



901
902
903
# File 'lib/new_relic/agent/transaction.rb', line 901

def apdex_t
  transaction_specific_apdex_t || Agent.config[:apdex_t]
end

#append_apdex_perf_zone(payload) ⇒ Object



773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
# File 'lib/new_relic/agent/transaction.rb', line 773

def append_apdex_perf_zone(payload)
  if recording_web_transaction?
    bucket = apdex_bucket(duration, apdex_t)
  elsif background_apdex_t = transaction_specific_apdex_t
    bucket = apdex_bucket(duration, background_apdex_t)
  end

  return unless bucket

  bucket_str = case bucket
  when :apdex_s then APDEX_S
  when :apdex_t then APDEX_T
  when :apdex_f then APDEX_F
  end
  payload[:apdex_perf_zone] = bucket_str if bucket_str
end

#append_synthetics_to(payload) ⇒ Object



790
791
792
793
794
795
796
797
798
799
800
801
802
# File 'lib/new_relic/agent/transaction.rb', line 790

def append_synthetics_to(payload)
  return unless is_synthetics_request?

  payload[:synthetics_resource_id] = synthetics_resource_id
  payload[:synthetics_job_id] = synthetics_job_id
  payload[:synthetics_monitor_id] = synthetics_monitor_id
  payload[:synthetics_type] = synthetics_info('type')
  payload[:synthetics_initiator] = synthetics_info('initiator')

  synthetics_additional_attributes do |key, value|
    payload[key] = value
  end
end

#assign_agent_attributesObject



628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
# File 'lib/new_relic/agent/transaction.rb', line 628

def assign_agent_attributes
  default_destinations = AttributeFilter::DST_TRANSACTION_TRACER |
    AttributeFilter::DST_TRANSACTION_EVENTS |
    AttributeFilter::DST_ERROR_COLLECTOR

  if http_response_code
    add_agent_attribute(:'http.statusCode', http_response_code, default_destinations)
  end

  if response_status
    add_agent_attribute(:'response.status', response_status, default_destinations)
  end

  if response_content_length
    add_agent_attribute(:'response.headers.contentLength', response_content_length.to_i, default_destinations)
  end

  if response_content_type
    add_agent_attribute(:'response.headers.contentType', response_content_type, default_destinations)
  end

  @request_attributes&.assign_agent_attributes(self)

  display_host = Agent.config[:'process_host.display_name']
  unless display_host == NewRelic::Agent::Hostname.get
    add_agent_attribute(:'host.displayName', display_host, default_destinations)
  end
end

#assign_intrinsicsObject



657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'lib/new_relic/agent/transaction.rb', line 657

def assign_intrinsics
  attributes.add_intrinsic_attribute(:priority, priority)

  if gc_time = calculate_gc_time
    attributes.add_intrinsic_attribute(:gc_time, gc_time)
  end

  if burn = cpu_burn
    attributes.add_intrinsic_attribute(:cpu_time, burn)
  end

  if is_synthetics_request?
    attributes.add_intrinsic_attribute(:synthetics_resource_id, synthetics_resource_id)
    attributes.add_intrinsic_attribute(:synthetics_job_id, synthetics_job_id)
    attributes.add_intrinsic_attribute(:synthetics_monitor_id, synthetics_monitor_id)
    attributes.add_intrinsic_attribute(:synthetics_type, synthetics_info('type'))
    attributes.add_intrinsic_attribute(:synthetics_initiator, synthetics_info('initiator'))

    synthetics_additional_attributes do |key, value|
      attributes.add_intrinsic_attribute(key, value)
    end
  end

  distributed_tracer.assign_intrinsics
end

#assign_segment_dt_attributesObject



621
622
623
624
625
626
# File 'lib/new_relic/agent/transaction.rb', line 621

def assign_segment_dt_attributes
  dt_payload = distributed_tracer.trace_state_payload || distributed_tracer.distributed_trace_payload
  parent_attributes = {}
  DistributedTraceAttributes.copy_parent_attributes(self, dt_payload, parent_attributes)
  parent_attributes.each { |k, v| initial_segment.add_agent_attribute(k, v) }
end

#background_summary_metricsObject



545
546
547
548
549
550
551
552
# File 'lib/new_relic/agent/transaction.rb', line 545

def background_summary_metrics
  segments = @frozen_name.split('/')
  if segments.size > 2
    ["OtherTransaction/#{segments[1]}/all", OTHER_SUMMARY_METRIC]
  else
    []
  end
end

#best_nameObject Also known as: transaction_name



416
417
418
419
420
421
# File 'lib/new_relic/agent/transaction.rb', line 416

def best_name
  @frozen_name ||
    @overridden_name ||
    @default_name ||
    NewRelic::Agent::UNKNOWN_METRIC
end

#calculate_gc_timeObject



690
691
692
693
# File 'lib/new_relic/agent/transaction.rb', line 690

def calculate_gc_time
  gc_stop_snapshot = NewRelic::Agent::StatsEngine::GCProfiler.take_snapshot
  NewRelic::Agent::StatsEngine::GCProfiler.record_delta(gc_start_snapshot, gc_stop_snapshot)
end

#calculate_transport_duration(distributed_trace_payload) ⇒ Object

This method returns transport_duration in seconds. Transport duration is stored in milliseconds on the payload, but it’s needed in seconds for metrics and intrinsics.



698
699
700
701
702
703
# File 'lib/new_relic/agent/transaction.rb', line 698

def calculate_transport_duration(distributed_trace_payload)
  return unless distributed_trace_payload

  duration = start_time - (distributed_trace_payload.timestamp / 1000.0)
  [duration, 0].max
end

#commit!(outermost_node_name) ⇒ Object



599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/new_relic/agent/transaction.rb', line 599

def commit!(outermost_node_name)
  generate_payload
  assign_intrinsics

  finalize_segments

  @transaction_trace = transaction_sampler.on_finishing_transaction(self)
  sql_sampler.on_finishing_transaction(state, @frozen_name)

  record_summary_metrics(outermost_node_name)
  record_total_time_metrics
  record_apdex unless ignore_apdex?
  record_queue_time
  distributed_tracer.record_metrics

  record_exceptions
  record_transaction_event
  record_log_events
  merge_metrics
  send_transaction_finished_event
end

#cpu_burnObject



964
965
966
# File 'lib/new_relic/agent/transaction.rb', line 964

def cpu_burn
  normal_cpu_burn || jruby_cpu_burn
end

#create_initial_segment(options = {}) ⇒ Object



483
484
485
486
# File 'lib/new_relic/agent/transaction.rb', line 483

def create_initial_segment(options = {})
  segment = create_segment(@default_name, options)
  segment.record_scoped_metric = false
end

#create_nested_segment(category, options) ⇒ Object



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'lib/new_relic/agent/transaction.rb', line 509

def create_nested_segment(category, options)
  if options[:filtered_params] && !options[:filtered_params].empty?
    @filtered_params = options[:filtered_params]
    merge_request_parameters(options[:filtered_params])
  end

  @ignore_apdex = options[:ignore_apdex] if options.key?(:ignore_apdex)
  @ignore_enduser = options[:ignore_enduser] if options.key?(:ignore_enduser)

  nest_initial_segment if segments.length == 1
  nested_name = self.class.nested_transaction_name(options[:transaction_name])

  segment = create_segment(nested_name, options)
  set_default_transaction_name(options[:transaction_name], category)
  segment
end

#create_segment(name, options = {}) ⇒ Object



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/new_relic/agent/transaction.rb', line 488

def create_segment(name, options = {})
  summary_metrics = nil

  if name.start_with?(MIDDLEWARE_PREFIX)
    summary_metrics = MIDDLEWARE_SUMMARY_METRICS
  end

  @nesting_max_depth += 1

  segment = Tracer.start_segment(
    name: name,
    unscoped_metrics: summary_metrics
  )

  # #code_information will glean the code info out of the options hash
  # if it exists or noop otherwise
  segment.code_information = options

  segment
end

#current_segmentObject



279
280
281
282
283
# File 'lib/new_relic/agent/transaction.rb', line 279

def current_segment
  current_segment_by_thread[current_segment_key] ||
    current_segment_by_thread[parent_segment_key] ||
    current_segment_by_thread[@starting_segment_key]
end

#current_segment_keyObject



271
272
273
# File 'lib/new_relic/agent/transaction.rb', line 271

def current_segment_key
  Tracer.current_segment_key
end

#default_name=(name) ⇒ Object



383
384
385
# File 'lib/new_relic/agent/transaction.rb', line 383

def default_name=(name)
  @default_name = Helper.correctly_encoded(name)
end

#default_priorityObject



334
335
336
# File 'lib/new_relic/agent/transaction.rb', line 334

def default_priority
  (sampled? ? rand + 1.0 : rand).round(NewRelic::PRIORITY_PRECISION)
end

#distributed_tracerObject



293
294
295
# File 'lib/new_relic/agent/transaction.rb', line 293

def distributed_tracer
  @distributed_tracer ||= DistributedTracer.new(self)
end

#finishObject



558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/new_relic/agent/transaction.rb', line 558

def finish
  @finish_mutex.synchronize do
    # Guard against double-finishing to prevent duplicate transaction recording
    # This can occur in multi-threaded/fiber environments or when finish is called
    # explicitly before the wrapping code calls it again (e.g., Tracer.in_transaction)
    return unless state.is_execution_traced? && initial_segment
    return if finished?

    @end_time = Process.clock_gettime(Process::CLOCK_REALTIME)
    @duration = @end_time - @start_time
    freeze_name_and_execute_if_not_ignored

    if nesting_max_depth == 1
      initial_segment.name = @frozen_name
    end

    initial_segment.transaction_name = @frozen_name
    assign_segment_dt_attributes
    assign_agent_attributes
    initial_segment.finish

    NewRelic::Agent::TransactionTimeAggregator.transaction_stop(@end_time, @starting_thread_id)

    commit!(initial_segment.name) unless @ignore_this_transaction
  end
rescue => e
  NewRelic::Agent.logger.error('Exception during Transaction#finish', e)
  nil
ensure
  state.reset
end

#finished?Boolean

Returns:

  • (Boolean)


479
480
481
# File 'lib/new_relic/agent/transaction.rb', line 479

def finished?
  initial_segment&.finished?
end

#freeze_name_and_execute_if_not_ignoredObject



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/new_relic/agent/transaction.rb', line 435

def freeze_name_and_execute_if_not_ignored
  if !name_frozen?
    name = promoted_transaction_name(best_name)
    name = NewRelic::Agent.instance.transaction_rules.rename(name)
    @name_frozen = true

    if name.nil?
      ignore!
      @frozen_name = best_name
    else
      @frozen_name = name
    end
  end

  if block_given? && !@ignore_this_transaction
    yield
  end
end

#generate_payloadObject



719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
# File 'lib/new_relic/agent/transaction.rb', line 719

def generate_payload
  @payload = {
    :name => @frozen_name,
    :bucket => recording_web_transaction? ? :request : :background,
    :start_timestamp => start_time,
    :duration => duration,
    :metrics => @metrics,
    :attributes => @attributes,
    :error => false,
    :priority => priority
  }

  distributed_tracer.append_payload(@payload)
  append_apdex_perf_zone(@payload)
  append_synthetics_to(@payload)
end

#had_error_affecting_apdex?Boolean

Returns:

  • (Boolean)


864
865
866
867
868
# File 'lib/new_relic/agent/transaction.rb', line 864

def had_error_affecting_apdex?
  @exceptions.each.any? do |exception, options|
    NewRelic::Agent.instance.error_collector.error_affects_apdex?(exception, options)
  end
end

#ignore!Object



980
981
982
# File 'lib/new_relic/agent/transaction.rb', line 980

def ignore!
  @ignore_this_transaction = true
end

#ignore?Boolean

Returns:

  • (Boolean)


984
985
986
# File 'lib/new_relic/agent/transaction.rb', line 984

def ignore?
  @ignore_this_transaction
end

#ignore_apdex!Object



988
989
990
# File 'lib/new_relic/agent/transaction.rb', line 988

def ignore_apdex!
  @ignore_apdex = true
end

#ignore_apdex?Boolean

Returns:

  • (Boolean)


992
993
994
# File 'lib/new_relic/agent/transaction.rb', line 992

def ignore_apdex?
  @ignore_apdex
end

#ignore_enduser!Object



996
997
998
# File 'lib/new_relic/agent/transaction.rb', line 996

def ignore_enduser!
  @ignore_enduser = true
end

#ignore_enduser?Boolean

Returns:

  • (Boolean)


1000
1001
1002
# File 'lib/new_relic/agent/transaction.rb', line 1000

def ignore_enduser?
  @ignore_enduser
end

#ignore_trace?Boolean

Returns:

  • (Boolean)


1004
1005
1006
# File 'lib/new_relic/agent/transaction.rb', line 1004

def ignore_trace?
  @ignore_trace
end

#include_guid?Boolean

Returns:

  • (Boolean)


736
737
738
# File 'lib/new_relic/agent/transaction.rb', line 736

def include_guid?
  is_synthetics_request?
end

#influences_transaction_name?(category) ⇒ Boolean

Returns:

  • (Boolean)


412
413
414
# File 'lib/new_relic/agent/transaction.rb', line 412

def influences_transaction_name?(category)
  !category || nesting_max_depth == 1 || similar_category?(category)
end

#initial_segmentObject



475
476
477
# File 'lib/new_relic/agent/transaction.rb', line 475

def initial_segment
  segments&.first
end

#instrumentation_stateObject

This transaction-local hash may be used as temporary storage by instrumentation that needs to pass data from one instrumentation point to another.

For example, if both A and B are instrumented, and A calls B but some piece of state needed by the instrumentation at B is only available at A, the instrumentation at A may write into the hash, call through, and then remove the key afterwards, allowing the instrumentation at B to read the value in between.

Keys should be symbols, and care should be taken to not generate key names dynamically, and to ensure that keys are removed upon return from the method that creates them.



375
376
377
# File 'lib/new_relic/agent/transaction.rb', line 375

def instrumentation_state
  @instrumentation_state ||= {}
end

#is_synthetics_request?Boolean

Returns:

  • (Boolean)


740
741
742
# File 'lib/new_relic/agent/transaction.rb', line 740

def is_synthetics_request?
  !synthetics_payload.nil? && !raw_synthetics_header.nil?
end

#jruby_cpu_burnObject



974
975
976
977
978
# File 'lib/new_relic/agent/transaction.rb', line 974

def jruby_cpu_burn
  return unless @jruby_cpu_start

  jruby_cpu_time - @jruby_cpu_start
end

#log_attributesObject



944
945
946
# File 'lib/new_relic/agent/transaction.rb', line 944

def log_attributes
  @log_attributes
end

#log_frozen_name(name) ⇒ Object



407
408
409
410
# File 'lib/new_relic/agent/transaction.rb', line 407

def log_frozen_name(name)
  NewRelic::Agent.logger.warn("Attempted to rename transaction to '#{name}' after transaction name was already frozen as '#{@frozen_name}'.")
  nil
end

#merge_metricsObject



804
805
806
# File 'lib/new_relic/agent/transaction.rb', line 804

def merge_metrics
  NewRelic::Agent.instance.stats_engine.merge_transaction_metrics!(@metrics, best_name)
end

#merge_request_parameters(params) ⇒ Object



387
388
389
# File 'lib/new_relic/agent/transaction.rb', line 387

def merge_request_parameters(params)
  merge_untrusted_agent_attributes(params, :'request.parameters', AttributeFilter::DST_NONE)
end

#merge_untrusted_agent_attributes(attributes, prefix, default_destinations) ⇒ Object



199
200
201
202
# File 'lib/new_relic/agent/transaction.rb', line 199

def merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
  @attributes.merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
  current_segment&.merge_untrusted_agent_attributes(attributes, prefix, default_destinations)
end

#name_frozen?Boolean

Returns:

  • (Boolean)


454
455
456
# File 'lib/new_relic/agent/transaction.rb', line 454

def name_frozen?
  @frozen_name ? true : false
end

#needs_middleware_summary_metrics?(name) ⇒ Boolean

Returns:

  • (Boolean)


554
555
556
# File 'lib/new_relic/agent/transaction.rb', line 554

def needs_middleware_summary_metrics?(name)
  name.start_with?(MIDDLEWARE_PREFIX)
end

#nest_initial_segmentObject



526
527
528
529
# File 'lib/new_relic/agent/transaction.rb', line 526

def nest_initial_segment
  self.initial_segment.name = self.class.nested_transaction_name(initial_segment.name)
  initial_segment.record_scoped_metric = true
end

#normal_cpu_burnObject



968
969
970
971
972
# File 'lib/new_relic/agent/transaction.rb', line 968

def normal_cpu_burn
  return unless @process_cpu_start

  process_cpu - @process_cpu_start
end

#notice_error(error, options = {}) ⇒ Object

Do not call this. Invoke the class method instead.



827
828
829
830
831
832
833
834
835
836
837
838
839
# File 'lib/new_relic/agent/transaction.rb', line 827

def notice_error(error, options = {}) # :nodoc:
  # Only the last error is kept
  if current_segment
    current_segment.notice_error(error, expected: options[:expected])
    options[:span_id] = current_segment.guid
  end

  if @exceptions[error]
    @exceptions[error].merge!(options)
  else
    @exceptions[error] = options
  end
end

#overridden_name=(name) ⇒ Object



379
380
381
# File 'lib/new_relic/agent/transaction.rb', line 379

def overridden_name=(name)
  @overridden_name = Helper.correctly_encoded(name)
end

#parent_segment_keyObject



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

def parent_segment_key
  (::Fiber.current.nr_parent_key if ::Fiber.current.respond_to?(:nr_parent_key)) || (::Thread.current.nr_parent_key if ::Thread.current.respond_to?(:nr_parent_key))
end

End common interface



427
428
429
430
431
432
433
# File 'lib/new_relic/agent/transaction.rb', line 427

def promoted_transaction_name(name)
  if name.start_with?(MIDDLEWARE_PREFIX)
    "#{CONTROLLER_PREFIX}#{name}"
  else
    name
  end
end

#queue_timeObject



849
850
851
# File 'lib/new_relic/agent/transaction.rb', line 849

def queue_time
  @apdex_start ? @start_time - @apdex_start : 0
end

#record_apdexObject



874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'lib/new_relic/agent/transaction.rb', line 874

def record_apdex
  return unless state.is_execution_traced?

  freeze_name_and_execute_if_not_ignored do
    if recording_web_transaction?
      record_apdex_metrics(APDEX_METRIC, APDEX_TXN_METRIC_PREFIX, apdex_t)
    else
      record_apdex_metrics(APDEX_OTHER_METRIC,
        APDEX_OTHER_TXN_METRIC_PREFIX,
        transaction_specific_apdex_t)
    end
  end
end

#record_apdex_metrics(rollup_metric, transaction_prefix, current_apdex_t) ⇒ Object



888
889
890
891
892
893
894
895
896
897
898
899
# File 'lib/new_relic/agent/transaction.rb', line 888

def record_apdex_metrics(rollup_metric, transaction_prefix, current_apdex_t)
  return unless current_apdex_t

  total_duration = end_time - apdex_start
  apdex_bucket_global = apdex_bucket(total_duration, current_apdex_t)
  apdex_bucket_txn = apdex_bucket(duration, current_apdex_t)

  @metrics.record_unscoped(rollup_metric, apdex_bucket_global, current_apdex_t)
  @metrics.record_unscoped(APDEX_ALL_METRIC, apdex_bucket_global, current_apdex_t)
  txn_apdex_metric = @frozen_name.sub(/^[^\/]+\//, transaction_prefix)
  @metrics.record_unscoped(txn_apdex_metric, apdex_bucket_txn, current_apdex_t)
end

#record_exception(exception, options, error_recorded) ⇒ Object



816
817
818
819
820
821
822
823
824
# File 'lib/new_relic/agent/transaction.rb', line 816

def record_exception(exception, options, error_recorded)
  options[:uri] ||= request_path if request_path
  options[:port] = request_port if request_port
  options[:metric] = best_name
  options[:attributes] = @attributes

  span_id = options.delete(:span_id)
  !!agent.error_collector.notice_error(exception, options, span_id) || error_recorded
end

#record_exceptionsObject



808
809
810
811
812
813
814
# File 'lib/new_relic/agent/transaction.rb', line 808

def record_exceptions
  error_recorded = false
  @exceptions.each do |exception, options|
    error_recorded = record_exception(exception, options, error_recorded)
  end
  payload&.[]=(:error, error_recorded)
end

#record_log_eventsObject



845
846
847
# File 'lib/new_relic/agent/transaction.rb', line 845

def record_log_events
  agent.log_event_aggregator.record_batch(self, @logs.to_a)
end

#record_queue_timeObject



853
854
855
856
857
858
859
860
861
862
# File 'lib/new_relic/agent/transaction.rb', line 853

def record_queue_time
  value = queue_time
  if value > 0.0
    if value < MethodTracerHelpers::MAX_ALLOWED_METRIC_DURATION
      @metrics.record_unscoped(QUEUE_TIME_METRIC, value)
    else
      ::NewRelic::Agent.logger.log_once(:warn, :too_high_queue_time, "Not recording unreasonably large queue time of #{value} s")
    end
  end
end

#record_summary_metrics(outermost_node_name) ⇒ Object

The summary metrics recorded by this method all end up with a duration equal to the transaction itself, and an exclusive time of zero.



707
708
709
710
711
# File 'lib/new_relic/agent/transaction.rb', line 707

def record_summary_metrics(outermost_node_name)
  metrics = summary_metrics
  metrics << @frozen_name unless @frozen_name == outermost_node_name
  @metrics.record_unscoped(metrics, duration, 0)
end

#record_transaction_eventObject



841
842
843
# File 'lib/new_relic/agent/transaction.rb', line 841

def record_transaction_event
  agent.transaction_event_recorder.record(payload)
end

#recording_web_transaction?Boolean

Returns:

  • (Boolean)


952
953
954
# File 'lib/new_relic/agent/transaction.rb', line 952

def recording_web_transaction?
  web_category?(@category)
end

#refererObject



349
350
351
# File 'lib/new_relic/agent/transaction.rb', line 349

def referer
  @request_attributes&.referer
end

#remove_current_segment_by_thread_id(id) ⇒ Object



289
290
291
# File 'lib/new_relic/agent/transaction.rb', line 289

def remove_current_segment_by_thread_id(id)
  @current_segment_lock.synchronize { current_segment_by_thread.delete(id) }
end

#request_pathObject



353
354
355
# File 'lib/new_relic/agent/transaction.rb', line 353

def request_path
  @request_attributes&.request_path
end

#request_portObject



357
358
359
# File 'lib/new_relic/agent/transaction.rb', line 357

def request_port
  @request_attributes&.port
end

#sampled?Boolean

Returns:

  • (Boolean)


297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/new_relic/agent/transaction.rb', line 297

def sampled?
  return false unless Agent.config[:'distributed_tracing.enabled']

  if @sampled.nil?
    @sampled = case NewRelic::Agent.config[:'distributed_tracing.sampler.root']
    when 'adaptive'
      NewRelic::Agent.instance.adaptive_sampler.sampled?
    when 'always_on'
      true
    when 'always_off'
      false
    when 'trace_id_ratio_based'
      trace_ratio_sampled?(NewRelic::Agent.config[:'distributed_tracing.sampler.root.trace_id_ratio_based.ratio'])
    end
  end
  @sampled
end

#send_transaction_finished_eventObject

This event is fired when the transaction is fully completed. The metric values and sampler can’t be successfully modified from this event.



715
716
717
# File 'lib/new_relic/agent/transaction.rb', line 715

def send_transaction_finished_event
  agent.events.notify(:transaction_finished, payload)
end

#set_current_segment(new_segment) ⇒ Object



285
286
287
# File 'lib/new_relic/agent/transaction.rb', line 285

def set_current_segment(new_segment)
  @current_segment_lock.synchronize { current_segment_by_thread[current_segment_key] = new_segment }
end

#set_default_transaction_name(name, category) ⇒ Object



391
392
393
394
395
396
397
398
# File 'lib/new_relic/agent/transaction.rb', line 391

def set_default_transaction_name(name, category)
  return log_frozen_name(name) if name_frozen?

  if influences_transaction_name?(category)
    self.default_name = name
    @category = category if category
  end
end

#set_overriding_transaction_name(name, category) ⇒ Object



400
401
402
403
404
405
# File 'lib/new_relic/agent/transaction.rb', line 400

def set_overriding_transaction_name(name, category)
  return log_frozen_name(name) if name_frozen?

  self.overridden_name = name
  @category = category if category
end

#similar_category?(category) ⇒ Boolean

Returns:

  • (Boolean)


960
961
962
# File 'lib/new_relic/agent/transaction.rb', line 960

def similar_category?(category)
  web_category?(@category) == web_category?(category)
end

#start(options = {}) ⇒ Object



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/new_relic/agent/transaction.rb', line 458

def start(options = {})
  return if !state.is_execution_traced?

  sql_sampler.on_start_transaction(state, request_path)
  NewRelic::Agent.instance.events.notify(:start_transaction)
  NewRelic::Agent::TransactionTimeAggregator.transaction_start(start_time)

  ignore! if user_defined_rules_ignore?

  create_initial_segment(options)
  Segment.merge_untrusted_agent_attributes( \
    @filtered_params,
    :'request.parameters',
    AttributeFilter::DST_SPAN_EVENTS
  )
end

#stateObject



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

def state
  NewRelic::Agent::Tracer.state
end

#summary_metricsObject



537
538
539
540
541
542
543
# File 'lib/new_relic/agent/transaction.rb', line 537

def summary_metrics
  if @frozen_name.start_with?(CONTROLLER_PREFIX)
    [WEB_SUMMARY_METRIC]
  else
    background_summary_metrics
  end
end

#synthetics_account_idObject



749
750
751
752
# File 'lib/new_relic/agent/transaction.rb', line 749

def 
  info = synthetics_payload or return nil
  info[1]
end

#synthetics_additional_attributes(&block) ⇒ Object



683
684
685
686
687
688
# File 'lib/new_relic/agent/transaction.rb', line 683

def synthetics_additional_attributes(&block)
  synthetics_info('attributes')&.each do |k, v|
    new_key = "synthetics_#{NewRelic::LanguageSupport.snakeize(k.to_s)}".to_sym
    yield(new_key, v.to_s)
  end
end

#synthetics_info(key) ⇒ Object



769
770
771
# File 'lib/new_relic/agent/transaction.rb', line 769

def synthetics_info(key)
  synthetics_info_payload[key] if synthetics_info_payload
end

#synthetics_job_idObject



759
760
761
762
# File 'lib/new_relic/agent/transaction.rb', line 759

def synthetics_job_id
  info = synthetics_payload or return nil
  info[3]
end

#synthetics_monitor_idObject



764
765
766
767
# File 'lib/new_relic/agent/transaction.rb', line 764

def synthetics_monitor_id
  info = synthetics_payload or return nil
  info[4]
end

#synthetics_resource_idObject



754
755
756
757
# File 'lib/new_relic/agent/transaction.rb', line 754

def synthetics_resource_id
  info = synthetics_payload or return nil
  info[2]
end

#synthetics_versionObject



744
745
746
747
# File 'lib/new_relic/agent/transaction.rb', line 744

def synthetics_version
  info = synthetics_payload or return nil
  info[0]
end

#thresholdObject



910
911
912
913
914
915
916
917
# File 'lib/new_relic/agent/transaction.rb', line 910

def threshold
  source_class = Agent.config.source(:'transaction_tracer.transaction_threshold').class
  if source_class == Configuration::DefaultSource
    apdex_t * 4
  else
    Agent.config[:'transaction_tracer.transaction_threshold']
  end
end

#trace_idObject



326
327
328
# File 'lib/new_relic/agent/transaction.rb', line 326

def trace_id
  @trace_id ||= NewRelic::Agent::GuidGenerator.generate_guid(32)
end

#trace_id=(value) ⇒ Object



330
331
332
# File 'lib/new_relic/agent/transaction.rb', line 330

def trace_id=(value)
  @trace_id = value
end

#trace_ratio_sampled?(ratio) ⇒ Boolean

Returns:

  • (Boolean)


315
316
317
318
319
320
321
322
323
324
# File 'lib/new_relic/agent/transaction.rb', line 315

def trace_ratio_sampled?(ratio)
  # In the opentelemetry-sdk TraceIdRatioBased sampler, the algorithm
  # looks like this:
  # ratio == 1.0 || trace_id[8, 8].unpack1('Q>') < (ratio * (2**64 - 1)).ceil
  # OTel stores their trace ids as binary strings
  # ex. Array(trace_id).pack('H*')
  # Since we don't store our trace ids as binary strings, this way is
  # faster, but still gets the same result.
  ratio == 1.0 || Integer(trace_id[16, 16], 16) < (ratio * (2**64 - 1)).ceil
end

#transaction_specific_apdex_tObject



905
906
907
908
# File 'lib/new_relic/agent/transaction.rb', line 905

def transaction_specific_apdex_t
  key = :web_transactions_apdex
  Agent.config[key] && Agent.config[key][best_name]
end

#user_defined_rules_ignore?Boolean

Returns:

  • (Boolean)


590
591
592
593
594
595
596
597
# File 'lib/new_relic/agent/transaction.rb', line 590

def user_defined_rules_ignore?
  return false unless request_path
  return false if (rules = NewRelic::Agent.config[:"rules.ignore_url_regexes"]).empty?

  rules.any? do |rule|
    request_path.match(rule)
  end
end

#web_category?(category) ⇒ Boolean

Returns:

  • (Boolean)


956
957
958
# File 'lib/new_relic/agent/transaction.rb', line 956

def web_category?(category)
  WEB_TRANSACTION_CATEGORIES.include?(category)
end

#with_database_metric_name(model, method, product = nil) ⇒ Object



919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
# File 'lib/new_relic/agent/transaction.rb', line 919

def with_database_metric_name(model, method, product = nil)
  previous = self.instrumentation_state[:datastore_override]
  model_name = case model
               when Class
                 model.name
               when String
                 model
               else
                 model.to_s
  end
  self.instrumentation_state[:datastore_override] = [method, model_name, product]
  yield
ensure
  self.instrumentation_state[:datastore_override] = previous
end