newrelic_rpm 9.4.2 → 9.6.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (92) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +138 -10
  3. data/Rakefile +1 -1
  4. data/lib/new_relic/agent/attribute_pre_filtering.rb +109 -0
  5. data/lib/new_relic/agent/configuration/default_source.rb +153 -33
  6. data/lib/new_relic/agent/http_clients/async_http_wrappers.rb +83 -0
  7. data/lib/new_relic/agent/http_clients/ethon_wrappers.rb +111 -0
  8. data/lib/new_relic/agent/http_clients/httpx_wrappers.rb +93 -0
  9. data/lib/new_relic/agent/instrumentation/active_record_helper.rb +1 -2
  10. data/lib/new_relic/agent/instrumentation/active_support_broadcast_logger/chain.rb +69 -0
  11. data/lib/new_relic/agent/instrumentation/active_support_broadcast_logger/instrumentation.rb +13 -0
  12. data/lib/new_relic/agent/instrumentation/active_support_broadcast_logger/prepend.rb +37 -0
  13. data/lib/new_relic/agent/instrumentation/active_support_broadcast_logger.rb +23 -0
  14. data/lib/new_relic/agent/instrumentation/active_support_logger/instrumentation.rb +4 -0
  15. data/lib/new_relic/agent/instrumentation/active_support_logger.rb +3 -1
  16. data/lib/new_relic/agent/instrumentation/async_http/chain.rb +23 -0
  17. data/lib/new_relic/agent/instrumentation/async_http/instrumentation.rb +37 -0
  18. data/lib/new_relic/agent/instrumentation/async_http/prepend.rb +15 -0
  19. data/lib/new_relic/agent/instrumentation/async_http.rb +26 -0
  20. data/lib/new_relic/agent/instrumentation/bunny/instrumentation.rb +9 -0
  21. data/lib/new_relic/agent/instrumentation/concurrent_ruby/instrumentation.rb +2 -2
  22. data/lib/new_relic/agent/instrumentation/curb/instrumentation.rb +4 -0
  23. data/lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb +3 -0
  24. data/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb +4 -1
  25. data/lib/new_relic/agent/instrumentation/ethon/chain.rb +39 -0
  26. data/lib/new_relic/agent/instrumentation/ethon/instrumentation.rb +105 -0
  27. data/lib/new_relic/agent/instrumentation/ethon/prepend.rb +35 -0
  28. data/lib/new_relic/agent/instrumentation/ethon.rb +39 -0
  29. data/lib/new_relic/agent/instrumentation/excon/middleware.rb +3 -0
  30. data/lib/new_relic/agent/instrumentation/grape/instrumentation.rb +4 -0
  31. data/lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb +4 -0
  32. data/lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb +4 -0
  33. data/lib/new_relic/agent/instrumentation/grpc_client.rb +1 -1
  34. data/lib/new_relic/agent/instrumentation/grpc_server.rb +1 -1
  35. data/lib/new_relic/agent/instrumentation/httpclient/instrumentation.rb +4 -0
  36. data/lib/new_relic/agent/instrumentation/httprb/instrumentation.rb +4 -0
  37. data/lib/new_relic/agent/instrumentation/httpx/chain.rb +20 -0
  38. data/lib/new_relic/agent/instrumentation/httpx/instrumentation.rb +51 -0
  39. data/lib/new_relic/agent/instrumentation/httpx/prepend.rb +15 -0
  40. data/lib/new_relic/agent/instrumentation/httpx.rb +27 -0
  41. data/lib/new_relic/agent/instrumentation/logger/instrumentation.rb +3 -0
  42. data/lib/new_relic/agent/instrumentation/memcache/instrumentation.rb +9 -0
  43. data/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb +1 -3
  44. data/lib/new_relic/agent/instrumentation/net_http/instrumentation.rb +5 -1
  45. data/lib/new_relic/agent/instrumentation/notifications_subscriber.rb +4 -0
  46. data/lib/new_relic/agent/instrumentation/padrino/instrumentation.rb +4 -0
  47. data/lib/new_relic/agent/instrumentation/rack/instrumentation.rb +6 -0
  48. data/lib/new_relic/agent/instrumentation/rails3/action_controller.rb +4 -0
  49. data/lib/new_relic/agent/instrumentation/rails_notifications/action_controller.rb +1 -0
  50. data/lib/new_relic/agent/instrumentation/rake/instrumentation.rb +4 -0
  51. data/lib/new_relic/agent/instrumentation/redis/instrumentation.rb +4 -0
  52. data/lib/new_relic/agent/instrumentation/resque/instrumentation.rb +4 -0
  53. data/lib/new_relic/agent/instrumentation/roda/ignorer.rb +45 -0
  54. data/lib/new_relic/agent/instrumentation/roda/instrumentation.rb +16 -0
  55. data/lib/new_relic/agent/instrumentation/roda/roda_transaction_namer.rb +1 -2
  56. data/lib/new_relic/agent/instrumentation/roda.rb +2 -0
  57. data/lib/new_relic/agent/instrumentation/sidekiq/client.rb +4 -0
  58. data/lib/new_relic/agent/instrumentation/sidekiq/server.rb +26 -3
  59. data/lib/new_relic/agent/instrumentation/sidekiq.rb +5 -3
  60. data/lib/new_relic/agent/instrumentation/sinatra/instrumentation.rb +4 -0
  61. data/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb +1 -3
  62. data/lib/new_relic/agent/instrumentation/stripe.rb +28 -0
  63. data/lib/new_relic/agent/instrumentation/stripe_subscriber.rb +77 -0
  64. data/lib/new_relic/agent/instrumentation/tilt/instrumentation.rb +4 -0
  65. data/lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb +5 -1
  66. data/lib/new_relic/agent/messaging.rb +2 -2
  67. data/lib/new_relic/agent/monitors/synthetics_monitor.rb +12 -1
  68. data/lib/new_relic/agent/rules_engine.rb +1 -1
  69. data/lib/new_relic/agent/span_event_primitive.rb +16 -4
  70. data/lib/new_relic/agent/system_info.rb +26 -0
  71. data/lib/new_relic/agent/tracer.rb +1 -3
  72. data/lib/new_relic/agent/transaction/abstract_segment.rb +55 -0
  73. data/lib/new_relic/agent/transaction/external_request_segment.rb +5 -2
  74. data/lib/new_relic/agent/transaction/message_broker_segment.rb +1 -2
  75. data/lib/new_relic/agent/transaction/request_attributes.rb +1 -3
  76. data/lib/new_relic/agent/transaction.rb +25 -2
  77. data/lib/new_relic/agent/transaction_error_primitive.rb +16 -0
  78. data/lib/new_relic/agent/transaction_event_primitive.rb +19 -0
  79. data/lib/new_relic/agent/utilization/gcp.rb +1 -3
  80. data/lib/new_relic/agent.rb +18 -2
  81. data/lib/new_relic/constants.rb +3 -0
  82. data/lib/new_relic/control/frameworks/rails.rb +14 -2
  83. data/lib/new_relic/language_support.rb +4 -0
  84. data/lib/new_relic/rack/agent_hooks.rb +1 -1
  85. data/lib/new_relic/rack/agent_middleware.rb +0 -16
  86. data/lib/new_relic/supportability_helper.rb +1 -0
  87. data/lib/new_relic/version.rb +2 -2
  88. data/lib/tasks/instrumentation_generator/instrumentation.thor +3 -3
  89. data/lib/tasks/tests.rake +71 -0
  90. data/newrelic.yml +93 -32
  91. data/newrelic_rpm.gemspec +4 -1
  92. metadata +39 -2
@@ -7,9 +7,16 @@ module NewRelic::Agent::Instrumentation::Sidekiq
7
7
  include NewRelic::Agent::Instrumentation::ControllerInstrumentation
8
8
  include Sidekiq::ServerMiddleware if defined?(Sidekiq::ServerMiddleware)
9
9
 
10
+ ATTRIBUTE_BASE_NAMESPACE = 'sidekiq.args'
11
+ ATTRIBUTE_FILTER_TYPES = %i[include exclude].freeze
12
+ ATTRIBUTE_JOB_NAMESPACE = :"job.#{ATTRIBUTE_BASE_NAMESPACE}"
13
+ INSTRUMENTATION_NAME = 'SidekiqServer'
14
+
10
15
  # Client middleware has additional parameters, and our tests use the
11
16
  # middleware client-side to work inline.
12
17
  def call(worker, msg, queue, *_)
18
+ NewRelic::Agent.record_instrumentation_invocation(INSTRUMENTATION_NAME)
19
+
13
20
  trace_args = if worker.respond_to?(:newrelic_trace_args)
14
21
  worker.newrelic_trace_args(msg, queue)
15
22
  else
@@ -18,10 +25,16 @@ module NewRelic::Agent::Instrumentation::Sidekiq
18
25
  trace_headers = msg.delete(NewRelic::NEWRELIC_KEY)
19
26
 
20
27
  perform_action_with_newrelic_trace(trace_args) do
21
- NewRelic::Agent::Transaction.merge_untrusted_agent_attributes(msg['args'], :'job.sidekiq.args',
22
- NewRelic::Agent::AttributeFilter::DST_NONE)
28
+ NewRelic::Agent::Transaction.merge_untrusted_agent_attributes(
29
+ NewRelic::Agent::AttributePreFiltering.pre_filter(msg['args'], self.class.nr_attribute_options),
30
+ ATTRIBUTE_JOB_NAMESPACE,
31
+ NewRelic::Agent::AttributeFilter::DST_NONE
32
+ )
33
+
34
+ if ::NewRelic::Agent.config[:'distributed_tracing.enabled'] && trace_headers&.any?
35
+ ::NewRelic::Agent::DistributedTracing::accept_distributed_trace_headers(trace_headers, 'Other')
36
+ end
23
37
 
24
- ::NewRelic::Agent::DistributedTracing::accept_distributed_trace_headers(trace_headers, 'Other') if ::NewRelic::Agent.config[:'distributed_tracing.enabled'] && trace_headers&.any?
25
38
  yield
26
39
  end
27
40
  end
@@ -33,5 +46,15 @@ module NewRelic::Agent::Instrumentation::Sidekiq
33
46
  :category => 'OtherTransaction/SidekiqJob'
34
47
  }
35
48
  end
49
+
50
+ def self.nr_attribute_options
51
+ @nr_attribute_options ||= begin
52
+ ATTRIBUTE_FILTER_TYPES.each_with_object({}) do |type, opts|
53
+ pattern =
54
+ NewRelic::Agent::AttributePreFiltering.formulate_regexp_union(:"#{ATTRIBUTE_BASE_NAMESPACE}.#{type}")
55
+ opts[type] = pattern if pattern
56
+ end.merge(attribute_namespace: ATTRIBUTE_JOB_NAMESPACE)
57
+ end
58
+ end
36
59
  end
37
60
  end
@@ -33,7 +33,9 @@ DependencyDetection.defer do
33
33
  end
34
34
 
35
35
  if config.respond_to?(:error_handlers)
36
- config.error_handlers << proc do |error, *_|
36
+ # Sidekiq 3.0.0 - 7.1.4 expect error_handlers to have 2 arguments
37
+ # Sidekiq 7.1.5+ expect error_handlers to have 3 arguments
38
+ config.error_handlers << proc do |error, _ctx, *_|
37
39
  NewRelic::Agent.notice_error(error)
38
40
  end
39
41
  end
@@ -43,8 +45,8 @@ DependencyDetection.defer do
43
45
  executes do
44
46
  next unless Gem::Version.new(Sidekiq::VERSION) < Gem::Version.new('5.0.0')
45
47
 
46
- deprecation_msg = 'Instrumentation for Sidekiq versions below 5.0.0 is deprecated.' \
47
- 'They will stop being monitored in version 9.0.0. ' \
48
+ deprecation_msg = 'Instrumentation for Sidekiq versions below 5.0.0 is deprecated ' \
49
+ 'and will be dropped entirely in a future major New Relic Ruby agent release.' \
48
50
  'Please upgrade your Sidekiq version to continue receiving full support. '
49
51
 
50
52
  NewRelic::Agent.logger.log_once(
@@ -13,6 +13,8 @@ module NewRelic::Agent::Instrumentation
13
13
  module Tracer
14
14
  include ::NewRelic::Agent::Instrumentation::ControllerInstrumentation
15
15
 
16
+ INSTRUMENTATION_NAME = 'Sinatra'
17
+
16
18
  def self.included(clazz)
17
19
  clazz.extend(self)
18
20
  end
@@ -90,6 +92,8 @@ module NewRelic::Agent::Instrumentation
90
92
  end
91
93
 
92
94
  def dispatch_with_tracing
95
+ NewRelic::Agent.record_instrumentation_invocation(INSTRUMENTATION_NAME)
96
+
93
97
  request_params = get_request_params
94
98
  filtered_params = ::NewRelic::Agent::ParameterFiltering::apply_filters(request.env, request_params || {})
95
99
 
@@ -25,14 +25,12 @@ module NewRelic
25
25
  transaction_name(::NewRelic::Agent::UNKNOWN_METRIC, request)
26
26
  end
27
27
 
28
- ROOT = '/'.freeze
29
-
30
28
  def transaction_name(route_text, request)
31
29
  verb = http_verb(request)
32
30
 
33
31
  route_text = route_text.source if route_text.is_a?(Regexp)
34
32
  name = route_text.gsub(%r{^[/^\\A]*(.*?)[/\$\?\\z]*$}, '\1')
35
- name = ROOT if name.empty?
33
+ name = NewRelic::ROOT if name.empty?
36
34
  name = "#{verb} #{name}" unless verb.nil?
37
35
  name
38
36
  rescue => e
@@ -0,0 +1,28 @@
1
+ # This file is distributed under New Relic's license terms.
2
+ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
+ # frozen_string_literal: true
4
+
5
+ require 'new_relic/agent/instrumentation/stripe_subscriber'
6
+
7
+ DependencyDetection.defer do
8
+ named :stripe
9
+
10
+ depends_on do
11
+ NewRelic::Agent.config[:'instrumentation.stripe'] == 'enabled'
12
+ end
13
+
14
+ depends_on do
15
+ defined?(Stripe) &&
16
+ Gem::Version.new(Stripe::VERSION) >= Gem::Version.new('5.38.0')
17
+ end
18
+
19
+ executes do
20
+ NewRelic::Agent.logger.info('Installing Stripe instrumentation')
21
+ end
22
+
23
+ executes do
24
+ newrelic_subscriber = NewRelic::Agent::Instrumentation::StripeSubscriber.new
25
+ Stripe::Instrumentation.subscribe(:request_begin) { |event| newrelic_subscriber.start_segment(event) }
26
+ Stripe::Instrumentation.subscribe(:request_end) { |event| newrelic_subscriber.finish_segment(event) }
27
+ end
28
+ end
@@ -0,0 +1,77 @@
1
+ # This file is distributed under New Relic's license terms.
2
+ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
+ # frozen_string_literal: true
4
+
5
+ module NewRelic
6
+ module Agent
7
+ module Instrumentation
8
+ class StripeSubscriber
9
+ DEFAULT_DESTINATIONS = AttributeFilter::DST_SPAN_EVENTS
10
+ EVENT_ATTRIBUTES = %i[http_status method num_retries path request_id].freeze
11
+ ATTRIBUTE_NAMESPACE = 'stripe.user_data'
12
+ ATTRIBUTE_FILTER_TYPES = %i[include exclude].freeze
13
+
14
+ def start_segment(event)
15
+ return unless is_execution_traced?
16
+
17
+ segment = NewRelic::Agent::Tracer.start_segment(name: metric_name(event))
18
+ event.user_data[:newrelic_segment] = segment
19
+ rescue => e
20
+ NewRelic::Agent.logger.error("Error starting New Relic Stripe segment: #{e}")
21
+ end
22
+
23
+ def finish_segment(event)
24
+ return unless is_execution_traced?
25
+
26
+ segment = remove_and_return_nr_segment(event)
27
+ add_stripe_attributes(segment, event)
28
+ add_custom_attributes(segment, event)
29
+ rescue => e
30
+ NewRelic::Agent.logger.error("Error finishing New Relic Stripe segment: #{e}")
31
+ ensure
32
+ segment&.finish
33
+ end
34
+
35
+ private
36
+
37
+ def is_execution_traced?
38
+ NewRelic::Agent::Tracer.state.is_execution_traced?
39
+ end
40
+
41
+ def metric_name(event)
42
+ "Stripe#{event.path}/#{event.method}"
43
+ end
44
+
45
+ def add_stripe_attributes(segment, event)
46
+ EVENT_ATTRIBUTES.each do |attribute|
47
+ segment.add_agent_attribute("stripe_#{attribute}", event.send(attribute), DEFAULT_DESTINATIONS)
48
+ end
49
+ end
50
+
51
+ def add_custom_attributes(segment, event)
52
+ return if NewRelic::Agent.config[:'stripe.user_data.include'].empty?
53
+
54
+ filtered_attributes = NewRelic::Agent::AttributePreFiltering.pre_filter_hash(event.user_data, nr_attribute_options)
55
+ filtered_attributes.each do |key, value|
56
+ segment.add_agent_attribute("stripe_user_data_#{key}", value, DEFAULT_DESTINATIONS)
57
+ end
58
+ end
59
+
60
+ def nr_attribute_options
61
+ ATTRIBUTE_FILTER_TYPES.each_with_object({}) do |type, opts|
62
+ pattern =
63
+ NewRelic::Agent::AttributePreFiltering.formulate_regexp_union(:"#{ATTRIBUTE_NAMESPACE}.#{type}")
64
+ opts[type] = pattern if pattern
65
+ end
66
+ end
67
+
68
+ def remove_and_return_nr_segment(event)
69
+ segment = event.user_data[:newrelic_segment]
70
+ event.user_data.delete(:newrelic_segment)
71
+
72
+ segment
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -6,6 +6,8 @@ module NewRelic
6
6
  module Agent
7
7
  module Instrumentation
8
8
  module Tilt
9
+ INSTRUMENTATION_NAME = NewRelic::Agent.base_name(name)
10
+
9
11
  def metric_name(klass, file)
10
12
  "View/#{klass}/#{file}/Rendering"
11
13
  end
@@ -21,6 +23,8 @@ module NewRelic
21
23
  end
22
24
 
23
25
  def render_with_tracing(*args, &block)
26
+ NewRelic::Agent.record_instrumentation_invocation(INSTRUMENTATION_NAME)
27
+
24
28
  begin
25
29
  finishable = Tracer.start_segment(
26
30
  name: metric_name(self.class, create_filename_for_metric(self.file))
@@ -8,8 +8,8 @@ module NewRelic
8
8
  module Typhoeus
9
9
  HYDRA_SEGMENT_NAME = 'External/Multiple/Typhoeus::Hydra/run'
10
10
  NOTICEABLE_ERROR_CLASS = 'Typhoeus::Errors::TyphoeusError'
11
-
12
11
  EARLIEST_VERSION = Gem::Version.new('0.5.3')
12
+ INSTRUMENTATION_NAME = NewRelic::Agent.base_name(name)
13
13
 
14
14
  def self.is_supported_version?
15
15
  Gem::Version.new(::Typhoeus::VERSION) >= EARLIEST_VERSION
@@ -31,6 +31,8 @@ module NewRelic
31
31
  end
32
32
 
33
33
  def with_tracing
34
+ NewRelic::Agent.record_instrumentation_invocation(INSTRUMENTATION_NAME)
35
+
34
36
  segment = NewRelic::Agent::Tracer.start_segment(name: HYDRA_SEGMENT_NAME)
35
37
  instance_variable_set(:@__newrelic_hydra_segment, segment)
36
38
  begin
@@ -41,6 +43,8 @@ module NewRelic
41
43
  end
42
44
 
43
45
  def self.trace(request)
46
+ NewRelic::Agent.record_instrumentation_invocation(INSTRUMENTATION_NAME)
47
+
44
48
  state = NewRelic::Agent::Tracer.state
45
49
  return unless state.is_execution_traced?
46
50
 
@@ -329,9 +329,9 @@ module NewRelic
329
329
 
330
330
  def transaction_name(library, destination_type, destination_name)
331
331
  transaction_name = Transaction::MESSAGE_PREFIX + library
332
- transaction_name << Transaction::MessageBrokerSegment::SLASH
332
+ transaction_name << NewRelic::SLASH
333
333
  transaction_name << Transaction::MessageBrokerSegment::TYPES[destination_type]
334
- transaction_name << Transaction::MessageBrokerSegment::SLASH
334
+ transaction_name << NewRelic::SLASH
335
335
 
336
336
  case destination_type
337
337
  when :queue
@@ -5,7 +5,8 @@
5
5
  module NewRelic
6
6
  module Agent
7
7
  class SyntheticsMonitor < InboundRequestMonitor
8
- SYNTHETICS_HEADER_KEY = 'HTTP_X_NEWRELIC_SYNTHETICS'.freeze
8
+ SYNTHETICS_HEADER_KEY = 'HTTP_X_NEWRELIC_SYNTHETICS'
9
+ SYNTHETICS_INFO_HEADER_KEY = 'HTTP_X_NEWRELIC_SYNTHETICS_INFO'
9
10
 
10
11
  SUPPORTED_VERSION = 1
11
12
  EXPECTED_PAYLOAD_LENGTH = 5
@@ -16,6 +17,7 @@ module NewRelic
16
17
 
17
18
  def on_before_call(request) # THREAD_LOCAL_ACCESS
18
19
  encoded_header = request[SYNTHETICS_HEADER_KEY]
20
+ info_header = request[SYNTHETICS_INFO_HEADER_KEY]
19
21
  return unless encoded_header
20
22
 
21
23
  incoming_payload = deserialize_header(encoded_header, SYNTHETICS_HEADER_KEY)
@@ -27,7 +29,16 @@ module NewRelic
27
29
 
28
30
  txn = Tracer.current_transaction
29
31
  txn.raw_synthetics_header = encoded_header
32
+ txn.raw_synthetics_info_header = info_header
30
33
  txn.synthetics_payload = incoming_payload
34
+ txn.synthetics_info_payload = load_json(info_header, SYNTHETICS_INFO_HEADER_KEY)
35
+ end
36
+
37
+ def load_json(header, key)
38
+ ::JSON.load(header)
39
+ rescue => err
40
+ NewRelic::Agent.logger.debug("Failure loading json header '#{key}' in #{self.class}, #{err.class}, #{err.message}")
41
+ nil
31
42
  end
32
43
 
33
44
  class << self
@@ -9,7 +9,7 @@ require 'new_relic/language_support'
9
9
  module NewRelic
10
10
  module Agent
11
11
  class RulesEngine
12
- SEGMENT_SEPARATOR = '/'.freeze
12
+ SEGMENT_SEPARATOR = NewRelic::SLASH
13
13
  LEADING_SLASH_REGEX = %r{^/}.freeze
14
14
 
15
15
  include Enumerable
@@ -29,12 +29,16 @@ module NewRelic
29
29
  CATEGORY_KEY = 'category'
30
30
  HTTP_URL_KEY = 'http.url'
31
31
  HTTP_METHOD_KEY = 'http.method'
32
+ HTTP_REQUEST_METHOD_KEY = 'http.request.method'
32
33
  HTTP_STATUS_CODE_KEY = 'http.statusCode'
33
34
  COMPONENT_KEY = 'component'
34
35
  DB_INSTANCE_KEY = 'db.instance'
35
36
  DB_STATEMENT_KEY = 'db.statement'
37
+ DB_SYSTEM_KEY = 'db.system'
36
38
  PEER_ADDRESS_KEY = 'peer.address'
37
39
  PEER_HOSTNAME_KEY = 'peer.hostname'
40
+ SERVER_ADDRESS_KEY = 'server.address'
41
+ SERVER_PORT_KEY = 'server.port'
38
42
  SPAN_KIND_KEY = 'span.kind'
39
43
  ENTRY_POINT_KEY = 'nr.entryPoint'
40
44
  TRUSTED_PARENT_KEY = 'trustedParentId'
@@ -69,10 +73,12 @@ module NewRelic
69
73
 
70
74
  intrinsics[COMPONENT_KEY] = segment.library
71
75
  intrinsics[HTTP_METHOD_KEY] = segment.procedure
76
+ intrinsics[HTTP_REQUEST_METHOD_KEY] = segment.procedure
72
77
  intrinsics[HTTP_STATUS_CODE_KEY] = segment.http_status_code if segment.http_status_code
73
78
  intrinsics[CATEGORY_KEY] = HTTP_CATEGORY
74
79
  intrinsics[SPAN_KIND_KEY] = CLIENT
75
-
80
+ intrinsics[SERVER_ADDRESS_KEY] = segment.uri.host
81
+ intrinsics[SERVER_PORT_KEY] = segment.uri.port
76
82
  agent_attributes = error_attributes(segment) || {}
77
83
 
78
84
  if allowed?(HTTP_URL_KEY)
@@ -86,7 +92,7 @@ module NewRelic
86
92
  [intrinsics, custom_attributes(segment), agent_attributes]
87
93
  end
88
94
 
89
- def for_datastore_segment(segment)
95
+ def for_datastore_segment(segment) # rubocop:disable Metrics/AbcSize
90
96
  intrinsics = intrinsics_for(segment)
91
97
 
92
98
  intrinsics[COMPONENT_KEY] = segment.product
@@ -101,9 +107,15 @@ module NewRelic
101
107
  if segment.host && segment.port_path_or_id && allowed?(PEER_ADDRESS_KEY)
102
108
  agent_attributes[PEER_ADDRESS_KEY] = truncate("#{segment.host}:#{segment.port_path_or_id}")
103
109
  end
104
- if segment.host && allowed?(PEER_HOSTNAME_KEY)
105
- agent_attributes[PEER_HOSTNAME_KEY] = truncate(segment.host)
110
+ if segment.host
111
+ [PEER_HOSTNAME_KEY, SERVER_ADDRESS_KEY].each do |key|
112
+ agent_attributes[key] = truncate(segment.host) if allowed?(key)
113
+ end
114
+ end
115
+ if segment.port_path_or_id&.match?(/^\d+$/) && allowed?(SERVER_PORT_KEY)
116
+ agent_attributes[SERVER_PORT_KEY] = segment.port_path_or_id
106
117
  end
118
+ agent_attributes[DB_SYSTEM_KEY] = segment.product if allowed?(DB_SYSTEM_KEY)
107
119
 
108
120
  if segment.sql_statement && allowed?(DB_STATEMENT_KEY)
109
121
  agent_attributes[DB_STATEMENT_KEY] = truncate(segment.sql_statement.safe_sql, 2000)
@@ -13,6 +13,8 @@ require 'socket'
13
13
  module NewRelic
14
14
  module Agent
15
15
  module SystemInfo
16
+ DOCKER_CGROUPS_V2_PATTERN = %r{.*/docker/containers/([0-9a-f]{64})/.*}.freeze
17
+
16
18
  def self.ruby_os_identifier
17
19
  RbConfig::CONFIG['target_os']
18
20
  end
@@ -172,15 +174,39 @@ module NewRelic
172
174
  proc_try_read('/proc/version')
173
175
  end
174
176
 
177
+ # When operating within a Docker container, attempt to obtain the
178
+ # container id.
179
+ #
180
+ # First look for `/proc/self/mountinfo` to exist on disk to signify
181
+ # cgroups v2. If that file exists, read it and expect it to contain one
182
+ # or more "/docker/containers/<container_id>/" lines from which the
183
+ # container id can be gleaned.
184
+ #
185
+ # Next look for `/proc/self/cgroup` to exist on disk to signify cgroup v1.
186
+ # If that file exists, read it and parse the "cpu" group info in the hope
187
+ # of finding a 64 character container id value.
188
+ #
189
+ # For non-cgroups based containers, use a `nil` value for the container
190
+ # id without generating any warnings or errors.
175
191
  def self.docker_container_id
176
192
  return unless ruby_os_identifier.include?('linux')
177
193
 
194
+ cgroupsv2_based_id = docker_container_id_for_cgroupsv2
195
+ return cgroupsv2_based_id if cgroupsv2_based_id
196
+
178
197
  cgroup_info = proc_try_read('/proc/self/cgroup')
179
198
  return unless cgroup_info
180
199
 
181
200
  parse_docker_container_id(cgroup_info)
182
201
  end
183
202
 
203
+ def self.docker_container_id_for_cgroupsv2
204
+ mountinfo = proc_try_read('/proc/self/mountinfo')
205
+ return unless mountinfo
206
+
207
+ Regexp.last_match(1) if mountinfo =~ DOCKER_CGROUPS_V2_PATTERN
208
+ end
209
+
184
210
  def self.parse_docker_container_id(cgroup_info)
185
211
  cpu_cgroup = parse_cgroup_ids(cgroup_info)['cpu']
186
212
  return unless cpu_cgroup
@@ -357,9 +357,7 @@ module NewRelic
357
357
  yield
358
358
  rescue => exception
359
359
  # needs else branch coverage
360
- if segment && segment.is_a?(Transaction::AbstractSegment) # rubocop:disable Style/SafeNavigation
361
- segment.notice_error(exception)
362
- end
360
+ segment.notice_error(exception) if segment&.is_a?(Transaction::AbstractSegment)
363
361
  raise
364
362
  end
365
363
 
@@ -24,6 +24,9 @@ module NewRelic
24
24
  attr_writer :record_metrics, :record_scoped_metric, :record_on_finish
25
25
  attr_reader :noticed_error
26
26
 
27
+ CALLBACK = :@callback
28
+ SEGMENT = 'segment'
29
+
27
30
  def initialize(name = nil, start_time = nil)
28
31
  @name = name
29
32
  @starting_segment_key = NewRelic::Agent::Tracer.current_segment_key
@@ -49,6 +52,7 @@ module NewRelic
49
52
  @code_function = nil
50
53
  @code_lineno = nil
51
54
  @code_namespace = nil
55
+ invoke_callback
52
56
  end
53
57
 
54
58
  def start
@@ -327,6 +331,57 @@ module NewRelic
327
331
  Tracer.state
328
332
  end
329
333
  end
334
+
335
+ # for segment callback usage info, see self.set_segment_callback
336
+ def invoke_callback
337
+ return unless self.class.instance_variable_defined?(CALLBACK)
338
+
339
+ NewRelic::Agent.logger.debug("Invoking callback for #{self.class.name}...")
340
+ self.class.instance_variable_get(CALLBACK).call
341
+ rescue Exception => e
342
+ NewRelic::Agent.logger.error("Error encountered while invoking callback for #{self.class.name}: " +
343
+ "#{e.class} - #{e.message}")
344
+ end
345
+
346
+ # Setting and invoking a segment callback
347
+ # =======================================
348
+ # Each individual segment class such as `ExternalRequestSegment` allows
349
+ # for exactly one instance of a `Proc` (meaning a proc or lambda) to be
350
+ # set as a callback. A callback can be set on a segment class by calling
351
+ # `.set_segment_callback` with a proc or lambda as the only argument.
352
+ # If set, the callback will be invoked with `#call` at segment class
353
+ # initialization time.
354
+ #
355
+ # Example usage:
356
+ # callback = -> { puts 'Hello, World! }
357
+ # ExternalRequestSegment.set_segment_callback(callback)
358
+ # ExternalRequestSegment.new(library, uri, procedure)
359
+ #
360
+ # A callback set on a segment class will only be called when that
361
+ # specific segment class is initialized. Other segment classes will not
362
+ # be impacted.
363
+ #
364
+ # Great caution should be taken in the defining of the callback block
365
+ # to not have the block perform anything too time consuming or resource
366
+ # intensive in order to keep the New Relic Ruby agent operating
367
+ # normally.
368
+ #
369
+ # Given that callbacks are user defined, they must be set entirely at
370
+ # the user's own risk. It is recommended that each callback use
371
+ # conditional logic that only performs work for certain qualified
372
+ # segments. It is recommended that each callback be thoroughly tested
373
+ # in non-production environments before being introduced to production
374
+ # environments.
375
+ def self.set_segment_callback(callback_proc)
376
+ unless callback_proc.is_a?(Proc)
377
+ NewRelic::Agent.logger.error("#{self}.#{__method__}: expected an argument of type Proc, " \
378
+ "got #{callback_proc.class}")
379
+ return
380
+ end
381
+
382
+ NewRelic::Agent.record_api_supportability_metric(:set_segment_callback)
383
+ instance_variable_set(CALLBACK, callback_proc)
384
+ end
330
385
  end
331
386
  end
332
387
  end
@@ -14,6 +14,7 @@ module NewRelic
14
14
  # @api public
15
15
  class ExternalRequestSegment < Segment
16
16
  NR_SYNTHETICS_HEADER = 'X-NewRelic-Synthetics'
17
+ NR_SYNTHETICS_INFO_HEADER = 'X-NewRelic-Synthetics-Info'
17
18
  APP_DATA_KEY = 'NewRelicAppData'
18
19
 
19
20
  EXTERNAL_ALL = 'External/all'
@@ -63,7 +64,8 @@ module NewRelic
63
64
  def add_request_headers(request)
64
65
  process_host_header(request)
65
66
  synthetics_header = transaction&.raw_synthetics_header
66
- insert_synthetics_header(request, synthetics_header) if synthetics_header
67
+ synthetics_info_header = transaction&.raw_synthetics_info_header
68
+ insert_synthetics_header(request, synthetics_header, synthetics_info_header) if synthetics_header
67
69
 
68
70
  return unless record_metrics?
69
71
 
@@ -207,8 +209,9 @@ module NewRelic
207
209
  end
208
210
  end
209
211
 
210
- def insert_synthetics_header(request, header)
212
+ def insert_synthetics_header(request, header, info)
211
213
  request[NR_SYNTHETICS_HEADER] = header
214
+ request[NR_SYNTHETICS_INFO_HEADER] = info if info
212
215
  end
213
216
 
214
217
  def segment_complete
@@ -15,7 +15,6 @@ module NewRelic
15
15
  PRODUCE = 'Produce'.freeze
16
16
  QUEUE = 'Queue'.freeze
17
17
  PURGE = 'Purge'.freeze
18
- SLASH = '/'.freeze
19
18
  TEMP = 'Temp'.freeze
20
19
  TOPIC = 'Topic'.freeze
21
20
  UNKNOWN = 'Unknown'.freeze
@@ -73,7 +72,7 @@ module NewRelic
73
72
  return @name if @name
74
73
 
75
74
  @name = METRIC_PREFIX + library
76
- @name << SLASH << TYPES[destination_type] << SLASH << ACTIONS[action] << SLASH
75
+ @name << NewRelic::SLASH << TYPES[destination_type] << NewRelic::SLASH << ACTIONS[action] << NewRelic::SLASH
77
76
 
78
77
  if destination_type == :temporary_queue || destination_type == :temporary_topic
79
78
  @name << TEMP
@@ -103,12 +103,10 @@ module NewRelic
103
103
  # rails construct the PATH_INFO enviroment variable improperly and we're generally
104
104
  # being defensive.
105
105
 
106
- ROOT_PATH = '/'.freeze
107
-
108
106
  def path_from_request(request)
109
107
  path = attribute_from_request(request, :path) || ''
110
108
  path = HTTPClients::URIUtil.strip_query_string(path)
111
- path.empty? ? ROOT_PATH : path
109
+ path.empty? ? NewRelic::ROOT : path
112
110
  end
113
111
 
114
112
  def content_length_from_request(request)
@@ -90,7 +90,7 @@ module NewRelic
90
90
  attr_reader :transaction_trace
91
91
 
92
92
  # Fields for tracking synthetics requests
93
- attr_accessor :raw_synthetics_header, :synthetics_payload
93
+ attr_accessor :raw_synthetics_header, :synthetics_payload, :synthetics_info_payload, :raw_synthetics_info_header
94
94
 
95
95
  # Return the currently active transaction, or nil.
96
96
  def self.tl_current
@@ -520,7 +520,7 @@ module NewRelic
520
520
  end
521
521
 
522
522
  def finish
523
- return unless state.is_execution_traced?
523
+ return unless state.is_execution_traced? && initial_segment
524
524
 
525
525
  @end_time = Process.clock_gettime(Process::CLOCK_REALTIME)
526
526
  @duration = @end_time - @start_time
@@ -623,11 +623,24 @@ module NewRelic
623
623
  attributes.add_intrinsic_attribute(:synthetics_resource_id, synthetics_resource_id)
624
624
  attributes.add_intrinsic_attribute(:synthetics_job_id, synthetics_job_id)
625
625
  attributes.add_intrinsic_attribute(:synthetics_monitor_id, synthetics_monitor_id)
626
+ attributes.add_intrinsic_attribute(:synthetics_type, synthetics_info('type'))
627
+ attributes.add_intrinsic_attribute(:synthetics_initiator, synthetics_info('initiator'))
628
+
629
+ synthetics_additional_attributes do |key, value|
630
+ attributes.add_intrinsic_attribute(key, value)
631
+ end
626
632
  end
627
633
 
628
634
  distributed_tracer.assign_intrinsics
629
635
  end
630
636
 
637
+ def synthetics_additional_attributes(&block)
638
+ synthetics_info('attributes')&.each do |k, v|
639
+ new_key = "synthetics_#{NewRelic::LanguageSupport.snakeize(k.to_s)}".to_sym
640
+ yield(new_key, v.to_s)
641
+ end
642
+ end
643
+
631
644
  def calculate_gc_time
632
645
  gc_stop_snapshot = NewRelic::Agent::StatsEngine::GCProfiler.take_snapshot
633
646
  NewRelic::Agent::StatsEngine::GCProfiler.record_delta(gc_start_snapshot, gc_stop_snapshot)
@@ -707,6 +720,10 @@ module NewRelic
707
720
  info[4]
708
721
  end
709
722
 
723
+ def synthetics_info(key)
724
+ synthetics_info_payload[key] if synthetics_info_payload
725
+ end
726
+
710
727
  def append_apdex_perf_zone(payload)
711
728
  if recording_web_transaction?
712
729
  bucket = apdex_bucket(duration, apdex_t)
@@ -730,6 +747,12 @@ module NewRelic
730
747
  payload[:synthetics_resource_id] = synthetics_resource_id
731
748
  payload[:synthetics_job_id] = synthetics_job_id
732
749
  payload[:synthetics_monitor_id] = synthetics_monitor_id
750
+ payload[:synthetics_type] = synthetics_info('type')
751
+ payload[:synthetics_initiator] = synthetics_info('initiator')
752
+
753
+ synthetics_additional_attributes do |key, value|
754
+ payload[key] = value
755
+ end
733
756
  end
734
757
 
735
758
  def merge_metrics