newrelic_rpm 9.5.0 → 9.8.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (132) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +154 -7
  3. data/CONTRIBUTING.md +0 -7
  4. data/README.md +1 -1
  5. data/Rakefile +1 -1
  6. data/bin/newrelic +2 -9
  7. data/bin/newrelic_rpm +15 -0
  8. data/init.rb +2 -2
  9. data/lib/new_relic/agent/agent.rb +1 -1
  10. data/lib/new_relic/agent/agent_helpers/shutdown.rb +1 -1
  11. data/lib/new_relic/agent/agent_helpers/special_startup.rb +1 -1
  12. data/lib/new_relic/agent/agent_helpers/start_worker_thread.rb +2 -2
  13. data/lib/new_relic/agent/agent_helpers/startup.rb +2 -2
  14. data/lib/new_relic/agent/attribute_filter.rb +3 -3
  15. data/lib/new_relic/agent/configuration/default_source.rb +131 -36
  16. data/lib/new_relic/agent/configuration/high_security_source.rb +1 -0
  17. data/lib/new_relic/agent/configuration/manager.rb +13 -9
  18. data/lib/new_relic/agent/configuration/security_policy_source.rb +11 -0
  19. data/lib/new_relic/agent/custom_event_aggregator.rb +27 -1
  20. data/lib/new_relic/agent/datastores/mongo/metric_translator.rb +1 -1
  21. data/lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb +3 -3
  22. data/lib/new_relic/agent/error_collector.rb +2 -0
  23. data/lib/new_relic/agent/event_loop.rb +1 -1
  24. data/lib/new_relic/agent/http_clients/abstract.rb +4 -0
  25. data/lib/new_relic/agent/http_clients/async_http_wrappers.rb +80 -0
  26. data/lib/new_relic/agent/http_clients/curb_wrappers.rb +1 -3
  27. data/lib/new_relic/agent/http_clients/ethon_wrappers.rb +109 -0
  28. data/lib/new_relic/agent/http_clients/excon_wrappers.rb +0 -3
  29. data/lib/new_relic/agent/http_clients/http_rb_wrappers.rb +1 -3
  30. data/lib/new_relic/agent/http_clients/httpclient_wrappers.rb +0 -3
  31. data/lib/new_relic/agent/http_clients/httpx_wrappers.rb +91 -0
  32. data/lib/new_relic/agent/http_clients/net_http_wrappers.rb +1 -4
  33. data/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb +0 -3
  34. data/lib/new_relic/agent/instrumentation/active_merchant.rb +1 -1
  35. data/lib/new_relic/agent/instrumentation/active_record_helper.rb +1 -2
  36. data/lib/new_relic/agent/instrumentation/active_support_broadcast_logger/chain.rb +69 -0
  37. data/lib/new_relic/agent/instrumentation/active_support_broadcast_logger/instrumentation.rb +17 -0
  38. data/lib/new_relic/agent/instrumentation/active_support_broadcast_logger/prepend.rb +37 -0
  39. data/lib/new_relic/agent/instrumentation/active_support_broadcast_logger.rb +23 -0
  40. data/lib/new_relic/agent/instrumentation/active_support_logger.rb +3 -1
  41. data/lib/new_relic/agent/instrumentation/async_http/chain.rb +23 -0
  42. data/lib/new_relic/agent/instrumentation/async_http/instrumentation.rb +37 -0
  43. data/lib/new_relic/agent/instrumentation/async_http/prepend.rb +15 -0
  44. data/lib/new_relic/agent/instrumentation/async_http.rb +28 -0
  45. data/lib/new_relic/agent/instrumentation/concurrent_ruby.rb +1 -0
  46. data/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb +1 -1
  47. data/lib/new_relic/agent/instrumentation/ethon/chain.rb +39 -0
  48. data/lib/new_relic/agent/instrumentation/ethon/instrumentation.rb +105 -0
  49. data/lib/new_relic/agent/instrumentation/ethon/prepend.rb +35 -0
  50. data/lib/new_relic/agent/instrumentation/ethon.rb +39 -0
  51. data/lib/new_relic/agent/instrumentation/fiber/instrumentation.rb +1 -4
  52. data/lib/new_relic/agent/instrumentation/grpc_server.rb +1 -1
  53. data/lib/new_relic/agent/instrumentation/httpx/chain.rb +20 -0
  54. data/lib/new_relic/agent/instrumentation/httpx/instrumentation.rb +51 -0
  55. data/lib/new_relic/agent/instrumentation/httpx/prepend.rb +15 -0
  56. data/lib/new_relic/agent/instrumentation/httpx.rb +27 -0
  57. data/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb +1 -3
  58. data/lib/new_relic/agent/instrumentation/net_http/instrumentation.rb +7 -1
  59. data/lib/new_relic/agent/instrumentation/rails_notifications/action_controller.rb +1 -0
  60. data/lib/new_relic/agent/instrumentation/roda/ignorer.rb +45 -0
  61. data/lib/new_relic/agent/instrumentation/roda/instrumentation.rb +12 -0
  62. data/lib/new_relic/agent/instrumentation/roda/roda_transaction_namer.rb +1 -2
  63. data/lib/new_relic/agent/instrumentation/roda.rb +2 -0
  64. data/lib/new_relic/agent/instrumentation/ruby_openai/chain.rb +36 -0
  65. data/lib/new_relic/agent/instrumentation/ruby_openai/instrumentation.rb +197 -0
  66. data/lib/new_relic/agent/instrumentation/ruby_openai/prepend.rb +20 -0
  67. data/lib/new_relic/agent/instrumentation/ruby_openai.rb +35 -0
  68. data/lib/new_relic/agent/instrumentation/sidekiq.rb +3 -1
  69. data/lib/new_relic/agent/instrumentation/sinatra/ignorer.rb +1 -1
  70. data/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb +1 -3
  71. data/lib/new_relic/agent/instrumentation/sinatra.rb +1 -1
  72. data/lib/new_relic/agent/instrumentation/thread/instrumentation.rb +1 -4
  73. data/lib/new_relic/agent/instrumentation/view_component/chain.rb +21 -0
  74. data/lib/new_relic/agent/instrumentation/view_component/instrumentation.rb +39 -0
  75. data/lib/new_relic/agent/instrumentation/view_component/prepend.rb +13 -0
  76. data/lib/new_relic/agent/instrumentation/view_component.rb +26 -0
  77. data/lib/new_relic/agent/javascript_instrumentor.rb +0 -1
  78. data/lib/new_relic/agent/llm/chat_completion_message.rb +25 -0
  79. data/lib/new_relic/agent/llm/chat_completion_summary.rb +66 -0
  80. data/lib/new_relic/agent/llm/embedding.rb +60 -0
  81. data/lib/new_relic/agent/llm/llm_event.rb +95 -0
  82. data/lib/new_relic/agent/llm/response_headers.rb +80 -0
  83. data/lib/new_relic/agent/llm.rb +49 -0
  84. data/lib/new_relic/agent/messaging.rb +2 -2
  85. data/lib/new_relic/agent/monitors/synthetics_monitor.rb +12 -1
  86. data/lib/new_relic/agent/new_relic_service/encoders.rb +2 -2
  87. data/lib/new_relic/agent/new_relic_service.rb +8 -6
  88. data/lib/new_relic/agent/obfuscator.rb +0 -2
  89. data/lib/new_relic/agent/pipe_channel_manager.rb +2 -2
  90. data/lib/new_relic/agent/rules_engine/segment_terms_rule.rb +1 -2
  91. data/lib/new_relic/agent/rules_engine.rb +1 -1
  92. data/lib/new_relic/agent/span_event_primitive.rb +16 -4
  93. data/lib/new_relic/agent/sql_sampler.rb +0 -1
  94. data/lib/new_relic/agent/system_info.rb +26 -0
  95. data/lib/new_relic/agent/threading/agent_thread.rb +1 -2
  96. data/lib/new_relic/agent/tracer.rb +9 -10
  97. data/lib/new_relic/agent/transaction/abstract_segment.rb +4 -1
  98. data/lib/new_relic/agent/transaction/external_request_segment.rb +5 -2
  99. data/lib/new_relic/agent/transaction/message_broker_segment.rb +1 -2
  100. data/lib/new_relic/agent/transaction/request_attributes.rb +1 -3
  101. data/lib/new_relic/agent/transaction/tracing.rb +11 -1
  102. data/lib/new_relic/agent/transaction.rb +25 -2
  103. data/lib/new_relic/agent/transaction_error_primitive.rb +16 -0
  104. data/lib/new_relic/agent/transaction_event_primitive.rb +19 -0
  105. data/lib/new_relic/agent/utilization/gcp.rb +1 -3
  106. data/lib/new_relic/agent/vm/{mri_vm.rb → c_ruby_vm.rb} +7 -15
  107. data/lib/new_relic/agent/vm.rb +2 -2
  108. data/lib/new_relic/agent/worker_loop.rb +1 -1
  109. data/lib/new_relic/agent.rb +102 -7
  110. data/lib/new_relic/base64.rb +25 -0
  111. data/lib/new_relic/cli/command.rb +6 -4
  112. data/lib/new_relic/constants.rb +5 -0
  113. data/lib/new_relic/control/frameworks/rails.rb +17 -5
  114. data/lib/new_relic/control/instrumentation.rb +1 -1
  115. data/lib/new_relic/language_support.rb +4 -0
  116. data/lib/new_relic/local_environment.rb +22 -13
  117. data/lib/new_relic/rack/browser_monitoring.rb +8 -4
  118. data/lib/new_relic/supportability_helper.rb +3 -1
  119. data/lib/new_relic/thread_local_storage.rb +31 -0
  120. data/lib/new_relic/version.rb +1 -1
  121. data/lib/tasks/config.rake +1 -1
  122. data/lib/tasks/helpers/config.html.erb +6 -6
  123. data/lib/tasks/helpers/newrelicyml.rb +1 -1
  124. data/lib/tasks/instrumentation_generator/instrumentation.thor +3 -3
  125. data/lib/tasks/instrumentation_generator/templates/chain.tt +0 -1
  126. data/lib/tasks/instrumentation_generator/templates/chain_method.tt +0 -1
  127. data/lib/tasks/tests.rake +71 -0
  128. data/newrelic.yml +76 -36
  129. data/newrelic_rpm.gemspec +5 -4
  130. data/test/agent_helper.rb +14 -2
  131. metadata +43 -7
  132. data/bin/newrelic_cmd +0 -7
@@ -0,0 +1,80 @@
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 Llm
8
+ module ResponseHeaders
9
+ ATTRIBUTES = %i[response_organization llm_version ratelimit_limit_requests
10
+ ratelimit_limit_tokens ratelimit_remaining_requests
11
+ ratelimit_remaining_tokens ratelimit_reset_requests
12
+ ratelimit_reset_tokens ratelimit_limit_tokens_usage_based
13
+ ratelimit_reset_tokens_usage_based
14
+ ratelimit_remaining_tokens_usage_based].freeze
15
+
16
+ ATTRIBUTE_NAME_EXCEPTIONS = {
17
+ response_organization: 'response.organization',
18
+ llm_version: 'response.headers.llmVersion',
19
+ ratelimit_limit_requests: 'response.headers.ratelimitLimitRequests',
20
+ ratelimit_limit_tokens: 'response.headers.ratelimitLimitTokens',
21
+ ratelimit_remaining_requests: 'response.headers.ratelimitRemainingRequests',
22
+ ratelimit_remaining_tokens: 'response.headers.ratelimitRemainingTokens',
23
+ ratelimit_reset_requests: 'response.headers.ratelimitResetRequests',
24
+ ratelimit_reset_tokens: 'response.headers.ratelimitResetTokens',
25
+ ratelimit_limit_tokens_usage_based: 'response.headers.ratelimitLimitTokensUsageBased',
26
+ ratelimit_reset_tokens_usage_based: 'response.headers.ratelimitResetTokensUsageBased',
27
+ ratelimit_remaining_tokens_usage_based: 'response.headers.ratelimitRemainingTokensUsageBased'
28
+ }.freeze
29
+
30
+ OPENAI_ORGANIZATION = 'openai-organization'
31
+ OPENAI_VERSION = 'openai-version'
32
+ X_RATELIMIT_LIMIT_REQUESTS = 'x-ratelimit-limit-requests'
33
+ X_RATELIMIT_LIMIT_TOKENS = 'x-ratelimit-limit-tokens'
34
+ X_RATELIMIT_REMAINING_REQUESTS = 'x-ratelimit-remaining-requests'
35
+ X_RATELIMIT_REMAINING_TOKENS = 'x-ratelimit-remaining-tokens'
36
+ X_RATELIMIT_RESET_REQUESTS = 'x-ratelimit-reset-requests'
37
+ X_RATELIMIT_RESET_TOKENS = 'x-ratelimit-reset-tokens'
38
+ X_RATELIMIT_LIMIT_TOKENS_USAGE_BASED = 'x-ratelimit-limit-tokens-usage-based'
39
+ X_RATELIMIT_RESET_TOKENS_USAGE_BASED = 'x-ratelimit-reset-tokens-usage-based'
40
+ X_RATELIMIT_REMAINING_TOKENS_USAGE_BASED = 'x-ratelimit-remaining-tokens-usage-based'
41
+ X_REQUEST_ID = 'x-request-id'
42
+
43
+ attr_accessor(*ATTRIBUTES)
44
+
45
+ # Headers is a hash of Net::HTTP response headers
46
+ def populate_openai_response_headers(headers)
47
+ # Embedding, ChatCompletionSummary, and ChatCompletionMessage all need
48
+ # request_id, so it's defined in LlmEvent. ChatCompletionMessage
49
+ # adds the attribute via ChatCompletionSummary.
50
+ self.request_id = headers[X_REQUEST_ID]&.first
51
+ self.response_organization = headers[OPENAI_ORGANIZATION]&.first
52
+ self.llm_version = headers[OPENAI_VERSION]&.first
53
+ self.ratelimit_limit_requests = headers[X_RATELIMIT_LIMIT_REQUESTS]&.first.to_i
54
+ self.ratelimit_limit_tokens = headers[X_RATELIMIT_LIMIT_TOKENS]&.first.to_i
55
+ remaining_headers(headers)
56
+ reset_headers(headers)
57
+ tokens_usage_based_headers(headers)
58
+ end
59
+
60
+ private
61
+
62
+ def remaining_headers(headers)
63
+ self.ratelimit_remaining_requests = headers[X_RATELIMIT_REMAINING_REQUESTS]&.first.to_i
64
+ self.ratelimit_remaining_tokens = headers[X_RATELIMIT_REMAINING_TOKENS]&.first.to_i
65
+ end
66
+
67
+ def reset_headers(headers)
68
+ self.ratelimit_reset_requests = headers[X_RATELIMIT_RESET_REQUESTS]&.first
69
+ self.ratelimit_reset_tokens = headers[X_RATELIMIT_RESET_TOKENS]&.first
70
+ end
71
+
72
+ def tokens_usage_based_headers(headers)
73
+ self.ratelimit_limit_tokens_usage_based = headers[X_RATELIMIT_LIMIT_TOKENS_USAGE_BASED]&.first.to_i
74
+ self.ratelimit_reset_tokens_usage_based = headers[X_RATELIMIT_RESET_TOKENS_USAGE_BASED]&.first
75
+ self.ratelimit_remaining_tokens_usage_based = headers[X_RATELIMIT_REMAINING_TOKENS_USAGE_BASED]&.first.to_i
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,49 @@
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_relative 'llm/llm_event'
6
+ require_relative 'llm/chat_completion_message'
7
+ require_relative 'llm/chat_completion_summary'
8
+ require_relative 'llm/embedding'
9
+ require_relative 'llm/response_headers'
10
+
11
+ module NewRelic
12
+ module Agent
13
+ class LLM
14
+ INPUT = 'input'
15
+ CONTENT = 'content'
16
+ SEGMENT_PATTERN = %r{Llm/.+/OpenAI/.+}.freeze
17
+
18
+ def self.instrumentation_enabled?
19
+ NewRelic::Agent.config[:'ai_monitoring.enabled']
20
+ end
21
+
22
+ # LLM content-related attributes are exempt from the 4095 byte limit
23
+ def self.exempt_event_attribute?(type, key)
24
+ return false unless instrumentation_enabled?
25
+
26
+ (type == NewRelic::Agent::Llm::Embedding::EVENT_NAME && key == INPUT) ||
27
+ (type == NewRelic::Agent::Llm::ChatCompletionMessage::EVENT_NAME && key == CONTENT)
28
+ end
29
+
30
+ def self.openai?
31
+ @openai ||= %i[prepend chain].include?(NewRelic::Agent.config[:'instrumentation.ruby_openai']) &&
32
+ NewRelic::Agent.config[:'ai_monitoring.enabled']
33
+ end
34
+
35
+ # Used in NetHTTP instrumentation
36
+ def self.openai_parent?(segment)
37
+ return false unless openai?
38
+
39
+ segment&.parent&.name&.match?(SEGMENT_PATTERN)
40
+ end
41
+
42
+ def self.populate_openai_response_headers(response, parent)
43
+ return unless parent.instance_variable_defined?(:@llm_event)
44
+
45
+ parent.llm_event.populate_openai_response_headers(response.to_hash)
46
+ end
47
+ end
48
+ end
49
+ end
@@ -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
@@ -2,10 +2,10 @@
2
2
  # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
3
  # frozen_string_literal: true
4
4
 
5
- require 'base64'
6
5
  require 'json'
7
6
  require 'stringio'
8
7
  require 'zlib'
8
+ require 'new_relic/base64'
9
9
 
10
10
  module NewRelic
11
11
  module Agent
@@ -45,7 +45,7 @@ module NewRelic
45
45
  data = NewRelic::Agent::EncodingNormalizer.normalize_object(data)
46
46
  end
47
47
  json = ::JSON.dump(data)
48
- Base64.encode64(Compressed::Deflate.encode(json))
48
+ NewRelic::Base64.encode64(Compressed::Deflate.encode(json))
49
49
  end
50
50
  end
51
51
  end
@@ -414,7 +414,7 @@ module NewRelic
414
414
  else
415
415
  request = Net::HTTP::Post.new(opts[:uri], headers)
416
416
  end
417
- @audit_logger.log_request_headers(opts[:uri], headers)
417
+ @audit_logger.log_request_headers(filtered_uri(opts[:uri]), headers)
418
418
  request['user-agent'] = user_agent
419
419
  request.content_type = 'application/octet-stream'
420
420
  request.body = opts[:data]
@@ -431,7 +431,7 @@ module NewRelic
431
431
  rescue *CONNECTION_ERRORS => e
432
432
  close_shared_connection
433
433
  if attempts < MAX_ATTEMPTS
434
- ::NewRelic::Agent.logger.debug("Retrying request to #{opts[:collector]}#{opts[:uri]} after #{e}")
434
+ ::NewRelic::Agent.logger.debug("Retrying request to #{opts[:collector]}#{filtered_uri(opts[:uri])} after #{e}")
435
435
  retry
436
436
  else
437
437
  raise ServerConnectionException, "Recoverable error talking to #{@collector} after #{attempts} attempts: #{e}"
@@ -444,7 +444,7 @@ module NewRelic
444
444
 
445
445
  def attempt_request(request, opts)
446
446
  conn = http_connection
447
- ::NewRelic::Agent.logger.debug("Sending request to #{opts[:collector]}#{opts[:uri]} with #{request.method}")
447
+ ::NewRelic::Agent.logger.debug("Sending request to #{opts[:collector]}#{filtered_uri(opts[:uri])} with #{request.method}")
448
448
  conn.request(request)
449
449
  end
450
450
 
@@ -689,9 +689,7 @@ module NewRelic
689
689
 
690
690
  def invoke_remote_send_request(method, payload, data, encoding)
691
691
  uri = remote_method_uri(method)
692
- full_uri = "#{@collector}#{uri}"
693
-
694
- @audit_logger.log_request(full_uri, payload, @marshaller)
692
+ @audit_logger.log_request("#{@collector}#{filtered_uri(uri)}", payload, @marshaller)
695
693
  request_send_ts = Process.clock_gettime(Process::CLOCK_MONOTONIC)
696
694
  response = send_request(:data => data,
697
695
  :uri => uri,
@@ -700,6 +698,10 @@ module NewRelic
700
698
  :endpoint => method)
701
699
  [response, request_send_ts, Process.clock_gettime(Process::CLOCK_MONOTONIC)]
702
700
  end
701
+
702
+ def filtered_uri(uri)
703
+ uri.gsub(license_key, ASTERISK * license_key.size)
704
+ end
703
705
  end
704
706
  end
705
707
  end
@@ -2,8 +2,6 @@
2
2
  # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
3
  # frozen_string_literal: true
4
4
 
5
- # require 'base64'
6
-
7
5
  module NewRelic
8
6
  module Agent
9
7
  class Obfuscator
@@ -2,7 +2,7 @@
2
2
  # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
3
  # frozen_string_literal: true
4
4
 
5
- require 'base64'
5
+ require 'new_relic/base64'
6
6
 
7
7
  module NewRelic
8
8
  module Agent
@@ -257,7 +257,7 @@ module NewRelic
257
257
  Marshal.load(data)
258
258
  rescue StandardError => e
259
259
  ::NewRelic::Agent.logger.error('Failure unmarshalling message from Resque child process', e)
260
- ::NewRelic::Agent.logger.debug(Base64.encode64(data))
260
+ ::NewRelic::Agent.logger.debug(NewRelic::Base64.encode64(data))
261
261
  nil
262
262
  end
263
263
 
@@ -8,7 +8,6 @@ module NewRelic
8
8
  class SegmentTermsRule
9
9
  PREFIX_KEY = 'prefix'.freeze
10
10
  TERMS_KEY = 'terms'.freeze
11
- SEGMENT_PLACEHOLDER = '*'.freeze
12
11
  ADJACENT_PLACEHOLDERS_REGEX = %r{((?:^|/)\*)(?:/\*)*}.freeze
13
12
  ADJACENT_PLACEHOLDERS_REPLACEMENT = '\1'.freeze
14
13
 
@@ -52,7 +51,7 @@ module NewRelic
52
51
  rest = string[@trim_range]
53
52
  leading_slash = rest.slice!(LEADING_SLASH_REGEX)
54
53
  segments = rest.split(SEGMENT_SEPARATOR, -1)
55
- segments.map! { |s| @terms.include?(s) ? s : SEGMENT_PLACEHOLDER }
54
+ segments.map! { |s| @terms.include?(s) ? s : ASTERISK }
56
55
  transformed_suffix = collapse_adjacent_placeholder_segments(segments)
57
56
 
58
57
  "#{@prefix}#{leading_slash}#{transformed_suffix}"
@@ -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)
@@ -3,7 +3,6 @@
3
3
  # frozen_string_literal: true
4
4
 
5
5
  require 'zlib'
6
- require 'base64'
7
6
  require 'digest/md5'
8
7
 
9
8
  module NewRelic
@@ -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
@@ -9,8 +9,7 @@ module NewRelic
9
9
  def self.create(label, &blk)
10
10
  ::NewRelic::Agent.logger.debug("Creating AgentThread: #{label}")
11
11
  wrapped_blk = proc do
12
- if ::Thread.current[:newrelic_tracer_state] && Thread.current[:newrelic_tracer_state].current_transaction
13
- txn = ::Thread.current[:newrelic_tracer_state].current_transaction
12
+ if (txn = ::NewRelic::ThreadLocalStorage[:newrelic_tracer_state]&.current_transaction)
14
13
  ::NewRelic::Agent.logger.warn("AgentThread created with current transaction #{txn.best_name}")
15
14
  end
16
15
  begin
@@ -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
 
@@ -394,11 +392,11 @@ module NewRelic
394
392
  #
395
393
  # If ever exposed, this requires additional synchronization
396
394
  def state_for(thread)
397
- state = thread[:newrelic_tracer_state]
395
+ state = ThreadLocalStorage.get(thread, :newrelic_tracer_state)
398
396
 
399
397
  if state.nil?
400
398
  state = Tracer::State.new
401
- thread[:newrelic_tracer_state] = state
399
+ ThreadLocalStorage.set(thread, :newrelic_tracer_state, state)
402
400
  end
403
401
 
404
402
  state
@@ -407,7 +405,7 @@ module NewRelic
407
405
  alias_method :tl_state_for, :state_for
408
406
 
409
407
  def clear_state
410
- Thread.current[:newrelic_tracer_state] = nil
408
+ ThreadLocalStorage[:newrelic_tracer_state] = nil
411
409
  end
412
410
 
413
411
  alias_method :tl_clear, :clear_state
@@ -420,16 +418,17 @@ module NewRelic
420
418
  NewRelic::Agent.config[:'instrumentation.thread.tracing']
421
419
  end
422
420
 
423
- def thread_block_with_current_transaction(segment_name:, parent: nil, &block)
421
+ def thread_block_with_current_transaction(segment_name: nil, parent: nil, &block)
424
422
  parent ||= current_segment
425
- current_txn = ::Thread.current[:newrelic_tracer_state]&.current_transaction if ::Thread.current[:newrelic_tracer_state]&.is_execution_traced?
423
+ current_txn = ThreadLocalStorage[:newrelic_tracer_state]&.current_transaction if ThreadLocalStorage[:newrelic_tracer_state]&.is_execution_traced?
426
424
  proc do |*args|
427
425
  begin
428
426
  if current_txn && !current_txn.finished?
429
427
  NewRelic::Agent::Tracer.state.current_transaction = current_txn
428
+ ThreadLocalStorage[:newrelic_thread_span_parent] = parent
430
429
  current_txn.async = true
431
- segment_name += "/Thread#{::Thread.current.object_id}/Fiber#{::Fiber.current.object_id}" if NewRelic::Agent.config[:'thread_ids_enabled']
432
- segment = NewRelic::Agent::Tracer.start_segment(name: segment_name, parent: parent)
430
+ segment_name = "#{segment_name}/Thread#{::Thread.current.object_id}/Fiber#{::Fiber.current.object_id}" if NewRelic::Agent.config[:'thread_ids_enabled']
431
+ segment = NewRelic::Agent::Tracer.start_segment(name: segment_name, parent: parent) if segment_name
433
432
  end
434
433
  NewRelic::Agent::Tracer.capture_segment_error(segment) do
435
434
  yield(*args)
@@ -20,7 +20,7 @@ module NewRelic
20
20
  # calculation in all other cases.
21
21
  #
22
22
  attr_reader :start_time, :end_time, :duration, :exclusive_duration, :guid, :starting_segment_key
23
- attr_accessor :name, :parent, :children_time, :transaction, :transaction_name
23
+ attr_accessor :name, :parent, :children_time, :transaction, :transaction_name, :llm_event
24
24
  attr_writer :record_metrics, :record_scoped_metric, :record_on_finish
25
25
  attr_reader :noticed_error
26
26
 
@@ -338,6 +338,9 @@ module NewRelic
338
338
 
339
339
  NewRelic::Agent.logger.debug("Invoking callback for #{self.class.name}...")
340
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}")
341
344
  end
342
345
 
343
346
  # Setting and invoking a segment callback
@@ -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)
@@ -22,7 +22,7 @@ module NewRelic
22
22
 
23
23
  def add_segment(segment, parent = nil)
24
24
  segment.transaction = self
25
- segment.parent = parent || current_segment
25
+ segment.parent = parent || thread_starting_span || current_segment
26
26
  set_current_segment(segment)
27
27
  if @segments.length < segment_limit
28
28
  @segments << segment
@@ -39,6 +39,16 @@ module NewRelic
39
39
  segment.transaction_assigned
40
40
  end
41
41
 
42
+ def thread_starting_span
43
+ # if the previous current segment was in another thread, use the thread local parent
44
+ if ThreadLocalStorage[:newrelic_thread_span_parent] &&
45
+ current_segment &&
46
+ current_segment.starting_segment_key != NewRelic::Agent::Tracer.current_segment_key
47
+
48
+ ThreadLocalStorage[:newrelic_thread_span_parent]
49
+ end
50
+ end
51
+
42
52
  def segment_complete(segment)
43
53
  # if parent was in another thread, remove the current_segment entry for this thread
44
54
  if segment.parent && segment.parent.starting_segment_key != NewRelic::Agent::Tracer.current_segment_key
@@ -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