newrelic_rpm 6.6.0.358 → 6.11.0.365

Sign up to get free protection for your applications and to get access to all the features.
Files changed (126) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +3 -0
  3. data/.travis.yml +81 -5
  4. data/CHANGELOG.md +262 -0
  5. data/Gemfile +6 -2
  6. data/Guardfile +18 -1
  7. data/LICENSE +1 -1
  8. data/Rakefile +2 -0
  9. data/lib/new_relic/agent.rb +89 -7
  10. data/lib/new_relic/agent/agent.rb +115 -58
  11. data/lib/new_relic/agent/agent_logger.rb +4 -0
  12. data/lib/new_relic/agent/attribute_filter.rb +7 -7
  13. data/lib/new_relic/agent/attributes.rb +150 -0
  14. data/lib/new_relic/agent/autostart.rb +19 -14
  15. data/lib/new_relic/agent/configuration/default_source.rb +154 -9
  16. data/lib/new_relic/agent/configuration/event_harvest_config.rb +11 -5
  17. data/lib/new_relic/agent/configuration/manager.rb +0 -8
  18. data/lib/new_relic/agent/configuration/server_source.rb +3 -2
  19. data/lib/new_relic/agent/configuration/yaml_source.rb +11 -6
  20. data/lib/new_relic/agent/connect/request_builder.rb +5 -13
  21. data/lib/new_relic/agent/database.rb +1 -2
  22. data/lib/new_relic/agent/database/obfuscation_helpers.rb +1 -1
  23. data/lib/new_relic/agent/datastores/mongo.rb +1 -1
  24. data/lib/new_relic/agent/datastores/mongo/event_formatter.rb +2 -2
  25. data/lib/new_relic/agent/datastores/mongo/obfuscator.rb +8 -8
  26. data/lib/new_relic/agent/distributed_tracing.rb +155 -6
  27. data/lib/new_relic/agent/{cross_app_payload.rb → distributed_tracing/cross_app_payload.rb} +2 -1
  28. data/lib/new_relic/agent/{cross_app_tracing.rb → distributed_tracing/cross_app_tracing.rb} +60 -45
  29. data/lib/new_relic/agent/distributed_tracing/distributed_trace_intrinsics.rb +80 -0
  30. data/lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb +75 -0
  31. data/lib/new_relic/agent/{distributed_trace_payload.rb → distributed_tracing/distributed_trace_payload.rb} +24 -101
  32. data/lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb +39 -0
  33. data/lib/new_relic/agent/distributed_tracing/trace_context.rb +246 -0
  34. data/lib/new_relic/agent/distributed_tracing/trace_context_payload.rb +126 -0
  35. data/lib/new_relic/agent/error_collector.rb +33 -16
  36. data/lib/new_relic/agent/error_event_aggregator.rb +7 -5
  37. data/lib/new_relic/agent/external.rb +7 -7
  38. data/lib/new_relic/agent/guid_generator.rb +28 -0
  39. data/lib/new_relic/agent/hostname.rb +7 -1
  40. data/lib/new_relic/agent/http_clients/abstract.rb +82 -0
  41. data/lib/new_relic/agent/http_clients/curb_wrappers.rb +24 -19
  42. data/lib/new_relic/agent/http_clients/excon_wrappers.rb +28 -13
  43. data/lib/new_relic/agent/http_clients/http_rb_wrappers.rb +17 -21
  44. data/lib/new_relic/agent/http_clients/httpclient_wrappers.rb +10 -11
  45. data/lib/new_relic/agent/http_clients/net_http_wrappers.rb +16 -4
  46. data/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb +4 -6
  47. data/lib/new_relic/agent/http_clients/uri_util.rb +3 -2
  48. data/lib/new_relic/agent/instrumentation/action_cable_subscriber.rb +5 -7
  49. data/lib/new_relic/agent/instrumentation/action_controller_subscriber.rb +4 -0
  50. data/lib/new_relic/agent/instrumentation/action_view_subscriber.rb +11 -2
  51. data/lib/new_relic/agent/instrumentation/active_record.rb +4 -2
  52. data/lib/new_relic/agent/instrumentation/active_record_subscriber.rb +7 -2
  53. data/lib/new_relic/agent/instrumentation/active_storage_subscriber.rb +8 -4
  54. data/lib/new_relic/agent/instrumentation/bunny.rb +45 -28
  55. data/lib/new_relic/agent/instrumentation/curb.rb +59 -18
  56. data/lib/new_relic/agent/instrumentation/data_mapper.rb +3 -1
  57. data/lib/new_relic/agent/instrumentation/excon.rb +1 -1
  58. data/lib/new_relic/agent/instrumentation/excon/connection.rb +6 -3
  59. data/lib/new_relic/agent/instrumentation/excon/middleware.rb +2 -1
  60. data/lib/new_relic/agent/instrumentation/grape.rb +5 -10
  61. data/lib/new_relic/agent/instrumentation/http.rb +6 -3
  62. data/lib/new_relic/agent/instrumentation/httpclient.rb +5 -3
  63. data/lib/new_relic/agent/instrumentation/memcache.rb +3 -1
  64. data/lib/new_relic/agent/instrumentation/memcache/dalli.rb +6 -2
  65. data/lib/new_relic/agent/instrumentation/mongo.rb +9 -3
  66. data/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb +13 -0
  67. data/lib/new_relic/agent/instrumentation/net.rb +6 -3
  68. data/lib/new_relic/agent/instrumentation/notifications_subscriber.rb +25 -1
  69. data/lib/new_relic/agent/instrumentation/redis.rb +9 -3
  70. data/lib/new_relic/agent/instrumentation/resque.rb +3 -0
  71. data/lib/new_relic/agent/instrumentation/sidekiq.rb +47 -23
  72. data/lib/new_relic/agent/instrumentation/typhoeus.rb +23 -6
  73. data/lib/new_relic/agent/logging.rb +139 -0
  74. data/lib/new_relic/agent/messaging.rb +5 -73
  75. data/lib/new_relic/agent/method_tracer.rb +18 -6
  76. data/lib/new_relic/agent/method_tracer_helpers.rb +2 -2
  77. data/lib/new_relic/agent/monitors.rb +27 -0
  78. data/lib/new_relic/agent/monitors/cross_app_monitor.rb +110 -0
  79. data/lib/new_relic/agent/monitors/distributed_tracing_monitor.rb +27 -0
  80. data/lib/new_relic/agent/{inbound_request_monitor.rb → monitors/inbound_request_monitor.rb} +1 -1
  81. data/lib/new_relic/agent/{synthetics_monitor.rb → monitors/synthetics_monitor.rb} +2 -4
  82. data/lib/new_relic/agent/new_relic_service.rb +7 -6
  83. data/lib/new_relic/agent/noticible_error.rb +22 -0
  84. data/lib/new_relic/agent/span_event_aggregator.rb +1 -0
  85. data/lib/new_relic/agent/span_event_primitive.rb +86 -53
  86. data/lib/new_relic/agent/sql_sampler.rb +3 -3
  87. data/lib/new_relic/agent/supported_versions.rb +2 -2
  88. data/lib/new_relic/agent/system_info.rb +12 -3
  89. data/lib/new_relic/agent/tracer.rb +65 -18
  90. data/lib/new_relic/agent/transaction.rb +84 -79
  91. data/lib/new_relic/agent/transaction/abstract_segment.rb +28 -2
  92. data/lib/new_relic/agent/transaction/distributed_tracer.rb +171 -0
  93. data/lib/new_relic/agent/transaction/distributed_tracing.rb +57 -146
  94. data/lib/new_relic/agent/transaction/external_request_segment.rb +29 -36
  95. data/lib/new_relic/agent/transaction/message_broker_segment.rb +3 -11
  96. data/lib/new_relic/agent/transaction/segment.rb +7 -1
  97. data/lib/new_relic/agent/transaction/trace.rb +2 -4
  98. data/lib/new_relic/agent/transaction/trace_context.rb +168 -0
  99. data/lib/new_relic/agent/transaction/trace_node.rb +10 -8
  100. data/lib/new_relic/agent/transaction_error_primitive.rb +10 -15
  101. data/lib/new_relic/agent/transaction_event_primitive.rb +28 -39
  102. data/lib/new_relic/cli/commands/deployments.rb +1 -1
  103. data/lib/new_relic/cli/commands/install.rb +3 -2
  104. data/lib/new_relic/coerce.rb +31 -6
  105. data/lib/new_relic/constants.rb +38 -0
  106. data/lib/new_relic/control/instance_methods.rb +10 -1
  107. data/lib/new_relic/dependency_detection.rb +4 -4
  108. data/lib/new_relic/environment_report.rb +5 -1
  109. data/lib/new_relic/noticed_error.rb +38 -17
  110. data/lib/new_relic/rack/browser_monitoring.rb +5 -0
  111. data/lib/new_relic/supportability_helper.rb +14 -0
  112. data/lib/new_relic/version.rb +1 -1
  113. data/lib/tasks/multiverse.rb +25 -0
  114. data/lib/tasks/tests.rake +6 -1
  115. data/newrelic_rpm.gemspec +19 -8
  116. data/test/agent_helper.rb +323 -71
  117. metadata +100 -33
  118. data/lib/new_relic/agent/cross_app_monitor.rb +0 -110
  119. data/lib/new_relic/agent/distributed_trace_monitor.rb +0 -40
  120. data/lib/new_relic/agent/http_clients/abstract_request.rb +0 -31
  121. data/lib/new_relic/agent/transaction/attributes.rb +0 -154
  122. data/lib/tasks/versions.html.erb +0 -28
  123. data/lib/tasks/versions.postface.html +0 -8
  124. data/lib/tasks/versions.preface.html +0 -9
  125. data/lib/tasks/versions.rake +0 -65
  126. data/lib/tasks/versions.txt.erb +0 -14
@@ -6,25 +6,56 @@
6
6
  # itself, and should be usable from within any multiverse suite.
7
7
 
8
8
  require 'json'
9
+ require 'net/http'
10
+ begin
11
+ require 'net/http/status'
12
+ rescue LoadError
13
+ # NOP -- Net::HTTP::STATUS_CODES was introduced in Ruby 2.5
14
+ end
15
+
16
+ module MiniTest
17
+ module Assertions
18
+ # The failure message is backwards. This patch reverses the message
19
+ # Note: passing +msg+ caused two failure messages to be shown on failure
20
+ # and was more confusing than patching here.
21
+ def assert_match matcher, obj, msg = nil
22
+ msg = message(msg) { "Expected #{mu_pp obj} to match #{mu_pp matcher}" }
23
+ assert_respond_to matcher, :"=~"
24
+ matcher = Regexp.new Regexp.escape matcher if String === matcher
25
+ assert matcher =~ obj, msg
26
+ end
27
+ end
28
+ end
9
29
 
10
30
  class ArrayLogDevice
11
- def initialize( array=[] )
31
+ def initialize array=[]
12
32
  @array = array
13
33
  end
14
34
  attr_reader :array
15
35
 
16
- def write( message )
36
+ def write message
17
37
  @array << message
18
38
  end
19
39
 
20
40
  def close; end
21
41
  end
22
42
 
23
- def assert_between(floor, ceiling, value, message="expected #{floor} <= #{value} <= #{ceiling}")
43
+ def fake_guid length=16
44
+ NewRelic::Agent::GuidGenerator.generate_guid length
45
+ end
46
+
47
+ def assert_match matcher, obj, msg = nil
48
+ msg = message(msg) { "Expected #{mu_pp matcher} to match #{mu_pp obj}" }
49
+ assert_respond_to matcher, :"=~"
50
+ matcher = Regexp.new Regexp.escape matcher if String === matcher
51
+ assert matcher =~ obj, msg
52
+ end
53
+
54
+ def assert_between floor, ceiling, value, message="expected #{floor} <= #{value} <= #{ceiling}"
24
55
  assert((floor <= value && value <= ceiling), message)
25
56
  end
26
57
 
27
- def assert_in_delta(expected, actual, delta)
58
+ def assert_in_delta expected, actual, delta
28
59
  assert_between((expected - delta), (expected + delta), actual)
29
60
  end
30
61
 
@@ -36,7 +67,7 @@ def reset_error_traces!
36
67
  NewRelic::Agent.instance.error_collector.error_trace_aggregator.reset!
37
68
  end
38
69
 
39
- def assert_has_traced_error(error_class)
70
+ def assert_has_traced_error error_class
40
71
  errors = harvest_error_traces!
41
72
  assert \
42
73
  errors.find {|e| e.exception_class_name == error_class.name} != nil, \
@@ -63,38 +94,38 @@ def last_error_event
63
94
  harvest_error_events!.last.last
64
95
  end
65
96
 
66
- unless defined?( assert_block )
67
- def assert_block(*msgs)
97
+ unless defined? assert_block
98
+ def assert_block *msgs
68
99
  assert yield, *msgs
69
100
  end
70
101
  end
71
102
 
72
- unless defined?( assert_includes )
73
- def assert_includes( collection, member, msg=nil )
103
+ unless defined? assert_includes
104
+ def assert_includes collection, member, msg=nil
74
105
  msg = "Expected #{collection.inspect} to include #{member.inspect}"
75
106
  assert_block( msg ) { collection.include?(member) }
76
107
  end
77
108
  end
78
109
 
79
- unless defined?( assert_not_includes )
80
- def assert_not_includes( collection, member, msg=nil )
110
+ unless defined? assert_not_includes
111
+ def assert_not_includes collection, member, msg=nil
81
112
  msg = "Expected #{collection.inspect} not to include #{member.inspect}"
82
113
  assert !collection.include?(member), msg
83
114
  end
84
115
  end
85
116
 
86
- unless defined?( assert_empty )
87
- def assert_empty(collection, msg=nil)
117
+ unless defined? assert_empty
118
+ def assert_empty collection, msg=nil
88
119
  assert collection.empty?, msg
89
120
  end
90
121
  end
91
122
 
92
- def assert_equal_unordered(left, right)
123
+ def assert_equal_unordered left, right
93
124
  assert_equal(left.length, right.length, "Lengths don't match. #{left.length} != #{right.length}")
94
125
  left.each { |element| assert_includes(right, element) }
95
126
  end
96
127
 
97
- def assert_audit_log_contains(audit_log_contents, needle)
128
+ def assert_audit_log_contains audit_log_contents, needle
98
129
  # Original request bodies dumped to the log have symbol keys, but once
99
130
  # they go through a dump/load, they're strings again, so we strip
100
131
  # double-quotes and colons from the log, and the strings we searching for.
@@ -112,7 +143,7 @@ end
112
143
  # orderings of the key/value pairs in Hashes that were embedded in the request
113
144
  # body). So, this method traverses an object graph and only makes assertions
114
145
  # about the terminal (non-Array-or-Hash) nodes therein.
115
- def assert_audit_log_contains_object(audit_log_contents, o, format = :json)
146
+ def assert_audit_log_contains_object audit_log_contents, o, format = :json
116
147
  case o
117
148
  when Hash
118
149
  o.each do |k,v|
@@ -130,12 +161,12 @@ def assert_audit_log_contains_object(audit_log_contents, o, format = :json)
130
161
  end
131
162
  end
132
163
 
133
- def compare_metrics(expected, actual)
164
+ def compare_metrics expected, actual
134
165
  actual.delete_if {|a| a.include?('GC/Transaction/') }
135
166
  assert_equal(expected.to_a.sort, actual.to_a.sort, "extra: #{(actual - expected).to_a.inspect}; missing: #{(expected - actual).to_a.inspect}")
136
167
  end
137
168
 
138
- def metric_spec_from_specish(specish)
169
+ def metric_spec_from_specish specish
139
170
  spec = case specish
140
171
  when String then NewRelic::MetricSpec.new(specish)
141
172
  when Array then NewRelic::MetricSpec.new(*specish)
@@ -143,7 +174,7 @@ def metric_spec_from_specish(specish)
143
174
  spec
144
175
  end
145
176
 
146
- def _normalize_metric_expectations(expectations)
177
+ def _normalize_metric_expectations expectations
147
178
  case expectations
148
179
  when Array
149
180
  hash = {}
@@ -157,7 +188,7 @@ def _normalize_metric_expectations(expectations)
157
188
  end
158
189
  end
159
190
 
160
- def dump_stats(stats)
191
+ def dump_stats stats
161
192
  str = " Call count: #{stats.call_count}\n"
162
193
  str << " Total call time: #{stats.total_call_time}\n"
163
194
  str << " Total exclusive time: #{stats.total_exclusive_time}\n"
@@ -170,7 +201,7 @@ def dump_stats(stats)
170
201
  str
171
202
  end
172
203
 
173
- def assert_stats_has_values(stats, expected_spec, expected_attrs)
204
+ def assert_stats_has_values stats, expected_spec, expected_attrs
174
205
  expected_attrs.each do |attr, expected_value|
175
206
  actual_value = stats.send(attr)
176
207
  if attr == :call_count
@@ -183,7 +214,7 @@ def assert_stats_has_values(stats, expected_spec, expected_attrs)
183
214
  end
184
215
  end
185
216
 
186
- def assert_metrics_recorded(expected)
217
+ def assert_metrics_recorded expected
187
218
  expected = _normalize_metric_expectations(expected)
188
219
  expected.each do |specish, expected_attrs|
189
220
  expected_spec = metric_spec_from_specish(specish)
@@ -212,9 +243,9 @@ end
212
243
  #
213
244
  # If you want to *allow* unexpected metrics matching certain patterns, use
214
245
  # the :ignore_filter option. This will allow you to specify a Regex that
215
- # whitelists broad swathes of metric territory (e.g. 'Supportability/').
246
+ # allowlists broad swathes of metric territory (e.g. 'Supportability/').
216
247
  #
217
- def assert_metrics_recorded_exclusive(expected, options={})
248
+ def assert_metrics_recorded_exclusive expected, options={}
218
249
  expected = _normalize_metric_expectations(expected)
219
250
  assert_metrics_recorded(expected)
220
251
 
@@ -252,7 +283,7 @@ def clear_metrics!
252
283
  NewRelic::Agent.instance.stats_engine.reset_for_test!
253
284
  end
254
285
 
255
- def assert_metrics_not_recorded(not_expected)
286
+ def assert_metrics_not_recorded not_expected
256
287
  not_expected = _normalize_metric_expectations(not_expected)
257
288
  found_but_not_expected = []
258
289
  not_expected.each do |specish, _|
@@ -266,7 +297,7 @@ end
266
297
 
267
298
  alias :refute_metrics_recorded :assert_metrics_not_recorded
268
299
 
269
- def assert_no_metrics_match(regex)
300
+ def assert_no_metrics_match regex
270
301
  matching_metrics = []
271
302
  NewRelic::Agent.instance.stats_engine.to_h.keys.map(&:to_s).each do |metric|
272
303
  matching_metrics << metric if metric.match regex
@@ -281,30 +312,30 @@ end
281
312
 
282
313
  alias :refute_metrics_match :assert_no_metrics_match
283
314
 
284
- def format_metric_spec_list(specs)
315
+ def format_metric_spec_list specs
285
316
  spec_strings = specs.map do |spec|
286
317
  "#{spec.name} (#{spec.scope.empty? ? '<unscoped>' : spec.scope})"
287
318
  end
288
319
  "[\n #{spec_strings.join(",\n ")}\n]"
289
320
  end
290
321
 
291
- def assert_truthy(expected, msg = nil)
322
+ def assert_truthy expected, msg=nil
292
323
  msg ||= "Expected #{expected.inspect} to be truthy"
293
324
  assert !!expected, msg
294
325
  end
295
326
 
296
- def assert_falsy(expected, msg = nil)
327
+ def assert_falsy expected, msg=nil
297
328
  msg ||= "Expected #{expected.inspect} to be falsy"
298
329
  assert !expected, msg
299
330
  end
300
331
 
301
- unless defined?( assert_false )
302
- def assert_false(expected)
332
+ unless defined? assert_false
333
+ def assert_false expected
303
334
  assert_equal false, expected
304
335
  end
305
336
  end
306
337
 
307
- unless defined?(refute)
338
+ unless defined? refute
308
339
  alias refute assert_false
309
340
  end
310
341
 
@@ -326,7 +357,7 @@ end
326
357
  # With a transaction name plus category:
327
358
  # in_transaction('foobar', :category => :controller) { ... }
328
359
  #
329
- def in_transaction(*args, &blk)
360
+ def in_transaction *args, &blk
330
361
  opts = (args.last && args.last.is_a?(Hash)) ? args.pop : {}
331
362
  category = (opts && opts.delete(:category)) || :other
332
363
 
@@ -345,25 +376,70 @@ def in_transaction(*args, &blk)
345
376
  txn
346
377
  end
347
378
 
348
- def stub_transaction_guid(guid)
379
+ # Temporarily disables default transformer so tests with invalid inputs can be tried
380
+ def with_disabled_defaults_transformer key
381
+ begin
382
+ transformer = NewRelic::Agent::Configuration::DEFAULTS[key][:transform]
383
+ NewRelic::Agent::Configuration::DEFAULTS[key][:transform] = nil
384
+ yield
385
+ ensure
386
+ NewRelic::Agent::Configuration::DEFAULTS[key][:transform] = transformer
387
+ end
388
+ end
389
+
390
+ # Convenience wrapper to stand up a transaction and provide a segment within
391
+ # that transaction to work with. The same arguements as provided to in_transaction
392
+ # may be supplied.
393
+ def with_segment *args, &blk
394
+ segment = nil
395
+ txn = in_transaction(*args) do |txn|
396
+ segment = txn.current_segment
397
+ yield segment, txn
398
+ end
399
+ [segment, txn]
400
+ end
401
+
402
+ # building error attributes on segments are deferred until it's time
403
+ # to publish/harvest them as spans, so for testing, we'll explicitly
404
+ # build 'em as appropriate so we can test 'em
405
+ def build_deferred_error_attributes segment
406
+ return unless segment.noticed_error
407
+ segment.noticed_error.build_error_attributes
408
+ end
409
+
410
+ def capture_segment_with_error
411
+ begin
412
+ segment_with_error = nil
413
+ with_segment do |segment|
414
+ segment_with_error = segment
415
+ raise "oops!"
416
+ end
417
+ rescue Exception => exception
418
+ assert segment_with_error, "expected to have a segment_with_error"
419
+ build_deferred_error_attributes segment_with_error
420
+ return segment_with_error, exception
421
+ end
422
+ end
423
+
424
+ def stub_transaction_guid guid
349
425
  NewRelic::Agent::Transaction.tl_current.instance_variable_set(:@guid, guid)
350
426
  end
351
427
 
352
428
  # Convenience wrapper around in_transaction that sets the category so that it
353
429
  # looks like we are in a web transaction
354
- def in_web_transaction(name='dummy')
430
+ def in_web_transaction name='dummy'
355
431
  in_transaction(name, :category => :controller, :request => stub(:path => '/')) do |txn|
356
432
  yield txn
357
433
  end
358
434
  end
359
435
 
360
- def in_background_transaction(name='silly')
436
+ def in_background_transaction name='silly'
361
437
  in_transaction(name, :category => :task) do |txn|
362
438
  yield txn
363
439
  end
364
440
  end
365
441
 
366
- def refute_contains_request_params(attributes)
442
+ def refute_contains_request_params attributes
367
443
  attributes.keys.each do |key|
368
444
  refute_match(/^request\.parameters\./, key.to_s)
369
445
  end
@@ -382,7 +458,7 @@ def last_transaction_trace_request_params
382
458
  end
383
459
  end
384
460
 
385
- def find_sql_trace(metric_name)
461
+ def find_sql_trace metric_name
386
462
  NewRelic::Agent.agent.sql_sampler.sql_traces.values.detect do |trace|
387
463
  trace.database_metric_name == metric_name
388
464
  end
@@ -392,7 +468,7 @@ def last_sql_trace
392
468
  NewRelic::Agent.agent.sql_sampler.sql_traces.values.last
393
469
  end
394
470
 
395
- def find_last_transaction_node(transaction_sample=nil)
471
+ def find_last_transaction_node transaction_sample=nil
396
472
  if transaction_sample
397
473
  root_node = transaction_sample.root_node
398
474
  else
@@ -405,7 +481,7 @@ def find_last_transaction_node(transaction_sample=nil)
405
481
  return last_node
406
482
  end
407
483
 
408
- def find_node_with_name(transaction_sample, name)
484
+ def find_node_with_name transaction_sample, name
409
485
  transaction_sample.root_node.each_node do |node|
410
486
  if node.metric_name == name
411
487
  return node
@@ -415,7 +491,7 @@ def find_node_with_name(transaction_sample, name)
415
491
  nil
416
492
  end
417
493
 
418
- def find_node_with_name_matching(transaction_sample, regex)
494
+ def find_node_with_name_matching transaction_sample, regex
419
495
  transaction_sample.root_node.each_node do |node|
420
496
  if node.metric_name.match regex
421
497
  return node
@@ -425,7 +501,7 @@ def find_node_with_name_matching(transaction_sample, regex)
425
501
  nil
426
502
  end
427
503
 
428
- def find_all_nodes_with_name_matching(transaction_sample, regexes)
504
+ def find_all_nodes_with_name_matching transaction_sample, regexes
429
505
  regexes = [regexes].flatten
430
506
  matching_nodes = []
431
507
 
@@ -440,7 +516,7 @@ def find_all_nodes_with_name_matching(transaction_sample, regexes)
440
516
  matching_nodes
441
517
  end
442
518
 
443
- def with_config(config_hash, at_start=true)
519
+ def with_config config_hash, at_start=true
444
520
  config = NewRelic::Agent::Configuration::DottedHash.new(config_hash, true)
445
521
  NewRelic::Agent.config.add_config_for_testing(config, at_start)
446
522
  NewRelic::Agent.instance.refresh_attribute_filter
@@ -459,13 +535,13 @@ def with_server_source config_hash, at_start=true
459
535
  end
460
536
  end
461
537
 
462
- def with_config_low_priority(config_hash)
538
+ def with_config_low_priority config_hash
463
539
  with_config(config_hash, false) do
464
540
  yield
465
541
  end
466
542
  end
467
543
 
468
- def with_transaction_renaming_rules(rule_specs)
544
+ def with_transaction_renaming_rules rule_specs
469
545
  original_engine = NewRelic::Agent.agent.instance_variable_get(:@transaction_rules)
470
546
  begin
471
547
  new_engine = NewRelic::Agent::RulesEngine.create_transaction_rules('transaction_name_rules' => rule_specs)
@@ -491,7 +567,7 @@ unless Time.respond_to?(:__original_now)
491
567
  end
492
568
  end
493
569
 
494
- def nr_freeze_time(now=Time.now)
570
+ def nr_freeze_time now=Time.now
495
571
  Time.__frozen_now = now
496
572
  end
497
573
 
@@ -499,11 +575,11 @@ def nr_unfreeze_time
499
575
  Time.__frozen_now = nil
500
576
  end
501
577
 
502
- def advance_time(seconds)
578
+ def advance_time seconds
503
579
  Time.__frozen_now = Time.now + seconds
504
580
  end
505
581
 
506
- def with_constant_defined(constant_symbol, implementation=Module.new)
582
+ def with_constant_defined constant_symbol, implementation=Module.new
507
583
  const_path = constant_path(constant_symbol.to_s)
508
584
 
509
585
  if const_path
@@ -523,7 +599,7 @@ def with_constant_defined(constant_symbol, implementation=Module.new)
523
599
  end
524
600
  end
525
601
 
526
- def constant_path(name, opts={})
602
+ def constant_path name, opts={}
527
603
  allow_partial = opts[:allow_partial]
528
604
  path = [Object]
529
605
  parts = name.gsub(/^::/, '').split('::')
@@ -536,13 +612,13 @@ def constant_path(name, opts={})
536
612
  path
537
613
  end
538
614
 
539
- def get_parent(constant_name)
615
+ def get_parent constant_name
540
616
  parent_name = constant_name.gsub(/::[^:]*$/, '')
541
617
  const_path = constant_path(parent_name)
542
618
  const_path ? const_path[-1] : nil
543
619
  end
544
620
 
545
- def undefine_constant(constant_symbol)
621
+ def undefine_constant constant_symbol
546
622
  const_str = constant_symbol.to_s
547
623
  parent = get_parent(const_str)
548
624
  const_name = const_str.gsub(/.*::/, '')
@@ -566,11 +642,11 @@ ensure
566
642
  NewRelic::Agent.logger = orig_logger
567
643
  end
568
644
 
569
- def create_agent_command(args = {})
645
+ def create_agent_command args={}
570
646
  NewRelic::Agent::Commands::AgentCommand.new([-1, { "name" => "command_name", "arguments" => args}])
571
647
  end
572
648
 
573
- def wait_for_backtrace_service_poll(opts={})
649
+ def wait_for_backtrace_service_poll opts={}
574
650
  defaults = {
575
651
  :timeout => 10.0,
576
652
  :service => NewRelic::Agent.agent.agent_command_router.backtrace_service,
@@ -596,7 +672,7 @@ def wait_for_backtrace_service_poll(opts={})
596
672
  end
597
673
  end
598
674
 
599
- def with_array_logger(level=:info)
675
+ def with_array_logger level=:info
600
676
  orig_logger = NewRelic::Agent.logger
601
677
  config = { :log_level => level }
602
678
  logdev = ArrayLogDevice.new
@@ -612,20 +688,90 @@ ensure
612
688
  NewRelic::Agent.logger = orig_logger
613
689
  end
614
690
 
615
- def with_environment(env)
616
- old_env = {}
617
- env.each do |key, val|
618
- old_env[key] = ENV[key]
619
- ENV[key] = val.to_s
691
+ # The EnvUpdater was introduced due to random fails in JRuby environment
692
+ # whereby attempting to set ENV[key] = some_value randomly failed.
693
+ # It is conjectured that this is thread related, but may also be
694
+ # a core bug in the JVM implementation of Ruby. Root cause was not
695
+ # discovered, but it was found that a combination of retrying and using
696
+ # mutex lock around the update operation was the only consistently working
697
+ # solution as the error continued to surface without the mutex and
698
+ # retry alone wasn't enough, either.
699
+ #
700
+ # JRUBY: oraclejdk8 + jruby-9.2.6.0
701
+ #
702
+ # NOTE: Singleton pattern to ensure one mutex lock for all threads
703
+ class EnvUpdater
704
+ MAX_RETRIES = 5
705
+
706
+ def initialize
707
+ @mutex = Mutex.new
620
708
  end
621
- begin
709
+
710
+ # Will attempt the given block up to MAX_RETRIES before
711
+ # surfacing the exception down the chain.
712
+ def with_retry retry_limit=MAX_RETRIES
713
+ retries ||= 0
714
+ sleep(retries)
622
715
  yield
623
- ensure
624
- old_env.each { |key, old_val| ENV[key] = old_val }
716
+ rescue
717
+ (retries += 1) < retry_limit ? retry : raise
718
+ end
719
+
720
+ # Locks and updates the ENV
721
+ def safe_update env
722
+ with_retry do
723
+ @mutex.synchronize do
724
+ env.each{ |key, val| ENV[key] = val.to_s }
725
+ end
726
+ end
727
+ end
728
+
729
+ # Locks and restores the ENV
730
+ def safe_restore old_env
731
+ with_retry do
732
+ @mutex.synchronize do
733
+ old_env.each{ |key, val| val ? ENV[key] = val : ENV.delete(key) }
734
+ end
735
+ end
625
736
  end
737
+
738
+ # Singleton pattern implemented via @@instance
739
+ def self.instance
740
+ @@instance ||= EnvUpdater.new
741
+ end
742
+
743
+ def self.safe_update env
744
+ instance.safe_update env
745
+ end
746
+
747
+ def self.safe_restore old_env
748
+ instance.safe_restore old_env
749
+ end
750
+
751
+ # Effectively saves current ENV settings for given env's key/values,
752
+ # runs given block, then restores ENV to original state before returning.
753
+ def self.inject env, &block
754
+ old_env = {}
755
+ env.each{ |key, val| old_env[key] = ENV[key] }
756
+ begin
757
+ safe_update(env)
758
+ yield
759
+ ensure
760
+ safe_restore(old_env)
761
+ end
762
+ end
763
+
764
+ # must call instance here to ensure only one @mutex for all threads.
765
+ instance
766
+ end
767
+
768
+ # Changes ENV settings to given and runs given block and restores ENV
769
+ # to original values before returning.
770
+ def with_environment env, &block
771
+ EnvUpdater.inject(env) { yield }
626
772
  end
627
773
 
628
- def with_argv(argv)
774
+ def with_argv argv
629
775
  old_argv = ARGV.dup
630
776
  ARGV.clear
631
777
  ARGV.concat(argv)
@@ -638,7 +784,7 @@ def with_argv(argv)
638
784
  end
639
785
  end
640
786
 
641
- def with_ignore_error_filter(filter, &blk)
787
+ def with_ignore_error_filter filter, &blk
642
788
  original_filter = NewRelic::Agent.ignore_error_filter
643
789
  NewRelic::Agent.ignore_error_filter(&filter)
644
790
 
@@ -647,7 +793,7 @@ ensure
647
793
  NewRelic::Agent::ErrorCollector.ignore_error_filter = original_filter
648
794
  end
649
795
 
650
- def json_dump_and_encode(object)
796
+ def json_dump_and_encode object
651
797
  Base64.encode64(::JSON.dump(object))
652
798
  end
653
799
 
@@ -655,7 +801,7 @@ def get_last_analytics_event
655
801
  NewRelic::Agent.agent.transaction_event_aggregator.harvest![1].last
656
802
  end
657
803
 
658
- def swap_instance_method(target, method_name, new_method_implementation, &blk)
804
+ def swap_instance_method target, method_name, new_method_implementation, &blk
659
805
  old_method_implementation = target.instance_method(method_name)
660
806
  target.send(:define_method, method_name, new_method_implementation)
661
807
  yield
@@ -670,7 +816,7 @@ def cross_agent_tests_dir
670
816
  File.expand_path(File.join(File.dirname(__FILE__), 'fixtures', 'cross_agent_tests'))
671
817
  end
672
818
 
673
- def load_cross_agent_test(name)
819
+ def load_cross_agent_test name
674
820
  test_file_path = File.join(cross_agent_tests_dir, "#{name}.json")
675
821
  data = File.read(test_file_path)
676
822
  data.gsub!('callCount', 'call_count')
@@ -679,13 +825,13 @@ def load_cross_agent_test(name)
679
825
  data
680
826
  end
681
827
 
682
- def each_cross_agent_test(options)
828
+ def each_cross_agent_test options
683
829
  options = {:dir => nil, :pattern => "*"}.update(options)
684
830
  path = File.join [cross_agent_tests_dir, options[:dir], options[:pattern]].compact
685
831
  Dir.glob(path).each { |file| yield file}
686
832
  end
687
833
 
688
- def assert_event_attributes(event, test_name, expected_attributes, non_expected_attributes)
834
+ def assert_event_attributes event, test_name, expected_attributes, non_expected_attributes
689
835
  incorrect_attributes = []
690
836
 
691
837
  event_attrs = event[0]
@@ -709,10 +855,116 @@ def assert_event_attributes(event, test_name, expected_attributes, non_expected_
709
855
  assert(incorrect_attributes.empty?, msg)
710
856
 
711
857
  non_expected_attributes.each do |name|
712
- assert_nil(event_attrs[name], "Found value '#{event_attrs[name]}' for attribute '#{name}', but expected nothing in #{test_name}")
858
+ refute event_attrs[name], "Found value '#{event_attrs[name]}' for attribute '#{name}', but expected nothing in #{test_name}"
713
859
  end
714
860
  end
715
861
 
716
- def attributes_for(sample, type)
862
+ def attributes_for sample, type
717
863
  sample.attributes.instance_variable_get("@#{type}_attributes")
718
864
  end
865
+
866
+ def uncache_trusted_account_key
867
+ NewRelic::Agent::Transaction::TraceContext::AccountHelpers.instance_variable_set :@trace_state_entry_key, nil
868
+ end
869
+
870
+ def reset_buffers_and_caches
871
+ NewRelic::Agent.drop_buffered_data
872
+ uncache_trusted_account_key
873
+ end
874
+
875
+ def message_for_status_code code
876
+ # Net::HTTP::STATUS_CODES was introduced in Ruby 2.5
877
+ if defined?(Net::HTTP::STATUS_CODES)
878
+ return Net::HTTP::STATUS_CODES[code]
879
+ end
880
+
881
+ case code
882
+ when 200 then "OK"
883
+ when 404 then "Not Found"
884
+ when 403 then "Forbidden"
885
+ else "Unknown"
886
+ end
887
+ end
888
+
889
+ # wraps the given headers in a Net::HTTPResponse which has accompanying
890
+ # http status code associated with it.
891
+ # a "status_code" may be passed in the headers to alter the HTTP Status Code
892
+ # that is wrapped in the response.
893
+ def mock_http_response headers, wrap_it=true
894
+ status_code = (headers.delete("status_code") || 200).to_i
895
+ net_http_resp = Net::HTTPResponse.new(1.0, status_code, message_for_status_code(status_code))
896
+ headers.each do |key, value|
897
+ net_http_resp.add_field key.to_s, value
898
+ end
899
+ return net_http_resp unless wrap_it
900
+ NewRelic::Agent::HTTPClients::NetHTTPResponse.new(net_http_resp)
901
+ end
902
+
903
+ # +expected+ can be a string or regular expression
904
+ def assert_match_or_equal expected, value
905
+ if expected.is_a?(Regexp)
906
+ assert_match expected, value
907
+ else
908
+ assert_equal expected, value
909
+ end
910
+ end
911
+
912
+ # selects the last segment with a noticed_error and checks
913
+ # the expectations against it.
914
+ def assert_segment_noticed_error txn, segment_name, error_classes, error_message
915
+ error_segment = txn.segments.reverse.detect{|s| s.noticed_error}
916
+ assert error_segment, "Expected at least one segment with a noticed_error"
917
+
918
+ assert_match_or_equal segment_name, error_segment.name
919
+
920
+ noticed_error = error_segment.noticed_error
921
+
922
+ assert_match_or_equal error_classes, noticed_error.exception_class_name
923
+ assert_match_or_equal error_message, noticed_error.message
924
+ end
925
+
926
+ def assert_transaction_noticed_error txn, error_classes
927
+ refute_empty txn.exceptions, "Expected transaction to notice the error"
928
+ assert_match_or_equal error_classes, txn.exceptions.keys.first.class.name
929
+ end
930
+
931
+ def refute_transaction_noticed_error txn, error_class
932
+ error_segment = txn.segments.reverse.detect{|s| s.noticed_error}
933
+ assert error_segment, "Expected at least one segment with a noticed_error"
934
+ assert_empty txn.exceptions, "Expected transaction to NOT notice any segment errors"
935
+ end
936
+
937
+ def refute_raises *exp
938
+ msg = "#{exp.pop}.\n" if String === exp.last
939
+
940
+ begin
941
+ yield
942
+ rescue MiniTest::Skip => e
943
+ puts "SKIP REPORTS: #{e.inspect}"
944
+ return e if exp.include? MiniTest::Skip
945
+ raise e
946
+ rescue Exception => e
947
+ puts "EXCEPTION RAISED: #{e.inspect}\n#{e.backtrace}"
948
+ exp = exp.first if exp.size == 1
949
+ flunk msg || "unexpected exception raised: #{e}"
950
+ end
951
+ end
952
+
953
+ def assert_implements instance, method, *args
954
+ fail_message = "expected #{instance.class}##{method} method to be implemented"
955
+ refute_raises NotImplementedError, fail_message do
956
+ instance.send(method, *args)
957
+ end
958
+ end
959
+
960
+ def defer_testing_to_min_supported_rails test_file, min_rails_version, supports_jruby=true
961
+ if defined?(::Rails) &&
962
+ defined?(::Rails::VERSION::STRING) &&
963
+ (::Rails::VERSION::STRING.to_f >= min_rails_version) &&
964
+ (supports_jruby || !NewRelic::LanguageSupport.jruby?)
965
+
966
+ yield
967
+ else
968
+ puts "Skipping tests in #{test_file} because Rails >= #{min_rails_version} is unavailable"
969
+ end
970
+ end